From 569f53eb353d25b8d0df4b61b3437d1f9e62a8b4 Mon Sep 17 00:00:00 2001 From: Jeffrey Smith Date: Sat, 5 Dec 2026 15:17:57 -0500 Subject: [PATCH 1/2] Revert "feat(server): default delegate_task placement to auto and protect active interactive hosts (#265)" This reverts commit 38fc745ba6d6029cc3348f686f26cff3f7ee3fbe. --- .../src/mcp/OrchestratorMcpService.test.ts | 394 ++---------- apps/server/src/mcp/OrchestratorMcpService.ts | 340 ++-------- ...OrchestratorMcpToolkit.integration.test.ts | 7 +- ...skCancelNativeSubagent.integration.test.ts | 11 +- apps/server/src/peer/RemoteDelegation.test.ts | 604 +----------------- apps/server/src/peer/RemoteDelegation.ts | 87 +-- .../contracts/src/orchestratorMcp.test.ts | 17 - packages/contracts/src/orchestratorMcp.ts | 14 +- 8 files changed, 146 insertions(+), 1328 deletions(-) diff --git a/apps/server/src/mcp/OrchestratorMcpService.test.ts b/apps/server/src/mcp/OrchestratorMcpService.test.ts index f26253f715413..3213027e059df 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.test.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.test.ts @@ -86,11 +86,6 @@ import * as ProviderRegistryMock from "../provider/testUtils/providerRegistryMoc const decodeTarget = Schema.decodeUnknownEffect(OrchestratorMcpTarget); -const localRemoteDelegationLayer = Layer.mock(RemoteDelegation.RemoteDelegation)({ - place: (scope) => Effect.succeed(scope.environmentId), - placed: () => Effect.succeedNone, -}); - const layerOrchestratorService = OrchestratorMcpService.layer.pipe( Layer.provide(Layer.mock(ThreadLaunchService.ThreadLaunchService)({})), Layer.provide(Layer.mock(GitVcsDriver.GitVcsDriver)({})), @@ -222,7 +217,7 @@ describe("OrchestratorMcpService", () => { }), Layer.mock(ProjectService.ProjectService)({ getById: () => Effect.succeedNone }), Layer.mock(SecretRequests.SecretRequests)({}), - localRemoteDelegationLayer, + Layer.mock(RemoteDelegation.RemoteDelegation)({}), Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), ); const scope: McpInvocationScope = { @@ -346,7 +341,7 @@ describe("OrchestratorMcpService", () => { }), Layer.mock(ProjectService.ProjectService)({ getById: () => Effect.succeedNone }), Layer.mock(SecretRequests.SecretRequests)({}), - localRemoteDelegationLayer, + Layer.mock(RemoteDelegation.RemoteDelegation)({}), Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), ); const scope: McpInvocationScope = { @@ -492,7 +487,7 @@ describe("OrchestratorMcpService", () => { }), Layer.mock(ProjectService.ProjectService)({ getById: () => Effect.succeedNone }), Layer.mock(SecretRequests.SecretRequests)({}), - localRemoteDelegationLayer, + Layer.mock(RemoteDelegation.RemoteDelegation)({}), Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), ); const scope: McpInvocationScope = { @@ -591,7 +586,7 @@ describe("OrchestratorMcpService", () => { }), Layer.mock(ProjectService.ProjectService)({ getById: () => Effect.succeedNone }), Layer.mock(SecretRequests.SecretRequests)({}), - localRemoteDelegationLayer, + Layer.mock(RemoteDelegation.RemoteDelegation)({}), Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), ); const scope: McpInvocationScope = { @@ -711,7 +706,7 @@ describe("OrchestratorMcpService", () => { }), Layer.mock(ProjectService.ProjectService)({ getById: () => Effect.succeedNone }), Layer.mock(SecretRequests.SecretRequests)({}), - localRemoteDelegationLayer, + Layer.mock(RemoteDelegation.RemoteDelegation)({}), Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), ); const scope: McpInvocationScope = { @@ -822,7 +817,7 @@ describe("OrchestratorMcpService", () => { }), Layer.mock(ProjectService.ProjectService)({ getById: () => Effect.succeedNone }), Layer.mock(SecretRequests.SecretRequests)({}), - localRemoteDelegationLayer, + Layer.mock(RemoteDelegation.RemoteDelegation)({}), Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), ); const scope: McpInvocationScope = { @@ -924,7 +919,7 @@ describe("OrchestratorMcpService", () => { }), Layer.mock(ProjectService.ProjectService)({ getById: () => Effect.succeedNone }), Layer.mock(SecretRequests.SecretRequests)({}), - localRemoteDelegationLayer, + Layer.mock(RemoteDelegation.RemoteDelegation)({}), Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), ); const scope: McpInvocationScope = { @@ -1033,7 +1028,7 @@ describe("OrchestratorMcpService", () => { }), Layer.mock(ProjectService.ProjectService)({ getById: () => Effect.succeedNone }), Layer.mock(SecretRequests.SecretRequests)({}), - localRemoteDelegationLayer, + Layer.mock(RemoteDelegation.RemoteDelegation)({}), Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), ); const scope: McpInvocationScope = { @@ -1130,7 +1125,7 @@ describe("OrchestratorMcpService", () => { }), Layer.mock(ProjectService.ProjectService)({ getById: () => Effect.succeedNone }), Layer.mock(SecretRequests.SecretRequests)({}), - localRemoteDelegationLayer, + Layer.mock(RemoteDelegation.RemoteDelegation)({}), Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), ); const scope: McpInvocationScope = { @@ -1224,7 +1219,7 @@ describe("OrchestratorMcpService", () => { }), Layer.mock(ProjectService.ProjectService)({ getById: () => Effect.succeedNone }), Layer.mock(SecretRequests.SecretRequests)({}), - localRemoteDelegationLayer, + Layer.mock(RemoteDelegation.RemoteDelegation)({}), Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), ); const scope: McpInvocationScope = { @@ -1316,7 +1311,7 @@ describe("OrchestratorMcpService", () => { }), Layer.mock(ProjectService.ProjectService)({ getById: () => Effect.succeedNone }), Layer.mock(SecretRequests.SecretRequests)({}), - localRemoteDelegationLayer, + Layer.mock(RemoteDelegation.RemoteDelegation)({}), Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), ); const scope: McpInvocationScope = { @@ -1506,7 +1501,7 @@ describe("OrchestratorMcpService", () => { }), Layer.mock(ProjectService.ProjectService)({ getById: () => Effect.succeedNone }), Layer.mock(SecretRequests.SecretRequests)({}), - localRemoteDelegationLayer, + Layer.mock(RemoteDelegation.RemoteDelegation)({}), Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), ); const scope: McpInvocationScope = { @@ -1786,7 +1781,7 @@ describe("OrchestratorMcpService provider resolution", () => { adapterRegistryLayer([codexInstanceId]), Layer.mock(ProjectService.ProjectService)({ getById: () => Effect.succeedNone }), Layer.mock(SecretRequests.SecretRequests)({}), - localRemoteDelegationLayer, + Layer.mock(RemoteDelegation.RemoteDelegation)({}), Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), ); yield* Effect.gen(function* () { @@ -1916,7 +1911,7 @@ describe("OrchestratorMcpService provider resolution", () => { adapterRegistryLayer([codexInstanceId]), Layer.mock(ProjectService.ProjectService)({ getById: () => Effect.succeedNone }), Layer.mock(SecretRequests.SecretRequests)({}), - localRemoteDelegationLayer, + Layer.mock(RemoteDelegation.RemoteDelegation)({}), Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), ); yield* Effect.gen(function* () { @@ -2008,7 +2003,7 @@ describe("OrchestratorMcpService provider resolution", () => { adapterRegistryLayer([codexInstanceId]), Layer.mock(ProjectService.ProjectService)({ getById: () => Effect.succeedNone }), Layer.mock(SecretRequests.SecretRequests)({}), - localRemoteDelegationLayer, + Layer.mock(RemoteDelegation.RemoteDelegation)({}), Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), ); yield* Effect.gen(function* () { @@ -2057,7 +2052,7 @@ describe("OrchestratorMcpService provider resolution", () => { adapterRegistryLayer([]), Layer.mock(ProjectService.ProjectService)({ getById: () => Effect.succeedNone }), Layer.mock(SecretRequests.SecretRequests)({}), - localRemoteDelegationLayer, + Layer.mock(RemoteDelegation.RemoteDelegation)({}), Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), ); yield* Effect.gen(function* () { @@ -2123,7 +2118,7 @@ describe("OrchestratorMcpService provider resolution", () => { adapterRegistryLayer([]), Layer.mock(ProjectService.ProjectService)({ getById: () => Effect.succeedNone }), Layer.mock(SecretRequests.SecretRequests)({}), - localRemoteDelegationLayer, + Layer.mock(RemoteDelegation.RemoteDelegation)({}), Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), ); yield* Effect.gen(function* () { @@ -2261,7 +2256,7 @@ describe("OrchestratorMcpService provider resolution", () => { ]), Layer.mock(ProjectService.ProjectService)({ getById: () => Effect.succeedNone }), Layer.mock(SecretRequests.SecretRequests)({}), - localRemoteDelegationLayer, + Layer.mock(RemoteDelegation.RemoteDelegation)({}), Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), Layer.mock(HostResources.HostResources)({ read: Effect.succeed(hostSnapshot) }), ); @@ -2448,7 +2443,7 @@ describe("OrchestratorMcpService provider resolution", () => { adapterRegistryLayer([codexInstanceId, opencodeInstanceId]), Layer.mock(ProjectService.ProjectService)({ getById: () => Effect.succeedNone }), Layer.mock(SecretRequests.SecretRequests)({}), - localRemoteDelegationLayer, + Layer.mock(RemoteDelegation.RemoteDelegation)({}), Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), ), ), @@ -2606,7 +2601,7 @@ describe("OrchestratorMcpService provider resolution", () => { adapterRegistryLayer([museInstanceId]), Layer.mock(ProjectService.ProjectService)({ getById: () => Effect.succeedNone }), Layer.mock(SecretRequests.SecretRequests)({}), - localRemoteDelegationLayer, + Layer.mock(RemoteDelegation.RemoteDelegation)({}), Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), ); yield* Effect.gen(function* () { @@ -2707,7 +2702,7 @@ describe("OrchestratorMcpService provider resolution", () => { getById: () => Effect.succeedSome({ id: projectId, workspaceRoot } as never), }), Layer.mock(SecretRequests.SecretRequests)({}), - localRemoteDelegationLayer, + Layer.mock(RemoteDelegation.RemoteDelegation)({}), Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), ); yield* Effect.gen(function* () { @@ -2789,7 +2784,7 @@ describe("OrchestratorMcpService provider resolution", () => { Effect.succeedSome({ id: projectId, title: "parent", workspaceRoot } as never), }), Layer.mock(SecretRequests.SecretRequests)({}), - localRemoteDelegationLayer, + Layer.mock(RemoteDelegation.RemoteDelegation)({}), Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), ); const notARepository = (cwd: string) => @@ -2891,31 +2886,20 @@ describe("OrchestratorMcpService provider resolution", () => { }), }), ServerSettings.layerTest(), - Layer.mock(ProviderRegistry.ProviderRegistry)({ - getProviders: Effect.succeed([ - providerSnapshot({ - instanceId: codexInstanceId, - driver: ProviderDriverKind.make("codex"), - model: "gpt-5.4", - }), - ]), - refreshWorkspaceSnapshot: () => - Effect.succeed([ - providerSnapshot({ - instanceId: codexInstanceId, - driver: ProviderDriverKind.make("codex"), - model: "gpt-5.4", - }), - ]), - }), + providerRegistryLayer([ + providerSnapshot({ + instanceId: codexInstanceId, + driver: ProviderDriverKind.make("codex"), + model: "gpt-5.4", + }), + ]), adapterRegistryLayer([codexInstanceId]), Layer.mock(ProjectService.ProjectService)({ getById: () => Effect.succeedSome({ id: projectId, title: "parent", workspaceRoot } as never), - workspaceScanDirectory: Effect.succeed, }), Layer.mock(SecretRequests.SecretRequests)({}), - localRemoteDelegationLayer, + Layer.mock(RemoteDelegation.RemoteDelegation)({}), Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), Layer.mock(ThreadLaunchService.ThreadLaunchService)({ isNonGitProject: () => Effect.succeed(false), @@ -2955,230 +2939,6 @@ describe("OrchestratorMcpService provider resolution", () => { ), ); - it.live( - "places isolation: worktree on a headless host from the pushed ref and refuses unpushed commits while a human is active", - () => - Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const git = yield* GitVcsDriver.GitVcsDriver; - const remoteRoot = yield* fileSystem.realPath( - yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-mcp-pushed-origin-" }), - ); - const workspaceRoot = yield* fileSystem.realPath( - yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-mcp-pushed-clone-" }), - ); - yield* git.execute({ operation: "pushed-test", cwd: remoteRoot, args: ["init", "--bare"] }); - for (const args of [ - ["init", "-b", "main"], - ["config", "user.email", "delegate@example.test"], - ["config", "user.name", "Delegate"], - ["commit", "--allow-empty", "-m", "initial"], - ["remote", "add", "origin", remoteRoot], - ["push", "-u", "origin", "main"], - ]) { - yield* git.execute({ operation: "pushed-test", cwd: workspaceRoot, args }); - } - - const remoteEnvId = EnvironmentId.make("environment:r720-headless"); - const delegatedCalls: Array<{ - readonly environmentId: EnvironmentId; - readonly workspaceStrategy: unknown; - }> = []; - const remoteTask = { - id: taskId, - threadId: parentThreadId, - origin: "app_owned", - childThreadId: null, - remoteChild: { - environmentId: remoteEnvId, - threadId: childThreadId, - label: "R720", - title: "Review PR", - }, - providerInstanceId: codexInstanceId, - model: "gpt-5.4", - status: "running", - result: null, - }; - const dependencies = Layer.mergeAll( - Layer.mock(ThreadManagementService.ThreadManagementService)({ - hasReceipt: () => Effect.succeed(false), - getThreadRecords: () => - Effect.succeed({ - ...parentProjection([remoteTask]), - thread: { - ...parentProjection([]).thread, - worktreePath: null, - branch: "main", - }, - } as OrchestrationV2ThreadProjection), - }), - ServerSettings.layerTest(), - Layer.mock(ProviderRegistry.ProviderRegistry)({ - getProviders: Effect.succeed([ - providerSnapshot({ - instanceId: codexInstanceId, - driver: ProviderDriverKind.make("codex"), - model: "gpt-5.4", - }), - ]), - refreshWorkspaceSnapshot: () => - Effect.succeed([ - providerSnapshot({ - instanceId: codexInstanceId, - driver: ProviderDriverKind.make("codex"), - model: "gpt-5.4", - }), - ]), - }), - adapterRegistryLayer([codexInstanceId]), - Layer.mock(ProjectService.ProjectService)({ - getById: () => - Effect.succeedSome({ id: projectId, title: "parent", workspaceRoot } as never), - workspaceScanDirectory: Effect.succeed, - }), - Layer.mock(SecretRequests.SecretRequests)({}), - Layer.mock(HostResources.HostResources)({ - read: Effect.succeed({ - sampledAt: 0, - cpuUtilization: 0.1, - cpuCount: 8, - availableMemoryBytes: 8 * 1024 ** 3, - totalMemoryBytes: 16 * 1024 ** 3, - loadPerCpu: 0.1, - runningAgents: 0, - placementRole: "interactive", - humanActive: true, - }), - }), - Layer.mock(RemoteDelegation.RemoteDelegation)({ - place: () => Effect.succeed(remoteEnvId), - placed: () => Effect.succeedNone, - delegate: (_scope, delegateInput) => { - delegatedCalls.push({ - environmentId: delegateInput.target.environmentId, - workspaceStrategy: delegateInput.workspaceStrategy, - }); - return Effect.succeed({ taskId }); - }, - runStatus: () => - Effect.succeed({ - runStatus: "running", - peerStatus: "reachable", - lastSeenAt: undefined, - }), - }), - Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), - Layer.mock(ThreadLaunchService.ThreadLaunchService)({ - isNonGitProject: () => Effect.succeed(false), - }), - Layer.succeed(GitVcsDriver.GitVcsDriver, git), - ); - - yield* Effect.gen(function* () { - const service = yield* OrchestratorMcpService.OrchestratorMcpService; - const placed = yield* service.delegateTask(scope, { - task: "Review PR from pushed ref.", - isolation: "worktree", - mode: "async", - clientRequestId: "pushed-worktree-1", - }); - assert.equal(placed.remoteChild?.environmentId, remoteEnvId); - assert.deepEqual(delegatedCalls, [ - { - environmentId: remoteEnvId, - workspaceStrategy: { - type: "worktree", - baseRef: "origin/main", - startFromOrigin: true, - }, - }, - ]); - - // Once local HEAD has an unpushed commit, remote placement cannot fetch it and the - // active-human interactive host refuses running locally without needsLocalCheckout. - yield* git.execute({ - operation: "pushed-test", - cwd: workspaceRoot, - args: ["commit", "--allow-empty", "-m", "unpushed local commit"], - }); - const refused = yield* service - .delegateTask(scope, { - task: "Review with unpushed local commit.", - isolation: "worktree", - mode: "async", - clientRequestId: "unpushed-worktree-1", - }) - .pipe(Effect.flip); - assert.equal(refused.code, "invalid_request"); - assert.include(refused.message, "active"); - assert.include(refused.message, "needsLocalCheckout"); - assert.equal(delegatedCalls.length, 1); - - // Push the second commit to origin/main, then check out an unpushed branch at the - // older commit (HEAD~1). Even though HEAD is an ancestor of origin/main, it must NOT - // fall back to the newer origin/main tip. - yield* git.execute({ - operation: "pushed-test", - cwd: workspaceRoot, - args: ["push", "origin", "main"], - }); - yield* git.execute({ - operation: "pushed-test", - cwd: workspaceRoot, - args: ["checkout", "-b", "feat/older-base", "HEAD~1"], - }); - const olderBaseRefused = yield* service - .delegateTask(scope, { - task: "Review branch cut from older origin/main commit.", - isolation: "worktree", - mode: "async", - clientRequestId: "older-base-worktree-1", - }) - .pipe(Effect.flip); - assert.equal(olderBaseRefused.code, "invalid_request"); - assert.include(olderBaseRefused.message, "no pushed ref covers HEAD"); - assert.equal(delegatedCalls.length, 1); - - // Once that older-base branch is pushed itself, remote placement targets origin/feat/older-base. - yield* git.execute({ - operation: "pushed-test", - cwd: workspaceRoot, - args: ["push", "-u", "origin", "feat/older-base"], - }); - const pushedFeature = yield* service.delegateTask(scope, { - task: "Review pushed older-base branch.", - isolation: "worktree", - mode: "async", - clientRequestId: "pushed-older-base-worktree-1", - }); - assert.equal(pushedFeature.remoteChild?.environmentId, remoteEnvId); - assert.deepEqual(delegatedCalls[1], { - environmentId: remoteEnvId, - workspaceStrategy: { - type: "worktree", - baseRef: "origin/feat/older-base", - startFromOrigin: true, - }, - }); - }).pipe(Effect.provide(OrchestratorMcpService.layer.pipe(Layer.provide(dependencies)))); - }).pipe( - Effect.provide( - Layer.mergeAll( - NodeServices.layer, - NodeCrypto.layer, - GitVcsDriver.layer.pipe( - Layer.provideMerge( - ServerConfig.layerTest(process.cwd(), { prefix: "t3-mcp-pushed-ref-" }), - ), - Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), - ), - ), - ), - Effect.scoped, - ), - ); - it.effect("rejects delegation to a provider without a registered adapter", () => Effect.gen(function* () { const forkOnlyInstanceId = ProviderInstanceId.make("forkOnly"); @@ -3207,7 +2967,7 @@ describe("OrchestratorMcpService provider resolution", () => { adapterRegistryLayer([codexInstanceId]), Layer.mock(ProjectService.ProjectService)({ getById: () => Effect.succeedNone }), Layer.mock(SecretRequests.SecretRequests)({}), - localRemoteDelegationLayer, + Layer.mock(RemoteDelegation.RemoteDelegation)({}), Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), ); @@ -3268,7 +3028,7 @@ describe("OrchestratorMcpService provider resolution", () => { adapterRegistryLayer([codexInstanceId]), Layer.mock(ProjectService.ProjectService)({ getById: () => Effect.succeedNone }), Layer.mock(SecretRequests.SecretRequests)({}), - localRemoteDelegationLayer, + Layer.mock(RemoteDelegation.RemoteDelegation)({}), Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), ); const error = yield* Effect.gen(function* () { @@ -3326,27 +3086,17 @@ describe("OrchestratorMcpService provider resolution", () => { : Effect.succeed({ storedEvents: [] } as never), }), ServerSettings.layerTest(), - Layer.mock(ProviderRegistry.ProviderRegistry)({ - getProviders: Effect.succeed([ - providerSnapshot({ - instanceId: codexInstanceId, - driver: ProviderDriverKind.make("codex"), - model: "gpt-5.4", - }), - ]), - refreshWorkspaceSnapshot: () => - Effect.succeed([ - providerSnapshot({ - instanceId: codexInstanceId, - driver: ProviderDriverKind.make("codex"), - model: "gpt-5.4", - }), - ]), - }), + providerRegistryLayer([ + providerSnapshot({ + instanceId: codexInstanceId, + driver: ProviderDriverKind.make("codex"), + model: "gpt-5.4", + }), + ]), adapterRegistryLayer([codexInstanceId]), Layer.mock(ProjectService.ProjectService)({ getById: () => Effect.succeedNone }), Layer.mock(SecretRequests.SecretRequests)({}), - localRemoteDelegationLayer, + Layer.mock(RemoteDelegation.RemoteDelegation)({}), Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), ); const error = yield* Effect.gen(function* () { @@ -3393,7 +3143,7 @@ describe("OrchestratorMcpService provider resolution", () => { adapterRegistryLayer([codexInstanceId]), Layer.mock(ProjectService.ProjectService)({ getById: () => Effect.succeedNone }), Layer.mock(SecretRequests.SecretRequests)({}), - localRemoteDelegationLayer, + Layer.mock(RemoteDelegation.RemoteDelegation)({}), Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), ); @@ -3519,7 +3269,7 @@ describe("OrchestratorMcpService provider resolution", () => { adapterRegistryLayer([codexInstanceId, claudeInstanceId]), Layer.mock(ProjectService.ProjectService)({ getById: () => Effect.succeedNone }), Layer.mock(SecretRequests.SecretRequests)({}), - localRemoteDelegationLayer, + Layer.mock(RemoteDelegation.RemoteDelegation)({}), Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), ); @@ -3635,7 +3385,7 @@ describe("OrchestratorMcpService provider resolution", () => { adapterRegistryLayer([codexInstanceId, altInstanceId]), Layer.mock(ProjectService.ProjectService)({ getById: () => Effect.succeedNone }), Layer.mock(SecretRequests.SecretRequests)({}), - localRemoteDelegationLayer, + Layer.mock(RemoteDelegation.RemoteDelegation)({}), Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), ServerSettings.layerTest(), ); @@ -3726,27 +3476,17 @@ describe("OrchestratorMcpService provider resolution", () => { } as never), ), }), - Layer.mock(ProviderRegistry.ProviderRegistry)({ - getProviders: Effect.succeed([ - providerSnapshot({ - instanceId: codexInstanceId, - driver: ProviderDriverKind.make("codex"), - model: "gpt-5.4", - }), - ]), - refreshWorkspaceSnapshot: () => - Effect.succeed([ - providerSnapshot({ - instanceId: codexInstanceId, - driver: ProviderDriverKind.make("codex"), - model: "gpt-5.4", - }), - ]), - }), + providerRegistryLayer([ + providerSnapshot({ + instanceId: codexInstanceId, + driver: ProviderDriverKind.make("codex"), + model: "gpt-5.4", + }), + ]), adapterRegistryLayer([codexInstanceId]), Layer.mock(ProjectService.ProjectService)({ getById: () => Effect.succeedNone }), Layer.mock(SecretRequests.SecretRequests)({}), - localRemoteDelegationLayer, + Layer.mock(RemoteDelegation.RemoteDelegation)({}), Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), ServerSettings.layerTest(), ); @@ -3866,7 +3606,7 @@ describe("OrchestratorMcpService provider resolution", () => { adapterRegistryLayer([codexInstanceId, altInstanceId]), Layer.mock(ProjectService.ProjectService)({ getById: () => Effect.succeedNone }), Layer.mock(SecretRequests.SecretRequests)({}), - localRemoteDelegationLayer, + Layer.mock(RemoteDelegation.RemoteDelegation)({}), Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), ServerSettings.layerTest(), ); @@ -3962,7 +3702,7 @@ describe("OrchestratorMcpService provider resolution", () => { ]), Layer.mock(ProjectService.ProjectService)({ getById: () => Effect.succeedNone }), Layer.mock(SecretRequests.SecretRequests)({}), - localRemoteDelegationLayer, + Layer.mock(RemoteDelegation.RemoteDelegation)({}), Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), ), ), @@ -4174,8 +3914,6 @@ describe("OrchestratorMcpService provider resolution", () => { Effect.gen(function* () { const orchestrator = yield* Orchestrator.OrchestratorV2; return Layer.mock(RemoteDelegation.RemoteDelegation)({ - place: (scope) => Effect.succeed(scope.environmentId), - placed: () => Effect.succeedNone, delegate: (_scope, input) => Effect.gen(function* () { const run = (yield* orchestrator.getThreadProjection(parentThreadId)).runs[0]!; @@ -4429,7 +4167,7 @@ describe("OrchestratorMcpService provider resolution", () => { ), Layer.mock(ProjectService.ProjectService)({ getById: () => Effect.succeedNone }), Layer.mock(SecretRequests.SecretRequests)({}), - localRemoteDelegationLayer, + Layer.mock(RemoteDelegation.RemoteDelegation)({}), Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), ); @@ -4613,7 +4351,7 @@ describe("OrchestratorMcpService provider resolution", () => { } as Project), }), Layer.mock(SecretRequests.SecretRequests)({}), - localRemoteDelegationLayer, + Layer.mock(RemoteDelegation.RemoteDelegation)({}), Layer.mock(ScheduledTaskService.ScheduledTaskService)({ list: () => created === undefined @@ -4796,7 +4534,7 @@ describe("OrchestratorMcpService provider resolution", () => { }), Layer.mock(ProjectService.ProjectService)({ getById: () => Effect.succeedNone }), Layer.mock(SecretRequests.SecretRequests)({}), - localRemoteDelegationLayer, + Layer.mock(RemoteDelegation.RemoteDelegation)({}), Layer.mock(ScheduledTaskService.ScheduledTaskService)({ list: () => Effect.succeed({ tasks: [bound] }), upsert: () => @@ -4893,7 +4631,7 @@ describe("OrchestratorMcpService provider resolution", () => { } as never), }), Layer.mock(SecretRequests.SecretRequests)({}), - localRemoteDelegationLayer, + Layer.mock(RemoteDelegation.RemoteDelegation)({}), Layer.mock(ScheduledTaskService.ScheduledTaskService)({ list: () => Effect.succeed({ tasks: [task] }), upsert: (input) => @@ -5250,7 +4988,7 @@ describe("OrchestratorMcpService provider resolution", () => { adapterRegistryLayer([]), Layer.mock(ProjectService.ProjectService)({ getById: () => Effect.succeedNone }), Layer.mock(SecretRequests.SecretRequests)({}), - localRemoteDelegationLayer, + Layer.mock(RemoteDelegation.RemoteDelegation)({}), Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), ); yield* Effect.gen(function* () { @@ -5468,7 +5206,7 @@ describe("OrchestratorMcpService provider resolution", () => { adapterRegistryLayer([codexInstanceId, peerId, antigravityId]), Layer.mock(ProjectService.ProjectService)({ getById: () => Effect.succeedNone }), Layer.mock(SecretRequests.SecretRequests)({}), - localRemoteDelegationLayer, + Layer.mock(RemoteDelegation.RemoteDelegation)({}), Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), ); yield* Effect.gen(function* () { @@ -5563,7 +5301,7 @@ describe("OrchestratorMcpService provider resolution", () => { adapterRegistryLayer([codexInstanceId]), Layer.mock(ProjectService.ProjectService)({ getById: () => Effect.succeedNone }), Layer.mock(SecretRequests.SecretRequests)({}), - localRemoteDelegationLayer, + Layer.mock(RemoteDelegation.RemoteDelegation)({}), Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), ); yield* Effect.gen(function* () { @@ -5617,7 +5355,7 @@ describe("OrchestratorMcpService provider resolution", () => { adapterRegistryLayer([codexInstanceId]), Layer.mock(ProjectService.ProjectService)({ getById: () => Effect.succeedNone }), Layer.mock(SecretRequests.SecretRequests)({}), - localRemoteDelegationLayer, + Layer.mock(RemoteDelegation.RemoteDelegation)({}), Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), ); const error = yield* Effect.gen(function* () { @@ -5660,7 +5398,7 @@ describe("OrchestratorMcpService provider resolution", () => { }), Layer.mock(ProjectService.ProjectService)({ getById: () => Effect.succeedNone }), Layer.mock(SecretRequests.SecretRequests)({}), - localRemoteDelegationLayer, + Layer.mock(RemoteDelegation.RemoteDelegation)({}), Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), ); const error = yield* Effect.gen(function* () { @@ -5744,7 +5482,7 @@ describe("OrchestratorMcpService thread lookup", () => { }), Layer.mock(ProjectService.ProjectService)({ getById: () => Effect.succeedNone }), Layer.mock(SecretRequests.SecretRequests)({}), - localRemoteDelegationLayer, + Layer.mock(RemoteDelegation.RemoteDelegation)({}), Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), ), ), @@ -6242,7 +5980,7 @@ describe("OrchestratorMcpService thread list", () => { : Effect.succeedNone, }), Layer.mock(SecretRequests.SecretRequests)({}), - localRemoteDelegationLayer, + Layer.mock(RemoteDelegation.RemoteDelegation)({}), Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), ), ), @@ -6483,7 +6221,7 @@ describe("OrchestratorMcpService thread stop", () => { Layer.mock(ProviderRegistry.ProviderRegistry)({ getProviders: Effect.succeed([]) }), Layer.mock(ProjectService.ProjectService)({ getById: () => Effect.succeedNone }), Layer.mock(SecretRequests.SecretRequests)({}), - localRemoteDelegationLayer, + Layer.mock(RemoteDelegation.RemoteDelegation)({}), Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), ), ), @@ -6702,7 +6440,7 @@ describe("OrchestratorMcpService thread stop", () => { Layer.mock(ProviderRegistry.ProviderRegistry)({ getProviders: Effect.succeed([]) }), Layer.mock(ProjectService.ProjectService)({}), Layer.mock(SecretRequests.SecretRequests)({}), - localRemoteDelegationLayer, + Layer.mock(RemoteDelegation.RemoteDelegation)({}), Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), ), ), diff --git a/apps/server/src/mcp/OrchestratorMcpService.ts b/apps/server/src/mcp/OrchestratorMcpService.ts index b96a1a68adbe4..69abe7d9c68de 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.ts @@ -109,7 +109,6 @@ import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as Ref from "effect/Ref"; import * as Schema from "effect/Schema"; -import * as Semaphore from "effect/Semaphore"; import * as Stream from "effect/Stream"; import * as ProviderAdapterRegistry from "../orchestration-v2/ProviderAdapterRegistry.ts"; @@ -1405,7 +1404,6 @@ const make = Effect.gen(function* () { const gitDriver = yield* GitVcsDriver.GitVcsDriver; const serverSettings = yield* ServerSettings.ServerSettingsService; const remoteDelegation = yield* RemoteDelegation.RemoteDelegation; - const localCheckoutLock = yield* Semaphore.make(1); const requireProject = (projectId: ProjectId) => projects.getById(projectId).pipe( @@ -2507,147 +2505,23 @@ const make = Effect.gen(function* () { ), ); - // Closura: fail closed when telemetry is present on an interactive host — unknown activity counts - // as active so agent-origin children do not disrupt an interactive machine in use. - const isInteractiveHostWithActiveHuman = Effect.fn( - "OrchestratorMcpService.isInteractiveHostWithActiveHuman", - )(function* () { - if (Option.isNone(hostResources)) return false; - const resources = yield* hostResources.value.read; - const tier = resources.placementRole === "headless" ? "headless" : "interactive"; - return tier === "interactive" && resources.humanActive !== false; - }); - - /** True when at least one local agent-origin child thread currently has an active run here. */ - const hasActiveLocalAgentChild = Effect.fn("OrchestratorMcpService.hasActiveLocalAgentChild")( - function* () { - const entries = yield* threadManagement - .listActiveShellIndex() - .pipe(Effect.mapError(threadManagementFailure)); - for (const entry of entries) { - if (entry.lineage.relationshipToParent !== "subagent" || !entry.mayBeLive) continue; - const records = yield* threadManagement - .getThreadRecords(entry.id, ["runs"], { - runStatuses: ThreadManagementService.ACTIVE_RUN_STATUSES, - }) - .pipe(Effect.orElseSucceed(() => ({ runs: [] }))); - if (records.runs.some(ThreadManagementService.isActiveRun)) return true; - } - return false; - }, - ); - - /** - * Closura: resolve a pushed remote ref whose tip matches the parent checkout's `HEAD` so - * `isolation: "worktree"` can be placed on a headless host via `startFromOrigin: true`. - */ - const resolvePushedWorktreeStrategy = Effect.fn( - "OrchestratorMcpService.resolvePushedWorktreeStrategy", - )(function* (parent: Pick) { - const project = yield* projects.getById(parent.thread.projectId).pipe( - Effect.map(Option.getOrUndefined), - Effect.orElseSucceed(() => undefined), - ); - if (project === undefined) return undefined; - const nonGit = yield* threadLaunch - .isNonGitProject(parent.thread.projectId) - .pipe(Effect.orElseSucceed(() => true)); - if (nonGit) return undefined; - const cwd = parent.thread.worktreePath ?? project.workspaceRoot; - const headCommit = yield* gitDriver.resolveCommit({ cwd, revision: "HEAD" }).pipe( - Effect.map((resolved) => resolved.commitSha), - Effect.orElseSucceed(() => null), - ); - if (headCommit === null) return undefined; - const symbolicBranch = yield* gitDriver - .execute({ - operation: "delegateTask.resolveBranch", - cwd, - args: ["symbolic-ref", "--quiet", "--short", "HEAD"], - allowNonZeroExit: true, - timeoutMs: 5_000, - }) - .pipe( - Effect.map((result) => { - const name = result.exitCode === 0 ? result.stdout.trim() : ""; - return name.length > 0 ? name : null; - }), - Effect.orElseSucceed(() => undefined), - ); - const branch = symbolicBranch === undefined ? parent.thread.branch : symbolicBranch; - const matchesHead = (remoteName: string, branchName: string) => - gitDriver.resolveCommit({ cwd, revision: `refs/remotes/${remoteName}/${branchName}` }).pipe( - Effect.map((resolved) => resolved.commitSha === headCommit), - Effect.orElseSucceed(() => false), - ); - if (branch !== null) { - const remote = yield* gitDriver - .resolveWorktreeBaseRemote({ cwd, refName: branch }) - .pipe(Effect.orElseSucceed(() => null)); - if (remote !== null && (yield* matchesHead(remote.remoteName, remote.branchName))) { - return { - type: "worktree" as const, - baseRef: `${remote.remoteName}/${remote.branchName}`, - startFromOrigin: true, - }; - } - } - const defaultRemote = yield* gitDriver.resolvePrimaryRemoteName(cwd).pipe( - Effect.flatMap((remoteName) => - gitDriver - .resolveDefaultBranchName(cwd, remoteName) - .pipe( - Effect.map((branchName) => (branchName === null ? null : { remoteName, branchName })), - ), - ), - Effect.orElseSucceed(() => null), - ); - if ( - defaultRemote !== null && - (yield* matchesHead(defaultRemote.remoteName, defaultRemote.branchName)) - ) { - return { - type: "worktree" as const, - baseRef: `${defaultRemote.remoteName}/${defaultRemote.branchName}`, - startFromOrigin: true, - }; - } - return undefined; - }); - /** The environment bound to an auto-placed task, for the parent's model or the exact one named. */ const placeTask = Effect.fn("OrchestratorMcpService.placeTask")(function* ( callerScope: McpInvocationScope, input: OrchestratorMcpDelegateTaskInput, key: string, - explicitAuto: boolean, ) { yield* requireCapability(callerScope); const { scope, parent } = yield* loadThreadCaller(callerScope, "delegate_task"); - const parentRun = - ThreadManagementService.latestActiveRun(parent) ?? - (yield* backgroundSubagentRun(scope, parent.thread.id)); - if ( - parentRun === undefined || - parentRun.rootNodeId === null || - parentRun.providerInstanceId !== scope.thread.providerInstanceId - ) { - return yield* failure( - "parent_not_active", - "Delegated tasks require an active run owned by this MCP provider session.", - ); - } const target = input.target; // Placement qualifies the project with this repository wherever it runs, and no other. if (target?.projectId !== undefined) { - if (!explicitAuto) return undefined; return yield* failure( "invalid_request", 'With placement "auto", omit target.projectId: the task runs in the project with this repository wherever it is placed. To use another project, pass target.environmentId with it.', ); } if (target?.driverKind !== undefined && target.providerInstanceId === undefined) { - if (!explicitAuto) return undefined; return yield* failure( "invalid_request", 'With placement "auto", name target.providerInstanceId instead of driverKind; every environment matches it exactly.', @@ -2658,7 +2532,6 @@ const make = Effect.gen(function* () { const model = target?.model ?? (instanceId === inherited.instanceId ? inherited.model : undefined); if (model === undefined) { - if (!explicitAuto) return undefined; return yield* failure( "target_required", 'With placement "auto" and another providerInstanceId, pass target.model.', @@ -3165,128 +3038,36 @@ const make = Effect.gen(function* () { // One key for the placement, the launch and the record, so a retry finds all three. const clientRequestId = yield* requestKey(input.clientRequestId); const named = input.target?.environmentId; - const needsLocalCheckout = input.needsLocalCheckout === true; - if (needsLocalCheckout && input.placement === "auto") { - return yield* failure( - "invalid_request", - 'needsLocalCheckout cannot be combined with placement "auto": a task needing this checkout must stay on this environment.', - ); - } - const existingLocalReceipt = - callerScope.thread !== undefined && input.clientRequestId !== undefined - ? yield* threadManagement.hasReceipt( - stableCommandId({ - scope: callerScope, - requestKey: clientRequestId, - operation: "delegate-task", - }), - ) - : false; - // Reconcile an already-placed clientRequestId before re-evaluating defaults or local HEAD, - // so a retry after toggling automaticPlacementByDefault or committing locally never duplicates locally. - const boundEnvironmentId = - callerScope.thread !== undefined && - input.clientRequestId !== undefined && - named === undefined && - !existingLocalReceipt - ? Option.getOrUndefined( - yield* remoteDelegation.placed(callerScope, { - operation: "delegate-task", - key: clientRequestId, - }), - ) - : undefined; - const boundRemote = - boundEnvironmentId !== undefined && - PeerForwarding.remoteTarget(callerScope, boundEnvironmentId) !== undefined; - // Closura: default `delegate_task` placement to `"auto"` (governed by `automaticPlacementByDefault`) - // so agent-origin children move off interactive hosts onto headless compute unless bound here. - const automaticByDefault = - boundEnvironmentId === undefined && - input.placement === undefined && - named === undefined && - !needsLocalCheckout && - !existingLocalReceipt && - (yield* serverSettings.getSettings.pipe( - Effect.map((settings) => settings.automaticPlacementByDefault), - Effect.orElseSucceed(() => false), - )); - const explicitAuto = - boundEnvironmentId === undefined && input.placement === "auto" && named === undefined; - const wantsAutoPlacement = explicitAuto || automaticByDefault; - // Closura: allow `isolation: "worktree"` to place on a headless host from the pushed ref - // instead of forcing the origin interactive host. - const namedRemote = - named !== undefined && PeerForwarding.remoteTarget(callerScope, named) !== undefined; - const needsPushedWorktree = - input.isolation === "worktree" && - !needsLocalCheckout && - !existingLocalReceipt && - (boundRemote || wantsAutoPlacement || namedRemote); - const preloadedCaller = - boundRemote || needsPushedWorktree - ? yield* loadThreadCaller(callerScope, "delegate_task") - : undefined; - const remoteWorktreeStrategy = - needsPushedWorktree && preloadedCaller !== undefined - ? yield* resolvePushedWorktreeStrategy(preloadedCaller.parent) - : undefined; - const boundRemoteModes = - boundRemote && preloadedCaller !== undefined - ? { - runtimeMode: yield* resolveRuntimeMode( - preloadedCaller.parent.thread.runtimeMode, - input.runtimeMode, - ), - interactionMode: yield* resolveInteractionMode( - preloadedCaller.parent.thread.interactionMode, - input.interactionMode, - ), - } - : undefined; - const canPlaceRemotely = - boundRemote || - (!needsLocalCheckout && - (input.isolation !== "worktree" || remoteWorktreeStrategy !== undefined || namedRemote)); + // A named target or the parent's checkout decides; only work needing neither is placed. const automatic = - wantsAutoPlacement && canPlaceRemotely - ? yield* placeTask(callerScope, input, clientRequestId, explicitAuto) + input.placement === "auto" && named === undefined && input.isolation === undefined + ? yield* placeTask(callerScope, input, clientRequestId) : undefined; const placed = - boundEnvironmentId ?? - (automatic !== undefined + automatic !== undefined ? automatic.environmentId : yield* admitPlacement( chooseThreadPlacement( { originEnvironmentId: callerScope.environmentId, pinnedEnvironmentId: named ?? callerScope.environmentId, - requiresOrigin: !canPlaceRemotely, + requiresOrigin: input.isolation === "worktree", }, [], 0, ), - needsLocalCheckout - ? "needsLocalCheckout requires this environment and cannot run in a linked environment." - : 'A task in a linked environment with isolation "worktree" requires a pushed ref (startFromOrigin: true). Push the branch first, omit isolation, or set needsLocalCheckout: true.', - )); + 'A task in a linked environment runs in that project\'s checkout; isolation "worktree" is not supported there. Omit isolation, or use t3_thread_launch with environmentId and a worktree workspaceStrategy.', + ); const environmentId = PeerForwarding.remoteTarget(callerScope, placed); if (environmentId !== undefined) { yield* requireCapability(callerScope); const scope = yield* requireThreadScope(callerScope, "delegate_task"); - const resolvedModes = automatic ?? boundRemoteModes; // The task's child runs as an ordinary thread there; this thread keeps the task. const { taskId } = yield* remoteDelegation.delegate(scope, { ...input, - ...(resolvedModes === undefined + ...(automatic === undefined ? {} - : { - runtimeMode: resolvedModes.runtimeMode, - interactionMode: resolvedModes.interactionMode, - }), - ...(remoteWorktreeStrategy === undefined - ? {} - : { workspaceStrategy: remoteWorktreeStrategy }), + : { runtimeMode: automatic.runtimeMode, interactionMode: automatic.interactionMode }), clientRequestId, target: { ...input.target, environmentId }, }); @@ -3325,18 +3106,6 @@ const make = Effect.gen(function* () { operation: "delegate-task", }); const isRetryOfAcceptedDelegation = yield* threadManagement.hasReceipt(commandId); - // Closura: refuse agent-origin children on an interactive host while its human is active, - // unless `needsLocalCheckout` is explicitly set (at most one active child at a time). - const activeHumanGuard = - !isRetryOfAcceptedDelegation && (yield* isInteractiveHostWithActiveHuman()); - if (activeHumanGuard && !needsLocalCheckout) { - return yield* failure( - "invalid_request", - needsPushedWorktree && remoteWorktreeStrategy === undefined - ? "Refusing agent-origin child on this interactive host while its human is active: no pushed ref covers HEAD for remote worktree placement. Push the branch so it can run on a headless host, or set needsLocalCheckout: true (at most one active child at a time)." - : "Refusing agent-origin child on this interactive host while its human is active. Place work on a headless host, or set needsLocalCheckout: true (at most one active child at a time).", - ); - } const target = yield* resolveTargetRechecking({ parent, target: input.target, @@ -3407,45 +3176,6 @@ const make = Effect.gen(function* () { } const safeTask = yield* resolveSafeTaskPrompt(input); const parentNodeId = parentRun.rootNodeId; - const dispatchLocalTask = () => - threadManagement - .dispatch({ - type: "delegated_task.request", - createdBy: "agent", - creationSource: "mcp", - commandId, - parentThreadId: scope.thread.threadId, - parentRunId: parentRun.id, - parentNodeId, - task: safeTask, - ...(input.title === undefined ? {} : { title: input.title }), - modelSelection: target.modelSelection, - runtimeMode, - interactionMode, - ...(workspaceStrategy === undefined ? {} : { workspaceStrategy }), - // Async delegations wake the parent on every child terminal; wait - // delegations deliver through the blocking tool call until `awaitTask` - // gives up the wait (timeout, cancelled call) and upgrades the wake. - completionWake: input.mode === "wait" ? "settled_only" : "always", - ...(input.mode === "wait" - ? { - staleTimeoutMs: staleTimeoutMs( - input.staleTimeoutMinutes, - BACKGROUND_WAIT_STALE_MINUTES, - ), - } - : {}), - }) - .pipe( - Effect.mapError((error) => - error._tag === "ThreadManagementProviderInstanceDisabledError" - ? threadManagementFailure(error) - : failure( - "orchestration_error", - `Unable to create delegated task: ${userFacingDispatchErrorMessage(error) ?? errorMessage(error)}`, - ), - ), - ); // The command commits the child's preparing run, which only this call // prepares, so a caller that goes away must not stop it in between. return yield* Effect.uninterruptibleMask((restore) => @@ -3453,22 +3183,44 @@ const make = Effect.gen(function* () { // ThreadManagementService.dispatch is the chokepoint for this command // type's own enablement check, using the same command id and its // receipt-replay exemption, so no separate assert runs here. - const result = activeHumanGuard - ? yield* localCheckoutLock.withPermits(1)( - Effect.gen(function* () { - if ( - !(yield* threadManagement.hasReceipt(commandId)) && - (yield* hasActiveLocalAgentChild()) - ) { - return yield* failure( - "invalid_request", - "This interactive host already has an active agent-origin child while its human is active; needsLocalCheckout allows at most one at a time.", - ); + const result = yield* threadManagement + .dispatch({ + type: "delegated_task.request", + createdBy: "agent", + creationSource: "mcp", + commandId, + parentThreadId: scope.thread.threadId, + parentRunId: parentRun.id, + parentNodeId, + task: safeTask, + ...(input.title === undefined ? {} : { title: input.title }), + modelSelection: target.modelSelection, + runtimeMode, + interactionMode, + ...(workspaceStrategy === undefined ? {} : { workspaceStrategy }), + // Async delegations wake the parent on every child terminal; wait + // delegations deliver through the blocking tool call until `awaitTask` + // gives up the wait (timeout, cancelled call) and upgrades the wake. + completionWake: input.mode === "wait" ? "settled_only" : "always", + ...(input.mode === "wait" + ? { + staleTimeoutMs: staleTimeoutMs( + input.staleTimeoutMinutes, + BACKGROUND_WAIT_STALE_MINUTES, + ), } - return yield* dispatchLocalTask(); - }), - ) - : yield* dispatchLocalTask(); + : {}), + }) + .pipe( + Effect.mapError((error) => + error._tag === "ThreadManagementProviderInstanceDisabledError" + ? threadManagementFailure(error) + : failure( + "orchestration_error", + `Unable to create delegated task: ${userFacingDispatchErrorMessage(error) ?? errorMessage(error)}`, + ), + ), + ); const taskEvent = result.storedEvents.find( (stored) => stored.event.type === "subagent.updated" && diff --git a/apps/server/src/mcp/OrchestratorMcpToolkit.integration.test.ts b/apps/server/src/mcp/OrchestratorMcpToolkit.integration.test.ts index e14584ec9d4e9..151d90e766440 100644 --- a/apps/server/src/mcp/OrchestratorMcpToolkit.integration.test.ts +++ b/apps/server/src/mcp/OrchestratorMcpToolkit.integration.test.ts @@ -289,12 +289,7 @@ describe("orchestrator MCP toolkit", () => { Layer.provide(layerOrchestration), ), ), - Layer.provide( - Layer.mock(RemoteDelegation.RemoteDelegation)({ - place: (scope) => Effect.succeed(scope.environmentId), - placed: () => Effect.succeedNone, - }), - ), + Layer.provide(Layer.mock(RemoteDelegation.RemoteDelegation)({})), Layer.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), ); diff --git a/apps/server/src/mcp/TaskCancelNativeSubagent.integration.test.ts b/apps/server/src/mcp/TaskCancelNativeSubagent.integration.test.ts index cdfcbfd85c482..b2e9a90bb7d3c 100644 --- a/apps/server/src/mcp/TaskCancelNativeSubagent.integration.test.ts +++ b/apps/server/src/mcp/TaskCancelNativeSubagent.integration.test.ts @@ -233,17 +233,10 @@ const cancelBackgroundOnlyTask = ( layerAdapters, Layer.mock(ProviderRegistry.ProviderRegistry)({ getProviders: Effect.succeed([provider]), - refreshWorkspaceSnapshot: () => Effect.succeed([provider]), - }), - Layer.mock(ProjectService.ProjectService)({ - getById: () => Effect.succeedNone, - workspaceScanDirectory: Effect.succeed, }), + Layer.mock(ProjectService.ProjectService)({}), Layer.mock(SecretRequests.SecretRequests)({}), - Layer.mock(RemoteDelegation.RemoteDelegation)({ - place: (scope) => Effect.succeed(scope.environmentId), - placed: () => Effect.succeedNone, - }), + Layer.mock(RemoteDelegation.RemoteDelegation)({}), ServerSettings.layerTest(), Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), NodeServices.layer, diff --git a/apps/server/src/peer/RemoteDelegation.test.ts b/apps/server/src/peer/RemoteDelegation.test.ts index 7929278f990f5..830e29d40c6ff 100644 --- a/apps/server/src/peer/RemoteDelegation.test.ts +++ b/apps/server/src/peer/RemoteDelegation.test.ts @@ -107,13 +107,6 @@ interface BoxThread { readonly holdRefill: Ref.Ref; readonly beforeTail: Ref.Ref>; readonly launched: Ref.Ref; - /** Every thread launched on this peer with its workspaceStrategy, in order. */ - readonly launches: Ref.Ref< - ReadonlyArray<{ - readonly threadId: ThreadId; - readonly workspaceStrategy?: ThreadLaunch.ThreadLaunchInput["workspaceStrategy"]; - }> - >; /** The link session that launched it, as the box stamps it. */ readonly linkOrigin: Ref.Ref<{ readonly sessionId: string; readonly label: string } | null>; /** The parent the launch names, so the thread there can link back to it. */ @@ -190,12 +183,6 @@ const makeBoxThread = Effect.gen(function* () { holdRefill: yield* Ref.make(false), beforeTail: yield* Ref.make>(Effect.void), launched: yield* Ref.make(null), - launches: yield* Ref.make< - ReadonlyArray<{ - readonly threadId: ThreadId; - readonly workspaceStrategy?: ThreadLaunch.ThreadLaunchInput["workspaceStrategy"]; - }> - >([]), linkOrigin: yield* Ref.make<{ readonly sessionId: string; readonly label: string } | null>( null, ), @@ -584,17 +571,6 @@ const boxToolkitLayer = (thread: BoxThread) => { Ref.get(thread.runless).pipe( Effect.flatMap((runless) => Ref.set(thread.launched, input.threadId!).pipe( - Effect.andThen( - Ref.update(thread.launches, (seen) => [ - ...seen, - { - threadId: input.threadId!, - ...(input.workspaceStrategy === undefined - ? {} - : { workspaceStrategy: input.workspaceStrategy }), - }, - ]), - ), Effect.andThen(Ref.set(thread.linkOrigin, input.linkOrigin ?? null)), Effect.andThen(Ref.set(thread.delegatedFrom, input.delegatedFrom ?? null)), Effect.andThen(Ref.set(thread.message, input.initialMessage?.text ?? null)), @@ -750,21 +726,6 @@ const makeLaptop = ( readonly afterSession?: (session: Option.Option) => Effect.Effect; /** Runs whenever something here reaches for a local launch, which this harness cannot make. */ readonly localLaunch?: Effect.Effect; - /** Host telemetry reported for the laptop itself when provided. */ - readonly hostResources?: Ref.Ref; - /** Pushed remote ref covering HEAD on the laptop checkout for remote worktree tests. */ - readonly pushedWorktreeRef?: - | { - readonly remoteName: string; - readonly branchName: string; - } - | Ref.Ref<{ - readonly remoteName: string; - readonly branchName: string; - } | null> - | null; - /** Local providers available on the laptop when testing local delegation. */ - readonly localProviders?: ReadonlyArray; } = {}, ) => Effect.gen(function* () { @@ -859,104 +820,32 @@ const makeLaptop = ( Layer.provide(Layer.mock(PeerLinkRequests.PeerLinkRequests)({})), Layer.provide(NodeCrypto.layer), Layer.provideMerge(layerThreads), - // The laptop lists no provider of its own unless configured for a local-delegation test. + // The laptop lists no provider of its own, so it never runs the box's model. Layer.provide( - Layer.mock(ProviderRegistry.ProviderRegistry)({ - getProviders: Effect.succeed(hooks.localProviders ?? []), - refreshWorkspaceSnapshot: () => Effect.succeed(hooks.localProviders ?? []), - }), + Layer.mock(ProviderRegistry.ProviderRegistry)({ getProviders: Effect.succeed([]) }), ), Layer.provide( Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({ - list: () => Effect.succeed((hooks.localProviders ?? []).map((p) => p.instanceId)), + list: () => Effect.succeed([]), }), ), - Layer.provide( - hooks.hostResources === undefined - ? Layer.empty - : Layer.succeed(HostResources.HostResources, { - read: Ref.get(hooks.hostResources), - }), - ), Layer.provide(Layer.mock(ScheduledTaskService.ScheduledTaskService)({})), Layer.provide( Layer.mock(ProjectService.ProjectService)({ getById: (id) => Effect.succeedSome({ ...laptopProject, id }), - workspaceScanDirectory: Effect.succeed, }), ), Layer.provide(Layer.mock(ProjectCloneTracker.ProjectCloneTracker)({})), Layer.provide(Layer.mock(SecretRequests.SecretRequests)({})), Layer.provide( Layer.mock(ThreadLaunch.ThreadLaunchService)({ - isNonGitProject: () => Effect.succeed(false), - prepareRun: () => Effect.void, launch: () => (hooks.localLaunch ?? Effect.void).pipe(Effect.andThen(Effect.die("no local launch"))), checkWorktreeBase: () => (hooks.localLaunch ?? Effect.void).pipe(Effect.andThen(Effect.die("no local launch"))), }), ), - Layer.provide( - (() => { - const readPushedWorktreeRef = - hooks.pushedWorktreeRef !== null && - hooks.pushedWorktreeRef !== undefined && - !("remoteName" in hooks.pushedWorktreeRef) - ? Ref.get(hooks.pushedWorktreeRef) - : Effect.succeed(hooks.pushedWorktreeRef ?? null); - return Layer.mock(GitVcsDriver.GitVcsDriver)({ - resolveCommit: ({ revision }) => - readPushedWorktreeRef.pipe( - Effect.flatMap((ref) => { - if (revision === "HEAD") { - return Effect.succeed({ - commitSha: "1111111111111111111111111111111111111111", - }); - } - if (ref && revision === `refs/remotes/${ref.remoteName}/${ref.branchName}`) { - return Effect.succeed({ - commitSha: "1111111111111111111111111111111111111111", - }); - } - return Effect.fail(new Error("unknown revision") as never); - }), - ), - resolveWorktreeBaseRemote: () => readPushedWorktreeRef, - resolvePrimaryRemoteName: () => - readPushedWorktreeRef.pipe( - Effect.flatMap((ref) => - ref - ? Effect.succeed(ref.remoteName) - : Effect.fail(new Error("no remote") as never), - ), - ), - resolveDefaultBranchName: () => - readPushedWorktreeRef.pipe(Effect.map((ref) => ref?.branchName ?? null)), - execute: ({ args }) => - readPushedWorktreeRef.pipe( - Effect.map((ref) => { - if (args[0] === "symbolic-ref") { - return { - exitCode: ref ? 0 : 1, - stdout: ref ? `${ref.branchName}\n` : "", - stderr: "", - stdoutTruncated: false, - stderrTruncated: false, - } as never; - } - return { - exitCode: 1, - stdout: "", - stderr: "", - stdoutTruncated: false, - stderrTruncated: false, - } as never; - }), - ), - }); - })(), - ), + Layer.provide(Layer.mock(GitVcsDriver.GitVcsDriver)({})), Layer.provide( Layer.merge( Layer.mock(ManagedProjectFolders.ManagedProjectFolders)({ namedProjectsRoot: "/p" }), @@ -4313,488 +4202,3 @@ it.effect( }), ).pipe(Effect.provide(NodeHttpServer.layerTest)), ); - -const localCodexProvider: ServerProvider = { - instanceId, - driver, - enabled: true, - installed: true, - version: "test", - status: "ready", - auth: { status: "authenticated" }, - checkedAt: "2026-09-13T00:00:00.000Z", - models: [{ slug: "gpt-5.4", name: "GPT-5.4", isCustom: false, capabilities: null }], - slashCommands: [], - skills: [], -}; - -const interactiveHostResources = (humanActive: boolean | undefined): HostResourcesSnapshot => ({ - sampledAt: 0, - cpuUtilization: 0.1, - cpuCount: 8, - availableMemoryBytes: 8 * GiB, - totalMemoryBytes: 16 * GiB, - loadPerCpu: 0.1, - runningAgents: 0, - activeRuns: 0, - placementRole: "interactive", - ...(humanActive === undefined ? {} : { humanActive }), -}); - -it.effect( - "replays the 12-request review burst: defaults placement to auto, places worktrees from the pushed ref on R720 and ASUS, queues overflow, and puts 0 on the active-human laptop", - () => - Effect.scoped( - Effect.gen(function* () { - const r720 = descriptorOf("environment-r720", "R720"); - const asus = descriptorOf("environment-asus", "ASUS"); - const r720Thread = yield* makeBoxThread; - const asusThread = yield* makeBoxThread; - yield* Ref.set(r720Thread.resources, { ...loadOf(0.1), runningAgents: 0, activeRuns: 0 }); - yield* Ref.set(asusThread.resources, { ...loadOf(0.1), runningAgents: 0, activeRuns: 0 }); - const r720Server = yield* Layer.build(Layer.fresh(NodeHttpServer.layerTest)); - const asusServer = yield* Layer.build(Layer.fresh(NodeHttpServer.layerTest)); - const r720Peer = yield* servePeer(r720, boxToolkitLayer(r720Thread)).pipe( - Effect.provideContext(r720Server), - ); - const asusPeer = yield* servePeer(asus, boxToolkitLayer(asusThread)).pipe( - Effect.provideContext(asusServer), - ); - - const offers = yield* SubscriptionRef.make< - ReadonlyArray - >([]); - const database = yield* SqlitePersistence.layerMemory.pipe(Layer.build); - const laptopResources = yield* Ref.make(interactiveHostResources(true)); - const a = yield* makeLaptop(database, offers, undefined, Effect.void, { - hostResources: laptopResources, - pushedWorktreeRef: { remoteName: "origin", branchName: "master" }, - localProviders: [localCodexProvider, boxClaude], - }); - yield* linkTo(a.links, r720Peer, "full-access"); - yield* linkTo(a.links, asusPeer, "full-access"); - yield* a.settings.updateSettings({ - automaticPlacementHosts: [ - { environmentId: r720.environmentId, maxLanes: 4, minAvailableMemoryGiB: 4 }, - { environmentId: asus.environmentId, maxLanes: 1, minAvailableMemoryGiB: 4 }, - { environmentId: laptop.environmentId, maxLanes: 0, minAvailableMemoryGiB: 4 }, - ], - }); - yield* seedParent(a); - - // Replay all 12 CTO review launches (PRs 2261-2272) omitting `placement` with `isolation: "worktree"`. - const results = yield* Effect.forEach( - Array.from({ length: 12 }, (_, index) => 2261 + index), - (prNumber) => - a.call("delegate_task", { - task: `Review product PR #${prNumber}.`, - title: `Review PR #${prNumber}`, - role: "review", - isolation: "worktree", - target: { providerInstanceId: boxClaude.instanceId, model: "claude-sonnet-4-6" }, - clientRequestId: `burst-pr-${prNumber}`, - }), - ); - - const placedOnR720 = results.filter( - (result) => - !result.isError && - (result.structuredContent as { remoteChild?: { environmentId?: string } }).remoteChild - ?.environmentId === r720.environmentId, - ); - const placedOnAsus = results.filter( - (result) => - !result.isError && - (result.structuredContent as { remoteChild?: { environmentId?: string } }).remoteChild - ?.environmentId === asus.environmentId, - ); - const queuedOverflow = results.filter( - (result) => - result.isError && JSON.stringify(result.content).includes("no-eligible-environment"), - ); - - expect(placedOnR720).toHaveLength(4); - expect(placedOnAsus).toHaveLength(1); - expect(queuedOverflow).toHaveLength(7); - - const r720Launches = yield* Ref.get(r720Thread.launches); - const asusLaunches = yield* Ref.get(asusThread.launches); - expect(r720Launches).toHaveLength(4); - expect(asusLaunches).toHaveLength(1); - for (const launched of [...r720Launches, ...asusLaunches]) { - expect(launched.workspaceStrategy).toEqual({ - type: "worktree", - baseRef: "origin/master", - startFromOrigin: true, - }); - } - // Zero local child threads were created on the active-human laptop. - expect(yield* a.orchestrator.listActiveSubagentThreadIds()).toHaveLength(0); - }), - ).pipe(Effect.provide(NodeHttpServer.layerTest)), -); - -it.effect( - "replays the 12-request review burst when neither headless executor is eligible: queues all 12 with 0 laptop placements", - () => - Effect.scoped( - Effect.gen(function* () { - const r720 = descriptorOf("environment-r720", "R720"); - const asus = descriptorOf("environment-asus", "ASUS"); - const r720Thread = yield* makeBoxThread; - const asusThread = yield* makeBoxThread; - yield* Ref.set(r720Thread.resources, { ...loadOf(0.1), runningAgents: 4, activeRuns: 4 }); - yield* Ref.set(asusThread.resources, { ...loadOf(0.1), runningAgents: 1, activeRuns: 1 }); - const r720Server = yield* Layer.build(Layer.fresh(NodeHttpServer.layerTest)); - const asusServer = yield* Layer.build(Layer.fresh(NodeHttpServer.layerTest)); - const r720Peer = yield* servePeer(r720, boxToolkitLayer(r720Thread)).pipe( - Effect.provideContext(r720Server), - ); - const asusPeer = yield* servePeer(asus, boxToolkitLayer(asusThread)).pipe( - Effect.provideContext(asusServer), - ); - - const offers = yield* SubscriptionRef.make< - ReadonlyArray - >([]); - const database = yield* SqlitePersistence.layerMemory.pipe(Layer.build); - const laptopResources = yield* Ref.make(interactiveHostResources(true)); - const a = yield* makeLaptop(database, offers, undefined, Effect.void, { - hostResources: laptopResources, - pushedWorktreeRef: { remoteName: "origin", branchName: "master" }, - localProviders: [localCodexProvider, boxClaude], - }); - yield* linkTo(a.links, r720Peer, "full-access"); - yield* linkTo(a.links, asusPeer, "full-access"); - // Omit laptop from automaticPlacementHosts to prove active-human refusal holds even without maxLanes: 0. - yield* a.settings.updateSettings({ - automaticPlacementHosts: [ - { environmentId: r720.environmentId, maxLanes: 4, minAvailableMemoryGiB: 4 }, - { environmentId: asus.environmentId, maxLanes: 1, minAvailableMemoryGiB: 4 }, - ], - }); - yield* seedParent(a); - - const results = yield* Effect.forEach( - Array.from({ length: 12 }, (_, index) => 2261 + index), - (prNumber) => - a.call("delegate_task", { - task: `Review product PR #${prNumber}.`, - title: `Review PR #${prNumber}`, - role: "review", - isolation: "worktree", - target: { providerInstanceId: boxClaude.instanceId, model: "claude-sonnet-4-6" }, - clientRequestId: `burst-full-pr-${prNumber}`, - }), - ); - - expect(results).toHaveLength(12); - for (const result of results) { - expect(result.isError).toBe(true); - expect(JSON.stringify(result.content)).toContain("no-eligible-environment"); - } - expect(yield* Ref.get(r720Thread.launches)).toHaveLength(0); - expect(yield* Ref.get(asusThread.launches)).toHaveLength(0); - expect(yield* a.orchestrator.listActiveSubagentThreadIds()).toHaveLength(0); - }), - ).pipe(Effect.provide(NodeHttpServer.layerTest)), -); - -it.effect( - "refuses agent-origin children on an interactive host while its human is active or activity is unknown, unless needsLocalCheckout is set", - () => - Effect.scoped( - Effect.gen(function* () { - const offers = yield* SubscriptionRef.make< - ReadonlyArray - >([]); - const database = yield* SqlitePersistence.layerMemory.pipe(Layer.build); - const laptopResources = yield* Ref.make(interactiveHostResources(true)); - const a = yield* makeLaptop(database, offers, undefined, Effect.void, { - hostResources: laptopResources, - pushedWorktreeRef: null, - localProviders: [localCodexProvider], - }); - yield* seedParent(a); - - // Explicit placement: "here" is refused while human is active without needsLocalCheckout. - const explicitHere = yield* a.call("delegate_task", { - task: "Run locally.", - placement: "here", - clientRequestId: "refuse-here", - }); - expect(explicitHere.isError).toBe(true); - expect(JSON.stringify(explicitHere.content)).toContain("needsLocalCheckout"); - - // Explicit placement: "here" with isolation: "worktree" refuses accurately without - // falsely claiming no pushed ref covers HEAD. - const explicitHereWorktree = yield* a.call("delegate_task", { - task: "Run worktree locally.", - placement: "here", - isolation: "worktree", - clientRequestId: "refuse-here-worktree", - }); - expect(explicitHereWorktree.isError).toBe(true); - expect(JSON.stringify(explicitHereWorktree.content)).toContain("needsLocalCheckout"); - expect(JSON.stringify(explicitHereWorktree.content)).not.toContain( - "no pushed ref covers HEAD", - ); - - // Explicit target.environmentId naming the interactive host with isolation: "worktree" - // also refuses without claiming no pushed ref covers HEAD. - const namedLaptop = yield* a.call("delegate_task", { - task: "Run on laptop.", - isolation: "worktree", - target: { environmentId: laptop.environmentId }, - clientRequestId: "refuse-named-laptop", - }); - expect(namedLaptop.isError).toBe(true); - expect(JSON.stringify(namedLaptop.content)).toContain("needsLocalCheckout"); - expect(JSON.stringify(namedLaptop.content)).not.toContain("no pushed ref covers HEAD"); - - // Unpushed worktree (no pushed ref) cannot place remotely and is refused locally while active. - const unpushedWorktree = yield* a.call("delegate_task", { - task: "Worktree without pushed ref.", - isolation: "worktree", - clientRequestId: "refuse-unpushed-worktree", - }); - expect(unpushedWorktree.isError).toBe(true); - expect(JSON.stringify(unpushedWorktree.content)).toContain("needsLocalCheckout"); - expect(JSON.stringify(unpushedWorktree.content)).toContain("no pushed ref covers HEAD"); - - // Unknown human activity fails closed as active. - yield* Ref.set(laptopResources, interactiveHostResources(undefined)); - const unknownActivity = yield* a.call("delegate_task", { - task: "Run while activity is unknown.", - placement: "here", - clientRequestId: "refuse-unknown-activity", - }); - expect(unknownActivity.isError).toBe(true); - expect(JSON.stringify(unknownActivity.content)).toContain("needsLocalCheckout"); - - // Conflicting locality: needsLocalCheckout cannot be combined with placement: "auto". - yield* Ref.set(laptopResources, interactiveHostResources(true)); - const conflicting = yield* a.call("delegate_task", { - task: "Conflicting request.", - placement: "auto", - needsLocalCheckout: true, - clientRequestId: "refuse-conflicting", - }); - expect(conflicting.isError).toBe(true); - expect(JSON.stringify(conflicting.content)).toContain("needsLocalCheckout"); - - // Zero local children started across all refusals. - expect(yield* a.orchestrator.listActiveSubagentThreadIds()).toHaveLength(0); - - // Once the human is away (humanActive: false), explicit local execution is allowed. - yield* Ref.set(laptopResources, interactiveHostResources(false)); - const whileAway = yield* a.call("delegate_task", { - task: "Run while human is away.", - placement: "here", - clientRequestId: "allow-away", - }); - expect(whileAway.isError, JSON.stringify(whileAway.content)).toBe(false); - expect(yield* a.orchestrator.listActiveSubagentThreadIds()).toHaveLength(1); - }), - ).pipe(Effect.provide(NodeHttpServer.layerTest)), -); - -it.effect( - "enforces the one-at-a-time needsLocalCheckout exception while an interactive host's human is active", - () => - Effect.scoped( - Effect.gen(function* () { - const offers = yield* SubscriptionRef.make< - ReadonlyArray - >([]); - const database = yield* SqlitePersistence.layerMemory.pipe(Layer.build); - const laptopResources = yield* Ref.make(interactiveHostResources(true)); - const a = yield* makeLaptop(database, offers, undefined, Effect.void, { - hostResources: laptopResources, - pushedWorktreeRef: null, - localProviders: [localCodexProvider], - }); - yield* seedParent(a); - - // First needsLocalCheckout child is admitted while human is active. - const first = yield* a.call("delegate_task", { - task: "Inspect uncommitted diff.", - needsLocalCheckout: true, - clientRequestId: "local-checkout-1", - }); - expect(first.isError, JSON.stringify(first.content)).toBe(false); - const firstTask = first.structuredContent as { - taskId: NodeId; - childThreadId: ThreadId; - childRunId: RunId; - }; - expect(firstTask.childThreadId).not.toBeNull(); - - // Retrying the same clientRequestId replays the accepted child instead of refusing itself. - const retryFirst = yield* a.call("delegate_task", { - task: "Inspect uncommitted diff.", - needsLocalCheckout: true, - clientRequestId: "local-checkout-1", - }); - expect(retryFirst.isError, JSON.stringify(retryFirst.content)).toBe(false); - expect((retryFirst.structuredContent as { taskId: NodeId }).taskId).toBe(firstTask.taskId); - - // A second distinct needsLocalCheckout child while the first is still active is refused. - const second = yield* a.call("delegate_task", { - task: "Second uncommitted task.", - needsLocalCheckout: true, - clientRequestId: "local-checkout-2", - }); - expect(second.isError).toBe(true); - expect(JSON.stringify(second.content)).toContain("at most one at a time"); - expect(yield* a.orchestrator.listActiveSubagentThreadIds()).toHaveLength(1); - - // Complete the first child's run so the single local-checkout slot frees up. - const firstProjection = yield* a.orchestrator.getThreadProjection(firstTask.childThreadId); - const firstRun = firstProjection.runs[0]!; - const now = yield* DateTime.now; - yield* a.sink.write({ - commandId: CommandId.make("command:complete-local-child-1"), - events: [ - { - id: EventId.make("event:complete-local-child-1"), - type: "run.updated", - threadId: firstTask.childThreadId, - runId: firstRun.id, - ...(firstRun.rootNodeId === null ? {} : { nodeId: firstRun.rootNodeId }), - providerInstanceId: firstRun.providerInstanceId, - occurredAt: now, - payload: { ...firstRun, status: "completed", completedAt: now }, - }, - ], - }); - - // Two concurrent needsLocalCheckout launches after completion: at most one succeeds. - const [concurrentA, concurrentB] = yield* Effect.all( - [ - a.call("delegate_task", { - task: "Concurrent local task A.", - needsLocalCheckout: true, - clientRequestId: "local-checkout-3a", - }), - a.call("delegate_task", { - task: "Concurrent local task B.", - needsLocalCheckout: true, - clientRequestId: "local-checkout-3b", - }), - ], - { concurrency: "unbounded" }, - ); - const succeeded = [concurrentA, concurrentB].filter((result) => !result.isError); - const refused = [concurrentA, concurrentB].filter((result) => result.isError); - expect(succeeded).toHaveLength(1); - expect(refused).toHaveLength(1); - expect(JSON.stringify(refused[0]!.content)).toContain("at most one at a time"); - }), - ).pipe(Effect.provide(NodeHttpServer.layerTest)), -); - -it.effect( - "reconciles an already-placed remote worktree task on retry after local HEAD becomes unpushed or automaticPlacementByDefault is turned off", - () => - Effect.scoped( - Effect.gen(function* () { - const boxThread = yield* makeBoxThread; - yield* Ref.set(boxThread.resources, { ...loadOf(0.1), runningAgents: 0, activeRuns: 0 }); - const b = yield* serveBox(boxThread); - const offers = yield* SubscriptionRef.make< - ReadonlyArray - >([]); - const database = yield* SqlitePersistence.layerMemory.pipe(Layer.build); - const laptopResources = yield* Ref.make(interactiveHostResources(true)); - const pushedRef = yield* Ref.make<{ - readonly remoteName: string; - readonly branchName: string; - } | null>({ remoteName: "origin", branchName: "master" }); - const a = yield* makeLaptop(database, offers, undefined, Effect.void, { - hostResources: laptopResources, - pushedWorktreeRef: pushedRef, - localProviders: [localCodexProvider, boxClaude], - }); - yield* linkTo(a.links, b, "full-access"); - yield* seedParent(a); - - // 1. Place and record a remote worktree task while HEAD is pushed and default auto placement is on. - const initial = yield* a.call("delegate_task", { - task: "Review PR in remote worktree.", - isolation: "worktree", - target: { providerInstanceId: boxClaude.instanceId, model: "claude-sonnet-4-6" }, - clientRequestId: "wt-retry-recorded", - }); - expect(initial.isError, JSON.stringify(initial.content)).toBe(false); - const initialTaskId = (initial.structuredContent as { taskId: NodeId }).taskId; - expect(yield* Ref.get(boxThread.launches)).toHaveLength(1); - expect(yield* a.orchestrator.listActiveSubagentThreadIds()).toHaveLength(0); - - // Local HEAD advances to an unpushed commit and automaticPlacementByDefault is turned off. - yield* Ref.set(pushedRef, null); - yield* a.settings.updateSettings({ automaticPlacementByDefault: false }); - - // Even while human is active, retrying the same clientRequestId reconciles the remote task. - const retryActive = yield* a.call("delegate_task", { - task: "Review PR in remote worktree.", - isolation: "worktree", - target: { providerInstanceId: boxClaude.instanceId, model: "claude-sonnet-4-6" }, - clientRequestId: "wt-retry-recorded", - }); - expect(retryActive.isError, JSON.stringify(retryActive.content)).toBe(false); - expect((retryActive.structuredContent as { taskId: NodeId }).taskId).toBe(initialTaskId); - - // Even on an idle laptop that could run locally, retrying never spawns a duplicate local child. - yield* Ref.set(laptopResources, interactiveHostResources(false)); - const retryIdle = yield* a.call("delegate_task", { - task: "Review PR in remote worktree.", - isolation: "worktree", - target: { providerInstanceId: boxClaude.instanceId, model: "claude-sonnet-4-6" }, - clientRequestId: "wt-retry-recorded", - }); - expect(retryIdle.isError, JSON.stringify(retryIdle.content)).toBe(false); - expect((retryIdle.structuredContent as { taskId: NodeId }).taskId).toBe(initialTaskId); - expect(yield* Ref.get(boxThread.launches)).toHaveLength(1); - expect(yield* a.orchestrator.listActiveSubagentThreadIds()).toHaveLength(0); - - // 2. Lost-answer case: remote launch runs on the box, response is lost before local recording, - // then local HEAD becomes unpushed and automaticPlacementByDefault is turned off before retry. - yield* Ref.set(laptopResources, interactiveHostResources(true)); - yield* Ref.set(pushedRef, { remoteName: "origin", branchName: "master" }); - yield* a.settings.updateSettings({ automaticPlacementByDefault: true }); - yield* Ref.set(boxThread.afterLaunch, Effect.die("connection lost")); - const lost = yield* a.call("delegate_task", { - task: "Review PR with lost answer.", - isolation: "worktree", - target: { providerInstanceId: boxClaude.instanceId, model: "claude-sonnet-4-6" }, - clientRequestId: "wt-retry-lost", - }); - expect(lost.isError).toBe(true); - const lostRemoteThreadId = yield* Ref.get(boxThread.launched); - expect(lostRemoteThreadId).not.toBeNull(); - yield* Ref.set(boxThread.afterLaunch, Effect.void); - - yield* Ref.set(pushedRef, null); - yield* a.settings.updateSettings({ automaticPlacementByDefault: false }); - yield* Ref.set(laptopResources, interactiveHostResources(false)); - - const recovered = yield* a.call("delegate_task", { - task: "Review PR with lost answer.", - isolation: "worktree", - target: { providerInstanceId: boxClaude.instanceId, model: "claude-sonnet-4-6" }, - clientRequestId: "wt-retry-lost", - }); - expect(recovered.isError, JSON.stringify(recovered.content)).toBe(false); - expect(yield* Ref.get(boxThread.launched)).toBe(lostRemoteThreadId); - expect(yield* a.orchestrator.listActiveSubagentThreadIds()).toHaveLength(0); - const recorded = yield* a.orchestrator - .getThreadProjection(parentThreadId) - .pipe(Effect.map((projection) => projection.subagents)); - expect(recorded).toHaveLength(2); - expect(recorded.some((task) => task.remoteChild?.threadId === lostRemoteThreadId)).toBe( - true, - ); - }), - ).pipe(Effect.provide(NodeHttpServer.layerTest)), -); diff --git a/apps/server/src/peer/RemoteDelegation.ts b/apps/server/src/peer/RemoteDelegation.ts index a47d24d648de7..dc40be891f2f1 100644 --- a/apps/server/src/peer/RemoteDelegation.ts +++ b/apps/server/src/peer/RemoteDelegation.ts @@ -18,7 +18,6 @@ import { type OrchestratorMcpThreadTimelineItem, type OrchestrationV2RemoteTaskChild, type OrchestrationV2Subagent, - type OrchestrationV2ThreadLaunchWorkspaceStrategy, type OrchestrationV2WorkerAlert, type PeerLink, OrchestrationV2ThreadPlacementAdmitError, @@ -168,8 +167,6 @@ export class RemoteDelegation extends Context.Service< readonly target: NonNullable & { readonly environmentId: EnvironmentId; }; - /** Closura: pushed-ref worktree strategy so `isolation: "worktree"` can run on a headless host. */ - readonly workspaceStrategy?: OrchestrationV2ThreadLaunchWorkspaceStrategy | undefined; }, ) => Effect.Effect<{ readonly taskId: NodeId }, OrchestratorMcpFailure>; /** @@ -987,17 +984,15 @@ const make = Effect.gen(function* () { const delegate: RemoteDelegation["Service"]["delegate"] = Effect.fn("RemoteDelegation.delegate")( function* (scope, input) { - const parent = yield* threads - .getThreadRecords(scope.thread.threadId, ["runs", "subagents"]) - .pipe( - Effect.mapError( - () => - new OrchestratorMcpFailure({ - code: "thread_not_found", - message: "The calling thread was not found.", - }), - ), - ); + const parent = yield* threads.getThreadRecords(scope.thread.threadId, ["runs"]).pipe( + Effect.mapError( + () => + new OrchestratorMcpFailure({ + code: "thread_not_found", + message: "The calling thread was not found.", + }), + ), + ); const parentRun = parent.runs .filter(ThreadManagement.isActiveRun) .toSorted((left, right) => right.ordinal - left.ordinal)[0]; @@ -1013,53 +1008,13 @@ const make = Effect.gen(function* () { } const parentNodeId = parentRun.rootNodeId; const { target } = input; - // One key for the launch there and the record here, so a retry finds both. - // Both are scoped to the provider session, as every key a caller passes is: - // the forwarder scopes the launch's, and the record's names it. - const key = input.clientRequestId ?? (yield* random.uuidV4()); - const keyed = (operation: string) => - CommandId.make( - `command:mcp:${encodeURIComponent(scope.requestNamespace)}:${operation}:${encodeURIComponent(key)}`, - ); - const commandId = keyed("remote-delegate"); - const launchId = keyed("remote-launch"); - const childId = keyed("remote-child"); - // Reconcile an already-launched/recorded remote task even when local HEAD has since - // moved to an unpushed commit and no pushed worktree ref is provided. - const priorLaunch = - input.clientRequestId === undefined - ? Option.none() - : yield* threads - .intentOf(launchId) - .pipe(Effect.orElseSucceed(() => Option.none())); - const priorChild = - input.clientRequestId === undefined - ? Option.none() - : yield* threads - .intentOf(childId) - .pipe(Effect.orElseSucceed(() => Option.none())); - if (Option.isSome(priorChild)) { - const recordedTask = parent.subagents.find( - (task) => - task.remoteChild?.environmentId === target.environmentId && - task.remoteChild.threadId === priorChild.value, - ); - if (recordedTask !== undefined) return { taskId: recordedTask.id }; - } - // Closura: allow `isolation: "worktree"` on a headless peer when given a pushed-ref - // strategy (`startFromOrigin: true`); refuse local-only worktrees the peer cannot fetch. - const remoteWorktreeStrategy = - input.isolation === "worktree" ? input.workspaceStrategy : undefined; - if ( - input.isolation === "worktree" && - Option.isNone(priorLaunch) && - (remoteWorktreeStrategy?.type !== "worktree" || - remoteWorktreeStrategy.startFromOrigin !== true) - ) { + // A worktree there would branch from a commit this checkout has and the + // other may not, so a remote task runs in that project's checkout. + if (input.isolation === "worktree") { return yield* new OrchestratorMcpFailure({ code: "invalid_request", message: - 'A task in a linked environment with isolation "worktree" requires a pushed ref (startFromOrigin: true). Push the branch first, omit isolation, or set needsLocalCheckout: true.', + 'A task in a linked environment runs in that project\'s checkout; isolation "worktree" is not supported there. Omit isolation, or use t3_thread_launch with environmentId and a worktree workspaceStrategy.', }); } // The provider and model inherit as they do for a task here. Another @@ -1103,6 +1058,15 @@ const make = Effect.gen(function* () { parent.thread.projectId, target.projectId, ); + // One key for the launch there and the record here, so a retry finds both. + // Both are scoped to the provider session, as every key a caller passes is: + // the forwarder scopes the launch's, and the record's names it. + const key = input.clientRequestId ?? (yield* random.uuidV4()); + const keyed = (operation: string) => + CommandId.make( + `command:mcp:${encodeURIComponent(scope.requestNamespace)}:${operation}:${encodeURIComponent(key)}`, + ); + const commandId = keyed("remote-delegate"); const link = yield* links.get(target.environmentId).pipe( Effect.map(Option.getOrUndefined), Effect.orElseSucceed(() => undefined), @@ -1113,8 +1077,8 @@ const make = Effect.gen(function* () { const sent = yield* launchThere(scope, { environmentId: target.environmentId, label, - launchId, - childId, + launchId: keyed("remote-launch"), + childId: keyed("remote-child"), threadId: parent.thread.id, params: { projectId, @@ -1122,9 +1086,6 @@ const make = Effect.gen(function* () { modelSelection: { instanceId, model, ...(options === undefined ? {} : { options }) }, ...(runtimeMode === undefined ? {} : { runtimeMode }), ...(interactionMode === undefined ? {} : { interactionMode }), - ...(remoteWorktreeStrategy === undefined - ? {} - : { workspaceStrategy: remoteWorktreeStrategy }), message: task, clientRequestId: `delegate:${scope.thread.threadId}:${key}`, // The thread there shows it is this thread's subagent, with a way back. diff --git a/packages/contracts/src/orchestratorMcp.test.ts b/packages/contracts/src/orchestratorMcp.test.ts index 8b776a4ad988f..d2908fa42db8c 100644 --- a/packages/contracts/src/orchestratorMcp.test.ts +++ b/packages/contracts/src/orchestratorMcp.test.ts @@ -81,21 +81,4 @@ describe("orchestrator MCP contracts", () => { }).next, ).toBe(next); }); - - it("decodes placement and needsLocalCheckout options on delegated task requests", () => { - expect( - decodeDelegateTaskInput({ - task: "Inspect uncommitted files.", - placement: "here", - needsLocalCheckout: true, - }), - ).toMatchObject({ placement: "here", needsLocalCheckout: true }); - expect( - decodeDelegateTaskInput({ - task: "Review PR 2261.", - isolation: "worktree", - placement: "auto", - }), - ).toMatchObject({ isolation: "worktree", placement: "auto" }); - }); }); diff --git a/packages/contracts/src/orchestratorMcp.ts b/packages/contracts/src/orchestratorMcp.ts index 4bf4c1d28db8f..75a1a45550027 100644 --- a/packages/contracts/src/orchestratorMcp.ts +++ b/packages/contracts/src/orchestratorMcp.ts @@ -190,21 +190,13 @@ export const OrchestratorMcpDelegateTaskInput = Schema.Struct({ isolation: Schema.optional( Schema.Literals(["shared", "worktree"]).annotate({ description: - "'shared' (default): parent checkout. 'worktree': new prepared checkout from the pushed ref on a headless host when placed, or from the parent commit locally. Uncommitted edits stay out.", + "'shared' (default): parent checkout. 'worktree': new prepared checkout from the parent commit, for a separate checkout or PR per child. Uncommitted edits stay out.", }), ), - // Closura: omitted placement defaults to 'auto' when automaticPlacementByDefault is on. placement: Schema.optional( - Schema.Literals(["auto", "here"]).annotate({ + Schema.Literals(["auto"]).annotate({ description: - "'auto' (default): runs on the least-loaded headless machine, here or linked, with spare capacity, this repository's project and your exact provider and model; when isolation is set to worktree, creates the checkout there from the pushed ref. 'here': keeps the task on this environment (refused on an interactive host while its human is active without needsLocalCheckout). Ignored with target.environmentId. Reuse clientRequestId on retry to keep the environment chosen.", - }), - ), - // Closura: explicit exception for agent-origin children that must use this checkout while a human is active. - needsLocalCheckout: Schema.optional( - Schema.Boolean.annotate({ - description: - "Set true only when the child must read or edit uncommitted state in this checkout. On an interactive host while its human is active, agent-origin children are refused unless this is true (at most one active child at a time).", + "'auto': use for any work that needs none of your checkout's changes. Runs on the least-loaded headless machine, here or linked, with spare capacity, this repository's project and your exact provider and model; there, in that project's checkout. Ignored with target.environmentId or isolation. Reuse clientRequestId on retry to keep the environment chosen.", }), ), mode: Schema.optional( From 94b213fe853659ff14df0169ad849958feb51e3e Mon Sep 17 00:00:00 2001 From: Jeffrey Smith Date: Sat, 5 Dec 2026 15:17:58 -0500 Subject: [PATCH 2/2] Revert "fix(server): stop completed delegate reruns and identical failing tool-call loops (CLO-1368) (#263)" This reverts commit 8630677cfdbac568e157ace7ea5ab18a38f8b9bd. --- apps/server/src/mcp/McpHttpServer.ts | 66 +- apps/server/src/mcp/McpToolLoopGuard.test.ts | 690 ------------------ apps/server/src/mcp/McpToolLoopGuard.ts | 178 ----- .../orchestration-v2/AgentOutputGate.test.ts | 108 +-- .../src/orchestration-v2/AgentOutputGate.ts | 14 +- .../src/orchestration-v2/CommandPolicy.ts | 40 - .../CompletedDelegateNoRerun.test.ts | 558 -------------- .../DelegationNudgeReactor.ts | 5 +- .../src/orchestration-v2/IdleCompaction.ts | 8 +- .../src/orchestration-v2/Orchestrator.ts | 32 - .../ProviderSessionManager.ts | 3 +- .../orchestration-v2/RestartContinuation.ts | 4 +- .../testkit/pullRequestFixtures.ts | 2 - .../PullRequestWatchService.test.ts | 17 - .../pullRequest/PullRequestWatchService.ts | 3 +- 15 files changed, 19 insertions(+), 1709 deletions(-) delete mode 100644 apps/server/src/mcp/McpToolLoopGuard.test.ts delete mode 100644 apps/server/src/mcp/McpToolLoopGuard.ts delete mode 100644 apps/server/src/orchestration-v2/CompletedDelegateNoRerun.test.ts diff --git a/apps/server/src/mcp/McpHttpServer.ts b/apps/server/src/mcp/McpHttpServer.ts index b026f41c1be40..5a936dadef325 100644 --- a/apps/server/src/mcp/McpHttpServer.ts +++ b/apps/server/src/mcp/McpHttpServer.ts @@ -55,14 +55,6 @@ import { advertisedJsonSchema } from "./advertisedJsonSchema.ts"; import * as McpInvocationContext from "./McpInvocationContext.ts"; import * as McpToolAccess from "./McpToolAccess.ts"; import * as McpToolExposure from "./McpToolExposure.ts"; -import { - failureFingerprintFromExit, - loopGuardScopeKey, - loopGuardTtlMs, - makeToolCallLoopGuard, - toolCallLoopBlockedResult, - toolCallLoopKey, -} from "./McpToolLoopGuard.ts"; import * as McpWebhookTransport from "./McpWebhookTransport.ts"; import { HTML_RENDER_TOOL_NAME } from "@t3tools/shared/htmlRender"; import { compactT3McpToolOutput } from "@t3tools/shared/toolOutput"; @@ -1313,52 +1305,6 @@ const withToolResultCapture = Effect.fn("McpHttpServer.withToolResultCapture")(f return yield* registration.pipe(Effect.provideService(McpServer.McpServer, capturingServer)); }); -const withToolLoopGuard = Effect.fn("McpHttpServer.withToolLoopGuard")(function* ( - registration: Effect.Effect, -) { - const server = yield* McpServer.McpServer; - const mcpSessions = yield* Effect.serviceOption(McpProviderSessions.McpProviderSessions); - const guard = yield* makeToolCallLoopGuard(); - const guardedServer = McpServer.McpServer.of({ - ...server, - addTool: Effect.fn("McpServer.addTool")(function (options) { - const toolName = options.tool.name; - return server.addTool({ - ...options, - handle: Effect.fnUntraced(function* (payload) { - const scope = Option.getOrUndefined( - yield* Effect.serviceOption(McpInvocationContext.McpInvocationContext), - ); - const thread = scope?.thread; - const epoch = - thread === undefined || Option.isNone(mcpSessions) - ? undefined - : yield* mcpSessions.value.toolResultEpoch(thread.threadId); - const scopeKey = loopGuardScopeKey(scope, epoch); - if (scopeKey === undefined) return yield* options.handle(payload); - const ttlMs = loopGuardTtlMs(scope); - const key = toolCallLoopKey(scopeKey, toolName, payload); - const decision = yield* guard.check(key, ttlMs); - if (decision.blocked) { - yield* Effect.logWarning("mcp.tool.identical-failure-loop-blocked", { - tool: toolName, - priorFailures: decision.priorFailures, - ...(thread === undefined ? {} : { threadId: thread.threadId }), - }); - return toolCallLoopBlockedResult(toolName, decision.priorFailures); - } - return yield* options - .handle(payload) - .pipe( - Effect.onExit((exit) => guard.record(key, failureFingerprintFromExit(exit), ttlMs)), - ); - }), - }); - }), - }); - return yield* registration.pipe(Effect.provideService(McpServer.McpServer, guardedServer)); -}); - /** Each tool call gets a span named for its tool; arguments stay out, as they carry prompts and IDs. */ const withToolSpans = Effect.fn("McpHttpServer.withToolSpans")(function* ( registration: Effect.Effect, @@ -1442,10 +1388,8 @@ export const toolkitRegistration = , EX, Layer.effectDiscard( withToolAnalytics( withToolResultCapture( - withToolLoopGuard( - withToolSpans( - withAdvertisedSchemas(toolkit, McpServer.registerToolkit(decodeAsAdvertised(toolkit))), - ), + withToolSpans( + withAdvertisedSchemas(toolkit, McpServer.registerToolkit(decodeAsAdvertised(toolkit))), ), ), ), @@ -1463,9 +1407,9 @@ const imageToolRegistration = , A, E, R, register: Effect.Effect, handlers: McpToolAccess.HandlersLayer, ) => - Layer.effectDiscard( - withToolAnalytics(withToolResultCapture(withToolLoopGuard(withToolSpans(register)))), - ).pipe(Layer.provide(McpToolAccess.HandlersLayer.layer(handlers))); + Layer.effectDiscard(withToolAnalytics(withToolResultCapture(withToolSpans(register)))).pipe( + Layer.provide(McpToolAccess.HandlersLayer.layer(handlers)), + ); export const layerHtmlToolkit = Layer.mergeAll( toolkitRegistration(HtmlRenderToolkit, HtmlHandlers.layerRender), diff --git a/apps/server/src/mcp/McpToolLoopGuard.test.ts b/apps/server/src/mcp/McpToolLoopGuard.test.ts deleted file mode 100644 index 7b4e05fbdaea1..0000000000000 --- a/apps/server/src/mcp/McpToolLoopGuard.test.ts +++ /dev/null @@ -1,690 +0,0 @@ -import { assert, describe, expect, it } from "@effect/vitest"; -import { - CommandId, - EnvironmentId, - MessageId, - OrchestratorMcpFailure, - ProjectId, - ProviderDriverKind, - ProviderInstanceId, - ProviderThreadId, - ProviderTurnId, - RunId, - ThreadId, - type OrchestrationV2ThreadShell, -} from "@t3tools/contracts"; -import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions"; -import type * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter"; -import { checkpointWorkspace } from "@t3tools/provider-testing/replayWorkspace"; -import { SEND_TO_USER_MAX_LENGTH } from "@t3tools/shared/toolOutput"; -import { McpSchema, McpServer, Tool, Toolkit } from "effect/ai"; -import * as DateTime from "effect/DateTime"; -import * as Duration from "effect/Duration"; -import * as Effect from "effect/Effect"; -import * as Exit from "effect/Exit"; -import * as Fiber from "effect/Fiber"; -import * as Layer from "effect/Layer"; -import * as Queue from "effect/Queue"; -import * as Ref from "effect/Ref"; -import * as Schema from "effect/Schema"; -import * as Stream from "effect/Stream"; -import * as TestClock from "effect/testing/TestClock"; - -import { CodexProviderCapabilitiesV2 } from "../orchestration-v2/Adapters/CodexAdapterV2.ts"; -import * as EffectWorker from "../orchestration-v2/EffectWorker.ts"; -import * as Orchestrator from "../orchestration-v2/Orchestrator.ts"; -import * as ProviderAdapterRegistry from "../orchestration-v2/ProviderAdapterRegistry.ts"; -import * as ProviderReplayHarness from "../orchestration-v2/testkit/ProviderReplayHarness.ts"; -import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts"; -import * as McpHttpServer from "./McpHttpServer.ts"; -import * as McpInvocationContext from "./McpInvocationContext.ts"; -import * as McpToolAccess from "./McpToolAccess.ts"; -import { - CLIENT_LOOP_GUARD_TTL_MS, - failureFingerprintFromExit, - loopGuardScopeKey, - loopGuardTtlMs, - makeToolCallLoopGuard, - MAX_IDENTICAL_FAILING_TOOL_CALLS, - TOOL_CALL_LOOP_BLOCKED_CODE, - toolCallLoopKey, -} from "./McpToolLoopGuard.ts"; - -const threadId = ThreadId.make("thread:antigravity-delegate"); -const envId = EnvironmentId.make("env:asus"); -const instanceId = ProviderInstanceId.make("antigravity"); -const client = McpSchema.McpServerClient.of({ - clientId: 1, - protocolVersion: "2025-06-18", - clientCapabilities: {}, - clientInfo: { name: "antigravity", version: "1.0.0" }, - initializePayload: { - protocolVersion: "2025-06-18", - capabilities: {}, - clientInfo: { name: "antigravity", version: "1.0.0" }, - }, - getClient: Effect.die("unused"), -}); - -const declaredFailure = (result: McpSchema.CallToolResult) => { - const text = result.content[0]; - return result.isError === true && text?.type === "text" ? JSON.parse(text.text) : undefined; -}; - -const threadScope = ( - overrides: Partial> = {}, -): McpInvocationContext.McpInvocationScope => ({ - environmentId: envId, - requestNamespace: "session:antigravity", - thread: { - threadId, - providerSessionId: "provider-session:antigravity-1", - providerInstanceId: instanceId, - ...overrides, - }, - client: undefined, - capabilities: new Set(["orchestration"]), - issuedAt: 0, -}); - -const liveAntigravityThreadsLayer = Layer.succeed(ThreadManagementService.ThreadManagementService, { - getThreadShell: (id: ThreadId) => - Effect.succeed({ - id, - archivedAt: null, - deletedAt: null, - activeRunId: RunId.make("run:active-1"), - providerInstanceId: instanceId, - runtimeMode: "full-access", - interactionMode: "default", - pendingBackgroundTasks: [], - } as unknown as OrchestrationV2ThreadShell), -} as unknown as ThreadManagementService.ThreadManagementService["Service"]); - -describe("McpToolLoopGuard", () => { - it.effect( - "blocks a third identical failing call and resets on argument/error change or success", - () => - Effect.gen(function* () { - const guard = yield* makeToolCallLoopGuard(); - const scopeKey = loopGuardScopeKey(threadScope(), 0)!; - const key = toolCallLoopKey(scopeKey, "send_to_user", { message: "too long" }); - - assert.equal(MAX_IDENTICAL_FAILING_TOOL_CALLS, 2); - assert.deepEqual(yield* guard.check(key), { blocked: false }); - - const errA = failureFingerprintFromExit( - Exit.fail(new McpSchema.InvalidParams({ message: "Expected length <= 4000" })), - ); - yield* guard.record(key, errA); - assert.deepEqual(yield* guard.check(key), { blocked: false }); - - // A different error resets the consecutive-same-failure count. - const errB = failureFingerprintFromExit( - Exit.fail(new McpSchema.InvalidParams({ message: "Different error" })), - ); - yield* guard.record(key, errB); - assert.deepEqual(yield* guard.check(key), { blocked: false }); - - // Two identical failures with errB trip the guard before a 3rd attempt. - yield* guard.record(key, errB); - assert.deepEqual(yield* guard.check(key), { blocked: true, priorFailures: 2 }); - - // Changed arguments use a distinct key and remain allowed. - const changedKey = toolCallLoopKey(scopeKey, "send_to_user", { message: "short" }); - assert.deepEqual(yield* guard.check(changedKey), { blocked: false }); - - // A success clears the failure streak. - const ok = failureFingerprintFromExit( - Exit.succeed( - new McpSchema.CallToolResult({ - isError: false, - content: [{ type: "text", text: "ok" }], - }), - ), - ); - assert.isNull(ok); - yield* guard.record(key, ok); - assert.deepEqual(yield* guard.check(key), { blocked: false }); - }), - ); - - it("excludes linked peer-transport callers from loop-guard scoping", () => { - const linkedPeerScope: McpInvocationContext.McpInvocationScope = { - environmentId: envId, - requestNamespace: "peer:r720", - thread: undefined, - client: { - sessionId: "peer-session-1", - label: "R720", - access: "full-access", - linked: true, - }, - capabilities: new Set(["orchestration"]), - issuedAt: 0, - }; - assert.isUndefined(loopGuardScopeKey(linkedPeerScope, undefined)); - }); - - it.effect( - "Dec 2 Antigravity Neon replay: blocks a 3rd identical send_to_user call over the 4,000-char cap", - () => - Effect.gen(function* () { - const server = yield* McpServer.McpServer; - const scope = threadScope(); - const oversized = "N".repeat(SEND_TO_USER_MAX_LENGTH + 250); - const invoke = (message: string) => - server - .callTool({ name: "send_to_user", arguments: { message } }) - .pipe( - Effect.provideService(McpInvocationContext.McpInvocationContext, scope), - Effect.provideService(McpSchema.McpServerClient, client), - ); - - // Attempts 1 and 2 fail schema validation identically. - const first = yield* invoke(oversized).pipe(Effect.flip); - expect(first).toMatchObject({ _tag: "InvalidParams" }); - const second = yield* invoke(oversized).pipe(Effect.flip); - expect(second).toMatchObject({ _tag: "InvalidParams" }); - - // Attempt 3 with the exact same payload is blocked before schema/handler execution. - const third = yield* invoke(oversized); - expect(third.isError).toBe(true); - expect(third.structuredContent).toMatchObject({ - _tag: "ToolCallLoopBlocked", - code: TOOL_CALL_LOOP_BLOCKED_CODE, - tool: "send_to_user", - priorFailures: 2, - }); - - // Changing the message to fit under the 4,000-character cap succeeds immediately. - const fixed = yield* invoke("Concise summary under cap."); - expect(fixed.isError).not.toBe(true); - }).pipe( - Effect.provide( - McpHttpServer.layerMessageToolkit.pipe( - Layer.provideMerge(McpHttpServer.layerInProcessMcpServer), - Layer.provideMerge(McpProviderSessions.layer), - Layer.provide(liveAntigravityThreadsLayer), - ), - ), - ), - ); - - it.effect( - "Dec 2 Antigravity Carbon replay: blocks a 3rd identical failing silent_ack call before handler execution", - () => - Effect.gen(function* () { - const handlerCalls = yield* Ref.make(0); - const activeRun = yield* Ref.make(null); - const ProbeTool = Tool.make("silent_ack_probe", { - description: "Probe tool mirroring silent_ack handler failures.", - parameters: Schema.Struct({ reason: Schema.optional(Schema.String) }), - success: Schema.Struct({ ok: Schema.Literal(true) }), - failure: OrchestratorMcpFailure, - failureMode: "return", - dependencies: [ - McpInvocationContext.McpInvocationContext, - ThreadManagementService.ThreadManagementService, - ], - }).annotate(McpSchema.EnabledWhen, McpInvocationContext.hiddenFromOutsideClients); - const ProbeToolkit = Toolkit.make(ProbeTool); - const ProbeHandlers = McpToolAccess.toLayer(ProbeToolkit, { - silent_ack_probe: McpToolAccess.readsAsCaller(() => - Ref.update(handlerCalls, (n) => n + 1).pipe( - Effect.andThen( - Effect.fail( - new OrchestratorMcpFailure({ - code: "parent_not_active", - message: "The calling provider no longer owns an active thread run.", - }), - ), - ), - ), - ), - }); - - const threadsLayer = Layer.succeed(ThreadManagementService.ThreadManagementService, { - getThreadShell: (id: ThreadId) => - Ref.get(activeRun).pipe( - Effect.map( - (activeRunId) => - ({ - id, - archivedAt: null, - deletedAt: null, - activeRunId, - providerInstanceId: instanceId, - runtimeMode: "full-access", - interactionMode: "default", - pendingBackgroundTasks: [], - }) as unknown as OrchestrationV2ThreadShell, - ), - ), - } as unknown as ThreadManagementService.ThreadManagementService["Service"]); - - const layer = Layer.mergeAll( - McpHttpServer.layerMessageToolkit, - McpHttpServer.toolkitRegistration(ProbeToolkit, ProbeHandlers), - ).pipe( - Layer.provideMerge(McpHttpServer.layerInProcessMcpServer), - Layer.provideMerge(McpProviderSessions.layer), - Layer.provide(threadsLayer), - ); - - yield* Effect.gen(function* () { - const server = yield* McpServer.McpServer; - const scope = threadScope(); - const call = (name: string, args: Record) => - server - .callTool({ name, arguments: args }) - .pipe( - Effect.provideService(McpInvocationContext.McpInvocationContext, scope), - Effect.provideService(McpSchema.McpServerClient, client), - ); - - // Real silent_ack failing parent_not_active (no active run) twice -> 3rd attempt blocked. - const ack1 = yield* call("silent_ack", { reason: "done" }); - expect(ack1.isError).toBe(true); - expect(declaredFailure(ack1)).toMatchObject({ code: "parent_not_active" }); - - const ack2 = yield* call("silent_ack", { reason: "done" }); - expect(ack2.isError).toBe(true); - expect(declaredFailure(ack2)).toMatchObject({ code: "parent_not_active" }); - - const ack3 = yield* call("silent_ack", { reason: "done" }); - expect(ack3.isError).toBe(true); - expect(ack3.structuredContent).toMatchObject({ - _tag: "ToolCallLoopBlocked", - code: TOOL_CALL_LOOP_BLOCKED_CODE, - tool: "silent_ack", - priorFailures: 2, - }); - - // Verify handler execution count stops strictly at 2 (never executes a 3rd time). - yield* call("silent_ack_probe", { reason: "loop" }); - yield* call("silent_ack_probe", { reason: "loop" }); - const blocked = yield* call("silent_ack_probe", { reason: "loop" }); - expect(blocked.isError).toBe(true); - expect(blocked.structuredContent).toMatchObject({ - code: TOOL_CALL_LOOP_BLOCKED_CODE, - tool: "silent_ack_probe", - priorFailures: 2, - }); - assert.equal(yield* Ref.get(handlerCalls), 2); - - // A genuinely new active turn clears tool results (bumping epoch) and resets the guard budget. - const sessions = yield* McpProviderSessions.McpProviderSessions; - yield* sessions.clearToolResults(threadId); - yield* Ref.set(activeRun, RunId.make("run:new-parent-followup")); - const afterNewRun = yield* call("silent_ack", { reason: "done" }); - expect(afterNewRun.isError).not.toBe(true); - }).pipe(Effect.provide(layer)); - }), - ); - - it.effect( - "expires non-linked external client streaks after TTL and resets immediately on success", - () => - Effect.gen(function* () { - const handlerCalls = yield* Ref.make(0); - const shouldFail = yield* Ref.make(true); - const ClientProbeTool = Tool.make("external_client_probe", { - description: "Probe tool for external non-linked MCP client TTL testing.", - parameters: Schema.Struct({ action: Schema.String }), - success: Schema.Struct({ ok: Schema.Literal(true) }), - failure: OrchestratorMcpFailure, - failureMode: "return", - dependencies: [McpInvocationContext.McpInvocationContext], - }); - const ClientProbeToolkit = Toolkit.make(ClientProbeTool); - const ClientProbeHandlers = McpToolAccess.toLayer(ClientProbeToolkit, { - external_client_probe: McpToolAccess.reads(() => - Ref.update(handlerCalls, (n) => n + 1).pipe( - Effect.andThen(Ref.get(shouldFail)), - Effect.flatMap((failing) => - failing - ? Effect.fail( - new OrchestratorMcpFailure({ - code: "orchestration_error", - message: "Transient external failure.", - }), - ) - : Effect.succeed({ ok: true as const }), - ), - ), - ), - }); - - const externalClientScope: McpInvocationContext.McpInvocationScope = { - environmentId: envId, - requestNamespace: "client:ext-1", - thread: undefined, - client: { - sessionId: "ext-session-1", - label: "External CLI", - access: "full-access", - linked: false, - }, - capabilities: new Set(["orchestration"]), - issuedAt: 0, - }; - assert.equal(loopGuardTtlMs(externalClientScope), CLIENT_LOOP_GUARD_TTL_MS); - - const layer = McpHttpServer.toolkitRegistration( - ClientProbeToolkit, - ClientProbeHandlers, - ).pipe( - Layer.provideMerge(McpHttpServer.layerInProcessMcpServer), - Layer.provideMerge(McpProviderSessions.layer), - ); - - yield* Effect.gen(function* () { - const server = yield* McpServer.McpServer; - const call = () => - server - .callTool({ name: "external_client_probe", arguments: { action: "sync" } }) - .pipe( - Effect.provideService( - McpInvocationContext.McpInvocationContext, - externalClientScope, - ), - Effect.provideService(McpSchema.McpServerClient, client), - ); - - expect((yield* call()).isError).toBe(true); - expect((yield* call()).isError).toBe(true); - const blocked = yield* call(); - expect(blocked.isError).toBe(true); - expect(blocked.structuredContent).toMatchObject({ - code: TOOL_CALL_LOOP_BLOCKED_CODE, - tool: "external_client_probe", - priorFailures: 2, - }); - assert.equal(yield* Ref.get(handlerCalls), 2); - - // Still blocked just before TTL expires. - yield* TestClock.adjust(Duration.millis(CLIENT_LOOP_GUARD_TTL_MS - 1)); - const stillBlocked = yield* call(); - expect(stillBlocked.structuredContent).toMatchObject({ - code: TOOL_CALL_LOOP_BLOCKED_CODE, - }); - assert.equal(yield* Ref.get(handlerCalls), 2); - - // Once TTL elapses, the client can retry and succeed. - yield* TestClock.adjust(Duration.millis(1)); - yield* Ref.set(shouldFail, false); - const recovered = yield* call(); - expect(recovered.isError).not.toBe(true); - assert.equal(yield* Ref.get(handlerCalls), 3); - - // A success clears a streak immediately without waiting for TTL. - yield* Ref.set(shouldFail, true); - expect((yield* call()).isError).toBe(true); - yield* Ref.set(shouldFail, false); - expect((yield* call()).isError).not.toBe(true); - yield* Ref.set(shouldFail, true); - expect((yield* call()).isError).toBe(true); - expect((yield* call()).isError).toBe(true); - assert.equal(yield* Ref.get(handlerCalls), 7); - const blockedAgain = yield* call(); - expect(blockedAgain.structuredContent).toMatchObject({ - code: TOOL_CALL_LOOP_BLOCKED_CODE, - }); - assert.equal(yield* Ref.get(handlerCalls), 7); - }).pipe(Effect.provide(layer)); - }), - ); - - it.live( - "non-ACP provider resets loop-guard budget across turns via ProviderSessionManager without adapter clearToolResults", - () => - Effect.gen(function* () { - const cwd = yield* checkpointWorkspace("non-acp-loop-guard-reset"); - const codexDriver = ProviderDriverKind.make("codex"); - const codexInstanceId = ProviderInstanceId.make("codex"); - const nonAcpThreadId = ThreadId.make("thread:codex-non-acp-loop-guard"); - const handlerCalls = yield* Ref.make(0); - const shouldFail = yield* Ref.make(true); - const sessionIdsUsed: Array = []; - - const NonAcpProbeTool = Tool.make("non_acp_probe", { - description: "Probe tool for non-ACP per-turn loop-guard reset testing.", - parameters: Schema.Struct({ target: Schema.String }), - success: Schema.Struct({ ok: Schema.Literal(true) }), - failure: OrchestratorMcpFailure, - failureMode: "return", - dependencies: [McpInvocationContext.McpInvocationContext], - }).annotate(McpSchema.EnabledWhen, McpInvocationContext.hiddenFromOutsideClients); - const NonAcpProbeToolkit = Toolkit.make(NonAcpProbeTool); - const NonAcpProbeHandlers = McpToolAccess.toLayer(NonAcpProbeToolkit, { - non_acp_probe: McpToolAccess.readsAsCaller(() => - Ref.update(handlerCalls, (n) => n + 1).pipe( - Effect.andThen(Ref.get(shouldFail)), - Effect.flatMap((failing) => - failing - ? Effect.fail( - new OrchestratorMcpFailure({ - code: "orchestration_error", - message: "Transient non-ACP failure.", - }), - ) - : Effect.succeed({ ok: true as const }), - ), - ), - ), - }); - - // Non-ACP adapter: never calls `clearToolResults` and reuses one provider session across turns. - const codexAdapter: ProviderAdapter.ProviderAdapterV2["Service"] = { - instanceId: codexInstanceId, - driver: codexDriver, - getCapabilities: () => Effect.succeed(CodexProviderCapabilitiesV2), - planSelectionTransition: () => Effect.succeed({ type: "apply_on_next_turn" }), - openSession: (session) => - Effect.gen(function* () { - const createdAt = yield* DateTime.now; - const events = yield* Queue.unbounded(); - return { - instanceId: codexInstanceId, - driver: codexDriver, - providerSessionId: session.providerSessionId, - providerSession: { - id: session.providerSessionId, - driver: codexDriver, - providerInstanceId: codexInstanceId, - status: "ready", - cwd, - model: "gpt-5", - capabilities: CodexProviderCapabilitiesV2, - createdAt, - updatedAt: createdAt, - lastError: null, - }, - events: Stream.fromQueue(events), - ensureThread: ({ threadId: id }) => - Effect.succeed({ - id: ProviderThreadId.make(`provider-thread:${id}`), - driver: codexDriver, - providerInstanceId: codexInstanceId, - providerSessionId: session.providerSessionId, - appThreadId: id, - ownerNodeId: null, - nativeThreadRef: { - driver: codexDriver, - nativeId: `native:${id}`, - strength: "strong", - }, - nativeConversationHeadRef: null, - status: "idle", - firstRunOrdinal: null, - lastRunOrdinal: null, - handoffIds: [], - forkedFrom: null, - createdAt, - updatedAt: createdAt, - }), - resumeThread: ({ providerThread }) => Effect.succeed(providerThread), - startTurn: (turn) => - Effect.gen(function* () { - sessionIdsUsed.push(session.providerSessionId); - const ts = yield* DateTime.now; - const providerTurnId = ProviderTurnId.make(`provider-turn:${turn.attemptId}`); - yield* Queue.offer(events, { - type: "provider_turn.updated", - driver: codexDriver, - providerTurn: { - id: providerTurnId, - providerThreadId: turn.providerThread.id, - nodeId: turn.rootNodeId, - runAttemptId: turn.attemptId, - nativeTurnRef: null, - ordinal: turn.providerTurnOrdinal, - status: "running", - startedAt: ts, - completedAt: null, - }, - }); - yield* Queue.offer(events, { - type: "provider_turn.updated", - driver: codexDriver, - providerTurn: { - id: providerTurnId, - providerThreadId: turn.providerThread.id, - nodeId: turn.rootNodeId, - runAttemptId: turn.attemptId, - nativeTurnRef: null, - ordinal: turn.providerTurnOrdinal, - status: "completed", - startedAt: ts, - completedAt: ts, - }, - }); - yield* Queue.offer(events, { - type: "turn.terminal", - driver: codexDriver, - providerThreadId: turn.providerThread.id, - providerTurnId, - runOrdinal: turn.runOrdinal, - status: "completed", - failure: null, - threadDisposition: "reusable", - }); - }), - steerTurn: () => Effect.die("unused"), - interruptTurn: () => Effect.void, - respondToRuntimeRequest: () => Effect.die("unused"), - readThreadSnapshot: () => Effect.die("unused"), - rollbackThread: () => Effect.die("unused"), - forkThread: () => Effect.die("unused"), - }; - }), - }; - - const layer = Layer.mergeAll( - ProviderReplayHarness.layerWithRegistry( - { name: "non-acp-loop-guard-reset" }, - ProviderAdapterRegistry.layerSingle(codexAdapter), - { runEffectWorker: false, runContinuationWorker: false }, - ), - McpHttpServer.toolkitRegistration(NonAcpProbeToolkit, NonAcpProbeHandlers).pipe( - Layer.provideMerge(McpHttpServer.layerInProcessMcpServer), - Layer.provideMerge(McpProviderSessions.layer), - ), - ); - - yield* Effect.gen(function* () { - const orchestrator = yield* Orchestrator.OrchestratorV2; - const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; - const mcpServer = yield* McpServer.McpServer; - const mcpSessions = yield* McpProviderSessions.McpProviderSessions; - - yield* orchestrator.dispatch({ - type: "thread.create", - commandId: CommandId.make("create:codex-non-acp"), - threadId: nonAcpThreadId, - projectId: ProjectId.make("project:t3code"), - title: "Codex non-ACP loop guard", - modelSelection: { instanceId: codexInstanceId, model: "gpt-5" }, - runtimeMode: "full-access", - interactionMode: "default", - branch: null, - worktreePath: cwd, - createdBy: "user", - creationSource: "web", - }); - - const runTurn = (ordinal: number) => - Effect.gen(function* () { - const completed = yield* orchestrator.streamDomainEvents.pipe( - Stream.filter( - (event) => - event.type === "run.updated" && - event.payload.threadId === nonAcpThreadId && - event.payload.ordinal === ordinal && - event.payload.status === "completed", - ), - Stream.take(1), - Stream.runDrain, - Effect.forkScoped, - ); - yield* orchestrator.dispatch({ - type: "message.dispatch", - commandId: CommandId.make(`dispatch:codex-turn-${ordinal}`), - threadId: nonAcpThreadId, - messageId: MessageId.make(`msg:codex-turn-${ordinal}`), - text: `Turn ${ordinal}`, - attachments: [], - dispatchMode: { type: "start_immediately" }, - createdBy: "user", - creationSource: "web", - }); - yield* worker.drain(); - yield* Fiber.join(completed); - // Drain turn-end checkpoint capture so the next turn starts immediately instead of queueing. - yield* worker.drain(); - }); - - // Turn 1: non-ACP provider starts turn -> 2 identical failures block the 3rd attempt. - yield* runTurn(1); - const reusedSessionId = sessionIdsUsed[0]!; - const epochTurn1 = yield* mcpSessions.toolResultEpoch(nonAcpThreadId); - const codexScope = threadScope({ - threadId: nonAcpThreadId, - providerSessionId: reusedSessionId, - providerInstanceId: codexInstanceId, - }); - const invoke = () => - mcpServer - .callTool({ name: "non_acp_probe", arguments: { target: "status" } }) - .pipe( - Effect.provideService(McpInvocationContext.McpInvocationContext, codexScope), - Effect.provideService(McpSchema.McpServerClient, client), - ); - - expect((yield* invoke()).isError).toBe(true); - expect((yield* invoke()).isError).toBe(true); - const blockedTurn1 = yield* invoke(); - expect(blockedTurn1.isError).toBe(true); - expect(blockedTurn1.structuredContent).toMatchObject({ - _tag: "ToolCallLoopBlocked", - code: TOOL_CALL_LOOP_BLOCKED_CODE, - tool: "non_acp_probe", - priorFailures: 2, - }); - assert.equal(yield* Ref.get(handlerCalls), 2); - - // Turn 2: reuses the exact same providerSessionId without adapter clearToolResults. - yield* Ref.set(shouldFail, false); - yield* runTurn(2); - assert.equal(sessionIdsUsed[1], reusedSessionId); - assert.isAbove(yield* mcpSessions.toolResultEpoch(nonAcpThreadId), epochTurn1); - - // Same tool + args + providerSessionId now succeeds cleanly on Turn 2. - const turn2Result = yield* invoke(); - expect(turn2Result.isError).not.toBe(true); - assert.equal(yield* Ref.get(handlerCalls), 3); - }).pipe(Effect.provide(layer)); - }), - ); -}); diff --git a/apps/server/src/mcp/McpToolLoopGuard.ts b/apps/server/src/mcp/McpToolLoopGuard.ts deleted file mode 100644 index cc28d566ed98f..0000000000000 --- a/apps/server/src/mcp/McpToolLoopGuard.ts +++ /dev/null @@ -1,178 +0,0 @@ -import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions"; -import { McpSchema } from "effect/ai"; -import * as Cause from "effect/Cause"; -import * as Clock from "effect/Clock"; -import * as Effect from "effect/Effect"; -import * as Exit from "effect/Exit"; -import * as Option from "effect/Option"; -import * as Predicate from "effect/Predicate"; -import * as Ref from "effect/Ref"; - -import { toolOutcome } from "../telemetry/ProviderDimensions.ts"; -import type * as McpInvocationContext from "./McpInvocationContext.ts"; - -/** Allow one retry after an initial failure; refuse a third identical failing attempt unchanged. */ -export const MAX_IDENTICAL_FAILING_TOOL_CALLS = 2; -export const TOOL_CALL_LOOP_BLOCKED_CODE = "repeated_failure_blocked"; -/** External non-linked MCP clients have no turn epoch, so failure streaks expire after 60s. */ -export const CLIENT_LOOP_GUARD_TTL_MS = 60_000; -const MAX_TRACKED_KEYS = 512; - -interface FailureStreak { - readonly failureKey: string; - readonly count: number; - readonly updatedAtMs: number; -} - -const textOfContent = (content: ReadonlyArray): string => - content - .flatMap((block) => (block.type === "text" ? [block.text] : [])) - .join("\n") - .trim(); - -const stringProperty = (value: unknown, key: string): string | undefined => - Predicate.isReadonlyObject(value) && typeof value[key] === "string" ? value[key] : undefined; - -/** - * Classifies an MCP tool exit for loop detection: - * - `string`: normalized failure fingerprint - * - `null`: tool succeeded (clears any prior streak for this call) - * - `undefined`: neutral outcome (interrupt or elicitation) - */ -export function failureFingerprintFromExit( - exit: Exit.Exit, -): string | null | undefined { - if (Exit.isFailure(exit)) { - if (Cause.hasInterruptsOnly(exit.cause)) return undefined; - const error = Option.getOrElse(Cause.findErrorOption(exit.cause), () => - Cause.squash(exit.cause), - ); - const tag = stringProperty(error, "_tag") ?? (error instanceof Error ? error.name : ""); - const code = stringProperty(error, "code") ?? ""; - const message = - stringProperty(error, "message") ?? (error instanceof Error ? error.message : String(error)); - return `fail:${tag}:${code}:${message.trim()}`; - } - const value = exit.value; - if (value instanceof McpSchema.InputRequired) return undefined; - const outcome = toolOutcome(value); - if (value.isError !== true && outcome.outcome !== "error") return null; - const tag = stringProperty(value.structuredContent, "_tag") ?? ""; - const code = outcome.outcome === "error" ? outcome.errorCode : ""; - const structuredMessage = stringProperty(value.structuredContent, "message") ?? ""; - const text = textOfContent(value.content); - return `result:${tag}:${code}:${structuredMessage || text}`; -} - -/** Server-to-server peer link transport is excluded so remote follower retries keep working. */ -export function loopGuardScopeKey( - scope: McpInvocationContext.McpInvocationScope | undefined, - toolResultEpoch: number | undefined, -): string | undefined { - if (scope === undefined) return undefined; - if (scope.thread !== undefined) { - return `thread:${scope.thread.threadId}:${scope.thread.providerSessionId}:${toolResultEpoch ?? 0}`; - } - if (scope.client !== undefined && scope.client.linked !== true) { - return `client:${scope.client.sessionId}`; - } - return undefined; -} - -export function loopGuardTtlMs( - scope: McpInvocationContext.McpInvocationScope | undefined, -): number | undefined { - if (scope?.thread !== undefined) return undefined; - if (scope?.client !== undefined && scope.client.linked !== true) { - return CLIENT_LOOP_GUARD_TTL_MS; - } - return undefined; -} - -export function toolCallLoopKey(scopeKey: string, toolName: string, payload: unknown): string { - return `${scopeKey}\0${toolName}\0${McpProviderSessions.hashToolInput(payload)}`; -} - -export function toolCallLoopBlockedResult( - toolName: string, - priorFailures: number, -): McpSchema.CallToolResult { - const message = `Blocked: \`${toolName}\` with identical arguments already failed ${priorFailures} times with the same error. Do not retry this call unchanged; change the arguments or take a different approach.`; - return new McpSchema.CallToolResult({ - isError: true, - structuredContent: { - _tag: "ToolCallLoopBlocked", - code: TOOL_CALL_LOOP_BLOCKED_CODE, - tool: toolName, - priorFailures, - message, - }, - content: [{ type: "text", text: message }], - }); -} - -export interface ToolCallLoopGuard { - readonly check: ( - key: string, - ttlMs?: number, - ) => Effect.Effect< - { readonly blocked: true; readonly priorFailures: number } | { readonly blocked: false } - >; - readonly record: ( - key: string, - fingerprint: string | null | undefined, - ttlMs?: number, - ) => Effect.Effect; -} - -const isExpired = (entry: FailureStreak, nowMs: number, ttlMs: number | undefined): boolean => - ttlMs !== undefined && nowMs - entry.updatedAtMs >= ttlMs; - -export const makeToolCallLoopGuard = Effect.fn("McpToolLoopGuard.make")(function* () { - const streaks = yield* Ref.make(new Map()); - return { - check: Effect.fn("McpToolLoopGuard.check")(function* (key: string, ttlMs?: number) { - const current = yield* Ref.get(streaks); - const entry = current.get(key); - if (entry === undefined) return { blocked: false } as const; - if (ttlMs !== undefined && isExpired(entry, yield* Clock.currentTimeMillis, ttlMs)) { - return { blocked: false } as const; - } - return entry.count >= MAX_IDENTICAL_FAILING_TOOL_CALLS - ? ({ blocked: true, priorFailures: entry.count } as const) - : ({ blocked: false } as const); - }), - record: Effect.fn("McpToolLoopGuard.record")(function* ( - key: string, - fingerprint: string | null | undefined, - ttlMs?: number, - ) { - if (fingerprint === undefined) return; - const nowMs = yield* Clock.currentTimeMillis; - yield* Ref.update(streaks, (current) => { - if (fingerprint === null) { - if (!current.has(key)) return current; - const next = new Map(current); - next.delete(key); - return next; - } - const next = new Map(current); - const existing = next.get(key); - const previous = - existing !== undefined && !isExpired(existing, nowMs, ttlMs) ? existing : undefined; - const updated: FailureStreak = - previous?.failureKey === fingerprint - ? { failureKey: fingerprint, count: previous.count + 1, updatedAtMs: nowMs } - : { failureKey: fingerprint, count: 1, updatedAtMs: nowMs }; - next.delete(key); - next.set(key, updated); - while (next.size > MAX_TRACKED_KEYS) { - const oldest = next.keys().next().value; - if (oldest === undefined) break; - next.delete(oldest); - } - return next; - }); - }), - } satisfies ToolCallLoopGuard; -}); diff --git a/apps/server/src/orchestration-v2/AgentOutputGate.test.ts b/apps/server/src/orchestration-v2/AgentOutputGate.test.ts index 36d6ab95920b0..93e2cc2a6a5f9 100644 --- a/apps/server/src/orchestration-v2/AgentOutputGate.test.ts +++ b/apps/server/src/orchestration-v2/AgentOutputGate.test.ts @@ -1,9 +1,7 @@ import { assert, describe, it } from "@effect/vitest"; import { - EnvironmentId, EventId, MessageId, - NodeId, ProjectId, ProviderInstanceId, RunId, @@ -46,22 +44,12 @@ const baseThread = ( overrides: Partial< Pick< OrchestrationV2AppThread, - | "deletedAt" - | "archivedAt" - | "lineage" - | "delegatedFrom" - | "replacedByThreadId" - | "settledOverride" + "deletedAt" | "archivedAt" | "lineage" | "replacedByThreadId" | "settledOverride" > > = {}, ): Pick< OrchestrationV2AppThread, - | "deletedAt" - | "archivedAt" - | "lineage" - | "delegatedFrom" - | "replacedByThreadId" - | "settledOverride" + "deletedAt" | "archivedAt" | "lineage" | "replacedByThreadId" | "settledOverride" > => ({ deletedAt: null, archivedAt: null, @@ -76,10 +64,8 @@ const baseThread = ( }); const baseRun = ( - overrides: Partial< - Pick - > = {}, -): Pick => ({ + overrides: Partial> = {}, +): Pick => ({ id: runId, status: "completed", userMessageId: agentMsgId, @@ -213,28 +199,6 @@ describe("AgentOutputGate policy", () => { turnItems: [assistantItem("a1", "Child task summary.")], }); assert.deepEqual(subagent, { action: "allow", reason: "subagent_thread" }); - - const remoteDelegate = evaluateAgentOutputGate({ - thread: baseThread({ - delegatedFrom: { - environmentId: EnvironmentId.make("env:r720"), - threadId: ThreadId.make("thread:lead"), - title: "Lead", - }, - }), - run: baseRun(), - userMessage: userMessage("agent"), - turnItems: [assistantItem("a1", "Remote delegate report.")], - }); - assert.deepEqual(remoteDelegate, { action: "allow", reason: "subagent_thread" }); - - const delegatedRun = evaluateAgentOutputGate({ - thread: baseThread(), - run: baseRun({ delegatedTaskId: NodeId.make("node:delegated-task") }), - userMessage: userMessage("agent"), - turnItems: [assistantItem("a1", "Delegated task summary.")], - }); - assert.deepEqual(delegatedRun, { action: "allow", reason: "subagent_thread" }); }); it("allows agent-originated turns that already used an explicit channel tool", () => { @@ -406,68 +370,4 @@ describe("AgentOutputGateReactor", () => { }).pipe(Effect.provide(layer)); }), ); - - it.effect("dispatches 0 bounces for a completed remote delegated thread (delegatedFrom)", () => - Effect.gen(function* () { - const dispatched = yield* Ref.make>([]); - const layer = Layer.mergeAll( - Layer.mock(Orchestrator.OrchestratorV2)({ - streamDomainEvents: Stream.empty, - dispatch: (command) => - Ref.update(dispatched, (list) => [...list, command]).pipe( - Effect.as({ sequence: 1, storedEvents: [] } as never), - ), - }), - Layer.mock(ProjectionStore.ProjectionStoreV2)({ - getThreadShell: () => Effect.succeed({ activeRunId: null, latestRunId: runId } as never), - getThreadRecords: () => - Effect.succeed({ - thread: { - ...baseThread({ - delegatedFrom: { - environmentId: EnvironmentId.make("env:r720"), - threadId: ThreadId.make("thread:lead"), - title: "Lead", - }, - }), - id: threadId, - projectId: ProjectId.make("project:gate"), - providerInstanceId: ProviderInstanceId.make("antigravity"), - }, - runs: [ - { - ...baseRun({ id: runId, userMessageId: agentMsgId }), - providerInstanceId: ProviderInstanceId.make("antigravity"), - }, - ], - messages: [ - { - id: agentMsgId, - threadId, - runId, - role: "user", - text: "Run audit", - ...userMessage("agent"), - }, - ], - turnItems: [assistantItem("a1", "Full delegate audit report.", runId)], - } as never), - getMessagesById: () => Effect.succeed(new Map()), - }), - Layer.mock(EventSink.EventSinkV2)({ - write: () => Effect.succeed([] as never), - }), - Layer.mock(IdAllocator.IdAllocatorV2)({ - allocate: { event: () => Effect.succeed(EventId.make("evt:1")) } as never, - derive: {} as never, - }), - ); - - yield* Effect.gen(function* () { - const reactor = yield* AgentOutputGateReactor.make; - yield* reactor.evaluateCompletedRun({ threadId, runId }); - assert.equal((yield* Ref.get(dispatched)).length, 0); - }).pipe(Effect.provide(layer)); - }), - ); }); diff --git a/apps/server/src/orchestration-v2/AgentOutputGate.ts b/apps/server/src/orchestration-v2/AgentOutputGate.ts index 5c0e5cf60db06..b83c2904b25e2 100644 --- a/apps/server/src/orchestration-v2/AgentOutputGate.ts +++ b/apps/server/src/orchestration-v2/AgentOutputGate.ts @@ -1,6 +1,5 @@ import { CommandId, - isDelegatedAppThread, MessageId, type OrchestrationV2AppThread, type OrchestrationV2ConversationMessage, @@ -18,7 +17,7 @@ import { const OUTPUT_GATE_BOUNCE_MESSAGE_PREFIX = "message:output-gate-bounce:"; export const OUTPUT_GATE_BOUNCE_PROMPT = - "Triggered by an agent/automation wake, not the user: plain assistant text stays folded and is not delivered. Route your response now: call `send_to_user` if it is for the founder, `t3_thread_send` or `ask_agent` if it is for another agent, or `silent_ack` if nothing needs delivery."; + "Triggered by an agent/automation wake, not the user — plain assistant text stays folded and is not delivered. Route your response now: call `send_to_user` if it is for the founder, `t3_thread_send` or `ask_agent` if it is for another agent, or `silent_ack` if nothing needs delivery."; const EXPLICIT_CHANNEL_TOOL_IDS: ReadonlySet = new Set([ SEND_TO_USER_TOOL_NAME, @@ -101,14 +100,9 @@ export type AgentOutputGateDecision = export function evaluateAgentOutputGate(input: { readonly thread: Pick< OrchestrationV2AppThread, - | "deletedAt" - | "archivedAt" - | "lineage" - | "delegatedFrom" - | "replacedByThreadId" - | "settledOverride" + "deletedAt" | "archivedAt" | "lineage" | "replacedByThreadId" | "settledOverride" >; - readonly run: Pick; + readonly run: Pick; readonly userMessage: | Pick< OrchestrationV2ConversationMessage, @@ -140,7 +134,7 @@ export function evaluateAgentOutputGate(input: { if (input.thread.lineage.sideChat === true) { return { action: "allow", reason: "side_chat" }; } - if (isDelegatedAppThread(input.thread) || input.run.delegatedTaskId !== undefined) { + if (input.thread.lineage.relationshipToParent === "subagent") { return { action: "allow", reason: "subagent_thread" }; } if (!isAgentOriginatedWake(input.userMessage)) { diff --git a/apps/server/src/orchestration-v2/CommandPolicy.ts b/apps/server/src/orchestration-v2/CommandPolicy.ts index d7833718c748c..32c862270c177 100644 --- a/apps/server/src/orchestration-v2/CommandPolicy.ts +++ b/apps/server/src/orchestration-v2/CommandPolicy.ts @@ -1,7 +1,6 @@ import { type ChatAttachment, CommandId, - isDelegatedAppThread, type OrchestrationV2Command, OrchestrationV2ProviderCapabilities, type OrchestrationV2GoalCommand, @@ -18,8 +17,6 @@ import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import * as Schema from "effect/Schema"; -import { isOutputGateBounceMessageId } from "./AgentOutputGate.ts"; - export const SteeringExecutionPolicyV2 = Schema.Literals(["active_steering", "interrupt_restart"]); export type SteeringExecutionPolicyV2 = typeof SteeringExecutionPolicyV2.Type; @@ -85,43 +82,6 @@ export function isNativeMaintenanceCommand(message: { ); } -/** - * Completed delegated threads (local subagents and remote `delegatedFrom` tasks) must not - * restart automatically on server/system wakes without genuinely new user or parent input. - */ -export function shouldSuppressCompletedDelegateDispatch( - projection: Pick, - command: Pick< - Extract, - | "messageId" - | "createdBy" - | "creationSource" - | "notification" - | "delegatedCompletion" - | "steerFollowUpOfRunId" - | "restartContinuationOfRunId" - | "usageLimitContinuationOfRunId" - | "idleCompaction" - >, -): boolean { - if (!isDelegatedAppThread(projection.thread)) return false; - if (projection.runs.some((run) => isActiveRun(run) || run.status === "queued")) return false; - if (latestExecutedRun(projection.runs)?.status !== "completed") return false; - if (command.createdBy === "user") return false; - if (command.steerFollowUpOfRunId !== undefined) return false; - if (command.delegatedCompletion !== undefined) return false; - if (command.creationSource === "provider") return false; - if ( - command.restartContinuationOfRunId !== undefined || - command.usageLimitContinuationOfRunId !== undefined || - command.idleCompaction !== undefined || - isOutputGateBounceMessageId(command.messageId) - ) { - return true; - } - return command.notification?.source.kind === "system"; -} - /** * A goal command sent into active work stops that work when it starts or * replaces goal work, or ends a goal that is driving the run. diff --git a/apps/server/src/orchestration-v2/CompletedDelegateNoRerun.test.ts b/apps/server/src/orchestration-v2/CompletedDelegateNoRerun.test.ts deleted file mode 100644 index 273e5adced06d..0000000000000 --- a/apps/server/src/orchestration-v2/CompletedDelegateNoRerun.test.ts +++ /dev/null @@ -1,558 +0,0 @@ -import { assert, describe, it } from "@effect/vitest"; -import { - CommandId, - EnvironmentId, - MessageId, - NodeId, - ProjectId, - ProviderDriverKind, - ProviderInstanceId, - ProviderThreadId, - ProviderTurnId, - RunId, - ThreadId, - TurnItemId, - type OrchestrationV2AppThread, - type OrchestrationV2Run, -} from "@t3tools/contracts"; -import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter"; -import { checkpointWorkspace } from "@t3tools/provider-testing/replayWorkspace"; -import * as DateTime from "effect/DateTime"; -import * as Effect from "effect/Effect"; -import * as Fiber from "effect/Fiber"; -import * as Queue from "effect/Queue"; -import * as Stream from "effect/Stream"; - -import { AcpProviderCapabilitiesV2 } from "@t3tools/provider-acp/server/adapter"; -import { - evaluateAgentOutputGate, - OUTPUT_GATE_BOUNCE_PROMPT, - outputGateBounceCommandId, - outputGateBounceMessageId, -} from "./AgentOutputGate.ts"; -import { shouldSuppressCompletedDelegateDispatch } from "./CommandPolicy.ts"; -import * as EffectWorker from "./EffectWorker.ts"; -import { idleCompactionWindow } from "./IdleCompaction.ts"; -import * as Orchestrator from "./Orchestrator.ts"; -import * as ProviderAdapterRegistry from "./ProviderAdapterRegistry.ts"; -import { restartContinuationBlocked } from "./RestartContinuation.ts"; -import * as ProviderReplayHarness from "./testkit/ProviderReplayHarness.ts"; - -const driver = ProviderDriverKind.make("antigravity"); -const instanceId = ProviderInstanceId.make("antigravity"); -const leadEnvId = EnvironmentId.make("env:r720"); -const leadThreadId = ThreadId.make("thread:lead-clo-1368"); -const now = DateTime.makeUnsafe("2026-12-02T12:00:00.000Z"); - -const makeAntigravityTestAdapter = ( - cwd: string, - replyTextForThread: (threadId: ThreadId) => string, -) => { - const startedTurns: Array<{ readonly threadId: ThreadId; readonly text: string }> = []; - const adapter: ProviderAdapter.ProviderAdapterV2["Service"] = { - instanceId, - driver, - getCapabilities: () => Effect.succeed(AcpProviderCapabilitiesV2), - planSelectionTransition: () => Effect.succeed({ type: "apply_on_next_turn" }), - openSession: (session) => - Effect.gen(function* () { - const createdAt = yield* DateTime.now; - const events = yield* Queue.unbounded(); - return { - instanceId, - driver, - providerSessionId: session.providerSessionId, - providerSession: { - id: session.providerSessionId, - driver, - providerInstanceId: instanceId, - status: "ready", - cwd, - model: "gemini-4-neon", - capabilities: AcpProviderCapabilitiesV2, - createdAt, - updatedAt: createdAt, - lastError: null, - }, - events: Stream.fromQueue(events), - ensureThread: ({ threadId }) => - Effect.succeed({ - id: ProviderThreadId.make(`provider-thread:${threadId}`), - driver, - providerInstanceId: instanceId, - providerSessionId: session.providerSessionId, - appThreadId: threadId, - ownerNodeId: null, - nativeThreadRef: { driver, nativeId: `native:${threadId}`, strength: "strong" }, - nativeConversationHeadRef: null, - status: "idle", - firstRunOrdinal: null, - lastRunOrdinal: null, - handoffIds: [], - forkedFrom: null, - createdAt, - updatedAt: createdAt, - }), - resumeThread: ({ providerThread }) => Effect.succeed(providerThread), - startTurn: (turn) => - Effect.gen(function* () { - startedTurns.push({ threadId: turn.threadId, text: turn.message.text }); - const ts = yield* DateTime.now; - const providerTurnId = ProviderTurnId.make(`provider-turn:${turn.attemptId}`); - const replyText = replyTextForThread(turn.threadId); - yield* Queue.offer(events, { - type: "provider_turn.updated", - driver, - providerTurn: { - id: providerTurnId, - providerThreadId: turn.providerThread.id, - nodeId: turn.rootNodeId, - runAttemptId: turn.attemptId, - nativeTurnRef: null, - ordinal: turn.providerTurnOrdinal, - status: "running", - startedAt: ts, - completedAt: null, - }, - }); - yield* Queue.offer(events, { - type: "turn_item.updated", - driver, - turnItem: { - type: "assistant_message", - id: TurnItemId.make(`assistant:${turn.attemptId}`), - threadId: turn.threadId, - runId: turn.runId, - nodeId: turn.rootNodeId, - providerThreadId: turn.providerThread.id, - providerTurnId, - nativeItemRef: null, - parentItemId: null, - ordinal: 1, - status: "completed", - title: null, - startedAt: ts, - completedAt: ts, - updatedAt: ts, - messageId: MessageId.make(`assistant-msg:${turn.attemptId}`), - text: replyText, - streaming: false, - }, - }); - yield* Queue.offer(events, { - type: "provider_turn.updated", - driver, - providerTurn: { - id: providerTurnId, - providerThreadId: turn.providerThread.id, - nodeId: turn.rootNodeId, - runAttemptId: turn.attemptId, - nativeTurnRef: null, - ordinal: turn.providerTurnOrdinal, - status: "completed", - startedAt: ts, - completedAt: ts, - }, - }); - yield* Queue.offer(events, { - type: "turn.terminal", - driver, - providerThreadId: turn.providerThread.id, - providerTurnId, - runOrdinal: turn.runOrdinal, - status: "completed", - failure: null, - threadDisposition: "reusable", - }); - }), - steerTurn: () => Effect.die("unused"), - interruptTurn: () => Effect.void, - respondToRuntimeRequest: () => Effect.die("unused"), - readThreadSnapshot: () => Effect.die("unused"), - rollbackThread: () => Effect.die("unused"), - forkThread: () => Effect.die("unused"), - }; - }), - }; - return { adapter, startedTurns }; -}; - -describe("Completed delegate no-rerun guards (CLO-1368 M0 item 8)", () => { - it.live( - "Dec 2 Antigravity replay: Neon and Carbon remote delegates have zero restarts after completion, while new parent/user input still runs", - () => - Effect.gen(function* () { - const cwd = yield* checkpointWorkspace("dec2-antigravity-delegates"); - const neonThreadId = ThreadId.make("thread:asus-gemini-neon"); - const carbonThreadId = ThreadId.make("thread:asus-gemini-carbon"); - const { adapter, startedTurns } = makeAntigravityTestAdapter(cwd, (id) => - id === neonThreadId - ? `${"Neon detailed audit report. ".repeat(200)}` - : "Carbon completed verification with no issues.", - ); - const layerTest = ProviderReplayHarness.layerWithRegistry( - { name: "dec2-antigravity-delegates" }, - ProviderAdapterRegistry.layerSingle(adapter), - { runEffectWorker: false, runContinuationWorker: false }, - ); - - yield* Effect.gen(function* () { - const orchestrator = yield* Orchestrator.OrchestratorV2; - const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; - const watchRunCompleted = (threadId: ThreadId, expectedOrdinal: number) => - orchestrator.streamDomainEvents.pipe( - Stream.filter( - (event) => - event.type === "run.updated" && - event.payload.threadId === threadId && - event.payload.ordinal === expectedOrdinal && - event.payload.status === "completed", - ), - Stream.take(1), - Stream.runDrain, - Effect.forkScoped, - ); - - const launchRemoteDelegate = ( - threadId: ThreadId, - title: string, - model: string, - prompt: string, - ) => - Effect.gen(function* () { - yield* orchestrator.dispatch({ - type: "thread.create", - commandId: CommandId.make(`create:${threadId}`), - threadId, - projectId: ProjectId.make("project:t3code"), - title, - modelSelection: { instanceId, model }, - runtimeMode: "full-access", - interactionMode: "default", - branch: null, - worktreePath: cwd, - linkOrigin: { - sessionId: "peer-session:r720", - label: "R720", - }, - delegatedFrom: { - environmentId: leadEnvId, - threadId: leadThreadId, - title: "Lead", - }, - createdBy: "agent", - creationSource: "mcp", - }); - const completed = yield* watchRunCompleted(threadId, 1); - yield* orchestrator.dispatch({ - type: "message.dispatch", - commandId: CommandId.make(`start:${threadId}`), - threadId, - messageId: MessageId.make(`msg:start:${threadId}`), - text: prompt, - attachments: [], - dispatchMode: { type: "start_immediately" }, - createdBy: "agent", - creationSource: "mcp", - }); - yield* worker.drain(); - yield* Fiber.join(completed); - const projection = yield* orchestrator.getThreadProjection(threadId); - assert.equal(projection.runs.length, 1); - assert.equal(projection.runs[0]!.status, "completed"); - return projection; - }); - - const neonProjection = yield* launchRemoteDelegate( - neonThreadId, - "Gemini Neon delegate", - "gemini-4-neon", - "Audit the runtime plan and return the full report.", - ); - const carbonProjection = yield* launchRemoteDelegate( - carbonThreadId, - "Gemini Carbon delegate", - "gemini-4-carbon", - "Verify the diff and summarize findings.", - ); - const neonRun = neonProjection.runs[0]!; - const carbonRun = carbonProjection.runs[0]!; - - // 1. AgentOutputGate must allow completed remote delegates without bouncing. - assert.deepEqual( - evaluateAgentOutputGate({ - thread: neonProjection.thread, - run: neonRun, - userMessage: neonProjection.messages.find((m) => m.id === neonRun.userMessageId), - turnItems: neonProjection.turnItems, - assistantMessages: neonProjection.messages, - }), - { action: "allow", reason: "subagent_thread" }, - ); - assert.deepEqual( - evaluateAgentOutputGate({ - thread: carbonProjection.thread, - run: carbonRun, - userMessage: carbonProjection.messages.find((m) => m.id === carbonRun.userMessageId), - turnItems: carbonProjection.turnItems, - assistantMessages: carbonProjection.messages, - }), - { action: "allow", reason: "subagent_thread" }, - ); - - // 2. Direct server/system automatic restarts (even while turn-end checkpoint capture is pending) - // must be suppressed by Orchestrator without queuing a second run. - yield* orchestrator.dispatch({ - type: "message.dispatch", - commandId: outputGateBounceCommandId(neonRun.id), - threadId: neonThreadId, - messageId: outputGateBounceMessageId(neonRun.id), - text: OUTPUT_GATE_BOUNCE_PROMPT, - notification: { - source: { kind: "monitor" }, - outcome: "updated", - summary: "Output routing reminder", - }, - attachments: [], - dispatchMode: { type: "queue_after_active" }, - createdBy: "agent", - creationSource: "server", - }); - yield* orchestrator.dispatch({ - type: "message.dispatch", - commandId: CommandId.make(`server:system-nudge:${carbonRun.id}`), - threadId: carbonThreadId, - messageId: MessageId.make(`message:system-nudge:${carbonRun.id}`), - text: "Delegation reminder", - notification: { - source: { kind: "system" }, - outcome: "updated", - summary: "Delegation reminder", - }, - attachments: [], - dispatchMode: { type: "queue_after_active" }, - createdBy: "agent", - creationSource: "server", - }); - yield* orchestrator.dispatch({ - type: "message.dispatch", - commandId: CommandId.make(`server:idle-compact:${neonThreadId}:${neonRun.id}`), - threadId: neonThreadId, - messageId: MessageId.make(`idle-compact:${neonThreadId}:${neonRun.id}`), - text: "/compact", - attachments: [], - idleCompaction: "beforeCacheExpires", - dispatchMode: { type: "start_immediately" }, - createdBy: "agent", - creationSource: "server", - }); - yield* worker.drain(); - - const neonAfterAuto = yield* orchestrator.getThreadProjection(neonThreadId); - const carbonAfterAuto = yield* orchestrator.getThreadProjection(carbonThreadId); - assert.equal(neonAfterAuto.runs.length, 1, "Neon had zero restarts after completion"); - assert.equal(carbonAfterAuto.runs.length, 1, "Carbon had zero restarts after completion"); - assert.equal(startedTurns.length, 2, "Only the initial delegated turns ran"); - - // 3. Genuinely new parent input (t3_thread_send via MCP) still runs cleanly. - const neonFollowUpDone = yield* watchRunCompleted(neonThreadId, 2); - yield* orchestrator.dispatch({ - type: "message.dispatch", - commandId: CommandId.make("parent-followup:neon"), - threadId: neonThreadId, - messageId: MessageId.make("msg:parent-followup:neon"), - text: "Follow up on section 2.2 row 14.", - attachments: [], - dispatchMode: { type: "queue_after_active" }, - createdBy: "agent", - creationSource: "mcp", - }); - yield* worker.drain(); - yield* Fiber.join(neonFollowUpDone); - assert.equal((yield* orchestrator.getThreadProjection(neonThreadId)).runs.length, 2); - - // 4. Genuinely new human user input still runs cleanly. - const carbonFollowUpDone = yield* watchRunCompleted(carbonThreadId, 2); - yield* orchestrator.dispatch({ - type: "message.dispatch", - commandId: CommandId.make("user-followup:carbon"), - threadId: carbonThreadId, - messageId: MessageId.make("msg:user-followup:carbon"), - text: "Can you clarify item 2?", - attachments: [], - dispatchMode: { type: "start_immediately" }, - createdBy: "user", - creationSource: "web", - }); - yield* worker.drain(); - yield* Fiber.join(carbonFollowUpDone); - assert.equal((yield* orchestrator.getThreadProjection(carbonThreadId)).runs.length, 2); - }).pipe(Effect.provide(layerTest)); - }), - ); - - it("blocks idle compaction and restart continuation on completed remote delegates", () => { - const threadId = ThreadId.make("thread:remote-delegate-guards"); - const runId = RunId.make("run:remote-delegate-1"); - const remoteThread = { - id: threadId, - deletedAt: null, - archivedAt: null, - settledAt: null, - settledOverride: null, - snoozedUntil: null, - activeProviderThreadId: ProviderThreadId.make("pt:1"), - providerInstanceId: ProviderInstanceId.make("claudeAgent"), - lineage: { rootThreadId: threadId, parentThreadId: null, relationshipToParent: null }, - delegatedFrom: { - environmentId: leadEnvId, - threadId: leadThreadId, - title: "Lead", - }, - } as unknown as OrchestrationV2AppThread; - const completedRun = { - id: runId, - threadId, - ordinal: 1, - status: "completed", - userMessageId: MessageId.make("msg:1"), - providerInstanceId: ProviderInstanceId.make("claudeAgent"), - providerThreadId: ProviderThreadId.make("pt:1"), - activeAttemptId: null, - startedAt: now, - completedAt: now, - } as unknown as OrchestrationV2Run; - - assert.isNull( - idleCompactionWindow( - { - thread: remoteThread, - runs: [completedRun], - messages: [ - { - id: MessageId.make("msg:1"), - text: "Run audit", - } as never, - ], - providerThreads: [], - providerTurns: [], - runtimeRequests: [], - turnItems: [], - contextTransfers: [], - }, - DateTime.toEpochMillis(now), - ), - ); - - assert.isTrue( - restartContinuationBlocked( - { - thread: remoteThread, - runtimeRequests: [], - providerTurns: [], - turnItems: [], - }, - completedRun, - now, - true, - ), - ); - }); - - it("policy distinguishes automatic restarts from genuine user/parent/child-work input", () => { - const threadId = ThreadId.make("thread:policy-delegate"); - const projection = { - thread: { - lineage: { rootThreadId: threadId, parentThreadId: null, relationshipToParent: null }, - delegatedFrom: { environmentId: leadEnvId, threadId: leadThreadId, title: "Lead" }, - } as unknown as OrchestrationV2AppThread, - runs: [ - { - id: RunId.make("run:1"), - ordinal: 1, - status: "completed", - startedAt: now, - completedAt: now, - } as unknown as OrchestrationV2Run, - ], - }; - - // Automatic server output-gate bounce / system nudge / compaction -> suppressed - assert.isTrue( - shouldSuppressCompletedDelegateDispatch(projection, { - messageId: outputGateBounceMessageId(RunId.make("run:1")), - createdBy: "agent", - creationSource: "server", - notification: { source: { kind: "monitor" }, outcome: "updated", summary: "Bounce" }, - }), - ); - assert.isTrue( - shouldSuppressCompletedDelegateDispatch(projection, { - messageId: MessageId.make("message:delegation-nudge:run:1:1"), - createdBy: "agent", - creationSource: "server", - notification: { source: { kind: "system" }, outcome: "updated", summary: "Nudge" }, - }), - ); - assert.isTrue( - shouldSuppressCompletedDelegateDispatch(projection, { - messageId: MessageId.make("message:idle-compact"), - createdBy: "agent", - creationSource: "server", - idleCompaction: "beforeCacheExpires", - }), - ); - - // Genuine user, parent MCP send, grandchild completion, provider background work, or non-bounce monitor -> allowed - assert.isFalse( - shouldSuppressCompletedDelegateDispatch(projection, { - messageId: MessageId.make("message:user-followup"), - createdBy: "user", - creationSource: "web", - }), - ); - assert.isFalse( - shouldSuppressCompletedDelegateDispatch(projection, { - messageId: MessageId.make("message:parent-followup"), - createdBy: "agent", - creationSource: "mcp", - }), - ); - assert.isFalse( - shouldSuppressCompletedDelegateDispatch(projection, { - messageId: MessageId.make("message:grandchild-completion"), - createdBy: "agent", - creationSource: "server", - delegatedCompletion: { - parentRunId: RunId.make("run:1"), - generation: 1, - taskIds: [NodeId.make("node:grandchild")], - }, - }), - ); - assert.isFalse( - shouldSuppressCompletedDelegateDispatch(projection, { - messageId: MessageId.make("message:provider-monitor-completed"), - createdBy: "agent", - creationSource: "provider", - notification: { - source: { kind: "monitor" }, - outcome: "completed", - summary: 'Monitor "sleep 60" finished', - }, - }), - ); - assert.isFalse( - shouldSuppressCompletedDelegateDispatch(projection, { - messageId: MessageId.make("message:followup-automatic-wake"), - createdBy: "agent", - creationSource: "server", - notification: { - source: { kind: "monitor" }, - outcome: "updated", - summary: "Monitor updated", - }, - }), - ); - }); -}); diff --git a/apps/server/src/orchestration-v2/DelegationNudgeReactor.ts b/apps/server/src/orchestration-v2/DelegationNudgeReactor.ts index 48027aa473ad9..fca9ac5fcea3e 100644 --- a/apps/server/src/orchestration-v2/DelegationNudgeReactor.ts +++ b/apps/server/src/orchestration-v2/DelegationNudgeReactor.ts @@ -1,6 +1,5 @@ import { CommandId, - isDelegatedAppThread, MessageId, type OrchestrationV2DomainEvent, type OrchestrationV2Run, @@ -161,13 +160,11 @@ export const make = Effect.gen(function* () { item: OrchestrationV2TurnItem | null, ) { const records = yield* projections.getThreadRecords(threadId, ["runs"]); - if (isDelegatedAppThread(records.thread)) return; const setting = records.thread.delegationNudge; if (setting?.enabled !== true) return; const run = records.runs.find((candidate) => candidate.id === runId); if (run === undefined || (run.status !== "running" && run.status !== "starting")) return; const watch = watchFor(run); - const previousStats = watch.stats; if (watch.seen.size === 0 && run.delegationNudge === undefined) { const prior = yield* projections.getThreadRecords(threadId, ["turnItems"], { turnItemRunId: run.id, @@ -182,7 +179,7 @@ export const make = Effect.gen(function* () { watch.stats.delegations > 0 || watch.stats.countedToolCalls < threshold ) { - if (item !== null && watch.stats !== previousStats) yield* record(threadId, run, watch.stats); + if (item !== null) yield* record(threadId, run, watch.stats); return; } const note = delegationNudgeNote(threshold, watch.stats.nudgesFired > 0); diff --git a/apps/server/src/orchestration-v2/IdleCompaction.ts b/apps/server/src/orchestration-v2/IdleCompaction.ts index 83099d1b615a2..5d68d558ed8e0 100644 --- a/apps/server/src/orchestration-v2/IdleCompaction.ts +++ b/apps/server/src/orchestration-v2/IdleCompaction.ts @@ -1,8 +1,4 @@ -import { - isDelegatedAppThread, - isListedThreadLineage, - type OrchestrationV2ThreadProjection, -} from "@t3tools/contracts"; +import { isListedThreadLineage, type OrchestrationV2ThreadProjection } from "@t3tools/contracts"; import { COMPACTION_SUGGESTION_MIN_TOKENS } from "@t3tools/shared/claudeCompaction"; import { derivePendingBackgroundWork } from "@t3tools/shared/orchestrationV2PendingBackgroundWork"; import { isWaitingDigestRun } from "@t3tools/shared/orchestrationV2ThreadError"; @@ -55,7 +51,7 @@ export function idleCompactionWindow( if (thread.settledAt !== null || thread.settledOverride === "settled") return null; if (thread.snoozedUntil != null && DateTime.toEpochMillis(thread.snoozedUntil) > nowMs) return null; - if (!isListedThreadLineage(thread.lineage) || isDelegatedAppThread(thread)) return null; + if (!isListedThreadLineage(thread.lineage)) return null; // A removed or steered queued message leaves a cancelled run that never started. const latestRun = runs .filter( diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index f6fab35be601f..8e958e4c47a92 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -46,7 +46,6 @@ import { PR_WATCH_STALE_MINUTES, type GuestMessageId, isCompactionCommandMessage, - isDelegatedAppThread, isDeliveredProviderTurn, isOrchestrationV2WorkActive, isProviderNativeSubagentThread, @@ -167,7 +166,6 @@ import { providerTurnCapabilities, resolveMessageDispatch, resolveMessageDispatchIntent, - shouldSuppressCompletedDelegateDispatch, } from "./CommandPolicy.ts"; import { CommandReceiptStoreV2, type CommandReceiptV2 } from "./CommandReceiptStore.ts"; import { @@ -8579,36 +8577,6 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio return; } - const completedDelegateProjection = - isDelegatedAppThread(projection.thread) && - projection.runs.some((run) => run.status === "waiting") - ? { - thread: projection.thread, - // `readCommandProjection` masks a completed run as `waiting` during turn-end capture. - runs: (yield* projectionStore - .getThreadRecords(command.threadId, ["runs"]) - .pipe(mapDispatchError(command))).runs, - } - : projection; - if (shouldSuppressCompletedDelegateDispatch(completedDelegateProjection, command)) { - yield* Effect.logInfo("orchestration-v2.completed-delegate.auto-restart-suppressed", { - threadId: command.threadId, - commandId: command.commandId, - creationSource: command.creationSource, - notificationKind: command.notification?.source.kind, - }); - yield* emit( - events, - command, - )({ - type: "thread.metadata-updated", - threadId: command.threadId, - occurredAt: yield* DateTime.now, - payload: projection.thread, - }); - return; - } - if (projection.thread.lastVisitedAt === null && !isNativeMaintenanceCommand(command)) { const now = yield* DateTime.now; // Null keeps imported history read. The first fresh dispatch establishes diff --git a/apps/server/src/orchestration-v2/ProviderSessionManager.ts b/apps/server/src/orchestration-v2/ProviderSessionManager.ts index db3d990384c2d..aecbcd067b3ec 100644 --- a/apps/server/src/orchestration-v2/ProviderSessionManager.ts +++ b/apps/server/src/orchestration-v2/ProviderSessionManager.ts @@ -2633,8 +2633,7 @@ export const layerWithOptions = ( // start instead of running it on a runtime being torn down. Effect.flatMap((marked) => marked - ? // Every provider's turn starts on a fresh tool-result epoch so loop-guard streaks reset across turns. - mcpSessions.clearToolResults(input.threadId) + ? Effect.void : Effect.fail( new ProviderAdapter.ProviderAdapterTurnStartError({ driver: runtime.driver, diff --git a/apps/server/src/orchestration-v2/RestartContinuation.ts b/apps/server/src/orchestration-v2/RestartContinuation.ts index 6f04cb9861f9c..806f17c20c197 100644 --- a/apps/server/src/orchestration-v2/RestartContinuation.ts +++ b/apps/server/src/orchestration-v2/RestartContinuation.ts @@ -2,7 +2,6 @@ import { runRanAfter } from "@t3tools/shared/orchestrationV2ThreadError"; import { resolveProjectSettings } from "@t3tools/shared/projectSettings"; import { CommandId, - isDelegatedAppThread, isOrchestrationV2WorkActive, latestProviderTurnForAttempt, MessageId, @@ -57,8 +56,7 @@ export function restartContinuationBlocked( thread.archivedAt !== null || thread.deletedAt !== null || thread.settledOverride === "settled" || - (thread.snoozedUntil != null && DateTime.isGreaterThan(thread.snoozedUntil, now)) || - (settled && source.status === "completed" && isDelegatedAppThread(thread)) + (thread.snoozedUntil != null && DateTime.isGreaterThan(thread.snoozedUntil, now)) ) return true; const turn = latestProviderTurnForAttempt(projection.providerTurns, source.activeAttemptId); diff --git a/apps/server/src/orchestration-v2/testkit/pullRequestFixtures.ts b/apps/server/src/orchestration-v2/testkit/pullRequestFixtures.ts index 655b38ec30c20..63b490cc7e9d1 100644 --- a/apps/server/src/orchestration-v2/testkit/pullRequestFixtures.ts +++ b/apps/server/src/orchestration-v2/testkit/pullRequestFixtures.ts @@ -23,7 +23,6 @@ export interface PullRequestTestThread { readonly branchPullRequest?: ThreadLinkedPullRequest | null; readonly latestUserMessageAt: string | null; readonly lineage?: OrchestrationV2ThreadShell["lineage"]; - readonly delegatedFrom?: OrchestrationV2ThreadShell["delegatedFrom"]; readonly createdAt: string; readonly updatedAt: string; readonly archivedAt: string | null; @@ -53,7 +52,6 @@ export function v2PullRequestThread(thread: PullRequestTestThread): Orchestratio parentThreadId: null, relationshipToParent: null, }, - ...(thread.delegatedFrom === undefined ? {} : { delegatedFrom: thread.delegatedFrom }), forkedFrom: null, latestRunId: null, activeRunId: null, diff --git a/apps/server/src/pullRequest/PullRequestWatchService.test.ts b/apps/server/src/pullRequest/PullRequestWatchService.test.ts index 6c48454d99afc..2a02bd7967952 100644 --- a/apps/server/src/pullRequest/PullRequestWatchService.test.ts +++ b/apps/server/src/pullRequest/PullRequestWatchService.test.ts @@ -1,5 +1,4 @@ import { - EnvironmentId, ProjectId, ProviderInstanceId, ThreadId, @@ -313,22 +312,6 @@ describe("PullRequestWatchService", () => { .pipe(Effect.flip); expect(error).toMatchObject({ _tag: "PullRequestWatchFromSubagentError" }); expect(yield* Ref.get(harness.commands)).toEqual([]); - - const remoteHarness = yield* makeHarness({ - thread: { - ...makeThread([makeLink(1, { headBranch: "feature" })]), - delegatedFrom: { - environmentId: EnvironmentId.make("env:r720"), - threadId: ThreadId.make("parent"), - title: "Parent", - }, - }, - }); - const remoteError = yield* remoteHarness - .setWatching(true, { repository: "t3tools/t3code", number: 1 }) - .pipe(Effect.flip); - expect(remoteError).toMatchObject({ _tag: "PullRequestWatchFromSubagentError" }); - expect(yield* Ref.get(remoteHarness.commands)).toEqual([]); }), ); }); diff --git a/apps/server/src/pullRequest/PullRequestWatchService.ts b/apps/server/src/pullRequest/PullRequestWatchService.ts index 2fc6108e1648a..953f956445f3f 100644 --- a/apps/server/src/pullRequest/PullRequestWatchService.ts +++ b/apps/server/src/pullRequest/PullRequestWatchService.ts @@ -1,6 +1,5 @@ import { CommandId, - isDelegatedAppThread, PR_WATCH_STALE_MINUTES, ThreadId, type OrchestrationV2ThreadShell, @@ -118,7 +117,7 @@ const make = Effect.gen(function* () { threadPullRequestsOf(shell).find( (link) => link.source !== "stack-dismissed" && threadPullRequestKeysEqual(link, target), ); - if (watching && isDelegatedAppThread(thread)) { + if (watching && thread.lineage.relationshipToParent === "subagent") { return yield* new PullRequestWatchFromSubagentError(); } const before = watchedLink(thread);