From 74af6b8bc640987dfc399f380fd5de928e2d3d51 Mon Sep 17 00:00:00 2001 From: Victor Vogel Date: Sat, 21 Nov 2026 14:53:09 +0000 Subject: [PATCH 01/34] fix(server): a stopped run's late typed result no longer lands on the next run --- apps/server/src/mcp/McpInvocationContext.ts | 4 + .../server/src/mcp/McpSessionRegistry.test.ts | 71 +- .../src/mcp/McpSessionRegistry.testkit.ts | 6 +- apps/server/src/mcp/McpSessionRegistry.ts | 44 +- apps/server/src/mcp/toolkits/core.test.ts | 117 +++ .../src/mcp/toolkits/thread/handlers.ts | 5 + .../Adapters/AcpAdapterV2.test.ts | 159 ++++ .../Adapters/ClaudeAdapterV2.test.ts | 157 ++++ .../Adapters/ClaudeAdapterV2.ts | 155 +++- .../Adapters/CodexAdapterV2.test.ts | 178 +++++ .../Adapters/OpenCode2AdapterV2.test.ts | 67 ++ .../src/orchestration-v2/Orchestrator.ts | 59 +- .../ProviderSessionManager.test.ts | 693 +++++++++++++++++ .../ProviderSessionManager.ts | 732 ++++++++++++++++-- .../ProviderTurnStartService.test.ts | 37 + .../ProviderTurnStartService.ts | 14 +- .../ThreadManagementService.ts | 58 +- apps/server/src/orchestration-v2/runOutput.ts | 44 +- .../src/orchestration-v2/runtimeLayer.test.ts | 343 +++++++- apps/server/src/preview/ServerBrowser.test.ts | 96 +++ packages/contracts/src/orchestrationV2.ts | 2 + packages/provider-acp/src/server/adapter.ts | 91 ++- .../src/server/mcpOverAcpBridge.test.ts | 335 ++++++++ .../src/server/mcpOverAcpBridge.ts | 214 ++++- .../src/server/ProviderAdapter.ts | 21 + packages/provider-core/src/server/failure.ts | 1 + .../provider-core/src/server/mcpSession.ts | 16 +- .../src/server/adapter.test.ts | 16 +- .../provider-cursor/src/server/adapter.ts | 1 + .../provider-muse/src/server/adapter.test.ts | 49 ++ packages/provider-muse/src/server/adapter.ts | 45 +- .../src/server/adapter.test.ts | 64 ++ .../provider-opencode/src/server/adapter.ts | 22 + .../src/server/v2/adapter.ts | 32 +- .../provider-pi/src/server/adapter.test.ts | 67 ++ packages/provider-pi/src/server/adapter.ts | 48 +- .../src/server/mcpBridge.testkit.ts | 53 +- .../src/server/mcpExtensionSource.test.ts | 178 +++++ .../src/server/mcpExtensionSource.ts | 92 ++- .../provider-pi/src/server/mcpInjection.ts | 6 + 40 files changed, 4185 insertions(+), 207 deletions(-) diff --git a/apps/server/src/mcp/McpInvocationContext.ts b/apps/server/src/mcp/McpInvocationContext.ts index 893c17f23311b..0d92c3d3e452a 100644 --- a/apps/server/src/mcp/McpInvocationContext.ts +++ b/apps/server/src/mcp/McpInvocationContext.ts @@ -7,6 +7,8 @@ import { type ProviderInstanceId, type ProviderInteractionMode, type OrchestrationV2LinkedSender, + type RunAttemptId, + type RunId, type RuntimeMode, type ThreadId, } from "@t3tools/contracts"; @@ -31,6 +33,8 @@ export interface McpThreadCaller { readonly threadId: ThreadId; readonly providerSessionId: string; readonly providerInstanceId: ProviderInstanceId; + readonly runId?: RunId | undefined; + readonly attemptId?: RunAttemptId | undefined; /** A delegated child task; its parent owns the work it hands back. */ readonly subagent?: boolean; } diff --git a/apps/server/src/mcp/McpSessionRegistry.test.ts b/apps/server/src/mcp/McpSessionRegistry.test.ts index 146a7b584897a..629420db6be47 100644 --- a/apps/server/src/mcp/McpSessionRegistry.test.ts +++ b/apps/server/src/mcp/McpSessionRegistry.test.ts @@ -2,7 +2,13 @@ import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; import * as NodeServices from "@effect/platform-node/NodeServices"; import * as Layer from "effect/Layer"; import { expect, it } from "@effect/vitest"; -import { EnvironmentId, ProviderInstanceId, ThreadId } from "@t3tools/contracts"; +import { + EnvironmentId, + ProviderInstanceId, + RunAttemptId, + RunId, + ThreadId, +} from "@t3tools/contracts"; import * as Effect from "effect/Effect"; import { HttpServer } from "effect/http"; import * as NetAddress from "effect/net/NetAddress"; @@ -261,3 +267,66 @@ it.effect.each(["provider-session", "thread", "all"] as const)( expect(yield* registry.resolve(token)).toBeUndefined(); }), ); + +it.effect("carries run and attempt identity on credentials and bounds per-thread retention", () => + Effect.gen(function* () { + const registry = yield* makeRegistry(() => 1_000); + const threadId = ThreadId.make("thread-run-scoped"); + const tokens: Array = []; + + for (let ordinal = 1; ordinal <= 18; ordinal++) { + const runId = RunId.make(`run-${ordinal}`); + const attemptId = RunAttemptId.make(`attempt-${ordinal}`); + const issued = yield* registry.issue({ + threadId, + providerInstanceId: ProviderInstanceId.make("codex"), + capabilities: new Set(), + runId, + attemptId, + }); + expect(issued.config.runId).toBe(runId); + expect(issued.config.attemptId).toBe(attemptId); + tokens.push(issued.config.authorizationHeader.replace(/^Bearer\s+/, "")); + } + + // Oldest credentials beyond the 16-token retention bound are evicted; recent ones stay distinct. + expect(yield* registry.resolve(tokens[0]!)).toBeUndefined(); + expect(yield* registry.resolve(tokens[1]!)).toBeUndefined(); + const keptOldest = yield* registry.resolve(tokens[2]!); + const keptNewest = yield* registry.resolve(tokens[17]!); + expect(keptOldest?.thread.runId).toBe(RunId.make("run-3")); + expect(keptOldest?.thread.attemptId).toBe(RunAttemptId.make("attempt-3")); + expect(keptNewest?.thread.runId).toBe(RunId.make("run-18")); + expect(keptNewest?.thread.attemptId).toBe(RunAttemptId.make("attempt-18")); + + yield* registry.revokeThread(threadId); + expect(yield* registry.resolve(tokens[2]!)).toBeUndefined(); + expect(yield* registry.resolve(tokens[17]!)).toBeUndefined(); + + // Preserving providerSessionId across rotations keeps a stable owner id while revoking per credentialId. + const first = yield* registry.issue({ + threadId, + providerInstanceId: ProviderInstanceId.make("codex"), + runId: RunId.make("run-owner-1"), + }); + const second = yield* registry.issue({ + threadId, + providerInstanceId: ProviderInstanceId.make("codex"), + providerSessionId: first.config.providerSessionId, + runId: RunId.make("run-owner-2"), + }); + expect(second.config.providerSessionId).toBe(first.config.providerSessionId); + expect(second.config.credentialId).toBeDefined(); + expect(second.config.credentialId).not.toBe(first.config.credentialId); + const firstToken = first.config.authorizationHeader.replace(/^Bearer\s+/, ""); + const secondToken = second.config.authorizationHeader.replace(/^Bearer\s+/, ""); + expect((yield* registry.resolve(secondToken))?.thread.providerSessionId).toBe( + first.config.providerSessionId, + ); + yield* registry.revokeCredential(second.config.credentialId!); + expect(yield* registry.resolve(secondToken)).toBeUndefined(); + expect((yield* registry.resolve(firstToken))?.thread.runId).toBe(RunId.make("run-owner-1")); + yield* registry.revokeProviderSession(first.config.providerSessionId); + expect(yield* registry.resolve(firstToken)).toBeUndefined(); + }), +); diff --git a/apps/server/src/mcp/McpSessionRegistry.testkit.ts b/apps/server/src/mcp/McpSessionRegistry.testkit.ts index 0c7822566f9f2..8998d02d7fc6b 100644 --- a/apps/server/src/mcp/McpSessionRegistry.testkit.ts +++ b/apps/server/src/mcp/McpSessionRegistry.testkit.ts @@ -7,12 +7,13 @@ import * as McpSessionRegistry from "./McpSessionRegistry.ts"; export const layer = Layer.succeed( McpSessionRegistry.McpSessionRegistry, McpSessionRegistry.McpSessionRegistry.of({ - issue: ({ threadId, providerInstanceId }) => + issue: ({ threadId, providerInstanceId, providerSessionId }) => Effect.succeed({ config: { environmentId: EnvironmentId.make("environment:mcp-test"), threadId, - providerSessionId: `mcp-test:${threadId}`, + providerSessionId: providerSessionId ?? `mcp-test:${threadId}`, + credentialId: `mcp-test-cred:${threadId}`, providerInstanceId, endpoint: "http://127.0.0.1/mcp", authorizationHeader: `Bearer mcp-test:${threadId}`, @@ -21,6 +22,7 @@ export const layer = Layer.succeed( }), resolve: () => Effect.undefined, touch: () => Effect.void, + revokeCredential: () => Effect.void, revokeProviderSession: () => Effect.void, revokeThread: () => Effect.void, revokeAll: Effect.void, diff --git a/apps/server/src/mcp/McpSessionRegistry.ts b/apps/server/src/mcp/McpSessionRegistry.ts index 9a7142cea3dfa..bd3b6f8a815fb 100644 --- a/apps/server/src/mcp/McpSessionRegistry.ts +++ b/apps/server/src/mcp/McpSessionRegistry.ts @@ -1,4 +1,4 @@ -import { ProviderInstanceId, ThreadId } from "@t3tools/contracts"; +import { ProviderInstanceId, RunAttemptId, RunId, ThreadId } from "@t3tools/contracts"; import * as Clock from "effect/Clock"; import * as Context from "effect/Context"; import * as Digest from "effect/crypto/Digest"; @@ -16,6 +16,10 @@ import * as McpProviderSession from "@t3tools/provider-core/server/mcpSession"; export interface McpCredentialRequest { readonly threadId: ThreadId; readonly providerInstanceId: ProviderInstanceId; + /** Stable session owner id preserved across run rotations on the same provider session. */ + readonly providerSessionId?: string | undefined; + readonly runId?: RunId | undefined; + readonly attemptId?: RunAttemptId | undefined; /** False omits the preview capability wherever the token is honored. Defaults to full access. */ readonly browserToolsAvailable?: boolean; readonly capabilities?: ReadonlySet; @@ -32,6 +36,7 @@ export interface McpSessionRegistryShape { rawToken: string, ) => Effect.Effect; readonly touch: (threadId: ThreadId) => Effect.Effect; + readonly revokeCredential: (credentialId: string) => Effect.Effect; readonly revokeProviderSession: (providerSessionId: string) => Effect.Effect; readonly revokeThread: (threadId: ThreadId) => Effect.Effect; readonly revokeAll: Effect.Effect; @@ -48,6 +53,7 @@ interface AliveMark { } interface CredentialRecord { + readonly credentialId: string; readonly tokenHash: string; readonly scope: McpInvocationContext.McpThreadInvocationScope; readonly lastAlive: AliveMark; @@ -71,6 +77,8 @@ export interface McpSessionRegistryOptions { * refresh the token its subprocess still holds; MCP requests cannot. */ const DEFAULT_LIVENESS_WINDOW_MS = 24 * 60 * 60 * 1_000; +// Bound retained prior-turn tokens per thread when rotating run identity without immediate revocation. +export const MAX_CREDENTIALS_PER_THREAD = 16; const bytesToHex = (bytes: Uint8Array): string => Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join(""); @@ -121,10 +129,14 @@ const makeWithOptions = Effect.fn("McpSessionRegistry.make")(function* ( const issue: McpSessionRegistryShape["issue"] = Effect.fn("McpSessionRegistry.issue")( function* (request) { const issuedAlive = yield* currentAliveMark; - const providerSessionId = yield* random.uuidV4(); + const providerSessionId = request.providerSessionId ?? (yield* random.uuidV4()); + const credentialId = yield* random.uuidV4(); const rawToken = yield* random.randomBytes(32).pipe(Effect.map(tokenFromBytes), Effect.orDie); const tokenHash = yield* hashToken(rawToken); const browserToolsAvailable = request.browserToolsAvailable ?? true; + const runId = request.runId === undefined ? undefined : RunId.make(request.runId); + const attemptId = + request.attemptId === undefined ? undefined : RunAttemptId.make(request.attemptId); const scope: McpInvocationContext.McpThreadInvocationScope = { environmentId, requestNamespace: providerSessionId, @@ -132,6 +144,8 @@ const makeWithOptions = Effect.fn("McpSessionRegistry.make")(function* ( threadId: ThreadId.make(request.threadId), providerSessionId, providerInstanceId: ProviderInstanceId.make(request.providerInstanceId), + ...(runId === undefined ? {} : { runId }), + ...(attemptId === undefined ? {} : { attemptId }), subagent: request.subagent === true, }, client: undefined, @@ -146,7 +160,25 @@ const makeWithOptions = Effect.fn("McpSessionRegistry.make")(function* ( }; yield* SynchronizedRef.update(state, ({ records }) => { const next = new Map(records); - next.set(tokenHash, { tokenHash, scope, lastAlive: issuedAlive, expired: false }); + next.set(tokenHash, { + credentialId, + tokenHash, + scope, + lastAlive: issuedAlive, + expired: false, + }); + let retainedForThread = 0; + const threadTokens: Array = []; + for (const [hash, record] of next) { + if (record.scope.thread.threadId === scope.thread.threadId) { + retainedForThread += 1; + threadTokens.push(hash); + } + } + for (let index = 0; index < retainedForThread - MAX_CREDENTIALS_PER_THREAD; index += 1) { + const evicted = threadTokens[index]; + if (evicted !== undefined) next.delete(evicted); + } return { records: next }; }); return { @@ -154,7 +186,10 @@ const makeWithOptions = Effect.fn("McpSessionRegistry.make")(function* ( environmentId, threadId: scope.thread.threadId, providerSessionId, + credentialId, providerInstanceId: scope.thread.providerInstanceId, + ...(runId === undefined ? {} : { runId }), + ...(attemptId === undefined ? {} : { attemptId }), endpoint, authorizationHeader: `Bearer ${rawToken}`, browserToolsAvailable: scope.capabilities.has("preview"), @@ -208,6 +243,9 @@ const makeWithOptions = Effect.fn("McpSessionRegistry.make")(function* ( issue, resolve, touch, + revokeCredential: Effect.fn("McpSessionRegistry.revokeCredential")(function* (credentialId) { + yield* revokeWhere((record) => record.credentialId === credentialId); + }), revokeProviderSession: Effect.fn("McpSessionRegistry.revokeProviderSession")( function* (providerSessionId) { yield* revokeWhere((record) => record.scope.thread.providerSessionId === providerSessionId); diff --git a/apps/server/src/mcp/toolkits/core.test.ts b/apps/server/src/mcp/toolkits/core.test.ts index 1272f367d439d..00499bf31cf44 100644 --- a/apps/server/src/mcp/toolkits/core.test.ts +++ b/apps/server/src/mcp/toolkits/core.test.ts @@ -13,6 +13,7 @@ import { ProjectId, ProviderDriverKind, ProviderInstanceId, + RunAttemptId, RunId, ScheduledTaskError, ScheduledTask, @@ -1656,3 +1657,119 @@ it.effect( ); }, ); + +it.effect("t3_submit_output forwards caller run and attempt identity and surfaces rejection", () => + Effect.gen(function* () { + const calls: Array<{ + readonly threadId: ThreadId; + readonly json: string; + readonly callerRunId?: RunId | undefined; + readonly callerAttemptId?: RunAttemptId | undefined; + readonly requireCallerRunId?: boolean | undefined; + }> = []; + const runA = RunId.make("run-a"); + const attemptA = RunAttemptId.make("attempt-a"); + const runB = RunId.make("run-b"); + const attemptB = RunAttemptId.make("attempt-b"); + + let rejectNext: string | undefined; + const serverLayer = layerThreadToolkit.pipe( + Layer.provideMerge(McpHttpServer.layerInProcessMcpServer), + Layer.provide(NodeCrypto.layer), + Layer.provide( + Layer.mock(ThreadManagement.ThreadManagementService)({ + getThreadShell: () => Effect.succeed(McpToolAccessTestkit.liveThreadShell(threadId)), + submitRunOutput: (input) => { + calls.push({ + threadId: input.threadId, + json: input.json, + callerRunId: input.callerRunId, + callerAttemptId: input.callerAttemptId, + requireCallerRunId: input.requireCallerRunId, + }); + if (rejectNext !== undefined) { + const problem = rejectNext; + rejectNext = undefined; + return Effect.fail( + new ThreadManagement.ThreadManagementRunOutputRejectedError({ + threadId: input.threadId, + problem, + }), + ); + } + return Effect.succeed({ runId: runB }); + }, + }), + ), + ); + + const callWith = ( + runId: RunId | undefined, + attemptId: RunAttemptId | undefined, + json: string, + ) => + Effect.gen(function* () { + const server = yield* McpServer.McpServer; + const { runId: _r, attemptId: _a, ...baseThread } = scope.thread!; + return yield* server.callTool({ name: "t3_submit_output", arguments: { json } }).pipe( + Effect.provideService(McpInvocationContext.McpInvocationContext, { + ...scope, + thread: { + ...baseThread, + ...(runId === undefined ? {} : { runId }), + ...(attemptId === undefined ? {} : { attemptId }), + }, + }), + Effect.provideService(McpSchema.McpServerClient, client), + ); + }); + + // Unbound MCP callers still pass requireCallerRunId: true and surface service rejections as invalid_request. + rejectNext = "This output was submitted for a turn that is no longer active."; + const unbound = yield* callWith(undefined, undefined, '{"ok":false}').pipe( + Effect.provide(serverLayer), + ); + expect(unbound.isError).toBe(true); + expect(declaredFailure(unbound)).toEqual({ + _tag: "OrchestratorMcpFailure", + code: "invalid_request", + message: "This output was submitted for a turn that is no longer active.", + }); + + rejectNext = "This output was submitted for a turn that is no longer active."; + const stale = yield* callWith(runA, attemptA, '{"ok":false}').pipe(Effect.provide(serverLayer)); + expect(stale.isError).toBe(true); + expect(declaredFailure(stale)).toEqual({ + _tag: "OrchestratorMcpFailure", + code: "invalid_request", + message: "This output was submitted for a turn that is no longer active.", + }); + + const active = yield* callWith(runB, attemptB, '{"ok":true}').pipe(Effect.provide(serverLayer)); + expect(active.isError).toBe(false); + expect(active.structuredContent).toEqual({ runId: runB }); + expect(calls).toEqual([ + { + threadId, + json: '{"ok":false}', + callerRunId: undefined, + callerAttemptId: undefined, + requireCallerRunId: true, + }, + { + threadId, + json: '{"ok":false}', + callerRunId: runA, + callerAttemptId: attemptA, + requireCallerRunId: true, + }, + { + threadId, + json: '{"ok":true}', + callerRunId: runB, + callerAttemptId: attemptB, + requireCallerRunId: true, + }, + ]); + }), +); diff --git a/apps/server/src/mcp/toolkits/thread/handlers.ts b/apps/server/src/mcp/toolkits/thread/handlers.ts index 220ed39eb3c81..258985159b9b4 100644 --- a/apps/server/src/mcp/toolkits/thread/handlers.ts +++ b/apps/server/src/mcp/toolkits/thread/handlers.ts @@ -292,6 +292,11 @@ export const layer = McpToolAccess.toLayer(ThreadToolkit, { threadId: scope.thread.threadId, commandId: yield* newCommandId(), json: input.json, + requireCallerRunId: true, + ...(scope.thread.runId === undefined ? {} : { callerRunId: scope.thread.runId }), + ...(scope.thread.attemptId === undefined + ? {} + : { callerAttemptId: scope.thread.attemptId }), }) .pipe( Effect.mapError((error) => diff --git a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts index 4946377c94502..96f5203049f80 100644 --- a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts @@ -6646,6 +6646,165 @@ describe("AcpAdapterV2", () => { }).pipe(Effect.provide(layerTest)), ); + it.live("refreshes ACP session MCP credentials when the thread token rotates between turns", () => + Effect.gen(function* () { + const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const selfInvocation = yield* resolveSelfInvocation(); + const mockAgentPath = yield* bundledMockAgentPath; + const protocolEvents = yield* Queue.bounded(256); + const instanceId = ProviderInstanceId.make("acp-test-mcp-rotate"); + const threadId = ThreadId.make("thread-acp-mcp-rotate"); + const mcpSessions = yield* McpProviderSessions.McpProviderSessions; + yield* mcpSessions.set({ + environmentId: EnvironmentId.make("environment-acp-mcp-rotate"), + threadId, + providerSessionId: "mcp-session-acp-rotate-1", + providerInstanceId: instanceId, + endpoint: "http://127.0.0.1:43123/mcp", + authorizationHeader: "Bearer acp-run-1-token", + browserToolsAvailable: false, + }); + const adapter = yield* makeAcpAdapterV2({ + instanceId, + flavor: { + driver: ACP_TEST_DRIVER, + capabilities: AcpProviderCapabilitiesV2, + makeRuntime: makeMockRuntime({ + childProcessSpawner, + mockAgentPath, + protocolEvents, + }), + }, + selfInvocation, + clientTerminals: {}, + }); + const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ + runtimeMode: "full-access", + interactionMode: "default", + cwd: process.cwd(), + }); + const modelSelection = { instanceId, model: "default" } as const; + const runtime = yield* adapter.openSession({ + threadId, + providerSessionId: ProviderSessionId.make("provider-session-acp-mcp-rotate"), + modelSelection, + runtimePolicy, + }); + const providerThread = yield* runtime.ensureThread({ + threadId, + modelSelection, + runtimePolicy, + }); + + yield* mcpSessions.set({ + environmentId: EnvironmentId.make("environment-acp-mcp-rotate"), + threadId, + providerSessionId: "mcp-session-acp-rotate-2", + providerInstanceId: instanceId, + endpoint: "http://127.0.0.1:43123/mcp", + authorizationHeader: "Bearer acp-run-2-token", + browserToolsAvailable: false, + }); + yield* runtime.startTurn( + makeTurnInput({ + threadId, + providerThread, + instanceId, + runtimePolicy, + now: yield* DateTime.now, + }), + ); + + const loggedEvents = [...(yield* Queue.takeAll(protocolEvents))]; + const reloadRequestEvent = loggedEvents.find( + (event) => + event.direction === "outgoing" && + (rawProtocolMethod(event) === "session/load" || + rawProtocolMethod(event) === "session/resume"), + ); + assert.isDefined( + reloadRequestEvent, + `expected session/load or session/resume in ${JSON.stringify(loggedEvents.map((e) => `${e.direction}:${rawProtocolMethod(e)}`))}`, + ); + const loadRequest = Option.getOrThrow( + Option.fromNullishOr(rawProtocolRequest(reloadRequestEvent!)), + ); + const mcpServers = ( + loadRequest.params as { + mcpServers?: ReadonlyArray<{ + name?: string; + env?: ReadonlyArray<{ name: string; value: string }>; + }>; + } + ).mcpServers; + const t3Server = mcpServers?.find((server) => server.name === "t3-code"); + assert.isDefined(t3Server); + assert.equal( + t3Server?.env?.find((entry) => entry.name === "T3_ACP_MCP_AUTHORIZATION")?.value, + "Bearer acp-run-2-token", + ); + assert.equal(runtime.mcpCredentialRotation, "reload"); + }).pipe(Effect.provide(layerTest)), + ); + + it.live( + "reports mcpCredentialRotation none for non-loadable ACP agents without MCP-over-ACP", + () => + Effect.gen(function* () { + const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const selfInvocation = yield* resolveSelfInvocation(); + const mockAgentPath = yield* bundledMockAgentPath; + const instanceId = ProviderInstanceId.make("acp-test-mcp-none"); + const threadId = ThreadId.make("thread-acp-mcp-none"); + const adapter = yield* makeAcpAdapterV2({ + instanceId, + flavor: { + driver: ACP_TEST_DRIVER, + capabilities: AcpProviderCapabilitiesV2, + makeRuntime: makeMockRuntime({ + childProcessSpawner, + mockAgentPath, + wrapRuntime: (runtime) => ({ + ...runtime, + start: () => + runtime.start().pipe( + Effect.map((started) => ({ + ...started, + initializeResult: { + ...started.initializeResult, + agentCapabilities: { + ...started.initializeResult.agentCapabilities, + loadSession: false, + sessionCapabilities: {}, + mcpCapabilities: { + ...started.initializeResult.agentCapabilities?.mcpCapabilities, + acp: false, + }, + }, + }, + })), + ), + }), + }), + }, + selfInvocation, + clientTerminals: {}, + }); + const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ + runtimeMode: "full-access", + interactionMode: "default", + cwd: process.cwd(), + }); + const runtime = yield* adapter.openSession({ + threadId, + providerSessionId: ProviderSessionId.make("provider-session-acp-mcp-none"), + modelSelection: { instanceId, model: "default" }, + runtimePolicy, + }); + assert.equal(runtime.mcpCredentialRotation, "none"); + }).pipe(Effect.provide(layerTest)), + ); + it.effect.each([ { label: "grants an ID-only execute approval its tracked command", diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts index e1665b1bafb3e..6ecca5421a958 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts @@ -3755,6 +3755,7 @@ describe("ClaudeAdapterV2 background wake turns", () => { offerAndWait: (message: SDKMessage) => Effect.Effect, ) => Effect.Effect; readonly renameSession?: ClaudeAdapterV2.ClaudeAgentSdkQuerySession["renameSession"]; + readonly setMcpServers?: ClaudeAdapterV2.ClaudeAgentSdkQuerySession["setMcpServers"]; readonly applyFlagSettings?: ClaudeAdapterV2.ClaudeAgentSdkQuerySession["applyFlagSettings"]; readonly stopTask?: ( taskId: string, @@ -3805,6 +3806,7 @@ describe("ClaudeAdapterV2 background wake turns", () => { const permissionModeChanges: Array = []; const renameCalls: Array = []; const liveSelectionChanges: Array = []; + const setMcpServersCalls: Array> = []; const continuationRequests: Array = []; const continuationReceipts = @@ -3945,6 +3947,10 @@ describe("ClaudeAdapterV2 background wake turns", () => { Effect.sync(() => { renameCalls.push(title); }).pipe(Effect.andThen(() => options?.renameSession?.(title) ?? Effect.void)), + setMcpServers: (servers) => + Effect.sync(() => { + setMcpServersCalls.push(servers); + }).pipe(Effect.andThen(() => options?.setMcpServers?.(servers) ?? Effect.void)), backgroundTasks: options?.backgroundTasks ?? (() => Effect.succeed(false)), mcpServerStatus: options?.mcp?.mcpServerStatus ?? Effect.succeed([]), readMcpResource: @@ -4037,6 +4043,7 @@ describe("ClaudeAdapterV2 background wake turns", () => { permissionModeChanges, renameCalls, liveSelectionChanges, + setMcpServersCalls, continuationRequests, continuationReceipts, events, @@ -25244,6 +25251,156 @@ describe("ClaudeAdapterV2 background wake turns", () => { ), ); + it.effect.each([ + { + mode: "live-refresh" as const, + description: + "refreshes MCP servers in place via setMcpServers when only the bearer token rotates", + }, + { + mode: "fallback-replace" as const, + description: + "falls back to replacing the Claude query when live setMcpServers fails on token rotation", + }, + { + mode: "blocked-by-background-work" as const, + description: + "fails explicitly when live setMcpServers fails on token rotation while background work is active", + }, + ])("$description", ({ mode }) => + Effect.gen(function* () { + const mcpSessions = yield* McpProviderSessions.McpProviderSessions; + const harness = + mode === "live-refresh" + ? yield* makeWakeHarness + : yield* makeWakeHarnessWithOptions({ + freshQueueOnReopen: true, + setMcpServers: () => + Effect.fail( + new ClaudeAdapterV2.ClaudeAgentSdkQueryRunnerError({ + method: "setMcpServers", + cause: new Error("setMcpServers rejected"), + }), + ), + }); + const envSlug = `environment-claude-mcp-${mode}`; + yield* mcpSessions.set({ + environmentId: EnvironmentId.make(envSlug), + threadId: harness.threadId, + providerSessionId: `mcp-session-claude-${mode}-1`, + providerInstanceId: ProviderInstanceId.make("claudeAgent"), + endpoint: "http://127.0.0.1:43123/mcp", + authorizationHeader: `Bearer claude-${mode}-run-1`, + browserToolsAvailable: false, + }); + + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now: yield* DateTime.now, + attemptId: RunAttemptId.make(`claude-mcp-${mode}-attempt-1`), + text: "First turn.", + attachments: [], + }), + ); + if (mode === "blocked-by-background-work") { + yield* harness.offerAndWait(wakeTaskStarted); + } + const firstQueue = + mode === "live-refresh" ? harness.sdkMessages : harness.processQueues[0]!; + yield* Queue.offer( + firstQueue, + makeResultFrame({ uuid: `claude-mcp-${mode}-result-1`, result: "Done 1." }), + ); + yield* Queue.take(harness.terminalReceipts); + if (mode === "blocked-by-background-work") { + assert.isTrue(yield* harness.hasPendingBackgroundWork); + } + + yield* mcpSessions.set({ + environmentId: EnvironmentId.make(envSlug), + threadId: harness.threadId, + providerSessionId: `mcp-session-claude-${mode}-2`, + providerInstanceId: ProviderInstanceId.make("claudeAgent"), + endpoint: "http://127.0.0.1:43123/mcp", + authorizationHeader: `Bearer claude-${mode}-run-2`, + browserToolsAvailable: false, + }); + + if (mode === "blocked-by-background-work") { + const rejected = yield* harness.runtime + .startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now: yield* DateTime.now, + attemptId: RunAttemptId.make(`claude-mcp-${mode}-attempt-2`), + text: "Second turn.", + attachments: [], + }), + ) + .pipe(Effect.flip); + assert.instanceOf( + rejected.cause, + ClaudeAdapterV2.ClaudeBackgroundWorkBlocksQueryReplacementError, + ); + assert.equal(harness.processQueues.length, 1); + assert.isTrue(yield* harness.hasPendingBackgroundWork); + return; + } + + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now: yield* DateTime.now, + attemptId: RunAttemptId.make(`claude-mcp-${mode}-attempt-2`), + text: "Second turn.", + attachments: [], + }), + ); + if (mode === "fallback-replace") { + assert.equal(harness.processQueues.length, 2); + yield* Queue.offer( + harness.processQueues[1]!, + makeResultFrame({ uuid: `claude-mcp-${mode}-result-2`, result: "Done 2." }), + ); + yield* Queue.take(harness.terminalReceipts); + assert.equal(harness.setMcpServersCalls.length, 1); + return; + } + + yield* Queue.offer( + harness.sdkMessages, + makeResultFrame({ uuid: `claude-mcp-${mode}-result-2`, result: "Done 2." }), + ); + yield* Queue.take(harness.terminalReceipts); + // Same query stayed alive (only 1 open); MCP auth rotated in place via setMcpServers. + assert.equal(harness.processQueues.length, 1); + assert.deepEqual(harness.setMcpServersCalls, [ + { + "t3-code": { + type: "http", + url: "http://127.0.0.1:43123/mcp", + headers: { Authorization: "Bearer claude-live-refresh-run-2" }, + timeout: 3_900_000, + }, + }, + ]); + }).pipe( + Effect.scoped, + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), + ), + ); + it.effect( "defers goal completion until an ambient subagent finishes and Claude checks again", () => diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts index b120f9feb5e5a..f56c0071ec28e 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts @@ -715,6 +715,9 @@ export interface ClaudeAgentSdkQuerySession { readonly setPermissionMode: ( mode: PermissionMode, ) => Effect.Effect; + readonly setMcpServers?: ( + mcpServers: NonNullable, + ) => Effect.Effect; readonly renameSession: (title: string) => Effect.Effect; readonly stopTask: (taskId: string) => Effect.Effect; readonly backgroundTasks: ( @@ -1890,6 +1893,43 @@ export const layerQueryRunner: Layer.Layer< }), ), ), + setMcpServers: Effect.fn("ClaudeAdapterV2.setMcpServers")(function* (servers) { + // Errors and mcp_status can echo headers; log only server names. + const failed = yield* Effect.tryPromise({ + try: () => queryRuntime.setMcpServers(servers), + catch: (cause) => queryRunnerError(cause, "setMcpServers"), + }).pipe( + Effect.map((result) => Object.keys(result.errors)), + Effect.timeoutOrElse({ + duration: CLAUDE_MCP_REGISTRATION_TIMEOUT, + orElse: () => + Effect.logWarning("orchestration-v2.claude-mcp-registration-timeout", { + threadId: input.threadId, + providerSessionId: input.providerSessionId, + phase: "setMcpServers", + }).pipe( + Effect.andThen( + Effect.fail( + queryRunnerError( + new ClaudeMcpRegistrationTimeoutError({ phase: "setMcpServers" }), + "setMcpServers", + ), + ), + ), + ), + }), + ); + if (failed.length > 0) { + yield* Effect.logWarning("orchestration-v2.claude-mcp-servers-unavailable", { + threadId: input.threadId, + servers: failed, + }); + return yield* queryRunnerError( + new Error(`Claude rejected MCP server update for: ${failed.join(", ")}`), + "setMcpServers", + ); + } + }), renameSession: (title) => Effect.tryPromise({ try: () => @@ -3708,6 +3748,36 @@ export function claudeEffectiveQueryPolicyKey( }); } +function claudeEffectiveQueryPolicyKeyWithoutMcpAuth( + queryPolicy: ClaudeRuntimeQueryPolicy, + mcpOverrides: { + readonly allowedTools?: ReadonlyArray; + readonly mcpServers?: ClaudeQueryOptions["mcpServers"]; + }, + workspace?: ProviderAdapter.ProviderAdapterV2RuntimePolicy["workspace"], +): string { + const sanitizedServers = + mcpOverrides.mcpServers === undefined + ? undefined + : Object.fromEntries( + Object.entries(mcpOverrides.mcpServers).map(([name, server]) => { + if (name === "t3-code" && server.type === "http" && server.headers !== undefined) { + const { Authorization: _authorization, ...restHeaders } = server.headers; + return [name, { ...server, headers: restHeaders }]; + } + return [name, server]; + }), + ); + return claudeEffectiveQueryPolicyKey( + queryPolicy, + { + ...mcpOverrides, + ...(sanitizedServers === undefined ? {} : { mcpServers: sanitizedServers }), + }, + workspace, + ); +} + type ClaudeToolItemType = Extract< OrchestrationV2TurnItem["type"], "command_execution" | "file_change" | "dynamic_tool" | "web_search" @@ -5299,7 +5369,8 @@ interface ClaudeLiveQueryContext { readonly settingsCwd: string | null; readonly launchArgSettings: ClaudeSdkSettings | undefined; readonly query: ClaudeAgentSdkQuerySession; - readonly queryPolicyKey: string; + queryPolicyKey: string; + readonly queryPolicyKeyWithoutMcpAuth: string; selection: CompiledClaudeModelSelection; readonly closed: Deferred.Deferred; lastTurn: ActiveClaudeTurnContext | null; @@ -13123,8 +13194,29 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( mcpOverrides, turnInput.runtimePolicy.workspace, ); + const queryPolicyKeyWithoutMcpAuth = claudeEffectiveQueryPolicyKeyWithoutMcpAuth( + queryPolicy, + mcpOverrides, + turnInput.runtimePolicy.workspace, + ); const resumeSessionAt = yield* getNativeConversationHeadId(turnInput.providerThread); const existing = yield* Ref.get(queryContext); + const canUpdateMcpLive = (candidate: ClaudeLiveQueryContext) => + candidate.queryPolicyKey !== queryPolicyKey && + candidate.queryPolicyKeyWithoutMcpAuth === queryPolicyKeyWithoutMcpAuth && + mcpOverrides.mcpServers !== undefined && + candidate.query.setMcpServers !== undefined; + const syncMcpServersLive = Effect.fnUntraced(function* ( + candidate: ClaudeLiveQueryContext, + ) { + if ( + mcpOverrides.mcpServers === undefined || + candidate.query.setMcpServers === undefined + ) + return; + yield* candidate.query.setMcpServers(mcpOverrides.mcpServers); + candidate.queryPolicyKey = queryPolicyKey; + }); // Continuations drain existing output without prompting; retain the live process regardless of selection. if ( existing !== null && @@ -13134,10 +13226,13 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( ) { return existing; } + const policyCompatible = + existing !== null && + (existing.queryPolicyKey === queryPolicyKey || canUpdateMcpLive(existing)); const reuseLaunchSettings = existing !== null && existing.nativeThreadId === nativeThreadId && - existing.queryPolicyKey === queryPolicyKey && + policyCompatible && !existing.stopping; const readLaunchSettings = readClaudeLaunchArgSettings({ settings: adapterOptions.settings, @@ -13158,7 +13253,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( !turnInput.resume && existing !== null && existing.nativeThreadId === nativeThreadId && - existing.queryPolicyKey === queryPolicyKey && + policyCompatible && !existing.stopping && existing.selection.queryIdentity !== compiledSelection.queryIdentity && canApplyClaudeSelectionLive(existing.selection, compiledSelection) && @@ -13171,28 +13266,44 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( !turnInput.resume && existing !== null && existing.nativeThreadId === nativeThreadId && - existing.queryPolicyKey === queryPolicyKey && + policyCompatible && !existing.stopping && existing.selection.queryIdentity === compiledSelection.queryIdentity ) { - // A denied ExitPlanMode leaves Claude in plan mode. Restore only from plan: - // Auto/default may reflect a policy restriction that forbids restoring bypass. - if (existing.permissionMode === "plan" && existing.openedPermissionMode !== "plan") { - existing.permissionMode = yield* existing.query - .setPermissionMode(existing.openedPermissionMode) - .pipe( - Effect.as(existing.openedPermissionMode), - Effect.catchTags({ - ClaudeAgentSdkQueryRunnerError: (error) => - existing.openedPermissionMode === "bypassPermissions" - ? existing.query - .setPermissionMode("default") - .pipe(Effect.as("default" as const)) - : Effect.fail(error), - }), - ); + const mcpRefreshed = canUpdateMcpLive(existing) + ? yield* syncMcpServersLive(existing).pipe( + Effect.as(true), + Effect.catchCauseIf( + (cause) => !Cause.hasInterruptsOnly(cause), + () => + // SDK errors can echo MCP headers; log only the failure category. + Effect.logWarning("orchestration-v2.claude-live-mcp-refresh-failed", { + threadId: turnInput.threadId, + reason: "failed", + }).pipe(Effect.as(false)), + ), + ) + : true; + if (mcpRefreshed) { + // A denied ExitPlanMode leaves Claude in plan mode. Restore only from plan: + // Auto/default may reflect a policy restriction that forbids restoring bypass. + if (existing.permissionMode === "plan" && existing.openedPermissionMode !== "plan") { + existing.permissionMode = yield* existing.query + .setPermissionMode(existing.openedPermissionMode) + .pipe( + Effect.as(existing.openedPermissionMode), + Effect.catchTags({ + ClaudeAgentSdkQueryRunnerError: (error) => + existing.openedPermissionMode === "bypassPermissions" + ? existing.query + .setPermissionMode("default") + .pipe(Effect.as("default" as const)) + : Effect.fail(error), + }), + ); + } + return existing; } - return existing; } // Replacing this thread's process kills its background work, even with a new native identity. @@ -13347,6 +13458,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( launchArgSettings, query: querySession, queryPolicyKey, + queryPolicyKeyWithoutMcpAuth, selection: compiledSelection, closed, lastTurn: null, @@ -14367,6 +14479,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( driver: CLAUDE_PROVIDER, providerSessionId: input.providerSessionId, providerSession: session, + mcpCredentialRotation: "live", getModelContextWindow: (selection) => claudeContextWindow(selection) ?? undefined, events: Stream.fromEffectRepeat(Queue.take(events)), backgroundTasksEndWithProcess: true, diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts index cd5e51a32f616..af2f71ca0b62a 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts @@ -2550,6 +2550,184 @@ describe("CodexAdapterV2 post-settle continuation", () => { ), ); + it.effect("applies a rotated MCP bearer token when a Codex thread is unloaded and resumed", () => + Effect.gen(function* () { + const scenario = "rotate-mcp-servers"; + const nativeThreadId = "rotate-mcp-thread"; + const threadId = ThreadId.make(`thread-${scenario}`); + const mcpSessions = yield* McpProviderSessions.McpProviderSessions; + yield* mcpSessions.set({ + environmentId: EnvironmentId.make("environment-codex-mcp-rotate"), + threadId, + providerSessionId: "provider-session-rotate-1", + providerInstanceId: ProviderInstanceId.make("codex"), + endpoint: "http://127.0.0.1:43123/mcp", + authorizationHeader: "Bearer codex-run-1-token", + browserToolsAvailable: false, + }); + const resumedConfigs: Array = []; + const preamble = codexReplayPreamble({ + nativeThreadId, + nativeTurnId: "rotate-turn-2", + prompt: "Second turn", + }); + const turn2Params = yield* CodexAdapterV2.buildCodexTurnStartParams({ + nativeThreadId, + codexInput: [{ type: "text", text: "Second turn" }], + runtimePolicy: CODEX_TEST_RUNTIME_POLICY, + modelSelection: CODEX_TEST_MODEL_SELECTION, + hasT3Mcp: true, + browserToolsAvailable: false, + }); + const harness = yield* makeCodexReplayHarness( + makeCodexReplayTranscript({ + scenario, + entries: [ + ...preamble.slice(0, 3), + { + type: "expect_outbound", + label: "config/read initial", + frame: { id: 2, method: "config/read", params: { includeLayers: false } }, + }, + { + type: "emit_inbound", + label: "config/read initial", + frame: { id: 2, result: { config: {}, origins: {} } }, + }, + ...preamble.slice(3, 5).map((entry) => withReplayRequestId(entry, 3)), + { + type: "expect_outbound", + label: "thread/unsubscribe on MCP rotation", + frame: { + id: 4, + method: "thread/unsubscribe", + params: { threadId: nativeThreadId }, + }, + }, + { + type: "emit_inbound", + label: "thread/unsubscribe result", + frame: { id: 4, result: { status: "unsubscribed" } }, + }, + { + type: "expect_outbound", + label: "config/read reload", + frame: { id: 5, method: "config/read", params: { includeLayers: false } }, + }, + { + type: "emit_inbound", + label: "config/read reload", + frame: { id: 5, result: { config: {}, origins: {} } }, + }, + { + type: "expect_outbound", + label: "thread/resume with rotated token", + frame: { + id: 6, + method: "thread/resume", + params: { + threadId: nativeThreadId, + cwd: "/workspace", + model: "gpt-5.4", + excludeTurns: true, + config: { + "tools.update_plan.enabled": true, + mcp_optional_startup_grace_ms: 10_000, + "features.concurrent_reasoning_summaries": true, + "shell_environment_policy.set.T3CODE_THREAD_ID": threadId, + "mcp_servers.t3-code": { + url: "http://127.0.0.1:43123/mcp", + tool_timeout_sec: 3_900, + http_headers: { Authorization: "Bearer codex-run-2-token" }, + disabled_tools: ["t3_thread_wait", "delegate_task"], + }, + "mcp_servers.t3-code-direct": { + url: "http://127.0.0.1:43123/mcp", + tool_timeout_sec: 3_900, + http_headers: { Authorization: "Bearer codex-run-2-token" }, + enabled_tools: ["t3_thread_wait", "delegate_task"], + omit_tools_from: ["code_mode", "deferred"], + }, + }, + }, + }, + }, + { + type: "emit_inbound", + label: "thread/resume result", + frame: { + id: 6, + result: { thread: { id: nativeThreadId, updatedAt: 1782622450, turns: [] } }, + }, + }, + { + type: "expect_outbound", + label: "thread/name/set before turn", + frame: { + id: 7, + method: "thread/name/set", + params: { threadId: nativeThreadId, name: "Codex continuation test" }, + }, + }, + { + type: "emit_inbound", + label: "thread/name/set result", + frame: { id: 7, result: {} }, + }, + { + type: "expect_outbound", + label: "turn/start", + frame: { id: 8, method: "turn/start", params: turn2Params }, + }, + ...preamble.slice(6).map((entry) => withReplayRequestId(entry, 8)), + ], + }), + () => Effect.void, + (method, params) => + Effect.sync(() => { + if (method === "thread/resume") resumedConfigs.push(params); + }), + ); + + yield* mcpSessions.set({ + environmentId: EnvironmentId.make("environment-codex-mcp-rotate"), + threadId, + providerSessionId: "provider-session-rotate-2", + providerInstanceId: ProviderInstanceId.make("codex"), + endpoint: "http://127.0.0.1:43123/mcp", + authorizationHeader: "Bearer codex-run-2-token", + browserToolsAvailable: false, + }); + yield* harness.runtime.unloadThread!({ providerThread: harness.providerThread }); + const resumedThread = yield* harness.runtime.resumeThread({ + threadId, + providerThread: harness.providerThread, + modelSelection: CODEX_TEST_MODEL_SELECTION, + runtimePolicy: CODEX_TEST_RUNTIME_POLICY, + }); + yield* harness.runtime.startTurn( + makeCodexTestTurnInput({ + threadId, + providerThread: resumedThread, + now: yield* DateTime.now, + attemptId: RunAttemptId.make("codex-rotate-attempt-2"), + text: "Second turn", + }), + ); + assert.equal(resumedConfigs.length, 1); + }).pipe( + Effect.scoped, + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), + ), + ); + // regression: #36520 MCP servers can tell a delegate_task child from a user thread it.effect("starts delegate_task children with the subagent thread source", () => Effect.gen(function* () { diff --git a/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts index 88563aeb43492..27cb9b3687854 100644 --- a/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts @@ -5486,6 +5486,73 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { }), ); + it.effect("removes and re-registers T3 MCP when its bearer token rotates between turns", () => + Effect.gen(function* () { + const mcpSessions = yield* McpProviderSessions.McpProviderSessions; + yield* mcpSessions.set({ + environmentId: EnvironmentId.make("environment:opencode2-adapter"), + threadId, + providerSessionId: "mcp:opencode2-rotate-1", + providerInstanceId: instanceId, + endpoint: "http://127.0.0.1:3773/mcp", + authorizationHeader: "Bearer opencode2-run-1", + browserToolsAvailable: false, + }); + yield* Effect.addFinalizer(() => mcpSessions.clear(threadId)); + const server = "t3-code-thread_opencode2-adapter"; + const addFor = (authorization: string) => + out("mcp.add", { + server, + "location[directory]": WORK, + config: { + type: "remote", + url: "http://127.0.0.1:3773/mcp", + headers: { Authorization: authorization }, + oauth: false, + }, + }); + const turn = [ + out("session.prompt", { sessionID: SESSION, text: "" }), + promptAccepted, + event("session.execution.succeeded", { sessionID: SESSION }), + ]; + const { runtime, thread } = yield* resumed([ + addFor("Bearer opencode2-run-1"), + reply("mcp.add", null), + ...turn, + out("mcp.remove", { server, "location[directory]": WORK }), + reply("mcp.remove", null), + addFor("Bearer opencode2-run-2"), + reply("mcp.add", null), + ...turn, + out("mcp.remove", { server, "location[directory]": WORK }), + reply("mcp.remove", null), + ]); + assert.equal(runtime.mcpCredentialRotation, "live"); + + const firstTerminal = yield* terminalOf(runtime).pipe(Effect.forkScoped); + const firstStarted = yield* runtime.startTurn(turnInput(thread)).pipe(Effect.forkScoped); + yield* TestClock.adjust("250 millis"); + yield* Fiber.join(firstStarted); + assert.equal((yield* Fiber.join(firstTerminal))?.status, "completed"); + + yield* mcpSessions.set({ + environmentId: EnvironmentId.make("environment:opencode2-adapter"), + threadId, + providerSessionId: "mcp:opencode2-rotate-2", + providerInstanceId: instanceId, + endpoint: "http://127.0.0.1:3773/mcp", + authorizationHeader: "Bearer opencode2-run-2", + browserToolsAvailable: false, + }); + const secondTerminal = yield* terminalOf(runtime).pipe(Effect.forkScoped); + const secondStarted = yield* runtime.startTurn(turnInput(thread)).pipe(Effect.forkScoped); + yield* TestClock.adjust("250 millis"); + yield* Fiber.join(secondStarted); + assert.equal((yield* Fiber.join(secondTerminal))?.status, "completed"); + }), + ); + it.effect("registers a long thread id's MCP server under a name OpenCode accepts", () => Effect.gen(function* () { const child = ThreadId.make( diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 00939843c13f1..11012b4a06be8 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -222,6 +222,18 @@ const isMessageQuestionAnswer = Schema.is( Schema.Union([TrimmedNonEmptyString, Schema.NonEmptyArray(TrimmedNonEmptyString)]), ); +export class RunOutputDispatchRejectionError extends Schema.TaggedError()( + "RunOutputDispatchRejectionError", + { + reason: Schema.Literals(["stale_caller", "stopped", "inactive"]), + detail: Schema.String, + }, +) { + override get message(): string { + return this.detail; + } +} + export class OrchestratorDispatchError extends Schema.TaggedError()( "OrchestratorDispatchError", { @@ -12158,15 +12170,58 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio return yield* new OrchestratorDispatchError({ commandId: command.commandId, commandType: command.type, - cause: `Run ${command.runId} is ${run.status} and takes no result.`, + cause: new RunOutputDispatchRejectionError({ + reason: "inactive", + detail: `Run ${command.runId} is ${run.status} and takes no result.`, + }), }); } + if (command.callerRunId !== undefined || command.callerAttemptId !== undefined) { + const active = projection.runs + .filter(isActiveRun) + .toSorted((left, right) => right.ordinal - left.ordinal)[0]; + const matchesRun = (candidate: OrchestrationV2Run | undefined) => + candidate !== undefined && + (command.callerRunId === undefined || candidate.id === command.callerRunId) && + (command.callerAttemptId === undefined || + candidate.activeAttemptId === command.callerAttemptId); + const callerAllowed = + (active !== undefined && matchesRun(active)) || (owes && matchesRun(run)); + if (!callerAllowed) { + return yield* new OrchestratorDispatchError({ + commandId: command.commandId, + commandType: command.type, + cause: new RunOutputDispatchRejectionError({ + reason: "stale_caller", + detail: `Caller run ${command.callerRunId ?? "unknown"} is no longer active on thread ${command.threadId}.`, + }), + }); + } + if ( + active !== undefined && + active.id !== run.id && + matchesRun(active) && + (yield* stopReachedRun(command, command.threadId, active.id)) + ) { + return yield* new OrchestratorDispatchError({ + commandId: command.commandId, + commandType: command.type, + cause: new RunOutputDispatchRejectionError({ + reason: "stopped", + detail: `Run ${active.id} was stopped and takes no result.`, + }), + }); + } + } // A stopped run stays active until its provider settles; what it submits then is not kept. if (yield* stopReachedRun(command, command.threadId, run.id)) { return yield* new OrchestratorDispatchError({ commandId: command.commandId, commandType: command.type, - cause: `Run ${command.runId} was stopped and takes no result.`, + cause: new RunOutputDispatchRejectionError({ + reason: "stopped", + detail: `Run ${command.runId} was stopped and takes no result.`, + }), }); } const now = yield* DateTime.now; diff --git a/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts b/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts index fcee608e3013f..8a710a7ad9748 100644 --- a/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts +++ b/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts @@ -7,6 +7,7 @@ import { EnvironmentId, MessageId, type ModelSelection, + NodeId, type OrchestrationV2AppThread, type OrchestrationV2DomainEvent, type OrchestrationV2PromptSuggestion, @@ -20,6 +21,7 @@ import { ProviderDriverKind, ProviderInstanceId, type ProviderSessionId, + RunAttemptId, RunId, ThreadId, TurnItemId, @@ -479,6 +481,7 @@ const makeProviderAdapter = Effect.fnUntraced(function* ( readonly mcpConfigs?: Ref.Ref< ReadonlyArray >; + readonly mcpCredentialRotation?: "live" | "reload" | "none"; readonly beforeOpen?: (input: { readonly providerSessionId: ProviderSessionId; readonly initialProviderItemIdentityVersion?: 2; @@ -567,6 +570,9 @@ const makeProviderAdapter = Effect.fnUntraced(function* ( instanceId: ProviderInstanceId.make("codex"), driver: CODEX_DRIVER, providerSessionId: input.providerSessionId, + ...(options.mcpCredentialRotation === undefined + ? {} + : { mcpCredentialRotation: options.mcpCredentialRotation }), ...(options.normalizeThreadLoadModelSelection === undefined ? {} : { normalizeThreadLoadModelSelection: options.normalizeThreadLoadModelSelection }), @@ -658,6 +664,7 @@ function layerTest(input: { readonly mcpConfigs?: Ref.Ref< ReadonlyArray >; + readonly mcpCredentialRotation?: "live" | "reload" | "none"; readonly beforeOpen?: (input: { readonly providerSessionId: ProviderSessionId; readonly initialProviderItemIdentityVersion?: 2; @@ -714,6 +721,9 @@ function layerTest(input: { ? {} : { extensionStatuses: input.extensionStatuses }), ...(input.mcpConfigs === undefined ? {} : { mcpConfigs: input.mcpConfigs }), + ...(input.mcpCredentialRotation === undefined + ? {} + : { mcpCredentialRotation: input.mcpCredentialRotation }), ...(input.beforeOpen === undefined ? {} : { beforeOpen: input.beforeOpen }), ...(input.hasPendingBackgroundWork === undefined ? {} @@ -3280,6 +3290,689 @@ it.effect("ProviderSessionManagerV2 terminal detach revokes the thread's MCP cre }), ); +it.effect.each([ + { + scenario: "live" as const, + description: + "ProviderSessionManagerV2 rotates run-scoped MCP credentials per turn for live-update runtimes and revokes all on close", + }, + { + scenario: "none" as const, + description: + "ProviderSessionManagerV2 fails explicitly instead of mutating non-rotatable credentials on a second typed run", + }, + { + scenario: "reload-blocked" as const, + description: + "ProviderSessionManagerV2 fails reload explicitly without unloading or mutating the loaded token when background work is active", + }, + { + scenario: "reload-when-required" as const, + description: + "ProviderSessionManagerV2 reloads a shared runtime thread on MCP rotation only when run-scoped MCP is required", + }, +])("$description", ({ scenario }) => + Effect.gen(function* () { + const state = yield* Ref.make(emptyState); + if (scenario === "live") { + const effect = Effect.gen(function* () { + const eventSink = yield* EventSink.EventSinkV2; + const idAllocator = yield* IdAllocator.IdAllocatorV2; + const manager = yield* ProviderSessionManager.ProviderSessionManagerV2; + const registry = yield* McpSessionRegistry.McpSessionRegistry; + const mcpSessions = yield* McpProviderSessions.McpProviderSessions; + const now = yield* DateTime.now; + const threadId = ThreadId.make("thread-provider-session-manager-live-rotate"); + const providerSessionId = yield* idAllocator.allocate.providerSession({ + providerInstanceId: modelSelection.instanceId, + threadId, + }); + yield* eventSink.write({ + events: [yield* makeThreadCreatedEvent({ idAllocator, threadId, now })], + }); + + const run1 = RunId.make("run-live-1"); + const attempt1 = RunAttemptId.make("attempt-live-1"); + yield* manager.open({ + threadId, + providerSessionId, + modelSelection, + runtimePolicy, + runId: run1, + attemptId: attempt1, + requireRunScopedMcp: true, + }); + const config1 = yield* mcpSessions.read(threadId); + assert.isDefined(config1); + const token1 = config1!.authorizationHeader.replace(/^Bearer\s+/, ""); + assert.equal((yield* registry.resolve(token1))?.thread.runId, run1); + assert.equal((yield* registry.resolve(token1))?.thread.attemptId, attempt1); + + // Plain turns skip rotation to avoid unnecessary reconnect churn. + yield* manager.open({ + threadId, + providerSessionId, + modelSelection, + runtimePolicy, + runId: RunId.make("run-live-plain"), + attemptId: RunAttemptId.make("attempt-live-plain"), + requireRunScopedMcp: false, + }); + assert.equal( + (yield* mcpSessions.read(threadId))?.authorizationHeader, + config1!.authorizationHeader, + ); + + const run2 = RunId.make("run-live-2"); + const attempt2 = RunAttemptId.make("attempt-live-2"); + yield* manager.open({ + threadId, + providerSessionId, + modelSelection, + runtimePolicy, + runId: run2, + attemptId: attempt2, + requireRunScopedMcp: true, + }); + const config2 = yield* mcpSessions.read(threadId); + assert.isDefined(config2); + const token2 = config2!.authorizationHeader.replace(/^Bearer\s+/, ""); + assert.notEqual(token2, token1); + assert.equal(config2!.providerSessionId, config1!.providerSessionId); + assert.notEqual(config2!.credentialId, config1!.credentialId); + // Prior run token stays resolvable with its original run identity so late calls get a clean rejection. + assert.equal((yield* registry.resolve(token1))?.thread.runId, run1); + assert.equal((yield* registry.resolve(token2))?.thread.runId, run2); + assert.equal((yield* registry.resolve(token2))?.thread.attemptId, attempt2); + assert.equal( + (yield* registry.resolve(token2))?.thread.providerSessionId, + config1!.providerSessionId, + ); + + yield* manager.close(providerSessionId); + assert.isUndefined(yield* registry.resolve(token1)); + assert.isUndefined(yield* registry.resolve(token2)); + }); + + yield* effect.pipe( + Effect.provide( + layerTest({ + state, + idleTimeoutMs: 1_000, + mcpCredentialRotation: "live", + }), + ), + ); + return; + } + + if (scenario === "none") { + const effect = Effect.gen(function* () { + const eventSink = yield* EventSink.EventSinkV2; + const idAllocator = yield* IdAllocator.IdAllocatorV2; + const manager = yield* ProviderSessionManager.ProviderSessionManagerV2; + const registry = yield* McpSessionRegistry.McpSessionRegistry; + const mcpSessions = yield* McpProviderSessions.McpProviderSessions; + const now = yield* DateTime.now; + const threadId = ThreadId.make("thread-provider-session-manager-no-rotation"); + const providerSessionId = yield* idAllocator.allocate.providerSession({ + providerInstanceId: modelSelection.instanceId, + threadId, + }); + const run1 = RunId.make("run-none-1"); + const run2 = RunId.make("run-none-2"); + const run3 = RunId.make("run-none-3"); + const rootNode1 = NodeId.make("node-none-1"); + const providerThread = makeProviderThread({ + idAllocator, + threadId, + providerSessionId, + now, + }); + yield* eventSink.write({ + events: [ + yield* makeThreadCreatedEvent({ idAllocator, threadId, now }), + { + id: yield* idAllocator.allocate.event({ threadId }), + type: "run.created", + threadId, + runId: run1, + nodeId: rootNode1, + driver: CODEX_DRIVER, + occurredAt: now, + payload: { + id: run1, + threadId, + ordinal: 1, + providerInstanceId: modelSelection.instanceId, + modelSelection, + providerThreadId: providerThread.id, + userMessageId: MessageId.make("msg-none-1"), + rootNodeId: rootNode1, + activeAttemptId: RunAttemptId.make("attempt-none-1"), + status: "completed", + requestedAt: now, + startedAt: now, + completedAt: now, + checkpointId: null, + contextHandoffId: null, + outputSchema: { type: "object" }, + }, + }, + ], + }); + + yield* manager.open({ + threadId, + providerSessionId, + modelSelection, + runtimePolicy, + runId: run1, + attemptId: RunAttemptId.make("attempt-none-1"), + requireRunScopedMcp: true, + }); + const config1 = yield* mcpSessions.read(threadId); + assert.isDefined(config1); + const token1 = config1!.authorizationHeader.replace(/^Bearer\s+/, ""); + assert.equal((yield* registry.resolve(token1))?.thread.runId, run1); + + // Plain turns and owed wakes for run1 succeed without rotating or mutating token1. + yield* manager.open({ + threadId, + providerSessionId, + modelSelection, + runtimePolicy, + runId: run2, + attemptId: RunAttemptId.make("attempt-none-2"), + requireRunScopedMcp: false, + }); + assert.equal( + (yield* mcpSessions.read(threadId))?.authorizationHeader, + config1!.authorizationHeader, + ); + assert.equal((yield* registry.resolve(token1))?.thread.runId, run1); + + // A second typed run requires a new run-bound token, which a non-rotatable runtime cannot deliver. + const rejected = yield* manager + .open({ + threadId, + providerSessionId, + modelSelection, + runtimePolicy, + runId: run3, + attemptId: RunAttemptId.make("attempt-none-3"), + requireRunScopedMcp: true, + }) + .pipe(Effect.flip); + assert.equal(rejected._tag, "ProviderSessionOpenError"); + assert.equal((yield* registry.resolve(token1))?.thread.runId, run1); + assert.equal( + (yield* mcpSessions.read(threadId))?.authorizationHeader, + config1!.authorizationHeader, + ); + yield* manager.close(providerSessionId); + }); + + yield* effect.pipe( + Effect.provide( + layerTest({ + state, + idleTimeoutMs: 1_000, + mcpCredentialRotation: "none", + }), + ), + ); + return; + } + + if (scenario === "reload-blocked") { + const unloads = yield* Queue.unbounded(); + const pendingBackgroundWork = yield* Ref.make(true); + const effect = Effect.gen(function* () { + const eventSink = yield* EventSink.EventSinkV2; + const idAllocator = yield* IdAllocator.IdAllocatorV2; + const manager = yield* ProviderSessionManager.ProviderSessionManagerV2; + const registry = yield* McpSessionRegistry.McpSessionRegistry; + const mcpSessions = yield* McpProviderSessions.McpProviderSessions; + const now = yield* DateTime.now; + const threadId = ThreadId.make("thread-provider-session-manager-bg-no-unload"); + const providerSessionId = yield* idAllocator.allocate.providerSession({ + providerInstanceId: modelSelection.instanceId, + threadId, + }); + const run1 = RunId.make("run-bg-1"); + const run2 = RunId.make("run-bg-2"); + const attempt1 = RunAttemptId.make("attempt-bg-1"); + const attempt2 = RunAttemptId.make("attempt-bg-2"); + const rootNode1 = NodeId.make("node-bg-1"); + const providerThread = makeProviderThread({ + idAllocator, + threadId, + providerSessionId, + now, + }); + yield* eventSink.write({ + events: [ + yield* makeThreadCreatedEvent({ idAllocator, threadId, now }), + { + id: yield* idAllocator.allocate.event({ threadId }), + type: "run.created", + threadId, + runId: run1, + nodeId: rootNode1, + driver: CODEX_DRIVER, + occurredAt: now, + payload: { + id: run1, + threadId, + ordinal: 1, + providerInstanceId: modelSelection.instanceId, + modelSelection, + providerThreadId: providerThread.id, + userMessageId: MessageId.make("msg-bg-1"), + rootNodeId: rootNode1, + activeAttemptId: attempt1, + status: "completed", + requestedAt: now, + startedAt: now, + completedAt: now, + checkpointId: null, + contextHandoffId: null, + }, + }, + ], + }); + const runtime = yield* manager.open({ + threadId, + providerSessionId, + modelSelection, + runtimePolicy, + runId: run1, + attemptId: attempt1, + requireRunScopedMcp: true, + }); + const loadedConfig = yield* mcpSessions.read(threadId); + assert.isDefined(loadedConfig); + const loadedToken = loadedConfig!.authorizationHeader.replace(/^Bearer\s+/, ""); + yield* runtime.resumeThread({ + threadId, + providerThread, + modelSelection, + runtimePolicy, + }); + yield* manager.open({ + threadId, + providerSessionId, + modelSelection, + runtimePolicy, + runId: run2, + attemptId: attempt2, + requireRunScopedMcp: true, + }); + const rotatedConfig = yield* mcpSessions.read(threadId); + assert.isDefined(rotatedConfig); + const rotatedToken = rotatedConfig!.authorizationHeader.replace(/^Bearer\s+/, ""); + assert.notEqual(rotatedToken, loadedToken); + + const failed = yield* runtime + .resumeThread({ + threadId, + providerThread, + modelSelection, + runtimePolicy, + }) + .pipe(Effect.flip); + assert.equal(failed._tag, "ProviderAdapterMcpRotationBlockedError"); + // Background work stayed alive (no unload), loaded token identity stayed immutable, and unused token was revoked. + assert.isTrue(Option.isNone(yield* Queue.poll(unloads))); + const resolvedLoaded = yield* registry.resolve(loadedToken); + assert.equal(resolvedLoaded?.thread.runId, run1); + assert.equal(resolvedLoaded?.thread.attemptId, attempt1); + assert.isUndefined(yield* registry.resolve(rotatedToken)); + assert.equal( + (yield* mcpSessions.read(threadId))?.authorizationHeader, + loadedConfig!.authorizationHeader, + ); + + // Also cover a thread initially attached to the shared session with an unbound (run-less) bearer: + // rolling back on blocked reload must keep that run-less bearer valid for running background work. + const unboundThreadId = ThreadId.make("thread-provider-session-manager-bg-unbound"); + const unboundProviderThread = makeProviderThread({ + idAllocator, + threadId: unboundThreadId, + providerSessionId, + now, + }); + yield* eventSink.write({ + events: [yield* makeThreadCreatedEvent({ idAllocator, threadId: unboundThreadId, now })], + }); + yield* manager.open({ + threadId: unboundThreadId, + providerSessionId, + modelSelection, + runtimePolicy, + }); + const unboundLoadedConfig = yield* mcpSessions.read(unboundThreadId); + assert.isDefined(unboundLoadedConfig); + assert.isUndefined(unboundLoadedConfig!.runId); + const unboundLoadedToken = unboundLoadedConfig!.authorizationHeader.replace( + /^Bearer\s+/, + "", + ); + yield* runtime.resumeThread({ + threadId: unboundThreadId, + providerThread: unboundProviderThread, + modelSelection, + runtimePolicy, + }); + yield* manager.open({ + threadId: unboundThreadId, + providerSessionId, + modelSelection, + runtimePolicy, + runId: RunId.make("run-bg-unbound-typed"), + attemptId: RunAttemptId.make("attempt-bg-unbound-typed"), + requireRunScopedMcp: true, + }); + const unboundRotatedConfig = yield* mcpSessions.read(unboundThreadId); + assert.isDefined(unboundRotatedConfig); + const unboundRotatedToken = unboundRotatedConfig!.authorizationHeader.replace( + /^Bearer\s+/, + "", + ); + assert.notEqual(unboundRotatedToken, unboundLoadedToken); + + const unboundFailed = yield* runtime + .resumeThread({ + threadId: unboundThreadId, + providerThread: unboundProviderThread, + modelSelection, + runtimePolicy, + }) + .pipe(Effect.flip); + assert.equal(unboundFailed._tag, "ProviderAdapterMcpRotationBlockedError"); + assert.isTrue(Option.isNone(yield* Queue.poll(unloads))); + const resolvedUnboundLoaded = yield* registry.resolve(unboundLoadedToken); + assert.isDefined(resolvedUnboundLoaded); + assert.isUndefined(resolvedUnboundLoaded?.thread.runId); + assert.isUndefined(yield* registry.resolve(unboundRotatedToken)); + assert.equal( + (yield* mcpSessions.read(unboundThreadId))?.authorizationHeader, + unboundLoadedConfig!.authorizationHeader, + ); + + // Enabling browser access (capability widening) before a blocked typed turn keeps the narrower + // loaded bearer valid on rollback, whereas disabling browser access (capability removal) revokes it. + const settings = yield* ServerSettings.ServerSettingsService; + yield* settings.updateSettings({ enableAgentBrowserAccess: false }); + const widenedThreadId = ThreadId.make("thread-provider-session-manager-bg-widened"); + const widenedProviderThread = makeProviderThread({ + idAllocator, + threadId: widenedThreadId, + providerSessionId, + now, + }); + yield* eventSink.write({ + events: [yield* makeThreadCreatedEvent({ idAllocator, threadId: widenedThreadId, now })], + }); + yield* manager.open({ + threadId: widenedThreadId, + providerSessionId, + modelSelection, + runtimePolicy, + }); + const narrowLoadedConfig = yield* mcpSessions.read(widenedThreadId); + assert.isDefined(narrowLoadedConfig); + assert.isFalse(narrowLoadedConfig!.browserToolsAvailable); + const narrowLoadedToken = narrowLoadedConfig!.authorizationHeader.replace(/^Bearer\s+/, ""); + yield* runtime.resumeThread({ + threadId: widenedThreadId, + providerThread: widenedProviderThread, + modelSelection, + runtimePolicy, + }); + yield* settings.updateSettings({ enableAgentBrowserAccess: true }); + yield* manager.open({ + threadId: widenedThreadId, + providerSessionId, + modelSelection, + runtimePolicy, + runId: RunId.make("run-bg-widened-typed"), + attemptId: RunAttemptId.make("attempt-bg-widened-typed"), + requireRunScopedMcp: true, + }); + const widerRotatedConfig = yield* mcpSessions.read(widenedThreadId); + assert.isDefined(widerRotatedConfig); + assert.isTrue(widerRotatedConfig!.browserToolsAvailable); + const widerRotatedToken = widerRotatedConfig!.authorizationHeader.replace(/^Bearer\s+/, ""); + const widenedFailed = yield* runtime + .resumeThread({ + threadId: widenedThreadId, + providerThread: widenedProviderThread, + modelSelection, + runtimePolicy, + }) + .pipe(Effect.flip); + assert.equal(widenedFailed._tag, "ProviderAdapterMcpRotationBlockedError"); + const resolvedNarrow = yield* registry.resolve(narrowLoadedToken); + assert.isDefined(resolvedNarrow); + assert.isFalse(resolvedNarrow!.capabilities.has("preview")); + assert.isUndefined(yield* registry.resolve(widerRotatedToken)); + assert.equal( + (yield* mcpSessions.read(widenedThreadId))?.authorizationHeader, + narrowLoadedConfig!.authorizationHeader, + ); + + // Capability removal revokes the previously wider bearer immediately and does not restore a dead token. + const narrowedThreadId = ThreadId.make("thread-provider-session-manager-bg-narrowed"); + const narrowedProviderThread = makeProviderThread({ + idAllocator, + threadId: narrowedThreadId, + providerSessionId, + now, + }); + yield* eventSink.write({ + events: [yield* makeThreadCreatedEvent({ idAllocator, threadId: narrowedThreadId, now })], + }); + yield* manager.open({ + threadId: narrowedThreadId, + providerSessionId, + modelSelection, + runtimePolicy, + }); + const broadLoadedConfig = yield* mcpSessions.read(narrowedThreadId); + assert.isDefined(broadLoadedConfig); + assert.isTrue(broadLoadedConfig!.browserToolsAvailable); + const broadLoadedToken = broadLoadedConfig!.authorizationHeader.replace(/^Bearer\s+/, ""); + yield* runtime.resumeThread({ + threadId: narrowedThreadId, + providerThread: narrowedProviderThread, + modelSelection, + runtimePolicy, + }); + yield* settings.updateSettings({ enableAgentBrowserAccess: false }); + yield* manager.open({ + threadId: narrowedThreadId, + providerSessionId, + modelSelection, + runtimePolicy, + runId: RunId.make("run-bg-narrowed-typed"), + attemptId: RunAttemptId.make("attempt-bg-narrowed-typed"), + requireRunScopedMcp: true, + }); + const narrowedRotatedConfig = yield* mcpSessions.read(narrowedThreadId); + assert.isDefined(narrowedRotatedConfig); + const narrowedRotatedToken = narrowedRotatedConfig!.authorizationHeader.replace( + /^Bearer\s+/, + "", + ); + const narrowedFailed = yield* runtime + .resumeThread({ + threadId: narrowedThreadId, + providerThread: narrowedProviderThread, + modelSelection, + runtimePolicy, + }) + .pipe(Effect.flip); + assert.equal(narrowedFailed._tag, "ProviderAdapterMcpRotationBlockedError"); + assert.isUndefined(yield* registry.resolve(broadLoadedToken)); + assert.isUndefined(yield* registry.resolve(narrowedRotatedToken)); + assert.isUndefined(yield* mcpSessions.read(narrowedThreadId)); + + // Once background work finishes, the next ordinary (non-typed) turn recovers a working + // MCP credential with browser access still disabled and reloads the thread cleanly. + yield* Ref.set(pendingBackgroundWork, false); + const nextPlainRun = RunId.make("run-bg-narrowed-next-plain"); + yield* manager.open({ + threadId: narrowedThreadId, + providerSessionId, + modelSelection, + runtimePolicy, + runId: nextPlainRun, + attemptId: RunAttemptId.make("attempt-bg-narrowed-next-plain"), + requireRunScopedMcp: false, + }); + yield* runtime.resumeThread({ + threadId: narrowedThreadId, + providerThread: narrowedProviderThread, + modelSelection, + runtimePolicy, + }); + assert.isTrue(Option.isSome(yield* Queue.poll(unloads))); + const recoveredConfig = yield* mcpSessions.read(narrowedThreadId); + assert.isDefined(recoveredConfig); + assert.isFalse(recoveredConfig!.browserToolsAvailable); + const recoveredToken = recoveredConfig!.authorizationHeader.replace(/^Bearer\s+/, ""); + const resolvedRecovered = yield* registry.resolve(recoveredToken); + assert.isDefined(resolvedRecovered); + assert.isFalse(resolvedRecovered!.capabilities.has("preview")); + assert.equal(resolvedRecovered!.thread.runId, nextPlainRun); + assert.equal(recoveredConfig!.providerSessionId, broadLoadedConfig!.providerSessionId); + assert.notEqual(recoveredConfig!.credentialId, broadLoadedConfig!.credentialId); + + // Also cover run-less open recovery after a cleared capability-removal rollback. + yield* mcpSessions.clear(narrowedThreadId); + yield* manager.open({ + threadId: narrowedThreadId, + providerSessionId, + modelSelection, + runtimePolicy, + }); + const runlessRecovered = yield* mcpSessions.read(narrowedThreadId); + assert.isDefined(runlessRecovered); + assert.equal(runlessRecovered!.providerSessionId, broadLoadedConfig!.providerSessionId); + assert.isFalse(runlessRecovered!.browserToolsAvailable); + + yield* manager.close(providerSessionId); + }); + + const serverSettingsLayer = ServerSettings.layerTest().pipe(Layer.orDie); + yield* effect.pipe( + Effect.provide( + Layer.merge( + layerTest({ + state, + idleTimeoutMs: 1_000, + unloads, + hasPendingBackgroundWorkForThread: Ref.get(pendingBackgroundWork), + serverSettingsLayer, + }), + serverSettingsLayer, + ), + ), + ); + return; + } + + const unloads = yield* Queue.unbounded(); + const effect = Effect.gen(function* () { + const eventSink = yield* EventSink.EventSinkV2; + const idAllocator = yield* IdAllocator.IdAllocatorV2; + const manager = yield* ProviderSessionManager.ProviderSessionManagerV2; + const mcpSessions = yield* McpProviderSessions.McpProviderSessions; + const now = yield* DateTime.now; + const threadId = ThreadId.make("thread-provider-session-manager-shared-rotate"); + const providerSessionId = yield* idAllocator.allocate.providerSession({ + providerInstanceId: modelSelection.instanceId, + threadId, + }); + yield* eventSink.write({ + events: [yield* makeThreadCreatedEvent({ idAllocator, threadId, now })], + }); + + const run1 = RunId.make("run-shared-1"); + const runtime = yield* manager.open({ + threadId, + providerSessionId, + modelSelection, + runtimePolicy, + runId: run1, + attemptId: RunAttemptId.make("attempt-shared-1"), + }); + const providerThread = makeProviderThread({ + idAllocator, + threadId, + providerSessionId, + now, + }); + yield* runtime.resumeThread({ + threadId, + providerThread, + modelSelection, + runtimePolicy, + }); + const token1 = (yield* mcpSessions.read(threadId))?.authorizationHeader; + assert.isDefined(token1); + assert.isTrue(Option.isNone(yield* Queue.poll(unloads))); + + // Plain turn on a shared runtime without live MCP updates keeps the loaded credential. + yield* manager.open({ + threadId, + providerSessionId, + modelSelection, + runtimePolicy, + runId: RunId.make("run-shared-2"), + attemptId: RunAttemptId.make("attempt-shared-2"), + requireRunScopedMcp: false, + }); + assert.equal((yield* mcpSessions.read(threadId))?.authorizationHeader, token1); + assert.isTrue(Option.isNone(yield* Queue.poll(unloads))); + + // Typed-output turn rotates the credential and reloads the thread via unloadThread + resumeThread. + const run3 = RunId.make("run-shared-3"); + yield* manager.open({ + threadId, + providerSessionId, + modelSelection, + runtimePolicy, + runId: run3, + attemptId: RunAttemptId.make("attempt-shared-3"), + requireRunScopedMcp: true, + }); + const token3 = (yield* mcpSessions.read(threadId))?.authorizationHeader; + assert.notEqual(token3, token1); + yield* runtime.resumeThread({ + threadId, + providerThread, + modelSelection, + runtimePolicy, + }); + assert.deepEqual([...(yield* Queue.takeAll(unloads))], ["unload:native-thread"]); + yield* manager.close(providerSessionId); + }); + + yield* effect.pipe( + Effect.provide( + layerTest({ + state, + idleTimeoutMs: 1_000, + unloads, + }), + ), + ); + }), +); + it.effect( "ProviderSessionManagerV2 stops serving prompt suggestions once a thread is deleted", () => diff --git a/apps/server/src/orchestration-v2/ProviderSessionManager.ts b/apps/server/src/orchestration-v2/ProviderSessionManager.ts index 297677bd5f520..b943e3139c294 100644 --- a/apps/server/src/orchestration-v2/ProviderSessionManager.ts +++ b/apps/server/src/orchestration-v2/ProviderSessionManager.ts @@ -16,6 +16,7 @@ import { type OrchestrationV2Subagent, ProviderInstanceId, ProviderSessionId, + type RunAttemptId, type RunId, ThreadId, type OrchestrationV2TurnItem, @@ -55,10 +56,12 @@ import { ProviderWorkspaceMissingError } from "../provider/Errors.ts"; import * as ProviderInstallationGate from "../provider/ProviderInstallationGate.ts"; import * as ProjectService from "../project/ProjectService.ts"; import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions"; +import * as McpProviderSession from "@t3tools/provider-core/server/mcpSession"; import * as ServerSettings from "../serverSettings.ts"; import * as McpSessionRegistry from "../mcp/McpSessionRegistry.ts"; import * as EffectOutbox from "./EffectOutbox.ts"; import * as EventSink from "./EventSink.ts"; +import { runRequiresRunScopedMcp } from "./runOutput.ts"; import { awaitingProviderThreadId, cancelledRosterTaskWork, @@ -247,6 +250,10 @@ export interface ProviderSessionManagerV2Shape { readonly providerSessionId: ProviderSessionId; readonly modelSelection: ModelSelection; readonly runtimePolicy: ProviderAdapter.ProviderAdapterV2RuntimePolicy; + readonly runId?: RunId; + readonly attemptId?: RunAttemptId; + readonly requireRunScopedMcp?: boolean; + readonly owedOutputRunId?: RunId; readonly resumeFromSession?: OrchestrationV2ProviderSession; readonly initialNativeThreadId?: string; readonly initialProviderItemIdentityVersion?: 2; @@ -325,11 +332,20 @@ export class ProviderSessionManagerV2 extends Context.Service< interface LiveSessionEntry { readonly attachedThreadIds: ReadonlySet; readonly loadedProviderThreadKeyByThread: ReadonlyMap; + /** Credential that was active when this thread was last loaded natively. */ + readonly loadedMcpCredentialByThread: ReadonlyMap< + ThreadId, + McpProviderSession.McpProviderSessionConfig + >; + /** Last (runId, attemptId) already evaluated for per-turn MCP rotation on this thread. */ + readonly mcpTurnCheckedKeyByThread: ReadonlyMap; /** null marks an unknown catalog; undefined means MCP refresh is not configured. */ readonly openedWithLinkedEnvironments: boolean | null | undefined; readonly linkedEnvironmentsByThread: ReadonlyMap; /** Scope revocation to recorded credential ids so superseded sessions cannot revoke replacements opened before detach. */ - readonly mcpCredentialIdByThread: ReadonlyMap; + readonly mcpCredentialIdsByThread: ReadonlyMap>; + /** Stable MCP owner session id per thread so run rotations preserve browser tab ownership and deferred tool discovery. */ + readonly mcpOwnerSessionIdByThread: ReadonlyMap; readonly supportsMultipleProviderThreads: boolean; readonly runtime: ProviderAdapter.ProviderAdapterV2SessionRuntime; readonly exposedRuntime: ProviderAdapter.ProviderAdapterV2SessionRuntime; @@ -560,6 +576,7 @@ export const layerWithOptions = ( const maxIdlePinMs = Math.max(0, options.maxIdlePinMs ?? DEFAULT_MAX_IDLE_PIN_MS); interface PreparedMcpCredential { readonly mcpCredentialId: string | undefined; + readonly mcpOwnerSessionId: string | undefined; readonly issued: boolean; } /** ACP and OpenCode consume credentials during openSession; reserve them against revocation until publication. */ @@ -582,15 +599,118 @@ export const layerWithOptions = ( const isMcpCredentialReserved = (threadId: ThreadId, mcpCredentialId: string) => (mcpCredentialReservations.get(mcpReservationKey(threadId, mcpCredentialId)) ?? 0) > 0; const mcpPrepareLock = yield* KeyedLock.make(); + const addSessionMcpCredentialId = ( + current: ReadonlyMap>, + threadId: ThreadId, + mcpCredentialId: string, + ): ReadonlyMap> => { + const existing = current.get(threadId); + if (existing?.has(mcpCredentialId) === true) return current; + const ids = new Set([...(existing ?? []), mcpCredentialId]); + for (const oldest of ids) { + if (ids.size <= McpSessionRegistry.MAX_CREDENTIALS_PER_THREAD) break; + ids.delete(oldest); + } + const next = new Map(current); + next.set(threadId, ids); + return next; + }; + const recordSessionMcpCredential = ( + providerSessionId: ProviderSessionId, + threadId: ThreadId, + mcpCredentialId: string, + mcpOwnerSessionId?: string, + ) => + Ref.update(sessions, (current) => { + const key = sessionKey(providerSessionId); + const entry = current.get(key); + if (entry === undefined) return current; + const mcpCredentialIdsByThread = addSessionMcpCredentialId( + entry.mcpCredentialIdsByThread, + threadId, + mcpCredentialId, + ); + const ownerUnchanged = + mcpOwnerSessionId === undefined || + entry.mcpOwnerSessionIdByThread.get(threadId) === mcpOwnerSessionId; + if (mcpCredentialIdsByThread === entry.mcpCredentialIdsByThread && ownerUnchanged) { + return current; + } + const mcpOwnerSessionIdByThread = ownerUnchanged + ? entry.mcpOwnerSessionIdByThread + : new Map(entry.mcpOwnerSessionIdByThread).set(threadId, mcpOwnerSessionId); + const updated = new Map(current); + updated.set(key, { ...entry, mcpCredentialIdsByThread, mcpOwnerSessionIdByThread }); + return updated; + }); + const removeSessionMcpCredential = ( + providerSessionId: ProviderSessionId, + threadId: ThreadId, + mcpCredentialId: string, + ) => + Ref.update(sessions, (current) => { + const key = sessionKey(providerSessionId); + const entry = current.get(key); + const existing = entry?.mcpCredentialIdsByThread.get(threadId); + if (entry === undefined || existing?.has(mcpCredentialId) !== true) return current; + const remaining = new Set(existing); + remaining.delete(mcpCredentialId); + const mcpCredentialIdsByThread = new Map(entry.mcpCredentialIdsByThread); + if (remaining.size === 0) { + mcpCredentialIdsByThread.delete(threadId); + } else { + mcpCredentialIdsByThread.set(threadId, remaining); + } + return new Map(current).set(key, { ...entry, mcpCredentialIdsByThread }); + }); + const mcpTurnKey = (runId: RunId, attemptId?: RunAttemptId) => `${runId}:${attemptId ?? ""}`; + const recordMcpTurnChecked = ( + providerSessionId: ProviderSessionId, + threadId: ThreadId, + turnKey: string | undefined, + ) => + Ref.update(sessions, (current) => { + const key = sessionKey(providerSessionId); + const entry = current.get(key); + if (entry === undefined || entry.mcpTurnCheckedKeyByThread.get(threadId) === turnKey) { + return current; + } + const mcpTurnCheckedKeyByThread = new Map(entry.mcpTurnCheckedKeyByThread); + if (turnKey === undefined) { + mcpTurnCheckedKeyByThread.delete(threadId); + } else { + mcpTurnCheckedKeyByThread.set(threadId, turnKey); + } + return new Map(current).set(key, { ...entry, mcpTurnCheckedKeyByThread }); + }); + const threadRequiresRunScopedMcp = ( + threadId: ThreadId, + runId: RunId | undefined, + currentCredentialRunId?: RunId, + ) => + projectionStore.getThreadRecords(threadId, ["runs"]).pipe( + Effect.map(({ runs }) => runRequiresRunScopedMcp(runs, runId, currentCredentialRunId)), + Effect.orElseSucceed(() => false), + ); /** Serialize prepares per thread so concurrent rotations cannot revoke each other's credentials. */ const prepareMcpSession = ( threadId: ThreadId, providerInstanceId: ProviderInstanceId, + turn?: { + readonly runId?: RunId; + readonly attemptId?: RunAttemptId; + readonly rotateOnRunChange?: boolean; + readonly ownerSessionId?: string; + }, ): Effect.Effect => options.configureMcp === false - ? mcpSessions - .clear(threadId) - .pipe(Effect.as({ mcpCredentialId: undefined, issued: false })) + ? mcpSessions.clear(threadId).pipe( + Effect.as({ + mcpCredentialId: undefined, + mcpOwnerSessionId: undefined, + issued: false, + }), + ) : mcpPrepareLock.withLock( threadId, Effect.gen(function* () { @@ -615,9 +735,12 @@ export const layerWithOptions = ( Effect.orElseSucceed(() => false), ); const existing = yield* mcpSessions.read(threadId); + let capabilitiesMatch = false; + let existingWithinRequestedCapabilities = false; if (existing !== undefined) { + const existingCredentialId = McpProviderSession.mcpCredentialIdOf(existing); // Reserve before async validation so release cannot revoke between validation and reservation. - reserveMcpCredential(threadId, existing.providerSessionId); + reserveMcpCredential(threadId, existingCredentialId); const rawToken = existing.authorizationHeader.replace(/^Bearer\s+/, ""); // Interrupted resolution must release the reservation before the caller learns of it. const resolved = yield* mcpSessionRegistry @@ -625,30 +748,58 @@ export const layerWithOptions = ( .pipe( Effect.onInterrupt(() => Effect.sync(() => - dropMcpCredentialReservation(threadId, existing.providerSessionId), + dropMcpCredentialReservation(threadId, existingCredentialId), ), ), ); - if ( + const sameIdentity = resolved !== undefined && resolved.thread.threadId === threadId && resolved.thread.providerInstanceId === providerInstanceId && + // A credential issued while the lineage read failed is replaced once it works. + (resolved.thread.subagent === true) === subagent; + capabilitiesMatch = + sameIdentity && resolved.capabilities.has("preview") === browserToolsAvailable && resolved.capabilities.has("device") === deviceToolsAvailable && // A failed capability read cannot tell that the live credential is wrong. (Option.isNone(backgroundWait) || - resolved.capabilities.has("background-wait") === backgroundWait.value) && - // A credential issued while the lineage read failed is replaced once it works. - (resolved.thread.subagent === true) === subagent - ) { - return { mcpCredentialId: existing.providerSessionId, issued: false }; + resolved.capabilities.has("background-wait") === backgroundWait.value); + // Capability widening keeps prior narrower tokens valid (bounded to 16 per thread) so + // late calls get clean rejections and blocked-reload rollbacks never 401 background work. + existingWithinRequestedCapabilities = + sameIdentity && + (!resolved.capabilities.has("preview") || browserToolsAvailable) && + (!resolved.capabilities.has("device") || deviceToolsAvailable) && + (Option.isNone(backgroundWait) || + !resolved.capabilities.has("background-wait") || + backgroundWait.value); + const runMatches = + turn?.rotateOnRunChange !== true || + ((turn.runId === undefined || resolved?.thread.runId === turn.runId) && + (turn.attemptId === undefined || + resolved?.thread.attemptId === turn.attemptId)); + if (capabilitiesMatch && runMatches) { + return { + mcpCredentialId: existingCredentialId, + mcpOwnerSessionId: existing.providerSessionId, + issued: false, + }; } - dropMcpCredentialReservation(threadId, existing.providerSessionId); + dropMcpCredentialReservation(threadId, existingCredentialId); + } + // Revoke prior thread tokens immediately on capability removal or identity/subagent change. + if (!capabilitiesMatch && !existingWithinRequestedCapabilities) { + yield* mcpSessionRegistry.revokeThread(threadId); } - yield* mcpSessionRegistry.revokeThread(threadId); const credential = yield* mcpSessionRegistry.issue({ threadId, providerInstanceId, + ...(turn?.ownerSessionId === undefined + ? {} + : { providerSessionId: turn.ownerSessionId }), + ...(turn?.runId === undefined ? {} : { runId: turn.runId }), + ...(turn?.attemptId === undefined ? {} : { attemptId: turn.attemptId }), browserToolsAvailable, capabilities, subagent, @@ -662,8 +813,13 @@ export const layerWithOptions = ( Effect.orElseSucceed(() => false), ), }); - reserveMcpCredential(threadId, credential.config.providerSessionId); - return { mcpCredentialId: credential.config.providerSessionId, issued: true }; + const issuedCredentialId = McpProviderSession.mcpCredentialIdOf(credential.config); + reserveMcpCredential(threadId, issuedCredentialId); + return { + mcpCredentialId: issuedCredentialId, + mcpOwnerSessionId: credential.config.providerSessionId, + issued: true, + }; }), ); const clearMcpSession = (threadId: ThreadId, mcpCredentialId?: string) => @@ -671,10 +827,14 @@ export const layerWithOptions = ( ? mcpSessionRegistry .revokeThread(threadId) .pipe(Effect.tap(() => mcpSessions.clear(threadId))) - : mcpSessionRegistry.revokeProviderSession(mcpCredentialId).pipe( + : mcpSessionRegistry.revokeCredential(mcpCredentialId).pipe( Effect.tap(() => Effect.gen(function* () { - if ((yield* mcpSessions.read(threadId))?.providerSessionId === mcpCredentialId) { + const current = yield* mcpSessions.read(threadId); + if ( + current !== undefined && + McpProviderSession.mcpCredentialIdOf(current) === mcpCredentialId + ) { yield* mcpSessions.clear(threadId); } }), @@ -1574,21 +1734,28 @@ export const layerWithOptions = ( Ref.get(sessions).pipe( Effect.flatMap((current) => Effect.forEach( - entry.mcpCredentialIdByThread, - ([threadId, mcpCredentialId]) => { - // Only holders of this credential may prevent its revocation; stale credentials must not leak it. - const heldElsewhere = - isMcpCredentialReserved(threadId, mcpCredentialId) || - Array.from(current.values()).some( - (other) => - other !== entry && - (other.attachedThreadIds.has(threadId) || - other.mcpCredentialIdByThread.get(threadId) === mcpCredentialId), - ); - return heldElsewhere - ? Effect.void - : clearMcpSession(threadId, mcpCredentialId); - }, + entry.mcpCredentialIdsByThread, + ([threadId, mcpCredentialIds]) => + Effect.forEach( + mcpCredentialIds, + (mcpCredentialId) => { + // Only holders of this credential may prevent its revocation; stale credentials must not leak it. + const heldElsewhere = + isMcpCredentialReserved(threadId, mcpCredentialId) || + Array.from(current.values()).some( + (other) => + other !== entry && + (other.attachedThreadIds.has(threadId) || + other.mcpCredentialIdsByThread + .get(threadId) + ?.has(mcpCredentialId) === true), + ); + return heldElsewhere + ? Effect.void + : clearMcpSession(threadId, mcpCredentialId); + }, + { discard: true }, + ), { discard: true }, ), ), @@ -1803,6 +1970,12 @@ export const layerWithOptions = ( attachedThreadIds.delete(input.threadId); const loadedProviderThreadKeyByThread = new Map(entry.loadedProviderThreadKeyByThread); loadedProviderThreadKeyByThread.delete(input.threadId); + const loadedMcpCredentialByThread = new Map(entry.loadedMcpCredentialByThread); + loadedMcpCredentialByThread.delete(input.threadId); + const mcpTurnCheckedKeyByThread = new Map(entry.mcpTurnCheckedKeyByThread); + mcpTurnCheckedKeyByThread.delete(input.threadId); + const mcpOwnerSessionIdByThread = new Map(entry.mcpOwnerSessionIdByThread); + mcpOwnerSessionIdByThread.delete(input.threadId); const linkedEnvironmentsByThread = new Map(entry.linkedEnvironmentsByThread); linkedEnvironmentsByThread.delete(input.threadId); const updated = new Map(current); @@ -1810,6 +1983,9 @@ export const layerWithOptions = ( ...entry, attachedThreadIds, loadedProviderThreadKeyByThread, + loadedMcpCredentialByThread, + mcpTurnCheckedKeyByThread, + mcpOwnerSessionIdByThread, linkedEnvironmentsByThread, }); return updated; @@ -1845,7 +2021,13 @@ export const layerWithOptions = ( } const loadedProviderThreadKeyByThread = new Map(entry.loadedProviderThreadKeyByThread); loadedProviderThreadKeyByThread.delete(input.threadId); - return new Map(current).set(key, { ...entry, loadedProviderThreadKeyByThread }); + const loadedMcpCredentialByThread = new Map(entry.loadedMcpCredentialByThread); + loadedMcpCredentialByThread.delete(input.threadId); + return new Map(current).set(key, { + ...entry, + loadedProviderThreadKeyByThread, + loadedMcpCredentialByThread, + }); }); /** Pass the setting read before a native load; cache hits keep the earlier record. */ @@ -1854,6 +2036,7 @@ export const layerWithOptions = ( readonly threadId: ThreadId; readonly providerThreadKey: string; readonly linkedEnvironments: boolean | null | undefined; + readonly mcpCredential?: McpProviderSession.McpProviderSessionConfig | undefined; }) => Ref.update(sessions, (current) => { const key = sessionKey(input.providerSessionId); @@ -1863,6 +2046,10 @@ export const layerWithOptions = ( } const loadedProviderThreadKeyByThread = new Map(entry.loadedProviderThreadKeyByThread); loadedProviderThreadKeyByThread.set(input.threadId, input.providerThreadKey); + const loadedMcpCredentialByThread = new Map(entry.loadedMcpCredentialByThread); + if (input.mcpCredential !== undefined) { + loadedMcpCredentialByThread.set(input.threadId, input.mcpCredential); + } const linkedEnvironmentsByThread = new Map(entry.linkedEnvironmentsByThread); if ( input.linkedEnvironments !== undefined && @@ -1874,15 +2061,22 @@ export const layerWithOptions = ( updated.set(key, { ...entry, loadedProviderThreadKeyByThread, + loadedMcpCredentialByThread, linkedEnvironmentsByThread, }); return updated; }); - const loadNatively = (load: Effect.Effect) => - readLinkedEnvironments.pipe( - Effect.flatMap((linkedEnvironments) => - load.pipe(Effect.map((loaded) => ({ loaded, linkedEnvironments }))), + const loadNatively = (threadId: ThreadId, load: Effect.Effect) => + Effect.all([readLinkedEnvironments, mcpSessions.read(threadId)]).pipe( + Effect.flatMap(([linkedEnvironments, mcpSession]) => + load.pipe( + Effect.map((loaded) => ({ + loaded, + linkedEnvironments, + mcpCredential: mcpSession, + })), + ), ), ); @@ -1912,17 +2106,12 @@ export const layerWithOptions = ( const prepared = yield* prepareMcpSession(input.threadId, input.providerInstanceId); preparedForCleanup = prepared; if (prepared.mcpCredentialId !== undefined) { - const mcpCredentialId = prepared.mcpCredentialId; - yield* Ref.update(sessions, (current) => { - const key = sessionKey(input.providerSessionId); - const entry = current.get(key); - if (entry === undefined) return current; - const mcpCredentialIdByThread = new Map(entry.mcpCredentialIdByThread); - mcpCredentialIdByThread.set(input.threadId, mcpCredentialId); - const updated = new Map(current); - updated.set(key, { ...entry, mcpCredentialIdByThread }); - return updated; - }); + yield* recordSessionMcpCredential( + input.providerSessionId, + input.threadId, + prepared.mcpCredentialId, + prepared.mcpOwnerSessionId, + ); } const entry = (yield* Ref.get(sessions)).get(sessionKey(input.providerSessionId)); if (entry !== undefined) { @@ -1958,8 +2147,9 @@ export const layerWithOptions = ( other.runtime !== attachedRuntime && (other.attachedThreadIds.has(input.threadId) || (mcpCredentialId !== undefined && - other.mcpCredentialIdByThread.get(input.threadId) === - mcpCredentialId)), + other.mcpCredentialIdsByThread + .get(input.threadId) + ?.has(mcpCredentialId) === true)), ) ? Effect.void : clearMcpSession(input.threadId, mcpCredentialId), @@ -1975,6 +2165,85 @@ export const layerWithOptions = ( .pipe(Effect.ensuring(Effect.sync(dropReservation))); }); + /** Rotates the thread's MCP credential to this turn's run/attempt when typed output requires run binding. */ + const ensureTurnMcpSession = Effect.fn("ProviderSessionManager.ensureTurnMcpSession")( + function* (input: { + readonly providerSessionId: ProviderSessionId; + readonly threadId: ThreadId; + readonly providerInstanceId: ProviderInstanceId; + readonly runtime: ProviderAdapter.ProviderAdapterV2SessionRuntime; + readonly runId: RunId; + readonly attemptId?: RunAttemptId; + readonly requireRunScopedMcp?: boolean; + readonly owedOutputRunId?: RunId; + }) { + if (options.configureMcp === false) return; + let reservedCredentialId: string | undefined; + const dropReservation = () => { + if (reservedCredentialId !== undefined) { + dropMcpCredentialReservation(input.threadId, reservedCredentialId); + reservedCredentialId = undefined; + } + }; + yield* Effect.gen(function* () { + const turnKey = mcpTurnKey(input.runId, input.attemptId); + if (input.requireRunScopedMcp === undefined) { + const alreadyChecked = + (yield* Ref.get(sessions)) + .get(sessionKey(input.providerSessionId)) + ?.mcpTurnCheckedKeyByThread.get(input.threadId) === turnKey; + if (alreadyChecked) return; + } + const current = yield* mcpSessions.read(input.threadId); + if ( + current !== undefined && + current.runId === input.runId && + (input.attemptId === undefined || current.attemptId === input.attemptId) + ) { + yield* recordMcpTurnChecked(input.providerSessionId, input.threadId, turnKey); + return; + } + const rotateOnRunChange = + input.requireRunScopedMcp !== undefined + ? input.requireRunScopedMcp || + (input.owedOutputRunId !== undefined && current?.runId !== input.owedOutputRunId) + : yield* threadRequiresRunScopedMcp(input.threadId, input.runId, current?.runId); + if (!rotateOnRunChange && current !== undefined) { + yield* recordMcpTurnChecked(input.providerSessionId, input.threadId, turnKey); + return; + } + if (input.runtime.mcpCredentialRotation === "none") { + if (current !== undefined) { + return yield* new ProviderSessionOpenError({ + instanceId: input.providerInstanceId, + providerSessionId: input.providerSessionId, + cause: `Provider ${input.runtime.driver} cannot rotate MCP credentials on a live session without session reload or MCP-over-ACP.`, + }); + } + } + const ownerSessionId = (yield* Ref.get(sessions)) + .get(sessionKey(input.providerSessionId)) + ?.mcpOwnerSessionIdByThread.get(input.threadId); + const prepared = yield* prepareMcpSession(input.threadId, input.providerInstanceId, { + runId: input.runId, + ...(input.attemptId === undefined ? {} : { attemptId: input.attemptId }), + ...(ownerSessionId === undefined ? {} : { ownerSessionId }), + rotateOnRunChange, + }); + reservedCredentialId = prepared.mcpCredentialId; + if (prepared.mcpCredentialId !== undefined) { + yield* recordSessionMcpCredential( + input.providerSessionId, + input.threadId, + prepared.mcpCredentialId, + prepared.mcpOwnerSessionId, + ); + } + yield* recordMcpTurnChecked(input.providerSessionId, input.threadId, turnKey); + }).pipe(Effect.ensuring(Effect.sync(dropReservation))); + }, + ); + // Marks only the entry this runtime belongs to: a released or replaced session must not // gain a busy turn that never ends. Succeeds with whether the turn was marked. const markBusy = ( @@ -2200,12 +2469,15 @@ export const layerWithOptions = ( latest.loadedProviderThreadKeyByThread, ); loadedProviderThreadKeyByThread.delete(input.threadId); + const loadedMcpCredentialByThread = new Map(latest.loadedMcpCredentialByThread); + loadedMcpCredentialByThread.delete(input.threadId); const idleThreadUnloads = new Map(latest.idleThreadUnloads); idleThreadUnloads.delete(input.threadId); const updated = new Map(current); updated.set(key, { ...latest, loadedProviderThreadKeyByThread, + loadedMcpCredentialByThread, idleThreadUnloads, }); return [true, updated] as const; @@ -2308,9 +2580,15 @@ export const layerWithOptions = ( latest.loadedProviderThreadKeyByThread, ); loadedProviderThreadKeyByThread.delete(input.threadId); + const loadedMcpCredentialByThread = new Map(latest.loadedMcpCredentialByThread); + loadedMcpCredentialByThread.delete(input.threadId); return [ true, - new Map(current).set(key, { ...latest, loadedProviderThreadKeyByThread }), + new Map(current).set(key, { + ...latest, + loadedProviderThreadKeyByThread, + loadedMcpCredentialByThread, + }), ] as const; }); if (!unloading) return; @@ -2337,6 +2615,134 @@ export const layerWithOptions = ( ); }); + /** A shared runtime without live MCP updates reloads this thread when its MCP credential rotated. */ + const unloadForMcpCredential = Effect.fn("ProviderSessionManager.unloadForMcpCredential")( + function* (input: { + readonly providerSessionId: ProviderSessionId; + readonly threadId: ThreadId; + readonly providerThread: OrchestrationV2ProviderThread; + }) { + const key = sessionKey(input.providerSessionId); + const entry = (yield* Ref.get(sessions)).get(key); + const loadedCredential = entry?.loadedMcpCredentialByThread.get(input.threadId); + const unloadThread = entry?.runtime.unloadThread; + if ( + entry === undefined || + !entry.supportsMultipleProviderThreads || + entry.runtime.mcpCredentialRotation === "live" || + entry.runtime.mcpCredentialRotation === "none" || + unloadThread === undefined || + loadedCredential === undefined || + input.providerThread.nativeThreadRef === null + ) { + return; + } + const currentCredential = yield* mcpSessions.read(input.threadId); + const loadedCredentialId = McpProviderSession.mcpCredentialIdOf(loadedCredential); + const currentCredentialId = + currentCredential === undefined + ? undefined + : McpProviderSession.mcpCredentialIdOf(currentCredential); + if (currentCredentialId === undefined || currentCredentialId === loadedCredentialId) { + return; + } + yield* threadAttachment.withLock( + threadAttachmentKey(input), + Effect.gen(function* () { + if (hasBusyTurn(entry, input.providerThread.id)) return; + // Unloading ends the thread's background work; a failed probe keeps it loaded too. + const hasPendingWork = + entry.runtime.hasPendingBackgroundWorkForThread === undefined + ? false + : yield* entry.runtime + .hasPendingBackgroundWorkForThread(input.providerThread, { + includeSubagents: true, + }) + .pipe( + Effect.catchCauseIf( + (cause) => !Cause.hasInterruptsOnly(cause), + () => Effect.succeed(true), + ), + ); + if (hasPendingWork) { + // Keep background work alive and never mutate an issued bearer's run identity. + // Restore the still-loaded credential only if still valid (capability removals revoke immediately). + const loadedRawToken = loadedCredential.authorizationHeader.replace( + /^Bearer\s+/, + "", + ); + if ((yield* mcpSessionRegistry.resolve(loadedRawToken)) !== undefined) { + yield* mcpSessions.set(loadedCredential); + } else { + yield* mcpSessions.clear(input.threadId); + } + yield* mcpSessionRegistry.revokeCredential(currentCredentialId); + yield* removeSessionMcpCredential( + input.providerSessionId, + input.threadId, + currentCredentialId, + ); + yield* recordMcpTurnChecked(input.providerSessionId, input.threadId, undefined); + return yield* new ProviderAdapter.ProviderAdapterMcpRotationBlockedError({ + driver: entry.runtime.driver, + providerSessionId: input.providerSessionId, + providerThreadId: input.providerThread.id, + detail: + "Cannot refresh MCP credentials while background work is running on this thread.", + }); + } + const unloading = yield* Ref.modify(sessions, (current) => { + const latest = current.get(key); + const latestLoaded = latest?.loadedMcpCredentialByThread.get(input.threadId); + if ( + latest?.runtime !== entry.runtime || + latestLoaded === undefined || + McpProviderSession.mcpCredentialIdOf(latestLoaded) !== loadedCredentialId || + hasBusyTurn(latest, input.providerThread.id) + ) { + return [false, current] as const; + } + const loadedProviderThreadKeyByThread = new Map( + latest.loadedProviderThreadKeyByThread, + ); + loadedProviderThreadKeyByThread.delete(input.threadId); + const loadedMcpCredentialByThread = new Map(latest.loadedMcpCredentialByThread); + loadedMcpCredentialByThread.delete(input.threadId); + return [ + true, + new Map(current).set(key, { + ...latest, + loadedProviderThreadKeyByThread, + loadedMcpCredentialByThread, + }), + ] as const; + }); + if (!unloading) return; + let unloaded = false; + yield* unloadThread({ providerThread: input.providerThread }).pipe( + Effect.timeout(UNLOAD_THREAD_TIMEOUT_MS), + Effect.tap(() => Effect.sync(() => (unloaded = true))), + Effect.catchCause((cause) => + Effect.logWarning("orchestration-v2.driver-session.mcp-unload-failed", { + providerSessionId: input.providerSessionId, + threadId: input.threadId, + cause, + }), + ), + ); + if (unloaded && loadedCredential.runId === undefined) { + yield* mcpSessionRegistry.revokeCredential(loadedCredentialId); + yield* removeSessionMcpCredential( + input.providerSessionId, + input.threadId, + loadedCredentialId, + ); + } + }), + ); + }, + ); + /** An exclusive runtime configures MCP at open, so it reopens once nothing would be lost. */ const releaseForLinkedEnvironments = Effect.fn( "ProviderSessionManager.releaseForLinkedEnvironments", @@ -2495,8 +2901,8 @@ export const layerWithOptions = ( providerInstanceId: runtime.instanceId, }), ).pipe( - Effect.andThen(loadNatively(runtime.ensureThread(input))), - Effect.tap(({ loaded: providerThread, linkedEnvironments }) => + Effect.andThen(loadNatively(input.threadId, runtime.ensureThread(input))), + Effect.tap(({ loaded: providerThread, linkedEnvironments, mcpCredential }) => markProviderThreadLoaded({ providerSessionId, threadId: input.threadId, @@ -2507,6 +2913,7 @@ export const layerWithOptions = ( runtimePolicy: input.runtimePolicy, }), linkedEnvironments, + mcpCredential, }), ), Effect.map(({ loaded }) => loaded), @@ -2546,6 +2953,13 @@ export const layerWithOptions = ( providerThread: input.providerThread, }), ), + Effect.andThen( + unloadForMcpCredential({ + providerSessionId, + threadId, + providerThread: input.providerThread, + }), + ), Effect.andThen( isProviderThreadLoaded({ providerSessionId, threadId, providerThreadKey }), ), @@ -2554,10 +2968,11 @@ export const layerWithOptions = ( ? Effect.succeed({ loaded: input.providerThread, linkedEnvironments: undefined, + mcpCredential: undefined, }) - : loadNatively(runtime.resumeThread(input)), + : loadNatively(threadId, runtime.resumeThread(input)), ), - Effect.tap(({ loaded: providerThread, linkedEnvironments }) => + Effect.tap(({ loaded: providerThread, linkedEnvironments, mcpCredential }) => markProviderThreadLoaded({ providerSessionId, threadId, @@ -2572,6 +2987,7 @@ export const layerWithOptions = ( : { runtimePolicy: input.runtimePolicy }), }), linkedEnvironments, + mcpCredential, }), ), Effect.map(({ loaded }) => loaded), @@ -2586,8 +3002,8 @@ export const layerWithOptions = ( providerInstanceId: runtime.instanceId, }), ).pipe( - Effect.andThen(loadNatively(runtime.forkThread(input))), - Effect.tap(({ loaded: providerThread, linkedEnvironments }) => + Effect.andThen(loadNatively(input.targetThreadId, runtime.forkThread(input))), + Effect.tap(({ loaded: providerThread, linkedEnvironments, mcpCredential }) => markProviderThreadLoaded({ providerSessionId, threadId: input.targetThreadId, @@ -2602,6 +3018,7 @@ export const layerWithOptions = ( : { runtimePolicy: input.runtimePolicy }), }), linkedEnvironments, + mcpCredential, }), ), Effect.map(({ loaded }) => loaded), @@ -2615,6 +3032,27 @@ export const layerWithOptions = ( providerInstanceId: runtime.instanceId, }), ).pipe( + Effect.andThen( + ensureTurnMcpSession({ + providerSessionId, + threadId: input.threadId, + providerInstanceId: runtime.instanceId, + runtime, + runId: input.runId, + attemptId: input.attemptId, + }).pipe( + Effect.mapError( + (cause) => + new ProviderAdapter.ProviderAdapterTurnStartError({ + driver: runtime.driver, + threadId: input.threadId, + providerThreadId: input.providerThread.id, + runId: input.runId, + cause, + }), + ), + ), + ), // Failed or stopped starts may omit turn.terminal; clear their turns so sessions can idle. Effect.andThen( holdThreadLoaded({ @@ -2674,6 +3112,101 @@ export const layerWithOptions = ( ), ), ), + ...(runtime.resumeTurn === undefined + ? {} + : { + resumeTurn: (input) => + observeActivity( + providerSessionId, + ensureThreadAttached({ + providerSessionId, + threadId: input.threadId, + providerInstanceId: runtime.instanceId, + }), + ).pipe( + Effect.andThen( + ensureTurnMcpSession({ + providerSessionId, + threadId: input.threadId, + providerInstanceId: runtime.instanceId, + runtime, + runId: input.runId, + attemptId: input.attemptId, + }).pipe( + Effect.mapError( + (cause) => + new ProviderAdapter.ProviderAdapterTurnStartError({ + driver: runtime.driver, + threadId: input.threadId, + providerThreadId: input.providerThread.id, + runId: input.runId, + cause, + }), + ), + ), + ), + Effect.andThen( + holdThreadLoaded({ + providerSessionId, + threadId: input.threadId, + providerThread: input.providerThread, + }), + ), + Effect.andThen( + Effect.acquireUseRelease( + markBusy( + providerSessionId, + busyTurnKey(input.providerThread.id, input.runOrdinal), + runtime, + ).pipe( + Effect.catchCause((cause) => + Effect.logWarning("orchestration-v2.driver-session.activity-failed", { + providerSessionId, + cause, + }).pipe(Effect.as(true)), + ), + Effect.flatMap((marked) => + marked + ? Effect.void + : Effect.fail( + new ProviderAdapter.ProviderAdapterTurnStartError({ + driver: runtime.driver, + threadId: input.threadId, + providerThreadId: input.providerThread.id, + runId: input.runId, + cause: + "The provider session was released while the turn resumed.", + }), + ), + ), + ), + () => + runtime.resumeTurn!(input).pipe( + turnMetrics("send", input.modelSelection.model), + ), + (_, exit) => + Exit.isFailure(exit) + ? observeActivity( + providerSessionId, + markIdle( + providerSessionId, + input.providerThread.id, + input.runOrdinal, + ), + ).pipe( + Effect.andThen( + forgetProviderThreadLoaded({ + providerSessionId, + threadId: input.threadId, + runtime, + }), + ), + ) + : Effect.void, + ), + ), + ), + }), steerTurn: (input) => observeActivity(providerSessionId, touchActivity(providerSessionId)).pipe( Effect.andThen(runtime.steerTurn(input).pipe(turnMetrics("steer"))), @@ -3163,6 +3696,51 @@ export const layerWithOptions = ( threadId: input.threadId, providerInstanceId: existing.runtime.instanceId, }); + if (input.runId !== undefined) { + yield* ensureTurnMcpSession({ + providerSessionId: input.providerSessionId, + threadId: input.threadId, + providerInstanceId: existing.runtime.instanceId, + runtime: existing.runtime, + runId: input.runId, + ...(input.attemptId === undefined ? {} : { attemptId: input.attemptId }), + ...(input.requireRunScopedMcp === undefined + ? {} + : { requireRunScopedMcp: input.requireRunScopedMcp }), + ...(input.owedOutputRunId === undefined + ? {} + : { owedOutputRunId: input.owedOutputRunId }), + }); + } else if ( + options.configureMcp !== false && + (yield* mcpSessions.read(input.threadId)) === undefined + ) { + const ownerSessionId = existing.mcpOwnerSessionIdByThread.get(input.threadId); + yield* Effect.acquireUseRelease( + prepareMcpSession( + input.threadId, + existing.runtime.instanceId, + ownerSessionId === undefined ? undefined : { ownerSessionId }, + ), + (prepared) => + prepared.mcpCredentialId === undefined + ? Effect.void + : recordSessionMcpCredential( + input.providerSessionId, + input.threadId, + prepared.mcpCredentialId, + prepared.mcpOwnerSessionId, + ), + (prepared) => { + const credentialId = prepared.mcpCredentialId; + return credentialId === undefined + ? Effect.void + : Effect.sync(() => + dropMcpCredentialReservation(input.threadId, credentialId), + ); + }, + ); + } yield* touchActivity(input.providerSessionId); return existing.exposedRuntime; } @@ -3181,6 +3759,14 @@ export const layerWithOptions = ( const prepared = yield* prepareMcpSession( input.threadId, input.modelSelection.instanceId, + input.runId !== undefined + ? { + runId: input.runId, + ...(input.attemptId === undefined ? {} : { attemptId: input.attemptId }), + rotateOnRunChange: + input.requireRunScopedMcp === true || input.owedOutputRunId !== undefined, + } + : undefined, ); const mcpCredentialId = prepared.mcpCredentialId; let reservationDropped = mcpCredentialId === undefined; @@ -3256,12 +3842,21 @@ export const layerWithOptions = ( const entry: LiveSessionEntry = { attachedThreadIds: new Set([input.threadId]), loadedProviderThreadKeyByThread: new Map(), + loadedMcpCredentialByThread: new Map(), + mcpTurnCheckedKeyByThread: + input.runId === undefined + ? new Map() + : new Map([[input.threadId, mcpTurnKey(input.runId, input.attemptId)]]), openedWithLinkedEnvironments, linkedEnvironmentsByThread: new Map(), - mcpCredentialIdByThread: + mcpCredentialIdsByThread: mcpCredentialId === undefined ? new Map() - : new Map([[input.threadId, mcpCredentialId]]), + : new Map([[input.threadId, new Set([mcpCredentialId])]]), + mcpOwnerSessionIdByThread: + prepared.mcpOwnerSessionId === undefined + ? new Map() + : new Map([[input.threadId, prepared.mcpOwnerSessionId]]), supportsMultipleProviderThreads: runtime.providerSession.capabilities.sessions .supportsMultipleProviderThreadsPerSession, @@ -3488,24 +4083,33 @@ export const layerWithOptions = ( entry.loadedProviderThreadKeyByThread, ); loadedProviderThreadKeyByThread.delete(input.threadId); + const loadedMcpCredentialByThread = new Map(entry.loadedMcpCredentialByThread); + loadedMcpCredentialByThread.delete(input.threadId); + const mcpTurnCheckedKeyByThread = new Map(entry.mcpTurnCheckedKeyByThread); + mcpTurnCheckedKeyByThread.delete(input.threadId); + const mcpOwnerSessionIdByThread = new Map(entry.mcpOwnerSessionIdByThread); + mcpOwnerSessionIdByThread.delete(input.threadId); const linkedEnvironmentsByThread = new Map(entry.linkedEnvironmentsByThread); linkedEnvironmentsByThread.delete(input.threadId); - const mcpCredentialIdByThread = + const mcpCredentialIdsByThread = input.revokeMcpCredential === true ? (() => { - const pruned = new Map(entry.mcpCredentialIdByThread); + const pruned = new Map(entry.mcpCredentialIdsByThread); pruned.delete(input.threadId); return pruned; })() - : entry.mcpCredentialIdByThread; + : entry.mcpCredentialIdsByThread; const idleThreadUnloads = new Map(entry.idleThreadUnloads); idleThreadUnloads.delete(input.threadId); const updatedEntry = { ...entry, attachedThreadIds, loadedProviderThreadKeyByThread, + loadedMcpCredentialByThread, + mcpTurnCheckedKeyByThread, + mcpOwnerSessionIdByThread, linkedEnvironmentsByThread, - mcpCredentialIdByThread, + mcpCredentialIdsByThread, idleThreadUnloads, }; const updated = new Map(current); diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts index 4bf6e71397fe5..efe3184958f90 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts @@ -3270,6 +3270,43 @@ effectIt.effect("fails the run instead of replacing a native thread another clie }), ); +effectIt.effect( + "fails the run instead of replacing a native thread when active background work blocks MCP rotation", + () => + Effect.gen(function* () { + const detail = + "Cannot refresh MCP credentials while background work is running on this thread."; + const harness = makeLocalCommandHarness({ + text: "Continue", + resumeFailure: new ProviderAdapter.ProviderAdapterMcpRotationBlockedError({ + driver: ProviderDriverKind.make("codex"), + providerSessionId: ProviderSessionId.make("provider-session-mcp-blocked"), + providerThreadId: ProviderThreadId.make("new-provider-thread"), + detail, + }), + }); + + const exit = yield* Effect.exit(harness.start); + + expect(harness.fallbackEnsureThread).not.toHaveBeenCalled(); + expect(exit._tag).toBe("Success"); + expect(harness.startRootRun).not.toHaveBeenCalled(); + const projection = harness.projection(); + expect(projection.providerThreads.at(-1)?.nativeThreadRef?.nativeId).toBe( + "native-resume-thread", + ); + expect(projection.contextHandoffs).toEqual([]); + expect(projection.runs.at(-1)).toMatchObject({ status: "failed", startedAt: null }); + expect(projection.turnItems).toMatchObject([ + { + type: "error", + title: "Provider turn failed to start", + failure: { class: "provider_error", message: detail }, + }, + ]); + }), +); + effectIt.effect("does not mistake a failed state read for a superseded run", () => Effect.gen(function* () { const harness = makeLocalCommandHarness({ text: "Continue", failReadsAfterRunning: true }); diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts index e47e88eda09a0..aec6f399b825b 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts @@ -61,7 +61,7 @@ import { latestNativeContextUsage, } from "@t3tools/provider-core/server/handoffBudget"; import { deliverContextHandoffs, withInlineContext } from "./ContextHandoffDelivery.ts"; -import { isProviderCommand, outputInstructions } from "./runOutput.ts"; +import { isProviderCommand, latestOwedOutputRun, outputInstructions } from "./runOutput.ts"; import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter"; import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator"; import * as ProjectionStore from "./ProjectionStore.ts"; @@ -939,12 +939,17 @@ export const layer: Layer.Layer< brokenNativeThread && providerThread.nativeThreadRef !== null && !(yield* providerSessions.isLive(providerSessionId)); + const owedOutputRun = latestOwedOutputRun(projection.runs); const sessionResult = yield* Effect.result( providerSessions.open({ threadId: projection.thread.id, providerSessionId, modelSelection: run.modelSelection, runtimePolicy: resolvedRuntimePolicy, + runId: run.id, + attemptId: attempt.id, + requireRunScopedMcp: run.outputSchema !== undefined, + ...(owedOutputRun === undefined ? {} : { owedOutputRunId: owedOutputRun.id }), ...(existingSessionProjection === undefined ? {} : { resumeFromSession: existingSessionProjection }), @@ -1670,11 +1675,12 @@ export const layer: Layer.Layer< resumedHandoffContext = undefined; resumedRetryHandoff = undefined; if (!(yield* isCurrentAttemptInStatus("starting"))) return undefined; - // Another client is still writing to the native thread. A fresh - // session here would silently split the conversation from it. + // Another client or active background work owns this native thread; + // starting a fresh session would silently split the conversation. if ( resumed._tag === "Failure" && - resumed.failure._tag === "ProviderAdapterThreadInUseError" + (resumed.failure._tag === "ProviderAdapterThreadInUseError" || + resumed.failure._tag === "ProviderAdapterMcpRotationBlockedError") ) { return yield* loadFromProvider(Effect.fail(resumed.failure)); } diff --git a/apps/server/src/orchestration-v2/ThreadManagementService.ts b/apps/server/src/orchestration-v2/ThreadManagementService.ts index 45b5e9effa8cf..a7df3d28f77fa 100644 --- a/apps/server/src/orchestration-v2/ThreadManagementService.ts +++ b/apps/server/src/orchestration-v2/ThreadManagementService.ts @@ -38,6 +38,7 @@ import { ProviderInstanceId, type ProviderSessionId, resolveProjectProviderInstanceEnabled, + type RunAttemptId, RunId, type ScheduledTaskId, ThreadId, @@ -73,7 +74,9 @@ import { cancelledBeforeStart } from "./RestartBackgroundNote.ts"; import * as LegacyV1ThreadImporter from "./legacy/LegacyV1ThreadImporter.ts"; import * as ServerSettings from "../serverSettings.ts"; import { ThreadWorktreeRestore } from "../workspace/restoreMissingWorktree.ts"; -import { checkOutput, outputRequestProblem } from "./runOutput.ts"; +import { checkOutput, latestOwedOutputRun, outputRequestProblem } from "./runOutput.ts"; + +const isRunOutputDispatchRejectionError = Schema.is(Orchestrator.RunOutputDispatchRejectionError); export type ThreadManagementSendMode = "auto" | "queue" | "steer" | "restart"; @@ -492,6 +495,9 @@ export interface ThreadManagementServiceShape { readonly threadId: ThreadId; readonly commandId: CommandId; readonly json: string; + readonly callerRunId?: RunId; + readonly callerAttemptId?: RunAttemptId; + readonly requireCallerRunId?: boolean; }) => Effect.Effect<{ readonly runId: RunId }, ThreadManagementFailure>; readonly assertProviderInstanceEnabled: (input: { readonly projectId: ProjectId; @@ -1039,21 +1045,36 @@ const make = Effect.gen(function* () { // A turn that ended without its result still owes it: the agent may have ended it to wait // for something, and answer from the turn that woke it. // Only an ended turn can owe one; a queued or running turn asked for one answers for itself. - const owed = records.runs - .filter( - (candidate) => - candidate.outputSchema !== undefined && - candidate.output === undefined && - candidate.status === "completed", - ) - .toSorted((left, right) => right.ordinal - left.ordinal)[0]; + const owed = latestOwedOutputRun(records.runs); const run = active?.outputSchema !== undefined ? active : owed; + // Check whether a result is expected before caller identity so plain turns keep their message. if (active === undefined || run?.outputSchema === undefined) { return yield* new ThreadManagementRunOutputRejectedError({ threadId: input.threadId, problem: "This turn was not asked for a result. Reply in your message instead.", }); } + if (input.requireCallerRunId === true && input.callerRunId === undefined) { + return yield* new ThreadManagementRunOutputRejectedError({ + threadId: input.threadId, + problem: "This output was submitted for a turn that is no longer active.", + }); + } + if (input.callerRunId !== undefined || input.callerAttemptId !== undefined) { + const matchesRun = (candidate: OrchestrationV2Run | undefined) => + candidate !== undefined && + (input.callerRunId === undefined || candidate.id === input.callerRunId) && + (input.callerAttemptId === undefined || + candidate.activeAttemptId === input.callerAttemptId); + // Accept the active run, or the un-stopped completed run whose own owed output is targeted. + const callerAllowed = matchesRun(active) || (run.id !== active.id && matchesRun(run)); + if (!callerAllowed) { + return yield* new ThreadManagementRunOutputRejectedError({ + threadId: input.threadId, + problem: "This output was submitted for a turn that is no longer active.", + }); + } + } const checked = yield* checkOutput(run.outputSchema, input.json); if (Result.isFailure(checked)) { return yield* new ThreadManagementRunOutputRejectedError({ @@ -1067,8 +1088,25 @@ const make = Effect.gen(function* () { commandId: input.commandId, threadId: input.threadId, runId: run.id, + ...(input.callerRunId === undefined ? {} : { callerRunId: input.callerRunId }), + ...(input.callerAttemptId === undefined ? {} : { callerAttemptId: input.callerAttemptId }), value: checked.success, - }); + }).pipe( + Effect.catchTags({ + OrchestratorDispatchError: (error) => + isRunOutputDispatchRejectionError(error.cause) + ? Effect.fail( + new ThreadManagementRunOutputRejectedError({ + threadId: input.threadId, + problem: + error.cause.reason === "stopped" + ? "This turn was stopped and takes no result." + : "This output was submitted for a turn that is no longer active.", + }), + ) + : Effect.fail(error), + }), + ); return { runId: run.id }; }); diff --git a/apps/server/src/orchestration-v2/runOutput.ts b/apps/server/src/orchestration-v2/runOutput.ts index 26df71c0fa2e8..a583b7f6527da 100644 --- a/apps/server/src/orchestration-v2/runOutput.ts +++ b/apps/server/src/orchestration-v2/runOutput.ts @@ -1,10 +1,52 @@ -import { parseGoalCommand } from "@t3tools/contracts"; +import { parseGoalCommand, type RunId } from "@t3tools/contracts"; import * as Effect from "effect/Effect"; import * as JsonSchema from "effect/JsonSchema"; import * as Result from "effect/Result"; import * as Schema from "effect/Schema"; import * as SchemaRepresentation from "effect/SchemaRepresentation"; +/** Latest completed run on the thread that still owes a typed result, if any. */ +export function latestOwedOutputRun< + TRun extends { + readonly id: RunId; + readonly ordinal: number; + readonly status: string; + readonly outputSchema?: unknown; + readonly output?: unknown; + }, +>(runs: ReadonlyArray): TRun | undefined { + return runs + .filter( + (candidate) => + candidate.outputSchema !== undefined && + candidate.output === undefined && + candidate.status === "completed", + ) + .toSorted((left, right) => right.ordinal - left.ordinal)[0]; +} + +/** Whether a turn needs its MCP credential rotated to match its run/attempt identity. */ +export function runRequiresRunScopedMcp( + runs: ReadonlyArray<{ + readonly id: RunId; + readonly ordinal: number; + readonly status: string; + readonly outputSchema?: unknown; + readonly output?: unknown; + }>, + runId: RunId | undefined, + currentCredentialRunId?: RunId, +): boolean { + if ( + runId !== undefined && + runs.some((candidate) => candidate.id === runId && candidate.outputSchema !== undefined) + ) { + return true; + } + const owed = latestOwedOutputRun(runs); + return owed !== undefined && currentCredentialRunId !== owed.id; +} + type OutputSchema = Readonly>; // A schema built from JSON Schema needs no services, which its `Schema.Top` type cannot say. diff --git a/apps/server/src/orchestration-v2/runtimeLayer.test.ts b/apps/server/src/orchestration-v2/runtimeLayer.test.ts index c899eb774bfc3..6ef06a0595f3f 100644 --- a/apps/server/src/orchestration-v2/runtimeLayer.test.ts +++ b/apps/server/src/orchestration-v2/runtimeLayer.test.ts @@ -37,6 +37,7 @@ import { ProviderSessionId, ProviderThreadId, ProviderTurnId, + RunAttemptId, RunId, ScheduledTaskId, ThreadId, @@ -11995,11 +11996,351 @@ it.layer(layerSharedApplicationDataPlaneTest)("run output after a stop", (it) => json: "{}", }) .pipe(Effect.flip); - assert.include(String((rejected as { cause?: unknown }).cause), "was stopped"); + assert.equal(rejected._tag, "ThreadManagementRunOutputRejectedError"); + assert.include(rejected.message, "was stopped"); const after = yield* orchestrator.getThreadProjection(threadId); assert.isUndefined(after.runs[0]?.output); }), ); + + const setupOutputThread = (slug: string) => + Effect.gen(function* () { + const projects = yield* ProjectService.ProjectService; + const orchestrator = yield* Orchestrator.OrchestratorV2; + const eventSink = yield* EventSink.EventSinkV2; + const threadManagement = yield* ThreadManagementService.ThreadManagementService; + const projectId = ProjectId.make(`runtime-layer-${slug}-project`); + const threadId = ThreadId.make(`runtime-layer-${slug}-thread`); + yield* projects.create({ + commandId: CommandId.make(`runtime-layer-${slug}-project-create`), + projectId, + title: `Project ${slug}`, + workspaceRoot: `/tmp/runtime-layer-${slug}`, + }); + yield* orchestrator.dispatch({ + type: "thread.create", + createdBy: "user", + creationSource: "web", + commandId: CommandId.make(`runtime-layer-${slug}-create`), + threadId, + projectId, + title: `Thread ${slug}`, + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: null, + }); + const send = (key: string, outputSchema?: { readonly type: "object" }) => + orchestrator.dispatch({ + type: "message.dispatch", + createdBy: "user", + creationSource: "web", + commandId: CommandId.make(`runtime-layer-${slug}-${key}`), + threadId, + messageId: MessageId.make(`runtime-layer-${slug}-${key}`), + text: key, + attachments: [], + modelSelection, + ...(outputSchema === undefined ? {} : { outputSchema }), + dispatchMode: { type: "start_immediately" }, + }); + return { orchestrator, eventSink, threadManagement, threadId, send }; + }); + + it.effect.each([ + { + scenario: "stopped-run-or-stale-attempt" as const, + description: + "turns down a late submission from a stopped run or stale attempt once the next run is active", + }, + { + scenario: "owed-run-and-wake" as const, + description: + "accepts an owed run's own caller or its wake's caller while rejecting an earlier stopped run", + }, + { + scenario: "completed-before-dispatch" as const, + description: + "accepts a bound caller's own output when the run completes just before orchestrator dispatch", + }, + ])("$description", ({ scenario }) => + Effect.gen(function* () { + if (scenario === "stopped-run-or-stale-attempt") { + const { orchestrator, eventSink, threadManagement, threadId, send } = + yield* setupOutputThread("late-stopped-run"); + + // Run A starts with a schema, then is stopped while its submission is in flight. + yield* send("run-a", { type: "object" }); + const runA = (yield* orchestrator.getThreadProjection(threadId)).runs[0]!; + yield* eventSink.write({ + events: [ + { + id: EventId.make(`${threadId}-run-a-interrupted`), + type: "run.updated", + threadId, + runId: runA.id, + occurredAt: runA.requestedAt, + payload: { ...runA, status: "interrupted", completedAt: runA.requestedAt }, + }, + ], + }); + + // Run B starts with a compatible schema and attempt 2 active. + yield* send("run-b", { type: "object" }); + const runB = (yield* orchestrator.getThreadProjection(threadId)).runs.find( + (run) => run.id !== runA.id, + )!; + const attempt1 = RunAttemptId.make(`${runB.id}:attempt:1`); + const attempt2 = RunAttemptId.make(`${runB.id}:attempt:2`); + yield* eventSink.write({ + events: [ + { + id: EventId.make(`${threadId}-run-b-attempt-2`), + type: "run.updated", + threadId, + runId: runB.id, + occurredAt: runB.requestedAt, + payload: { ...runB, activeAttemptId: attempt2 }, + }, + ], + }); + + const unboundOnTyped = yield* threadManagement + .submitRunOutput({ + threadId, + commandId: CommandId.make("runtime-layer-unbound-run-output"), + json: '{"from":"unbound"}', + requireCallerRunId: true, + }) + .pipe(Effect.flip); + assert.equal(unboundOnTyped._tag, "ThreadManagementRunOutputRejectedError"); + assert.include(unboundOnTyped.message, "no longer active"); + + const lateFromA = yield* threadManagement + .submitRunOutput({ + threadId, + commandId: CommandId.make("runtime-layer-late-run-output-from-a"), + json: '{"from":"run-a"}', + callerRunId: runA.id, + }) + .pipe(Effect.flip); + assert.equal(lateFromA._tag, "ThreadManagementRunOutputRejectedError"); + assert.include(lateFromA.message, "no longer active"); + + const lateFromAttempt1 = yield* threadManagement + .submitRunOutput({ + threadId, + commandId: CommandId.make("runtime-layer-late-run-output-from-attempt-1"), + json: '{"from":"attempt-1"}', + callerRunId: runB.id, + callerAttemptId: attempt1, + }) + .pipe(Effect.flip); + assert.equal(lateFromAttempt1._tag, "ThreadManagementRunOutputRejectedError"); + assert.include(lateFromAttempt1.message, "no longer active"); + + const mid = yield* orchestrator.getThreadProjection(threadId); + assert.isUndefined(mid.runs.find((run) => run.id === runB.id)?.output); + + const acceptedB = yield* threadManagement.submitRunOutput({ + threadId, + commandId: CommandId.make("runtime-layer-late-run-output-from-b"), + json: '{"from":"run-b"}', + callerRunId: runB.id, + callerAttemptId: attempt2, + }); + assert.equal(acceptedB.runId, runB.id); + const afterB = yield* orchestrator.getThreadProjection(threadId); + assert.deepEqual(afterB.runs.find((run) => run.id === runB.id)?.output?.value, { + from: "run-b", + }); + + // A plain turn with no schema preserves the plain-turn guidance even for stale/unbound MCP callers. + yield* eventSink.write({ + events: [ + { + id: EventId.make(`${threadId}-run-b-completed`), + type: "run.updated", + threadId, + runId: runB.id, + occurredAt: runB.requestedAt, + payload: { ...runB, status: "completed", completedAt: runB.requestedAt }, + }, + ], + }); + yield* send("run-plain"); + const plainFromStale = yield* threadManagement + .submitRunOutput({ + threadId, + commandId: CommandId.make("runtime-layer-plain-run-output-stale"), + json: "{}", + callerRunId: runA.id, + requireCallerRunId: true, + }) + .pipe(Effect.flip); + assert.equal(plainFromStale._tag, "ThreadManagementRunOutputRejectedError"); + assert.include(plainFromStale.message, "not asked for a result"); + const plainFromUnbound = yield* threadManagement + .submitRunOutput({ + threadId, + commandId: CommandId.make("runtime-layer-plain-run-output-unbound"), + json: "{}", + requireCallerRunId: true, + }) + .pipe(Effect.flip); + assert.equal(plainFromUnbound._tag, "ThreadManagementRunOutputRejectedError"); + assert.include(plainFromUnbound.message, "not asked for a result"); + return; + } + + if (scenario === "owed-run-and-wake") { + const { orchestrator, eventSink, threadManagement, threadId, send } = + yield* setupOutputThread("owed-wake-output"); + + yield* send("run-a", { type: "object" }); + const runA = (yield* orchestrator.getThreadProjection(threadId)).runs[0]!; + yield* eventSink.write({ + events: [ + { + id: EventId.make(`${threadId}-run-a-interrupted`), + type: "run.updated", + threadId, + runId: runA.id, + occurredAt: runA.requestedAt, + payload: { ...runA, status: "interrupted", completedAt: runA.requestedAt }, + }, + ], + }); + + yield* send("run-c", { type: "object" }); + const runC = (yield* orchestrator.getThreadProjection(threadId)).runs.find( + (run) => run.id !== runA.id, + )!; + yield* eventSink.write({ + events: [ + { + id: EventId.make(`${threadId}-run-c-completed`), + type: "run.updated", + threadId, + runId: runC.id, + occurredAt: runC.requestedAt, + payload: { ...runC, status: "completed", completedAt: runC.requestedAt }, + }, + ], + }); + yield* send("run-d-wake"); + const runD = (yield* orchestrator.getThreadProjection(threadId)).runs.find( + (run) => run.id !== runA.id && run.id !== runC.id, + )!; + const staleAOnWake = yield* threadManagement + .submitRunOutput({ + threadId, + commandId: CommandId.make("runtime-layer-late-run-output-from-a-during-wake"), + json: '{"from":"stale-run-a"}', + callerRunId: runA.id, + }) + .pipe(Effect.flip); + assert.equal(staleAOnWake._tag, "ThreadManagementRunOutputRejectedError"); + + const acceptedFromC = yield* threadManagement.submitRunOutput({ + threadId, + commandId: CommandId.make("runtime-layer-late-run-output-from-c"), + json: '{"from":"run-c"}', + callerRunId: runC.id, + }); + assert.equal(acceptedFromC.runId, runC.id); + const afterC = yield* orchestrator.getThreadProjection(threadId); + assert.deepEqual(afterC.runs.find((run) => run.id === runC.id)?.output?.value, { + from: "run-c", + }); + + yield* eventSink.write({ + events: [ + { + id: EventId.make(`${threadId}-run-d-completed`), + type: "run.updated", + threadId, + runId: runD.id, + occurredAt: runD.requestedAt, + payload: { ...runD, status: "completed", completedAt: runD.requestedAt }, + }, + ], + }); + yield* send("run-e", { type: "object" }); + const runE = (yield* orchestrator.getThreadProjection(threadId)).runs.find( + (run) => ![runA.id, runC.id, runD.id].includes(run.id), + )!; + yield* eventSink.write({ + events: [ + { + id: EventId.make(`${threadId}-run-e-completed`), + type: "run.updated", + threadId, + runId: runE.id, + occurredAt: runE.requestedAt, + payload: { ...runE, status: "completed", completedAt: runE.requestedAt }, + }, + ], + }); + yield* send("run-f-wake"); + const runF = (yield* orchestrator.getThreadProjection(threadId)).runs.find( + (run) => ![runA.id, runC.id, runD.id, runE.id].includes(run.id), + )!; + const acceptedFromF = yield* threadManagement.submitRunOutput({ + threadId, + commandId: CommandId.make("runtime-layer-late-run-output-from-f"), + json: '{"from":"run-f"}', + callerRunId: runF.id, + }); + assert.equal(acceptedFromF.runId, runE.id); + const afterF = yield* orchestrator.getThreadProjection(threadId); + assert.deepEqual(afterF.runs.find((run) => run.id === runE.id)?.output?.value, { + from: "run-f", + }); + return; + } + + const { orchestrator, eventSink, threadId, send } = yield* setupOutputThread( + "completed-before-dispatch", + ); + yield* send("run-own", { type: "object" }); + const run = (yield* orchestrator.getThreadProjection(threadId)).runs[0]!; + const attempt = RunAttemptId.make(`${run.id}:attempt:1`); + yield* eventSink.write({ + events: [ + { + id: EventId.make(`${threadId}-run-own-completed`), + type: "run.updated", + threadId, + runId: run.id, + occurredAt: run.requestedAt, + payload: { + ...run, + activeAttemptId: attempt, + status: "completed", + completedAt: run.requestedAt, + }, + }, + ], + }); + + // Simulate the race where the run completes after service validation, with no active run. + yield* orchestrator.dispatch({ + type: "run.output.submit", + commandId: CommandId.make("runtime-layer-completed-before-dispatch-submit"), + threadId, + runId: run.id, + callerRunId: run.id, + callerAttemptId: attempt, + value: { answer: "landed-on-completion-race" }, + }); + const after = yield* orchestrator.getThreadProjection(threadId); + assert.deepEqual(after.runs[0]?.output?.value, { + answer: "landed-on-completion-race", + }); + }), + ); }); it.layer(layerTest)("snooze queued runs", (it) => { diff --git a/apps/server/src/preview/ServerBrowser.test.ts b/apps/server/src/preview/ServerBrowser.test.ts index 9d1460c9befd5..b3710cb6a73a2 100644 --- a/apps/server/src/preview/ServerBrowser.test.ts +++ b/apps/server/src/preview/ServerBrowser.test.ts @@ -12,6 +12,7 @@ import { EnvironmentId, PreviewTabId, ProviderInstanceId, + RunId, ThreadId, type PreviewAutomationLoadError, type PreviewAutomationResizeResult, @@ -21,11 +22,13 @@ import { import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; import * as Exit from "effect/Exit"; +import { HttpServer } from "effect/http"; import * as Scope from "effect/Scope"; import * as Fiber from "effect/Fiber"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as Logger from "effect/Logger"; +import * as NetAddress from "effect/net/NetAddress"; import * as Option from "effect/Option"; import * as Path from "effect/Path"; import * as PubSub from "effect/PubSub"; @@ -37,6 +40,7 @@ import { beforeEach, expect, vi } from "vite-plus/test"; import * as ServerConfig from "../config.ts"; import * as ServerEnvironment from "../environment/ServerEnvironment.ts"; +import * as McpSessionRegistry from "../mcp/McpSessionRegistry.ts"; import * as Broker from "../mcp/PreviewAutomationBroker.ts"; import * as DesktopChannel from "./DesktopBrowserChannel.ts"; import * as Manager from "./Manager.ts"; @@ -1541,6 +1545,98 @@ it.effect("enforces provider ownership and explicit targets when a session has m ).pipe(Effect.provide(layer)), ); +it.effect( + "preserves browser tab ownership across per-run MCP credential rotations while still blocking separate sessions", + () => + Effect.scoped( + Effect.gen(function* () { + const broker = yield* Broker.PreviewAutomationBroker; + const registry = yield* McpSessionRegistry.__testing.make().pipe( + Effect.provideService( + HttpServer.HttpServer, + HttpServer.HttpServer.of({ + address: NetAddress.inetAddressFromIpStringUnsafe("127.0.0.1", 43123), + serve: (() => Effect.void) as HttpServer.HttpServer["Service"]["serve"], + }), + ), + ); + yield* Effect.yieldNow; + + const runA = yield* registry.issue({ + threadId: scope.thread.threadId, + providerInstanceId: scope.thread.providerInstanceId, + capabilities: new Set(["preview"]), + runId: RunId.make("run-a"), + }); + const scopeA = yield* registry.resolve( + runA.config.authorizationHeader.replace(/^Bearer\s+/, ""), + ); + expect(scopeA).toBeDefined(); + const opened = yield* broker.invoke({ + scope: scopeA!, + operation: "open", + input: { reuseExistingTab: false, show: false }, + }); + const tabId = PreviewTabId.make(opened.tabId!); + + const runB = yield* registry.issue({ + threadId: scope.thread.threadId, + providerInstanceId: scope.thread.providerInstanceId, + capabilities: new Set(["preview"]), + providerSessionId: runA.config.providerSessionId, + runId: RunId.make("run-b"), + }); + expect(runB.config.providerSessionId).toBe(runA.config.providerSessionId); + expect(runB.config.credentialId).not.toBe(runA.config.credentialId); + const scopeB = yield* registry.resolve( + runB.config.authorizationHeader.replace(/^Bearer\s+/, ""), + ); + expect(scopeB?.thread.runId).toBe("run-b"); + + yield* broker.invoke({ + scope: scopeB!, + tabId, + operation: "navigate", + input: { url: "http://localhost:5173/after-rotation" }, + }); + expect(contexts[0]!.page.goto).toHaveBeenCalledWith( + "http://localhost:5173/after-rotation", + expect.anything(), + ); + const evaluated = yield* broker.invoke({ + scope: scopeB!, + tabId, + operation: "evaluate", + input: { expression: "ownedAfterRotation()" }, + }); + expect(evaluated).toBe("evaluated"); + + const separateSession = yield* registry.issue({ + threadId: scope.thread.threadId, + providerInstanceId: scope.thread.providerInstanceId, + capabilities: new Set(["preview"]), + runId: RunId.make("run-c"), + }); + expect(separateSession.config.providerSessionId).not.toBe(runA.config.providerSessionId); + const scopeOther = yield* registry.resolve( + separateSession.config.authorizationHeader.replace(/^Bearer\s+/, ""), + ); + const foreign = yield* broker + .invoke({ + scope: scopeOther!, + tabId, + operation: "navigate", + input: { url: "http://localhost:5173/separate-session" }, + }) + .pipe(Effect.flip); + expect(foreign).toMatchObject({ + _tag: "PreviewAutomationControlInterruptedError", + reason: "agentMismatch", + }); + }), + ).pipe(Effect.provide(layer)), +); + it.effect("a first still that never returns does not stall the tab's later captures", () => Effect.scoped( Effect.gen(function* () { diff --git a/packages/contracts/src/orchestrationV2.ts b/packages/contracts/src/orchestrationV2.ts index e08c5555a65c8..1a57100e750e8 100644 --- a/packages/contracts/src/orchestrationV2.ts +++ b/packages/contracts/src/orchestrationV2.ts @@ -3764,6 +3764,8 @@ const OrchestrationV2InternalCommand = Schema.Union([ commandId: CommandId, threadId: ThreadId, runId: RunId, + callerRunId: Schema.optional(RunId), + callerAttemptId: Schema.optional(RunAttemptId), value: Schema.Json, }), // Guest share commands the server issues after checking T3 Connect and the guest token. diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts index cf7bb6c0f92fd..87d6730e2bc8c 100644 --- a/packages/provider-acp/src/server/adapter.ts +++ b/packages/provider-acp/src/server/adapter.ts @@ -2263,6 +2263,8 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( : flavor.extractSubagentUpdate?.(tool); let turnAttached = yield* Deferred.make(); const activeSessionId = yield* Ref.make(null); + // Tracks the MCP Authorization header the active ACP session was created/loaded with. + const activeMcpAuthorization = yield* Ref.make(undefined); // session/load replays history before activeSessionId names the loaded session. const loadingSessionId = yield* Ref.make(null); const contextUsageBySessionId = yield* Ref.make( @@ -7931,7 +7933,9 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( threadId: ThreadId | null, candidate: AcpSessionRuntime.AcpSessionRuntimeStartResult, ) { - rememberTerminalEnvironment(candidate.sessionId, yield* readMcpContext(threadId)); + const mcpContext = yield* readMcpContext(threadId); + rememberTerminalEnvironment(candidate.sessionId, mcpContext); + yield* Ref.set(activeMcpAuthorization, mcpContext.authorization); yield* Ref.set(runtimeRestartRequired, false); yield* Ref.set(activeSessionId, candidate.sessionId); yield* setActiveSessionSetup(candidate); @@ -7988,10 +7992,12 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( prepareClaimableTerminalEnvironment(yield* readMcpContext(input.threadId)); return yield* startAcpRuntime(input.threadId); }); + const initialMcpContext = yield* readMcpContext(input.threadId); yield* Ref.set(activeSessionId, started.sessionId); + yield* Ref.set(activeMcpAuthorization, initialMcpContext.authorization); yield* Ref.set(loadingSessionId, null); yield* setActiveSessionSetup(started); - rememberTerminalEnvironment(started.sessionId, yield* readMcpContext(input.threadId)); + rememberTerminalEnvironment(started.sessionId, initialMcpContext); yield* runtime.drainEvents; const steersWithPrompt = flavor.steersWithPrompt?.(started.initializeResult) === true; const capabilities = negotiatedCapabilities( @@ -8004,6 +8010,8 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( const canLoadSession = started.initializeResult.agentCapabilities?.loadSession === true; const canResumeSession = started.initializeResult.agentCapabilities?.sessionCapabilities?.resume != null; + const usesMcpOverAcp = + started.initializeResult.agentCapabilities?.mcpCapabilities?.acp === true; const supportsImagePrompts = acpSupportsImagePrompts({ flavorSupportsImagePrompts: flavor.supportsImagePrompts, negotiatedImage: @@ -8034,10 +8042,40 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( detail: `ACP driver cannot load or resume session ${sessionId}`, }); }).pipe(Effect.onError(() => Ref.set(loadingSessionId, null))); - rememberTerminalEnvironment(activated.sessionId, yield* readMcpContext(threadId)); + if (runtimeMcpBridge !== undefined && mcpContext.authorization !== undefined) { + runtimeMcpBridge.setAuthorization(mcpContext.authorization); + } + rememberTerminalEnvironment(activated.sessionId, mcpContext); + yield* Ref.set(activeMcpAuthorization, mcpContext.authorization); return activated; }); + const syncMcpCredentialForSession = Effect.fnUntraced(function* ( + sessionId: string, + threadId: ThreadId | null, + options?: { readonly allowReload?: boolean }, + ) { + const currentMcpContext = yield* readMcpContext(threadId); + if (currentMcpContext.authorization === (yield* Ref.get(activeMcpAuthorization))) { + return false; + } + rememberTerminalEnvironment(sessionId, currentMcpContext); + if ( + usesMcpOverAcp && + runtimeMcpBridge !== undefined && + currentMcpContext.authorization !== undefined + ) { + runtimeMcpBridge.setAuthorization(currentMcpContext.authorization); + yield* Ref.set(activeMcpAuthorization, currentMcpContext.authorization); + return false; + } + if (options?.allowReload !== false && (canLoadSession || canResumeSession)) { + return true; + } + // Non-loadable agents or continuation wakes keep their active session; do not record as applied. + return false; + }); + const validateModelSelection = Effect.fn("AcpAdapterV2.validateModelSelection")(function* ( modelSelection: ModelSelection, ) { @@ -9006,6 +9044,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( yield* restartAcpRuntime(threadId); yield* Ref.set(runtimeRestartRequired, false); yield* Ref.set(activeSessionId, null); + yield* Ref.set(activeMcpAuthorization, undefined); yield* Ref.set(activeSessionSetup, null); yield* Ref.set(activeSelection, null); yield* Ref.set(activeInteractionMode, null); @@ -9279,8 +9318,20 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( const restartAfterInterrupt = yield* restartRuntimeAfterTeardownIfRequired( turnInput.threadId, ); + // Continuations consume existing wake traffic without re-prompting or reloading ACP. + const isContinuationTurn = + (postSettleContinuationEnabled || followsAgentWorkState) && + acpIsProviderContinuationMessage(turnInput.message); + const mcpReloadRequired = + !restartAfterInterrupt && + (yield* Ref.get(activeSessionId)) === requestedSessionId && + (yield* syncMcpCredentialForSession(requestedSessionId, turnInput.threadId, { + allowReload: !isContinuationTurn, + })); const needsSessionActivation = - (yield* Ref.get(activeSessionId)) !== requestedSessionId || restartAfterInterrupt; + (yield* Ref.get(activeSessionId)) !== requestedSessionId || + restartAfterInterrupt || + mcpReloadRequired; if (needsSessionActivation) { const activated = yield* activateSession(requestedSessionId, turnInput.threadId); yield* Ref.set(activeSessionId, activated.sessionId); @@ -9346,10 +9397,6 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( }); yield* Ref.set(suppressPostSettleMonitorPrompt, false); yield* Ref.set(handledBackgroundTaskIdsInActiveTurn, new Set()); - // Continuations consume existing wake traffic without re-prompting ACP. - const isContinuationTurn = - (postSettleContinuationEnabled || followsAgentWorkState) && - acpIsProviderContinuationMessage(turnInput.message); const isAppOwnedWakeTurn = acpIsAppOwnedWakeTurn(turnInput.message); if (!isAppOwnedWakeTurn) { yield* Ref.set(midTurnUnreportedCompletedTaskIds, new Set()); @@ -9829,6 +9876,12 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( return providerSession; }, canResumeAfterRestart: canLoadSession || canResumeSession, + mcpCredentialRotation: + usesMcpOverAcp && runtimeMcpBridge !== undefined + ? "live" + : canLoadSession || canResumeSession + ? "reload" + : "none", events: Stream.fromEffectRepeat(Queue.take(events)), ...(flavor.getModelContextWindow === undefined ? {} @@ -9975,7 +10028,18 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( const restartAfterInterrupt = yield* restartRuntimeAfterTeardownIfRequired( threadInput.providerThread.appThreadId, ).pipe(Effect.tapError(() => restorePreviousItemIdentity)); - if ((yield* Ref.get(activeSessionId)) !== sessionId || restartAfterInterrupt) { + const mcpReloadRequired = + !restartAfterInterrupt && + (yield* Ref.get(activeSessionId)) === sessionId && + (yield* syncMcpCredentialForSession( + sessionId, + threadInput.providerThread.appThreadId, + )); + if ( + (yield* Ref.get(activeSessionId)) !== sessionId || + restartAfterInterrupt || + mcpReloadRequired + ) { yield* Ref.set(snapshot, emptySnapshotState()); const activated = yield* activateSession( sessionId, @@ -10664,11 +10728,12 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( acpMcpActivation(mcpContext), forkMeta, ); - rememberTerminalEnvironment( - forked.sessionId, - yield* readMcpContext(forkInput.targetThreadId), - ); + if (runtimeMcpBridge !== undefined && mcpContext.authorization !== undefined) { + runtimeMcpBridge.setAuthorization(mcpContext.authorization); + } + rememberTerminalEnvironment(forked.sessionId, mcpContext); yield* Ref.set(activeSessionId, forked.sessionId); + yield* Ref.set(activeMcpAuthorization, mcpContext.authorization); yield* setActiveSessionSetup(forked); yield* Ref.set(activeSelection, null); yield* Ref.set(activeInteractionMode, null); diff --git a/packages/provider-acp/src/server/mcpOverAcpBridge.test.ts b/packages/provider-acp/src/server/mcpOverAcpBridge.test.ts index 04d9fe4b55632..00001e0db9a49 100644 --- a/packages/provider-acp/src/server/mcpOverAcpBridge.test.ts +++ b/packages/provider-acp/src/server/mcpOverAcpBridge.test.ts @@ -254,4 +254,339 @@ describe("AcpMcpOverAcpBridge", () => { expect(failure.message).toContain("exceeds 8 MiB"); }), ); + + it.effect.each([ + { + scenario: "reinitialize-and-stale-headers" as const, + description: + "re-initializes stateful MCP on setAuthorization and ignores stale in-flight session headers", + }, + { + scenario: "init-race-and-waiting-rejection" as const, + description: + "reconnects cleanly when auth rotates during initial initialize and rejects waiting calls from the prior generation", + }, + { + scenario: "error-and-malformed-initialize" as const, + description: + "fails reconnect when initialize returns an error or malformed envelope without sending notifications/initialized", + }, + ])("$description", ({ scenario }) => + Effect.gen(function* () { + if (scenario === "reinitialize-and-stale-headers") { + const seen: Array<{ + readonly authorization: string | null; + readonly sessionId: string | null; + readonly method: unknown; + }> = []; + const slowCallStarted = Promise.withResolvers(); + const releaseSlowCall = Promise.withResolvers(); + let sessionCounter = 0; + const sessionAuth = new Map(); + const bridge = yield* makeAcpMcpOverAcpBridge({ + endpoint: "http://127.0.0.1:1/mcp", + authorization: "Bearer run-1-token", + allocateConnectionId: Effect.succeed("connection-1"), + fetchImplementation: async (_url, init) => { + const headers = new Headers(init?.headers); + const auth = headers.get("authorization"); + const incomingSid = headers.get("mcp-session-id"); + const body = JSON.parse(String(init?.body)) as { + readonly id?: unknown; + readonly method?: unknown; + readonly params?: { readonly name?: string }; + }; + seen.push({ authorization: auth, sessionId: incomingSid, method: body.method }); + if (body.method === "initialize") { + const sid = `session-${++sessionCounter}`; + sessionAuth.set(sid, auth ?? ""); + return new Response( + JSON.stringify({ + jsonrpc: "2.0", + id: body.id, + result: { protocolVersion: "2025-06-18", capabilities: {}, serverInfo: {} }, + }), + { headers: { "content-type": "application/json", "mcp-session-id": sid } }, + ); + } + // Stateful MCP 2025-06-18 rejects non-initialize requests without a valid session id. + if (incomingSid === null || sessionAuth.get(incomingSid) !== auth) { + return new Response("Mcp-Session-Id does not exist", { status: 400 }); + } + if (body.method === "notifications/initialized") { + return new Response(null, { status: 202 }); + } + if (body.params?.name === "slow_call") { + slowCallStarted.resolve(); + await releaseSlowCall.promise; + } + return new Response( + JSON.stringify({ jsonrpc: "2.0", id: body.id, result: { content: [] } }), + { headers: { "content-type": "application/json", "mcp-session-id": incomingSid } }, + ); + }, + }); + + const { connectionId } = yield* bridge.connect({ serverId: "t3-code" }); + yield* bridge.message({ + connectionId, + method: "initialize", + params: { protocolVersion: "2025-06-18", capabilities: {}, clientInfo: { name: "acp" } }, + }); + const inFlight = yield* bridge + .message({ connectionId, method: "tools/call", params: { name: "slow_call" } }) + .pipe(Effect.forkChild); + yield* Effect.promise(() => slowCallStarted.promise); + + // Rotate auth while generation-1 call is in flight, then let generation-1 finish. + bridge.setAuthorization("Bearer run-2-token"); + releaseSlowCall.resolve(); + yield* Fiber.join(inFlight); + + // Generation-2 call must transparently re-initialize with run-2-token, not reuse session-1. + expect( + yield* bridge.message({ + connectionId, + method: "tools/call", + params: { name: "t3_submit_output" }, + }), + ).toEqual({ content: [] }); + + expect(seen).toEqual([ + { authorization: "Bearer run-1-token", sessionId: null, method: "initialize" }, + { authorization: "Bearer run-1-token", sessionId: "session-1", method: "tools/call" }, + { authorization: "Bearer run-2-token", sessionId: null, method: "initialize" }, + { + authorization: "Bearer run-2-token", + sessionId: "session-2", + method: "notifications/initialized", + }, + { authorization: "Bearer run-2-token", sessionId: "session-2", method: "tools/call" }, + ]); + return; + } + + if (scenario === "init-race-and-waiting-rejection") { + const seen: Array<{ + readonly authorization: string | null; + readonly sessionId: string | null; + readonly method: string; + }> = []; + const initStarted = Promise.withResolvers(); + const releaseInit = Promise.withResolvers(); + const reconnect3Started = Promise.withResolvers(); + const releaseReconnect3 = Promise.withResolvers(); + let nextSessionOrdinal = 0; + const activeSessionByAuth = new Map(); + const bridge = yield* makeAcpMcpOverAcpBridge({ + endpoint: "http://127.0.0.1:43123/mcp", + authorization: "Bearer run-1-token", + allocateConnectionId: Effect.succeed("conn-init-race"), + fetchImplementation: async (_input, init) => { + const headers = new Headers(init?.headers); + const auth = headers.get("authorization") ?? ""; + const incomingSid = headers.get("mcp-session-id"); + const body = JSON.parse(String(init?.body)) as { + id?: number; + method: string; + params?: { name?: string }; + }; + seen.push({ authorization: auth, sessionId: incomingSid, method: body.method }); + if (body.method === "initialize") { + if (auth === "Bearer run-1-token") { + initStarted.resolve(); + await releaseInit.promise; + } + if (auth === "Bearer run-3-token") { + reconnect3Started.resolve(); + await releaseReconnect3.promise; + } + const sid = `session-${++nextSessionOrdinal}`; + activeSessionByAuth.set(auth, sid); + return new Response( + JSON.stringify({ + jsonrpc: "2.0", + id: body.id, + result: { protocolVersion: "2025-06-18", capabilities: {} }, + }), + { headers: { "content-type": "application/json", "mcp-session-id": sid } }, + ); + } + const expectedSid = activeSessionByAuth.get(auth); + if (!incomingSid || incomingSid !== expectedSid) { + return new Response("Mcp-Session-Id does not exist", { status: 400 }); + } + if (body.method === "notifications/initialized") { + return new Response(null, { status: 202 }); + } + return new Response( + JSON.stringify({ jsonrpc: "2.0", id: body.id, result: { content: [] } }), + { headers: { "content-type": "application/json", "mcp-session-id": incomingSid } }, + ); + }, + }); + + // 1. Auth rotates while initial initialize is still in flight; subsequent call must reconnect. + const { connectionId } = yield* bridge.connect({ serverId: "t3-code" }); + const initFiber = yield* bridge + .message({ + connectionId, + method: "initialize", + params: { + protocolVersion: "2025-06-18", + capabilities: {}, + clientInfo: { name: "acp" }, + }, + }) + .pipe(Effect.forkChild); + yield* Effect.promise(() => initStarted.promise); + bridge.setAuthorization("Bearer run-2-token"); + releaseInit.resolve(); + yield* Fiber.join(initFiber); + + expect( + yield* bridge.message({ + connectionId, + method: "tools/call", + params: { name: "after_init_race" }, + }), + ).toEqual({ content: [] }); + + // 2. A gen-3 call waiting on reconnect while auth rotates to gen-4 is rejected before posting. + bridge.setAuthorization("Bearer run-3-token"); + const waitingGen3 = yield* bridge + .message({ connectionId, method: "tools/call", params: { name: "t3_submit_output" } }) + .pipe(Effect.flip, Effect.forkChild); + yield* Effect.promise(() => reconnect3Started.promise); + bridge.setAuthorization("Bearer run-4-token"); + releaseReconnect3.resolve(); + const rejected = yield* Fiber.join(waitingGen3); + expect(rejected.message).toContain("rotated"); + // Verify run-4-token never received the stale waiting gen-3 t3_submit_output call. + expect(seen.filter((entry) => entry.authorization === "Bearer run-4-token")).toEqual([]); + return; + } + + const methods: Array = []; + let nextInitMode: "ok" | "error" | "malformed" = "ok"; + const bridge = yield* makeAcpMcpOverAcpBridge({ + endpoint: "http://127.0.0.1:43123/mcp", + authorization: "Bearer run-1-token", + allocateConnectionId: Effect.succeed("conn-init-err"), + fetchImplementation: async (_input, init) => { + const body = JSON.parse(String(init?.body)) as { id?: number; method: string }; + methods.push(body.method); + if (body.method === "initialize") { + const mode = nextInitMode; + nextInitMode = "ok"; + if (mode === "error") { + return new Response( + JSON.stringify({ + jsonrpc: "2.0", + id: body.id, + error: { code: -32000, message: "initialize rejected" }, + }), + { headers: { "content-type": "application/json" } }, + ); + } + if (mode === "malformed") { + return new Response(JSON.stringify({ jsonrpc: "2.0", id: body.id }), { + headers: { "content-type": "application/json" }, + }); + } + return new Response( + JSON.stringify({ + jsonrpc: "2.0", + id: body.id, + result: { protocolVersion: "2025-06-18", capabilities: {} }, + }), + { headers: { "content-type": "application/json", "mcp-session-id": "sid-ok" } }, + ); + } + if (body.method === "notifications/initialized") { + return new Response(null, { status: 202 }); + } + return new Response( + JSON.stringify({ jsonrpc: "2.0", id: body.id, result: { content: [] } }), + { headers: { "content-type": "application/json", "mcp-session-id": "sid-ok" } }, + ); + }, + }); + const { connectionId } = yield* bridge.connect({ serverId: "t3-code" }); + yield* bridge.message({ + connectionId, + method: "initialize", + params: { protocolVersion: "2025-06-18", capabilities: {}, clientInfo: { name: "acp" } }, + }); + bridge.setAuthorization("Bearer run-2-token"); + nextInitMode = "error"; + const failedError = yield* bridge + .message({ connectionId, method: "tools/call", params: { name: "t3_submit_output" } }) + .pipe(Effect.flip); + expect(failedError.message).toContain("initialize rejected"); + nextInitMode = "malformed"; + const failedMalformed = yield* bridge + .message({ connectionId, method: "tools/call", params: { name: "t3_submit_output" } }) + .pipe(Effect.flip); + expect(failedMalformed.message).toContain("valid initialize response"); + expect(methods).toEqual(["initialize", "initialize", "initialize"]); + // Next call still retries reconnect because needsReconnect stayed true. + expect( + yield* bridge.message({ + connectionId, + method: "tools/call", + params: { name: "t3_submit_output" }, + }), + ).toEqual({ content: [] }); + expect(methods).toEqual([ + "initialize", + "initialize", + "initialize", + "initialize", + "notifications/initialized", + "tools/call", + ]); + + // An agent-issued initialize with an error or malformed response does not clear needsReconnect. + bridge.setAuthorization("Bearer run-3-token"); + nextInitMode = "error"; + const explicitError = yield* bridge + .message({ + connectionId, + method: "initialize", + params: { + protocolVersion: "2025-06-18", + capabilities: {}, + clientInfo: { name: "acp" }, + }, + }) + .pipe(Effect.flip); + expect(explicitError.message).toContain("initialize rejected"); + nextInitMode = "malformed"; + expect( + yield* bridge.message({ + connectionId, + method: "initialize", + params: { + protocolVersion: "2025-06-18", + capabilities: {}, + clientInfo: { name: "acp" }, + }, + }), + ).toBeNull(); + const methodsBeforeRecovery = methods.length; + expect( + yield* bridge.message({ + connectionId, + method: "tools/call", + params: { name: "t3_submit_output" }, + }), + ).toEqual({ content: [] }); + expect(methods.slice(methodsBeforeRecovery)).toEqual([ + "initialize", + "notifications/initialized", + "tools/call", + ]); + }), + ); }); diff --git a/packages/provider-acp/src/server/mcpOverAcpBridge.ts b/packages/provider-acp/src/server/mcpOverAcpBridge.ts index 779076a622b5b..d8b135393ef22 100644 --- a/packages/provider-acp/src/server/mcpOverAcpBridge.ts +++ b/packages/provider-acp/src/server/mcpOverAcpBridge.ts @@ -24,6 +24,9 @@ interface Connection { readonly mutex: Semaphore.Semaphore; sessionId: string | null; protocolVersion: string | null; + initializeParams: unknown; + hasInitialized: boolean; + needsReconnect: boolean; nextRequestId: number; } @@ -84,6 +87,8 @@ export interface AcpMcpOverAcpBridge { readonly disconnect: ( request: AcpSchema.DisconnectMcpRequest, ) => Effect.Effect; + /** Updates the Bearer header for future requests; in-flight calls keep the header they started with. */ + readonly setAuthorization: (authorization: string) => void; /** Fails every call in flight, so Stop releases their HTTP responses. */ readonly stopCalls: Effect.Effect; readonly dispose: Effect.Effect; @@ -93,6 +98,8 @@ export const makeAcpMcpOverAcpBridge = Effect.fn("AcpMcpOverAcpBridge.make")(fun options: AcpMcpOverAcpBridgeOptions, ): Effect.fn.Return { const fetchImplementation = options.fetchImplementation ?? fetch; + let authorization = options.authorization; + let authorizationGeneration = 0; const connections = yield* Effect.sync(() => new Map()); let callsStopped = yield* Deferred.make(); @@ -108,59 +115,169 @@ export const makeAcpMcpOverAcpBridge = Effect.fn("AcpMcpOverAcpBridge.make")(fun : Effect.succeed(connection); }); - // Only initialization needs ordering; negotiated calls may wait independently. + // Only initialization and auth-rotation reconnects need ordering; negotiated calls wait independently. const untilNegotiated = (connection: Connection, effect: Effect.Effect) => Effect.suspend(() => - connection.protocolVersion === null ? connection.mutex.withPermits(1)(effect) : effect, + connection.protocolVersion === null || connection.needsReconnect + ? connection.mutex.withPermits(1)(effect) + : effect, ); + const postOnce = Effect.fn("AcpMcpOverAcpBridge.postOnce")(function* ( + connection: Connection, + message: unknown, + requestAuthorization: string, + requestGeneration: number, + requestSessionId: string | null, + requestProtocolVersion: string | null, + ) { + const body = JSON.stringify(message); + if (Buffer.byteLength(body) > MAX_MESSAGE_BYTES) { + return yield* new AcpMcpOverAcpError({ message: "MCP-over-ACP message exceeds 8 MiB." }); + } + const response = yield* Effect.tryPromise({ + try: (signal) => + fetchImplementation(options.endpoint, { + method: "POST", + signal, + headers: { + "content-type": "application/json", + accept: "application/json, text/event-stream", + authorization: requestAuthorization, + ...(requestSessionId === null ? {} : { "mcp-session-id": requestSessionId }), + ...(requestProtocolVersion === null + ? {} + : { "mcp-protocol-version": requestProtocolVersion }), + }, + body, + }), + catch: bridgeError, + }); + if (requestGeneration === authorizationGeneration) { + connection.sessionId = response.headers.get("mcp-session-id") ?? connection.sessionId; + } + if (!response.ok) { + yield* Effect.promise( + () => response.body?.cancel().catch(() => undefined) ?? Promise.resolve(), + ); + return yield* new AcpMcpOverAcpError({ + message: `T3 Code MCP endpoint responded with HTTP ${response.status}.`, + }); + } + const payloads = [...(yield* Stream.runCollect(responsePayloads(response, bridgeError)))]; + if (requestGeneration === authorizationGeneration) { + for (const payload of payloads) { + connection.protocolVersion = protocolVersionOf(payload) ?? connection.protocolVersion; + } + } + return payloads; + }, Effect.mapError(bridgeError)); + + const reconnectIfNeeded = Effect.fn("AcpMcpOverAcpBridge.reconnectIfNeeded")(function* ( + connection: Connection, + message: unknown, + ) { + const method = asEnvelope(message)?.method; + if (!connection.needsReconnect || method === "initialize") return; + const reconnectGeneration = authorizationGeneration; + const reconnectAuth = authorization; + const initId = ++connection.nextRequestId; + const initPayloads = yield* postOnce( + connection, + { + jsonrpc: "2.0", + id: initId, + method: "initialize", + ...(connection.initializeParams == null ? {} : { params: connection.initializeParams }), + }, + reconnectAuth, + reconnectGeneration, + null, + null, + ); + const initEnvelope = asEnvelope( + initPayloads.find((payload) => asEnvelope(payload)?.id === initId), + ); + if ( + initEnvelope === null || + initEnvelope.error !== undefined || + protocolVersionOf(initEnvelope) === null + ) { + return yield* new AcpMcpOverAcpError({ + message: + initEnvelope?.error !== undefined + ? errorMessage(initEnvelope.error) + : "MCP server did not return a valid initialize response during reconnect.", + }); + } + if (reconnectGeneration !== authorizationGeneration) return; + yield* postOnce( + connection, + { jsonrpc: "2.0", method: "notifications/initialized" }, + reconnectAuth, + reconnectGeneration, + connection.sessionId, + connection.protocolVersion, + ); + if (reconnectGeneration === authorizationGeneration) { + connection.needsReconnect = false; + } + }); + const sendNow = ( connection: Connection, message: unknown, - ): Effect.Effect, AcpMcpOverAcpError> => - untilNegotiated( + ): Effect.Effect, AcpMcpOverAcpError> => { + const method = asEnvelope(message)?.method; + const pinnedGeneration = authorizationGeneration; + return untilNegotiated( connection, Effect.gen(function* () { - const body = JSON.stringify(message); - if (Buffer.byteLength(body) > MAX_MESSAGE_BYTES) { - return yield* new AcpMcpOverAcpError({ message: "MCP-over-ACP message exceeds 8 MiB." }); + if (method !== "initialize") { + while (connection.needsReconnect) { + if (authorizationGeneration !== pinnedGeneration) { + return yield* new AcpMcpOverAcpError({ + message: "MCP credentials rotated while the request was waiting to send.", + }); + } + yield* reconnectIfNeeded(connection, message); + } + if (authorizationGeneration !== pinnedGeneration) { + return yield* new AcpMcpOverAcpError({ + message: "MCP credentials rotated while the request was waiting to send.", + }); + } } - const response = yield* Effect.tryPromise({ - try: (signal) => - fetchImplementation(options.endpoint, { - method: "POST", - signal, - headers: { - "content-type": "application/json", - accept: "application/json, text/event-stream", - authorization: options.authorization, - ...(connection.sessionId === null - ? {} - : { "mcp-session-id": connection.sessionId }), - ...(connection.protocolVersion === null - ? {} - : { "mcp-protocol-version": connection.protocolVersion }), - }, - body, - }), - catch: bridgeError, - }); - connection.sessionId = response.headers.get("mcp-session-id") ?? connection.sessionId; - if (!response.ok) { - yield* Effect.promise( - () => response.body?.cancel().catch(() => undefined) ?? Promise.resolve(), + const requestGeneration = authorizationGeneration; + const requestAuthorization = authorization; + const requestSessionId = method === "initialize" ? null : connection.sessionId; + const requestProtocolVersion = method === "initialize" ? null : connection.protocolVersion; + const payloads = yield* postOnce( + connection, + message, + requestAuthorization, + requestGeneration, + requestSessionId, + requestProtocolVersion, + ); + if (method === "initialize") { + const requestId = asEnvelope(message)?.id; + const initEnvelope = asEnvelope( + payloads.find((payload) => asEnvelope(payload)?.id === requestId), ); - return yield* new AcpMcpOverAcpError({ - message: `T3 Code MCP endpoint responded with HTTP ${response.status}.`, - }); - } - const payloads = [...(yield* Stream.runCollect(responsePayloads(response, bridgeError)))]; - for (const payload of payloads) { - connection.protocolVersion = protocolVersionOf(payload) ?? connection.protocolVersion; + if ( + initEnvelope !== null && + initEnvelope.error === undefined && + protocolVersionOf(initEnvelope) !== null + ) { + connection.hasInitialized = true; + connection.needsReconnect = requestGeneration !== authorizationGeneration; + } } return payloads; - }).pipe(Effect.mapError(bridgeError)), + }), ); + }; const send = ( connection: Connection, @@ -191,7 +308,7 @@ export const makeAcpMcpOverAcpBridge = Effect.fn("AcpMcpOverAcpBridge.make")(fun method: "DELETE", signal, headers: { - authorization: options.authorization, + authorization, "mcp-session-id": sessionId, ...(connection.protocolVersion === null ? {} @@ -240,12 +357,18 @@ export const makeAcpMcpOverAcpBridge = Effect.fn("AcpMcpOverAcpBridge.make")(fun mutex: yield* Semaphore.make(1), sessionId: null, protocolVersion: null, + initializeParams: undefined, + hasInitialized: false, + needsReconnect: false, nextRequestId: 0, }); return { connectionId }; }), message: Effect.fn("mcpOverAcpBridge.message")(function* (request) { const connection = yield* connectionFor(request.connectionId); + if (request.method === "initialize") { + connection.initializeParams = request.params; + } const id = ++connection.nextRequestId; const payloads = yield* send(connection, { jsonrpc: "2.0", @@ -274,6 +397,17 @@ export const makeAcpMcpOverAcpBridge = Effect.fn("AcpMcpOverAcpBridge.make")(fun }); }), disconnect, + setAuthorization: (nextAuthorization) => { + if (nextAuthorization === authorization) return; + authorization = nextAuthorization; + authorizationGeneration += 1; + for (const connection of connections.values()) { + connection.sessionId = null; + if (connection.hasInitialized) { + connection.needsReconnect = true; + } + } + }, stopCalls: Effect.suspend(() => { const stopped = callsStopped; callsStopped = Deferred.makeUnsafe(); diff --git a/packages/provider-core/src/server/ProviderAdapter.ts b/packages/provider-core/src/server/ProviderAdapter.ts index 18ebf74baa1c7..d0bfe1635e1f1 100644 --- a/packages/provider-core/src/server/ProviderAdapter.ts +++ b/packages/provider-core/src/server/ProviderAdapter.ts @@ -294,6 +294,24 @@ export class ProviderAdapterThreadInUseError extends Schema.TaggedError()( + "ProviderAdapterMcpRotationBlockedError", + { + driver: ProviderDriverKind, + providerSessionId: ProviderSessionId, + providerThreadId: ProviderThreadId, + detail: Schema.String, + }, +) { + override get message(): string { + return this.detail; + } +} + /** * The user sent `/compact` to a driver whose session has no native compaction. */ @@ -517,6 +535,7 @@ export const ProviderAdapterV2Error = Schema.Union([ ProviderAdapterCloseSessionError, ProviderAdapterResumeThreadError, ProviderAdapterThreadInUseError, + ProviderAdapterMcpRotationBlockedError, ProviderAdapterEnsureThreadError, ProviderAdapterReadThreadSnapshotError, ProviderAdapterRollbackThreadError, @@ -740,6 +759,8 @@ export interface ProviderAdapterV2SessionRuntime { readonly providerSession: OrchestrationV2ProviderSession; /** False keeps conversations alive when the provider cannot restore them after a restart. */ readonly canResumeAfterRestart?: boolean; + /** How this runtime delivers rotated per-turn MCP credentials ("reload" when omitted). */ + readonly mcpCredentialRotation?: "live" | "reload" | "none"; readonly events: Stream.Stream; /** Manager runtimes broadcast independent subscriptions; adapters may expose only a single-consumer stream. */ readonly subscribeEvents?: Effect.Effect; diff --git a/packages/provider-core/src/server/failure.ts b/packages/provider-core/src/server/failure.ts index cfdb0eb3df9a6..d9d45bb1fb50b 100644 --- a/packages/provider-core/src/server/failure.ts +++ b/packages/provider-core/src/server/failure.ts @@ -141,6 +141,7 @@ function curatedCauseMessages(cause: unknown): { case "CodexGoalObjectiveTooLongError": case "ProviderSetupError": case "ProviderAdapterThreadInUseError": + case "ProviderAdapterMcpRotationBlockedError": case "ProviderCompactionUnsupportedError": return { known: stringField(cause, "message"), category: categoryMessage() }; case "CodexAppServerRequestError": { diff --git a/packages/provider-core/src/server/mcpSession.ts b/packages/provider-core/src/server/mcpSession.ts index 20d17df610fd7..cf3182293fe45 100644 --- a/packages/provider-core/src/server/mcpSession.ts +++ b/packages/provider-core/src/server/mcpSession.ts @@ -1,4 +1,10 @@ -import type { EnvironmentId, ProviderInstanceId, ThreadId } from "@t3tools/contracts"; +import type { + EnvironmentId, + ProviderInstanceId, + RunAttemptId, + RunId, + ThreadId, +} from "@t3tools/contracts"; import type * as Effect from "effect/Effect"; /** @@ -11,7 +17,11 @@ export interface McpProviderSessionConfig { readonly environmentId: EnvironmentId; readonly threadId: ThreadId; readonly providerSessionId: string; + /** Distinct per-token identifier so run rotations can keep a stable owner `providerSessionId`. */ + readonly credentialId?: string | undefined; readonly providerInstanceId: ProviderInstanceId; + readonly runId?: RunId | undefined; + readonly attemptId?: RunAttemptId | undefined; readonly endpoint: string; readonly authorizationHeader: string; /** Omit preview_* instructions when the user withholds agent browser access. */ @@ -22,6 +32,10 @@ export interface McpProviderSessionConfig { readonly hasPendingWake?: Effect.Effect; } +export const mcpCredentialIdOf = ( + config: Pick, +): string => config.credentialId ?? config.providerSessionId; + export function withAgentDeviceEnvironment( base: NodeJS.ProcessEnv, config: Pick | undefined, diff --git a/packages/provider-cursor/src/server/adapter.test.ts b/packages/provider-cursor/src/server/adapter.test.ts index 5c0a1940d671c..fd64491c466e2 100644 --- a/packages/provider-cursor/src/server/adapter.test.ts +++ b/packages/provider-cursor/src/server/adapter.test.ts @@ -3262,21 +3262,31 @@ describe("CursorAdapterV2", () => { assert.deepEqual(openedWith?.mcpServers, t3Servers); yield* sendTurn(1); assert.deepEqual(sentWith[0], { ...expectedServers, ...t3Servers }); - // A server switched off between turns stays off on the next one. + // A server switched off between turns stays off on the next one, and rotated MCP auth propagates. yield* fileSystem.writeFileString( path.join(home, ".cursor", "projects", projectDirectory, "mcp-disabled.json"), JSON.stringify(["off", "repro"]), ); + yield* mcpSessions.set({ + environmentId: EnvironmentId.make("cursor-mcp-environment"), + threadId, + providerSessionId: "cursor-mcp-session-2", + providerInstanceId: instanceId, + endpoint: "http://127.0.0.1:43123/mcp", + authorizationHeader: "Bearer rotated-cursor-token", + browserToolsAvailable: false, + }); + const rotatedT3Servers = cursorMcpServers(yield* mcpSessions.read(threadId)); yield* sendTurn(2); const { repro: _disabled, ...stillEnabled } = expectedServers; - assert.deepEqual(sentWith[1], { ...stillEnabled, ...t3Servers }); + assert.deepEqual(sentWith[1], { ...stillEnabled, ...rotatedT3Servers }); // Unreadable disabled state starts none of the overrides, and the turn still goes out. yield* fileSystem.writeFileString( path.join(home, ".cursor", "projects", projectDirectory, "mcp-disabled.json"), "[", ); yield* sendTurn(3); - assert.deepEqual(sentWith[2], t3Servers); + assert.deepEqual(sentWith[2], rotatedT3Servers); yield* fileSystem.writeFileString( path.join(workspace, ".cursor", "mcp.json"), JSON.stringify({ mcpServers: { plain: { command: "node", args: ["server.mjs"] } } }), diff --git a/packages/provider-cursor/src/server/adapter.ts b/packages/provider-cursor/src/server/adapter.ts index 7aadadaf9ddd4..03ef2807de3ef 100644 --- a/packages/provider-cursor/src/server/adapter.ts +++ b/packages/provider-cursor/src/server/adapter.ts @@ -3228,6 +3228,7 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* ( driver: CursorAgentSdk.CURSOR_PROVIDER, providerSessionId: input.providerSessionId, providerSession: session, + mcpCredentialRotation: "live", getModelContextWindow: (selection) => selection.instanceId === adapterOptions.instanceId ? cursorContextWindowTokens(selection, adapterOptions.getModels?.() ?? []) diff --git a/packages/provider-muse/src/server/adapter.test.ts b/packages/provider-muse/src/server/adapter.test.ts index f23f7ca84d7ea..37a3983855df9 100644 --- a/packages/provider-muse/src/server/adapter.test.ts +++ b/packages/provider-muse/src/server/adapter.test.ts @@ -416,6 +416,55 @@ describe("MuseAdapterV2", () => { }).pipe(Effect.scoped, Effect.provide(testLayer)), ); + it.effect("re-resumes with rotated MCP credentials on the next turn", () => + Effect.gen(function* () { + const mcpSessions = yield* McpProviderSessions.McpProviderSessions; + yield* mcpSessions.set({ + environmentId: EnvironmentId.make("test-environment"), + threadId: THREAD_ID, + providerSessionId: "test-session-1", + providerInstanceId: INSTANCE_ID, + endpoint: "http://127.0.0.1:43210/mcp", + authorizationHeader: "Bearer muse-run-1-token", + browserToolsAvailable: false, + }); + const fake = yield* makeFakeMuse(); + fake.host.initializeResult.grantedCapabilities.push("sessionMcp"); + const harness = yield* makeHarness(fake, INSTANCE_ID); + const started = yield* fake.takeCall("session/start"); + assert.strictEqual( + ( + started.params.config as { + mcpServers?: { "t3-code"?: { headers?: { Authorization?: string } } }; + } + )?.mcpServers?.["t3-code"]?.headers?.Authorization, + "Bearer muse-run-1-token", + ); + + yield* mcpSessions.set({ + environmentId: EnvironmentId.make("test-environment"), + threadId: THREAD_ID, + providerSessionId: "test-session-2", + providerInstanceId: INSTANCE_ID, + endpoint: "http://127.0.0.1:43210/mcp", + authorizationHeader: "Bearer muse-run-2-token", + browserToolsAvailable: false, + }); + yield* harness.runtime.startTurn(yield* turnInput(harness.providerThread, 2)); + const resumed = yield* fake.takeCall("session/resume"); + assert.deepStrictEqual(resumed.params.config, { + mcpServers: { + "t3-code": { + transport: "streamableHttp", + mode: "optional", + url: "http://127.0.0.1:43210/mcp", + headers: { Authorization: "Bearer muse-run-2-token" }, + }, + }, + }); + }).pipe(Effect.scoped, Effect.provide(testLayer)), + ); + it.effect("selects the runtime mode's permission profile on native start and resume", () => Effect.gen(function* () { for (const [runtimeMode, profile, approvalMode] of [ diff --git a/packages/provider-muse/src/server/adapter.ts b/packages/provider-muse/src/server/adapter.ts index 0b5835e0bad12..b132884c1bbe6 100644 --- a/packages/provider-muse/src/server/adapter.ts +++ b/packages/provider-muse/src/server/adapter.ts @@ -354,6 +354,7 @@ export const makeMuseAdapterV2 = Effect.fn("makeMuseAdapterV2")(function* ( let broken = false; // Only idle host failures can be retried on this runtime. let relaunchable = false; + let registeredMcpAuthorization: string | undefined; let nativeSessionId: string | undefined; let thread: OrchestrationV2ProviderThread | undefined; let active: ActiveTurn | undefined; @@ -1908,6 +1909,7 @@ export const makeMuseAdapterV2 = Effect.fn("makeMuseAdapterV2")(function* ( relaunchable = false; thread = undefined; nativeSessionId = undefined; + registeredMcpAuthorization = undefined; yield* updateSession("ready", null); } if (active) @@ -1921,17 +1923,25 @@ export const makeMuseAdapterV2 = Effect.fn("makeMuseAdapterV2")(function* ( const requestedId = existing ? (existing.nativeThreadRef?.nativeId ?? undefined) : input.initialNativeThreadId; - if ( - thread && + const mcpSession = yield* mcpSessions.read(args.threadId); + const sameThread = + thread !== undefined && (!requestedId || requestedId === nativeSessionId) && - thread.appThreadId === args.threadId - ) + thread.appThreadId === args.threadId; + if ( + thread !== undefined && + sameThread && + registeredMcpAuthorization === mcpSession?.authorizationHeader + ) { return thread; - if (thread) return yield* protocolError("Open a new host to attach another Muse session"); + } + if (thread && !sameThread) { + return yield* protocolError("Open a new host to attach another Muse session"); + } let missingNativeSession = false; return yield* Effect.gen(function* () { - nativeSessionId = requestedId ?? host.connection.mintCommandId(); - const mcpSession = yield* mcpSessions.read(args.threadId); + const resumeExistingId = sameThread ? nativeSessionId : requestedId; + nativeSessionId = resumeExistingId ?? host.connection.mintCommandId(); if (mcpSession && !host.initializeResult.grantedCapabilities.includes("sessionMcp")) return yield* protocolError( "Update Muse Code to a version that supports session MCP servers", @@ -1952,8 +1962,8 @@ export const makeMuseAdapterV2 = Effect.fn("makeMuseAdapterV2")(function* ( const startModel = yield* resolveModel(args.modelSelection); const permissionProfile = musePermissionProfile(args.runtimePolicy.runtimeMode); const result = yield* request( - requestedId ? "session/resume" : "session/start", - requestedId + resumeExistingId ? "session/resume" : "session/start", + resumeExistingId ? { excludeItems: true, ...(config ? { config } : {}), permissionProfile } : { workspaceRoot: cwd, @@ -1966,7 +1976,7 @@ export const makeMuseAdapterV2 = Effect.fn("makeMuseAdapterV2")(function* ( ).pipe( Effect.catch((error) => { missingNativeSession = - requestedId !== undefined && + resumeExistingId !== undefined && error.payload instanceof MspError && (error.payload.kind === "sessionNotFound" || error.payload.kind === "notFound"); return Effect.fail(error); @@ -1979,10 +1989,11 @@ export const makeMuseAdapterV2 = Effect.fn("makeMuseAdapterV2")(function* ( return yield* protocolError( "Muse cannot stream this session because its live view is unavailable", ); - if (requestedId) + if (resumeExistingId) yield* request("session/setApprovalMode", { mode: museApprovalMode(args.runtimePolicy.runtimeMode), }); + registeredMcpAuthorization = mcpSession?.authorizationHeader; const createdAt = yield* DateTime.now; thread = existing ? { @@ -2092,6 +2103,17 @@ export const makeMuseAdapterV2 = Effect.fn("makeMuseAdapterV2")(function* ( const continuation = turnInput.message.createdBy === "agent" && turnInput.message.creationSource === "provider"; + if (!continuation) { + const currentMcp = yield* mcpSessions.read(turnInput.threadId); + if (currentMcp?.authorizationHeader !== registeredMcpAuthorization) { + yield* register({ + threadId: turnInput.threadId, + modelSelection: turnInput.modelSelection, + runtimePolicy: turnInput.runtimePolicy, + existingProviderThread: turnInput.providerThread, + }); + } + } const adopted = continuation ? wake : undefined; const effort = continuation ? undefined : yield* selectionEffort(turnInput.modelSelection); const parts = compact || continuation ? [] : yield* prompt(turnInput.message); @@ -2276,6 +2298,7 @@ export const makeMuseAdapterV2 = Effect.fn("makeMuseAdapterV2")(function* ( instanceId: options.instanceId, driver: MUSE_PROVIDER, providerSessionId: input.providerSessionId, + mcpCredentialRotation: "live", providerSession: session, events: Stream.fromQueue(events), backgroundTasksEndWithProcess: true, diff --git a/packages/provider-opencode/src/server/adapter.test.ts b/packages/provider-opencode/src/server/adapter.test.ts index 3cd83ac152f8c..4c4590fe4f71d 100644 --- a/packages/provider-opencode/src/server/adapter.test.ts +++ b/packages/provider-opencode/src/server/adapter.test.ts @@ -9,6 +9,7 @@ import type { OpencodeClient, ToolPart } from "@opencode-ai/sdk/v2"; import { toolOutputImages } from "@t3tools/shared/toolOutput"; import { CheckpointId, + EnvironmentId, NodeId, ProjectId, ProviderInstanceId, @@ -316,6 +317,69 @@ describe("OpenCodeAdapterV2", () => { }).pipe(Effect.provide(Layer.merge(IdAllocator.layer, McpProviderSessions.layer))), ); + it.effect("refreshes the t3-code MCP server on startTurn when credentials rotate", () => + Effect.gen(function* () { + const mcpAdds: Array = []; + const nativeEvents = asyncEventStream(); + const mcpSessions = yield* McpProviderSessions.McpProviderSessions; + const threadId = ThreadId.make("thread-opencode-mcp-rotate"); + const instanceId = ProviderInstanceId.make("opencode-mcp-rotate"); + yield* mcpSessions.set({ + environmentId: EnvironmentId.make("env-opencode-mcp-rotate"), + threadId, + providerSessionId: "mcp-session-opencode-1", + providerInstanceId: instanceId, + endpoint: "http://127.0.0.1:43123/mcp", + authorizationHeader: "Bearer opencode-run-1-token", + browserToolsAvailable: false, + }); + const harness = yield* makeOpenCodeRuntimeHarness( + "mcp-rotate", + "ses_mcp_rotate", + { + event: { subscribe: async () => ({ stream: nativeEvents.stream }) }, + mcp: { + add: async (input: unknown) => { + mcpAdds.push(input); + return { data: {} }; + }, + }, + session: { + create: async () => ({ + data: { id: "ses_mcp_rotate", time: { created: 1, updated: 1 } }, + }), + promptAsync: async () => ({ data: undefined }), + }, + }, + {}, + { exitCode: Effect.never }, + ); + assert.equal(mcpAdds.length, 1); + + yield* mcpSessions.set({ + environmentId: EnvironmentId.make("env-opencode-mcp-rotate"), + threadId, + providerSessionId: "mcp-session-opencode-2", + providerInstanceId: instanceId, + endpoint: "http://127.0.0.1:43123/mcp", + authorizationHeader: "Bearer opencode-run-2-token", + browserToolsAvailable: false, + }); + yield* harness.startTurn("Second turn", harness.providerThread, harness.policy, false, "2"); + assert.deepEqual( + mcpAdds.map( + (entry) => + (entry as { config?: { headers?: { Authorization?: string } } }).config?.headers + ?.Authorization, + ), + ["Bearer opencode-run-1-token", "Bearer opencode-run-2-token"], + ); + }).pipe( + Effect.scoped, + Effect.provide(Layer.merge(IdAllocator.layer, McpProviderSessions.layer)), + ), + ); + it.effect.each([ ["empty", "prompt"], ["unsupported", "command"], diff --git a/packages/provider-opencode/src/server/adapter.ts b/packages/provider-opencode/src/server/adapter.ts index d0e1d27cc2a7b..0dd8580dd15fe 100644 --- a/packages/provider-opencode/src/server/adapter.ts +++ b/packages/provider-opencode/src/server/adapter.ts @@ -1096,6 +1096,7 @@ export const makeOpenCodeAdapterV2 = Effect.fn("makeOpenCodeAdapterV2")(function hasT3Mcp, mcpSession?.capabilities?.has("device") === true, ); + let appliedMcpAuthorization: string | undefined = undefined; if (hasT3Mcp) { yield* OpenCodeRuntime.runOpenCodeSdk("mcp.add", () => client.mcp.add({ @@ -1108,6 +1109,7 @@ export const makeOpenCodeAdapterV2 = Effect.fn("makeOpenCodeAdapterV2")(function }, }), ); + appliedMcpAuthorization = mcpSession.authorizationHeader; } const now = yield* DateTime.now; @@ -3628,6 +3630,7 @@ export const makeOpenCodeAdapterV2 = Effect.fn("makeOpenCodeAdapterV2")(function driver: OPENCODE_PROVIDER, providerSessionId: input.providerSessionId, providerSession: sessionEntity, + mcpCredentialRotation: "live", events: Stream.fromEffectRepeat(Queue.take(events)), hasPendingBackgroundWork: Effect.sync( () => @@ -3753,6 +3756,25 @@ export const makeOpenCodeAdapterV2 = Effect.fn("makeOpenCodeAdapterV2")(function ); } yield* applyPermissionRules(state, turnInput.runtimePolicy); + const currentMcp = yield* mcpSessions.read(turnInput.threadId); + if ( + currentMcp !== undefined && + !connection.external && + currentMcp.authorizationHeader !== appliedMcpAuthorization + ) { + yield* OpenCodeRuntime.runOpenCodeSdk("mcp.add", () => + client.mcp.add({ + name: "t3-code", + config: { + type: "remote", + url: currentMcp.endpoint, + headers: { Authorization: currentMcp.authorizationHeader }, + oauth: false, + }, + }), + ); + appliedMcpAuthorization = currentMcp.authorizationHeader; + } // A continuation admits a wake OpenCode is already running, so it sends no prompt. const isCompaction = !continuation && diff --git a/packages/provider-opencode/src/server/v2/adapter.ts b/packages/provider-opencode/src/server/v2/adapter.ts index 9e14f8c4ef36b..6ba2f498c43b5 100644 --- a/packages/provider-opencode/src/server/v2/adapter.ts +++ b/packages/provider-opencode/src/server/v2/adapter.ts @@ -43,6 +43,7 @@ import { type ProviderInstanceId, type RunId, type RuntimeRequestId, + type ThreadId, } from "@t3tools/contracts"; import type * as Cause from "effect/Cause"; import * as DateTime from "effect/DateTime"; @@ -4375,14 +4376,13 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr ), ); - const prepareTurn = Effect.fnUntraced(function* ( - sessionId: string, + const syncMcpServer = Effect.fnUntraced(function* ( state: ThreadState, - turnInput: ProviderAdapter.ProviderAdapterV2TurnInput, + threadId: ThreadId, + directory: string, ) { - const mcpSession = yield* mcpSessions.read(turnInput.threadId); - const directory = turnInput.runtimePolicy.cwd ?? host.paths.cwd; - const name = yield* mcpServerNameFor(turnInput.threadId); + const mcpSession = yield* mcpSessions.read(threadId); + const name = yield* mcpServerNameFor(threadId); // An external server may not reach T3's MCP endpoint, as with 1.x. const wanted = mcpSession === undefined || connection.external @@ -4428,6 +4428,20 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr yield* Effect.sleep(MCP_TOOL_RELOAD_SETTLE); } } + return { mcpSession, mcpAvailable }; + }); + + const prepareTurn = Effect.fnUntraced(function* ( + sessionId: string, + state: ThreadState, + turnInput: ProviderAdapter.ProviderAdapterV2TurnInput, + ) { + const directory = turnInput.runtimePolicy.cwd ?? host.paths.cwd; + const { mcpSession, mcpAvailable } = yield* syncMcpServer( + state, + turnInput.threadId, + directory, + ); const instructions = [ buildRuntimeInstructions({ harness: "OpenCode", @@ -4565,6 +4579,11 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr state: ThreadState, turnInput: ProviderAdapter.ProviderAdapterV2TurnInput, ) { + yield* syncMcpServer( + state, + turnInput.threadId, + turnInput.runtimePolicy.cwd ?? host.paths.cwd, + ); yield* beginTurn(state, turnInput, false); yield* lock.withPermit( Effect.gen(function* () { @@ -4764,6 +4783,7 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr instanceId, driver, providerSessionId: input.providerSessionId, + mcpCredentialRotation: "live", get providerSession() { return session; }, diff --git a/packages/provider-pi/src/server/adapter.test.ts b/packages/provider-pi/src/server/adapter.test.ts index 019af2a98783f..b555225f91df4 100644 --- a/packages/provider-pi/src/server/adapter.test.ts +++ b/packages/provider-pi/src/server/adapter.test.ts @@ -2172,14 +2172,81 @@ describe("PiAdapterV2", () => { // A thread's long-lived process keeps Pi's startup model refresh unless the user opts out. assert.notInclude(spawn.args, "--offline"); assert.isUndefined(spawn.env.PI_OFFLINE); + const fs = yield* FileSystem.FileSystem; assert.isTrue(extensions.some((path) => path?.endsWith("pi-t3-mcp-extension.ts"))); assert.equal(spawn.env.T3_MCP_URL, "http://127.0.0.1:43123/mcp"); assert.equal(spawn.env.T3_MCP_BEARER_TOKEN, "secret-pi-token"); + assert.isString(spawn.env.T3_MCP_BEARER_TOKEN_FILE); + assert.equal( + yield* fs.readFileString(String(spawn.env.T3_MCP_BEARER_TOKEN_FILE)), + "secret-pi-token", + ); assert.equal(spawn.env.T3_PI_RUNTIME_MODE, "full-access"); assert.equal(spawn.env.T3CODE_THREAD_ID, THREAD_ID); }).pipe(Effect.scoped, Effect.provide(layerTest)), ); + it.effect("writes rotated MCP bearer tokens to the session token file before the next turn", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const mcpSessions = yield* McpProviderSessions.McpProviderSessions; + yield* mcpSessions.set({ + environmentId: EnvironmentId.make("environment-pi-mcp-rotate"), + threadId: THREAD_ID, + providerSessionId: "mcp-session-pi-1", + providerInstanceId: PI_INSTANCE_ID, + endpoint: "http://127.0.0.1:43123/mcp", + authorizationHeader: "Bearer secret-pi-token-1", + browserToolsAvailable: false, + }); + const fake = yield* makeFakePi; + const { runtime, takeEvent } = yield* openRuntime(fake); + const rawTokenFile = fake.lastSpawn().env.T3_MCP_BEARER_TOKEN_FILE; + assert.isString(rawTokenFile); + const tokenFile = String(rawTokenFile); + assert.equal(yield* fs.readFileString(tokenFile), "secret-pi-token-1"); + const providerThread = yield* runtime.ensureThread({ + threadId: THREAD_ID, + modelSelection: modelSelection("default"), + runtimePolicy, + }); + + const runTurn = (text: string, ordinal: number) => + Effect.gen(function* () { + yield* startTurn(runtime, providerThread, "default", [], text, undefined, ordinal); + while (String((yield* fake.takeRequest("prompt"))["message"]).startsWith("/")) {} + yield* fake.emit({ type: "agent_start" }); + yield* fake.emit({ type: "agent_end", messages: [], willRetry: false }); + yield* fake.emit({ type: "agent_settled" }); + yield* takeEvent((event) => event.type === "turn.terminal"); + }); + + yield* runTurn("First turn", 1); + yield* mcpSessions.set({ + environmentId: EnvironmentId.make("environment-pi-mcp-rotate"), + threadId: THREAD_ID, + providerSessionId: "mcp-session-pi-2", + providerInstanceId: PI_INSTANCE_ID, + endpoint: "http://127.0.0.1:43123/mcp", + authorizationHeader: "Bearer secret-pi-token-2", + browserToolsAvailable: false, + }); + yield* runTurn("Second turn", 2); + + assert.equal(yield* fs.readFileString(tokenFile), "secret-pi-token-2"); + assert.deepEqual( + fake + .allRequests() + .filter( + (request) => + request["type"] === "prompt" && + String(request["message"]).includes("secret-pi-token"), + ), + [], + ); + }).pipe(Effect.scoped, Effect.provide(layerTest)), + ); + it.effect( "resumes a persisted session at spawn without replacing it or clearing model selection", () => diff --git a/packages/provider-pi/src/server/adapter.ts b/packages/provider-pi/src/server/adapter.ts index eae7f3eb6c2fa..611ddd7c84a69 100644 --- a/packages/provider-pi/src/server/adapter.ts +++ b/packages/provider-pi/src/server/adapter.ts @@ -491,7 +491,32 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( ) { const scope = yield* Effect.scope; const cwd = input.runtimePolicy.cwd ?? host.paths.cwd; - const mcpSession = yield* mcpSessions.read(input.threadId); + let appliedMcpAuthorization: string | undefined = undefined; + const mcpAuthDir = yield* fileSystem + .makeTempDirectoryScoped({ prefix: "t3-pi-mcp-auth-" }) + .pipe( + Effect.provideService(Scope.Scope, scope), + Effect.mapError( + (cause) => + new ProviderAdapter.ProviderAdapterOpenSessionError({ + driver: PI_PROVIDER, + providerSessionId: input.providerSessionId, + cause, + }), + ), + ); + const mcpTokenFilePath = path.join(mcpAuthDir, "token"); + let mcpTokenWriteOrdinal = 0; + const writeMcpTokenFile = Effect.fn("PiAdapterV2.writeMcpTokenFile")(function* ( + authorizationHeader: string, + ) { + const bearerToken = authorizationHeader.startsWith("Bearer ") + ? authorizationHeader.slice("Bearer ".length) + : authorizationHeader; + const stagingPath = path.join(mcpAuthDir, `token.${++mcpTokenWriteOrdinal}.tmp`); + yield* fileSystem.writeFileString(stagingPath, bearerToken, { mode: 0o600 }); + yield* fileSystem.rename(stagingPath, mcpTokenFilePath); + }); const provideCacheFs = (effect: Effect.Effect) => effect.pipe( Effect.provideService(FileSystem.FileSystem, fileSystem), @@ -536,11 +561,17 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( const startConnection = Effect.fnUntraced(function* (sessionPath?: string) { const connectionScope = yield* Scope.fork(scope, "sequential"); return yield* Effect.gen(function* () { + const liveMcpSession = yield* mcpSessions.read(input.threadId); + if (liveMcpSession !== undefined) { + yield* writeMcpTokenFile(liveMcpSession.authorizationHeader); + } + appliedMcpAuthorization = liveMcpSession?.authorizationHeader; const launch = buildPiRpcLaunch({ launchArgs: resolvedLaunchArgs.args, // PortScanner.AGENT_THREAD_ENV, as a literal because this package cannot reach apps/server. environment: { ...options.environment, T3CODE_THREAD_ID: input.threadId }, - mcpSession, + mcpSession: liveMcpSession, + mcpBearerTokenFile: liveMcpSession === undefined ? undefined : mcpTokenFilePath, extensionPath, sessionPath, runtimeMode: input.runtimePolicy.runtimeMode, @@ -3331,6 +3362,7 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( instanceId: options.instanceId, driver: PI_PROVIDER, providerSessionId: input.providerSessionId, + mcpCredentialRotation: "live", get providerSession() { return sessionEntity; }, @@ -3415,6 +3447,18 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( const continuation = turnInput.message.createdBy === "agent" && turnInput.message.creationSource === "provider"; + const currentMcp = yield* mcpSessions.read(turnInput.threadId); + if ( + currentMcp !== undefined && + currentMcp.authorizationHeader !== appliedMcpAuthorization + ) { + yield* writeMcpTokenFile(currentMcp.authorizationHeader).pipe( + Effect.mapError((cause) => + protocolError("Could not update Pi MCP credential", cause), + ), + ); + appliedMcpAuthorization = currentMcp.authorizationHeader; + } if (!continuation) yield* applySelection(turnInput.modelSelection); if (turnInput.appThread.title !== appliedSessionName) { yield* request({ diff --git a/packages/provider-pi/src/server/mcpBridge.testkit.ts b/packages/provider-pi/src/server/mcpBridge.testkit.ts index 759c8346ba037..8749805110625 100644 --- a/packages/provider-pi/src/server/mcpBridge.testkit.ts +++ b/packages/provider-pi/src/server/mcpBridge.testkit.ts @@ -63,13 +63,22 @@ export async function loadMcpBridge( readonly allowsTool?: (name: string) => boolean; readonly runtimeMode?: string; readonly inputSchema?: Record; + readonly fetchOverride?: ( + url: string, + transport: { body: string; headers: Record; signal?: AbortSignal }, + request: { readonly id: number; readonly method: string; readonly params?: unknown }, + defaultResponse: () => Promise, + ) => Promise; + readonly readTokenFileOverride?: (readCurrent: () => string) => Promise; } = {}, ) { const handlers = new Map(); + const commands = new Map Promise | void>(); const tools: RegisteredTool[] = []; const requests: Array<{ readonly method: string; readonly params?: unknown }> = []; let activeTools = ["read"]; let bridgeSourcePath = "/fixture/pi-t3-extension.ts"; + let bearerTokenFileContent = "fixture-token"; const transports: Array<{ readonly url: string; readonly authorization: string; @@ -105,12 +114,23 @@ export async function loadMcpBridge( env: { T3_MCP_URL: "http://fixture.invalid/mcp", T3_MCP_BEARER_TOKEN: "fixture-token", + T3_MCP_BEARER_TOKEN_FILE: "/fixture/pi-t3-mcp-token", T3_PI_MCP_EXTENSION_PATH: "/fixture/pi-t3-extension.ts", T3_PI_RUNTIME_MODE: options.runtimeMode, }, }, AbortSignal, NodeCrypto, + NodeFSP: { + readFile: async (filePath: string) => { + if (filePath === "/fixture/pi-t3-mcp-token") { + return options.readTokenFileOverride !== undefined + ? options.readTokenFileOverride(() => bearerTokenFileContent) + : bearerTokenFileContent; + } + throw new Error(`Unexpected file read: ${filePath}`); + }, + }, NodePath, Type: { Unsafe: (schema: unknown) => schema }, fetch: async ( @@ -129,19 +149,28 @@ export async function loadMcpBridge( params?: unknown; }; requests.push(request); - const result = - request.method === "tools/list" - ? { tools: catalog } - : request.method === "tools/call" - ? (options.result ?? { content: [{ type: "text", text: "browser snapshot" }] }) - : {}; - return new Response(JSON.stringify({ jsonrpc: "2.0", id: request.id, result }), { - headers: { "content-type": "application/json" }, - }); + const defaultResponse = async () => { + const result = + request.method === "tools/list" + ? { tools: catalog } + : request.method === "tools/call" + ? (options.result ?? { content: [{ type: "text", text: "browser snapshot" }] }) + : {}; + return new Response(JSON.stringify({ jsonrpc: "2.0", id: request.id, result }), { + headers: { "content-type": "application/json" }, + }); + }; + if (options.fetchOverride !== undefined) { + return options.fetchOverride(url, transport, request, defaultResponse); + } + return defaultResponse(); }, pi: { on: (name: string, handler: AgentStartHook) => handlers.set(name, handler), - registerCommand: () => {}, + registerCommand: ( + name: string, + command: { readonly handler: (args: string) => Promise | void }, + ) => commands.set(name, command.handler), registerTool: (tool: RegisteredTool) => { if (options.allowsTool && !options.allowsTool(tool.name)) return; const index = tools.findIndex((current) => current.name === tool.name); @@ -205,6 +234,7 @@ export async function loadMcpBridge( }; return { handlers, + commands, tools, declaredTools, callableTools: () => callableTools().map((tool) => tool.name), @@ -218,6 +248,9 @@ export async function loadMcpBridge( setBridgeSourcePath: (path: string) => { bridgeSourcePath = path; }, + setBearerTokenFile: (token: string) => { + bearerTokenFileContent = token; + }, requests, servers, transports, diff --git a/packages/provider-pi/src/server/mcpExtensionSource.test.ts b/packages/provider-pi/src/server/mcpExtensionSource.test.ts index 7506f155ab229..e0cfaa0618d7d 100644 --- a/packages/provider-pi/src/server/mcpExtensionSource.test.ts +++ b/packages/provider-pi/src/server/mcpExtensionSource.test.ts @@ -174,6 +174,184 @@ describe("Pi MCP tool results", () => { assert.deepEqual(output.content, [{ type: "text", text: '{"count":2}' }]); assert.deepEqual(output.structuredContent, result); }); + + it.each([ + { + scenario: "rotate-and-coalesce" as const, + description: + "rotates the MCP bearer token from the token file on turn start and reconnects before the next tool call", + }, + { + scenario: "ignore-stale-session-id" as const, + description: "ignores a late generation-1 mcp-session-id header after token rotation", + }, + { + scenario: "reject-waiting-on-rotation" as const, + description: + "rejects a waiting tool call if the MCP bearer token rotates during its first read or connect", + }, + ])("$description", async ({ scenario }) => { + if (scenario === "rotate-and-coalesce") { + const bridge = await loadMcpBridge(); + const startTurn = () => + bridge.handlers.get("before_agent_start")!( + { systemPrompt: "" }, + { ui: { notify: assert.fail } }, + ); + const tool = bridge.tools[0]!; + await tool.execute("call-1", {}); + assert.equal(bridge.transports.at(-1)?.authorization, "Bearer fixture-token"); + + bridge.setBearerTokenFile("rotated-run-2-token"); + await startTurn(); + + const requestCountBefore = bridge.requests.length; + await tool.execute("call-2", {}); + const afterMethods = bridge.requests.slice(requestCountBefore).map((req) => req.method); + assert.deepEqual(afterMethods, ["initialize", "notifications/initialized", "tools/call"]); + assert.deepEqual( + bridge.transports.slice(requestCountBefore).map((t) => t.authorization), + ["Bearer rotated-run-2-token", "Bearer rotated-run-2-token", "Bearer rotated-run-2-token"], + ); + + // Concurrent calls after a rotation coalesce into a single initialize handshake. + bridge.setBearerTokenFile("rotated-run-3-token"); + await startTurn(); + const concurrentStart = bridge.requests.length; + await Promise.all([tool.execute("call-3a", {}), tool.execute("call-3b", {})]); + const concurrentMethods = bridge.requests.slice(concurrentStart).map((req) => req.method); + assert.equal(concurrentMethods.filter((method) => method === "initialize").length, 1); + assert.equal(concurrentMethods.filter((method) => method === "tools/call").length, 2); + return; + } + + if (scenario === "ignore-stale-session-id") { + const slowStarted = Promise.withResolvers(); + const releaseSlow = Promise.withResolvers(); + const seen: Array<{ readonly method: string; readonly auth: string; readonly sid?: string }> = + []; + const bridge = await loadMcpBridge({ + fetchOverride: async (_url, transport, request, defaultResponse) => { + seen.push({ + method: request.method, + auth: transport.headers.authorization!, + ...(transport.headers["mcp-session-id"] === undefined + ? {} + : { sid: transport.headers["mcp-session-id"] }), + }); + if ( + request.method === "tools/call" && + transport.headers.authorization === "Bearer fixture-token" + ) { + slowStarted.resolve(); + await releaseSlow.promise; + return new Response( + JSON.stringify({ jsonrpc: "2.0", id: request.id, result: { content: [] } }), + { headers: { "content-type": "application/json", "mcp-session-id": "stale-sid-1" } }, + ); + } + const response = await defaultResponse(); + if (request.method === "initialize") { + return new Response(await response.text(), { + headers: { + "content-type": "application/json", + "mcp-session-id": + transport.headers.authorization === "Bearer fixture-token" + ? "stale-sid-1" + : "fresh-sid-2", + }, + }); + } + return response; + }, + }); + const tool = bridge.tools[0]!; + const inFlight = tool.execute("late-1", {}); + await slowStarted.promise; + bridge.setBearerTokenFile("run-2-token"); + releaseSlow.resolve(); + await inFlight; + await bridge.handlers.get("before_agent_start")!( + { systemPrompt: "" }, + { ui: { notify: assert.fail } }, + ); + + const beforeGen2 = seen.length; + await tool.execute("fresh-2", {}); + assert.deepEqual(seen.slice(beforeGen2), [ + { method: "initialize", auth: "Bearer run-2-token" }, + { method: "notifications/initialized", auth: "Bearer run-2-token", sid: "fresh-sid-2" }, + { method: "tools/call", auth: "Bearer run-2-token", sid: "fresh-sid-2" }, + ]); + return; + } + + const firstReadStarted = Promise.withResolvers(); + const releaseFirstRead = Promise.withResolvers(); + let interceptFirstRead = false; + const initStarted = Promise.withResolvers(); + const releaseInit = Promise.withResolvers(); + const postedCalls: Array<{ readonly auth: string; readonly params: unknown }> = []; + const bridge = await loadMcpBridge({ + readTokenFileOverride: async (readCurrent) => { + if (interceptFirstRead) { + interceptFirstRead = false; + firstReadStarted.resolve(); + await releaseFirstRead.promise; + } + return readCurrent(); + }, + fetchOverride: async (_url, transport, request, defaultResponse) => { + if ( + request.method === "initialize" && + transport.headers.authorization === "Bearer run-2-token" + ) { + initStarted.resolve(); + await releaseInit.promise; + } + if (request.method === "tools/call") { + postedCalls.push({ auth: transport.headers.authorization!, params: request.params }); + } + return defaultResponse(); + }, + }); + const tool = bridge.tools[0]!; + const startTurn = () => + bridge.handlers.get("before_agent_start")!( + { systemPrompt: "" }, + { ui: { notify: assert.fail } }, + ); + + // 1. Run A's call starts before Run B's turn; Run B renames the token file while Run A reads it. + interceptFirstRead = true; + const waitingFirstRead = tool.execute("late-from-run-a", { stale: true }); + await firstReadStarted.promise; + bridge.setBearerTokenFile("run-2-token"); + releaseFirstRead.resolve(); + let firstReadError: unknown; + try { + await waitingFirstRead; + } catch (caught) { + firstReadError = caught; + } + assert.include(String(firstReadError), "rotated"); + assert.deepEqual(postedCalls, []); + + // 2. Run B's turn starts and syncs run-2-token, then token rotates to run-3-token during connect. + await startTurn(); + const waitingGen2 = tool.execute("waiting-gen2", { stale: true }); + await initStarted.promise; + bridge.setBearerTokenFile("run-3-token"); + releaseInit.resolve(); + let error: unknown; + try { + await waitingGen2; + } catch (caught) { + error = caught; + } + assert.include(String(error), "rotated"); + assert.deepEqual(postedCalls, []); + }); }); describe("Pi MCP tool exposure", () => { diff --git a/packages/provider-pi/src/server/mcpExtensionSource.ts b/packages/provider-pi/src/server/mcpExtensionSource.ts index e934ce60e6ba6..25ac78eacb2d2 100644 --- a/packages/provider-pi/src/server/mcpExtensionSource.ts +++ b/packages/provider-pi/src/server/mcpExtensionSource.ts @@ -6,6 +6,7 @@ export const PI_T3_MCP_EXTENSION_FILENAME = "pi-t3-mcp-extension.ts"; export const T3_MCP_URL_ENV = "T3_MCP_URL"; export const T3_MCP_BEARER_ENV = "T3_MCP_BEARER_TOKEN"; +export const T3_MCP_BEARER_FILE_ENV = "T3_MCP_BEARER_TOKEN_FILE"; export const T3_PI_RUNTIME_MODE_ENV = "T3_PI_RUNTIME_MODE"; export const T3_PI_MCP_EXTENSION_PATH_ENV = "T3_PI_MCP_EXTENSION_PATH"; export const PI_T3_SERVICE_TIER_COMMAND = "t3-service-tier"; @@ -22,6 +23,7 @@ import { Type } from "typebox"; const URL_ENV = ${JSON.stringify(T3_MCP_URL_ENV)}; const TOKEN_ENV = ${JSON.stringify(T3_MCP_BEARER_ENV)}; +const TOKEN_FILE_ENV = ${JSON.stringify(T3_MCP_BEARER_FILE_ENV)}; const RUNTIME_MODE_ENV = ${JSON.stringify(T3_PI_RUNTIME_MODE_ENV)}; const EXTENSION_PATH_ENV = ${JSON.stringify(T3_PI_MCP_EXTENSION_PATH_ENV)}; const ORCHESTRATION_INSTRUCTIONS = ${JSON.stringify(T3_CODE_ORCHESTRATION_INSTRUCTIONS.trim())}; @@ -170,11 +172,35 @@ function isMcpToolError(result: unknown): boolean { ); } -function createMcpClient(endpoint: string, token: string) { +function createMcpClient(endpoint: string, initialToken: string, tokenFile: string | undefined) { let nextId = 1; let sessionId: string | undefined; + let currentToken = initialToken; + let authGeneration = 0; + let needsReconnect = false; + let connectInFlight: { readonly generation: number; readonly promise: Promise } | undefined; + + const setToken = (nextToken: string) => { + if (nextToken === currentToken) return; + currentToken = nextToken; + process.env[TOKEN_ENV] = nextToken; + authGeneration += 1; + sessionId = undefined; + connectInFlight = undefined; + needsReconnect = true; + }; + + const syncToken = async () => { + if (tokenFile === undefined) return; + try { + const next = (await NodeFSP.readFile(tokenFile, "utf8")).trim(); + if (next.length > 0 && next !== currentToken) setToken(next); + } catch { + // Missing or transient file read keeps the current in-memory bearer. + } + }; - const headers = (): Record => { + const headers = (token: string, sid: string | undefined): Record => { const next: Record = { accept: "application/json, text/event-stream", authorization: token.startsWith("Bearer ") ? token : \`Bearer \${token}\`, @@ -184,20 +210,24 @@ function createMcpClient(endpoint: string, token: string) { // header; initialize itself does not require it. "mcp-protocol-version": PROTOCOL, }; - if (sessionId !== undefined) next["mcp-session-id"] = sessionId; + if (sid !== undefined) next["mcp-session-id"] = sid; return next; }; const request = async (method: string, params?: unknown, signal?: AbortSignal) => { const id = nextId++; + const reqGeneration = authGeneration; + const reqToken = currentToken; + const reqSessionId = sessionId; const response = await fetch(endpoint, { method: "POST", - headers: headers(), + headers: headers(reqToken, reqSessionId), body: JSON.stringify({ jsonrpc: "2.0", id, method, params }), signal, }); + await syncToken(); const nextSession = response.headers.get("mcp-session-id"); - if (nextSession) sessionId = nextSession; + if (nextSession && reqGeneration === authGeneration) sessionId = nextSession; const body = await response.text(); if (!response.ok) { throw new Error(\`MCP \${method} failed (\${response.status}): \${body.slice(0, 400)}\`); @@ -213,14 +243,19 @@ function createMcpClient(endpoint: string, token: string) { const notify = async (method: string, params?: unknown, signal?: AbortSignal) => { await fetch(endpoint, { method: "POST", - headers: headers(), + headers: headers(currentToken, sessionId), body: JSON.stringify({ jsonrpc: "2.0", method, params }), signal, }); }; - return { - async connect(signal?: AbortSignal) { + const connect = async (signal?: AbortSignal) => { + await syncToken(); + const targetGeneration = authGeneration; + if (connectInFlight?.generation === targetGeneration) { + return connectInFlight.promise; + } + const promise = (async () => { await request( "initialize", { @@ -230,8 +265,24 @@ function createMcpClient(endpoint: string, token: string) { }, signal, ); - await notify("notifications/initialized", {}, signal).catch(() => undefined); - }, + if (targetGeneration === authGeneration) { + await notify("notifications/initialized", {}, signal).catch(() => undefined); + } + if (targetGeneration === authGeneration) { + needsReconnect = false; + } + })().finally(() => { + if (connectInFlight?.promise === promise) { + connectInFlight = undefined; + } + }); + connectInFlight = { generation: targetGeneration, promise }; + return promise; + }; + + return { + connect, + syncToken, async listTools(signal?: AbortSignal) { const tools: McpTool[] = []; let cursor: string | undefined; @@ -247,6 +298,21 @@ function createMcpClient(endpoint: string, token: string) { return tools; }, async callTool(name: string, args: Record, signal?: AbortSignal) { + const pinnedGeneration = authGeneration; + await syncToken(); + if (authGeneration !== pinnedGeneration) { + throw new Error("MCP credentials rotated while the tool call was waiting to send."); + } + while (needsReconnect) { + if (authGeneration !== pinnedGeneration) { + throw new Error("MCP credentials rotated while the tool call was waiting to send."); + } + await connect(signal); + await syncToken(); + } + if (authGeneration !== pinnedGeneration) { + throw new Error("MCP credentials rotated while the tool call was waiting to send."); + } return request("tools/call", { name, arguments: args }, signal); }, }; @@ -411,7 +477,7 @@ export default async function t3McpExtension(pi: ExtensionAPI) { (isDeferred(name) || active.includes("mcp__t3-code__" + name)); let catalog: ReadonlyArray = []; - const client = createMcpClient(endpoint, token); + const client = createMcpClient(endpoint, token, env(TOKEN_FILE_ENV)); let started: Promise | undefined; const registerTools = () => { @@ -517,6 +583,7 @@ export default async function t3McpExtension(pi: ExtensionAPI) { pi.on("session_tree", (_event, ctx) => reconcileDiscovery(ctx)); pi.on("model_select", (_event, ctx) => reconcileDiscovery(ctx)); pi.on("session_start", async (_event, ctx) => { + await client.syncToken(); reconcileDiscovery(ctx); try { await ensureStarted(); @@ -527,7 +594,8 @@ export default async function t3McpExtension(pi: ExtensionAPI) { }); // Keep guidance in the system prompt so leading slash commands still expand. - pi.on("before_agent_start", (event, ctx) => { + pi.on("before_agent_start", async (event, ctx) => { + await client.syncToken(); reconcileDiscovery(ctx); const instructions = ORCHESTRATION_INSTRUCTIONS + "\\n\\n" + PULL_REQUEST_LINKING_INSTRUCTIONS; const sections = event.systemPromptOptions?.sections; diff --git a/packages/provider-pi/src/server/mcpInjection.ts b/packages/provider-pi/src/server/mcpInjection.ts index 679b81ac33b78..738558e5d91c9 100644 --- a/packages/provider-pi/src/server/mcpInjection.ts +++ b/packages/provider-pi/src/server/mcpInjection.ts @@ -7,6 +7,7 @@ import { PI_T3_MCP_EXTENSION_FILENAME, PI_T3_MCP_EXTENSION_SOURCE, T3_MCP_BEARER_ENV, + T3_MCP_BEARER_FILE_ENV, T3_MCP_URL_ENV, T3_PI_RUNTIME_MODE_ENV, T3_PI_MCP_EXTENSION_PATH_ENV, @@ -250,6 +251,7 @@ export function buildPiRpcLaunch(input: { readonly launchArgs: ReadonlyArray; readonly environment: NodeJS.ProcessEnv; readonly mcpSession: McpProviderSessionConfig | undefined; + readonly mcpBearerTokenFile?: string | undefined; readonly extensionPath: string | undefined; readonly sessionPath?: string | undefined; readonly ephemeral?: boolean; @@ -296,6 +298,7 @@ export function buildPiRpcLaunch(input: { // MCP credentials belong to this T3 session; discard inherited server/parent credentials. delete environment[T3_MCP_URL_ENV]; delete environment[T3_MCP_BEARER_ENV]; + delete environment[T3_MCP_BEARER_FILE_ENV]; delete environment[T3_PI_MCP_EXTENSION_PATH_ENV]; return { @@ -317,6 +320,9 @@ export function buildPiRpcLaunch(input: { [T3_MCP_BEARER_ENV]: bearerTokenFromAuthorizationHeader( input.mcpSession.authorizationHeader, ), + ...(input.mcpBearerTokenFile === undefined + ? {} + : { [T3_MCP_BEARER_FILE_ENV]: input.mcpBearerTokenFile }), } : {}), }, From dd21241c112dc058602ef31dbc4f10612462256b Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 21 Nov 2026 15:56:25 +0000 Subject: [PATCH 02/34] docs(server): t3_submit_output rejects late calls from a stopped turn Co-Authored-By: Claude Opus 5.5 --- docs/orchestration-v2/orchestrator-mcp-server.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/orchestration-v2/orchestrator-mcp-server.md b/docs/orchestration-v2/orchestrator-mcp-server.md index 71d8845e74c75..e2ff45093c599 100644 --- a/docs/orchestration-v2/orchestrator-mcp-server.md +++ b/docs/orchestration-v2/orchestrator-mcp-server.md @@ -467,7 +467,9 @@ with no `output`. Stores the calling thread's result on its running turn, once it fits the schema that turn was sent with. A turn that was asked for nothing answers for the newest turn that was asked and has not answered yet, which is how an agent that -ended its turn to wait gives its result after it is woken. A rejection names what did not fit, so the agent can +ended its turn to wait gives its result after it is woken. A typed turn's MCP +credential carries its run and attempt, so a late call from a stopped or +superseded turn is rejected instead of landing on the next one. A rejection names what did not fit, so the agent can correct it and call again; a later accepted submission replaces an earlier one. ### `t3_thread_wait` From ba18ef7387a9efaa4aaaf33a898dcc22884dd9ff Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 21 Nov 2026 16:09:45 +0000 Subject: [PATCH 03/34] fix(server): MCP credential rotation keeps the old credential when it cannot apply the new one - A failed or timed-out unload fails the turn and keeps the loaded thread on its old credential, instead of resuming a possibly still-loaded thread with new config. - A rotation rollback leaves a credential that a later open published. - Closing a session revokes superseded credentials that no other runtime holds. - A failed run lookup fails the turn instead of keeping the old credential. - ACP: block a credential reload while background work runs, install the incoming policy before reactivation, and reconnect a connection whose DELETE raced a rotation. - Claude: a continuation turn refreshes MCP servers on the retained query. Co-Authored-By: Claude Opus 5.5 --- .../Adapters/ClaudeAdapterV2.ts | 14 ++ .../ProviderSessionManager.test.ts | 58 ++++++ .../ProviderSessionManager.ts | 166 ++++++++++++------ packages/provider-acp/src/server/adapter.ts | 55 ++++-- .../src/server/mcpOverAcpBridge.ts | 17 +- 5 files changed, 239 insertions(+), 71 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts index f56c0071ec28e..825cc56d7f097 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts @@ -13224,6 +13224,20 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( !existing.stopping && isClaudeProviderContinuationTurn(turnInput) ) { + // The turn's run may have rotated the credential; the retained query must carry it. + // Reopening would end the wake, so a failed refresh keeps the query and is logged. + if (canUpdateMcpLive(existing)) { + yield* syncMcpServersLive(existing).pipe( + Effect.catchCauseIf( + (cause) => !Cause.hasInterruptsOnly(cause), + () => + Effect.logWarning("orchestration-v2.claude-live-mcp-refresh-failed", { + threadId: turnInput.threadId, + reason: "continuation", + }), + ), + ); + } return existing; } const policyCompatible = diff --git a/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts b/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts index 8a710a7ad9748..3e69a5f8a3b70 100644 --- a/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts +++ b/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts @@ -3528,6 +3528,7 @@ it.effect.each([ if (scenario === "reload-blocked") { const unloads = yield* Queue.unbounded(); const pendingBackgroundWork = yield* Ref.make(true); + const failUnload = yield* Ref.make(false); const effect = Effect.gen(function* () { const eventSink = yield* EventSink.EventSinkV2; const idAllocator = yield* IdAllocator.IdAllocatorV2; @@ -3863,6 +3864,60 @@ it.effect.each([ assert.equal(runlessRecovered!.providerSessionId, broadLoadedConfig!.providerSessionId); assert.isFalse(runlessRecovered!.browserToolsAvailable); + // A failed unload may leave the thread loaded, where a resume ignores new config: keep the old credential. + const unloadFailedThreadId = ThreadId.make("thread-provider-session-manager-unload-failed"); + const unloadFailedProviderThread = makeProviderThread({ + idAllocator, + threadId: unloadFailedThreadId, + providerSessionId, + now, + }); + yield* eventSink.write({ + events: [ + yield* makeThreadCreatedEvent({ idAllocator, threadId: unloadFailedThreadId, now }), + ], + }); + yield* manager.open({ + threadId: unloadFailedThreadId, + providerSessionId, + modelSelection, + runtimePolicy, + }); + const beforeFailedUnload = yield* mcpSessions.read(unloadFailedThreadId); + yield* runtime.resumeThread({ + threadId: unloadFailedThreadId, + providerThread: unloadFailedProviderThread, + modelSelection, + runtimePolicy, + }); + yield* manager.open({ + threadId: unloadFailedThreadId, + providerSessionId, + modelSelection, + runtimePolicy, + runId: RunId.make("run-unload-failed-typed"), + attemptId: RunAttemptId.make("attempt-unload-failed-typed"), + requireRunScopedMcp: true, + }); + const stagedToken = (yield* mcpSessions.read( + unloadFailedThreadId, + ))!.authorizationHeader.replace(/^Bearer\s+/, ""); + yield* Ref.set(failUnload, true); + const unloadFailed = yield* runtime + .resumeThread({ + threadId: unloadFailedThreadId, + providerThread: unloadFailedProviderThread, + modelSelection, + runtimePolicy, + }) + .pipe(Effect.flip); + assert.equal(unloadFailed._tag, "ProviderAdapterMcpRotationBlockedError"); + assert.isUndefined(yield* registry.resolve(stagedToken)); + assert.equal( + (yield* mcpSessions.read(unloadFailedThreadId))?.authorizationHeader, + beforeFailedUnload!.authorizationHeader, + ); + yield* manager.close(providerSessionId); }); @@ -3875,6 +3930,9 @@ it.effect.each([ idleTimeoutMs: 1_000, unloads, hasPendingBackgroundWorkForThread: Ref.get(pendingBackgroundWork), + beforeUnload: Ref.get(failUnload).pipe( + Effect.flatMap((fail) => (fail ? Effect.die("unload failed") : Effect.void)), + ), serverSettingsLayer, }), serverSettingsLayer, diff --git a/apps/server/src/orchestration-v2/ProviderSessionManager.ts b/apps/server/src/orchestration-v2/ProviderSessionManager.ts index b943e3139c294..85c9f60bd4d90 100644 --- a/apps/server/src/orchestration-v2/ProviderSessionManager.ts +++ b/apps/server/src/orchestration-v2/ProviderSessionManager.ts @@ -688,10 +688,11 @@ export const layerWithOptions = ( runId: RunId | undefined, currentCredentialRunId?: RunId, ) => - projectionStore.getThreadRecords(threadId, ["runs"]).pipe( - Effect.map(({ runs }) => runRequiresRunScopedMcp(runs, runId, currentCredentialRunId)), - Effect.orElseSucceed(() => false), - ); + projectionStore + .getThreadRecords(threadId, ["runs"]) + .pipe( + Effect.map(({ runs }) => runRequiresRunScopedMcp(runs, runId, currentCredentialRunId)), + ); /** Serialize prepares per thread so concurrent rotations cannot revoke each other's credentials. */ const prepareMcpSession = ( threadId: ThreadId, @@ -1738,22 +1739,27 @@ export const layerWithOptions = ( ([threadId, mcpCredentialIds]) => Effect.forEach( mcpCredentialIds, - (mcpCredentialId) => { - // Only holders of this credential may prevent its revocation; stale credentials must not leak it. - const heldElsewhere = - isMcpCredentialReserved(threadId, mcpCredentialId) || - Array.from(current.values()).some( - (other) => - other !== entry && - (other.attachedThreadIds.has(threadId) || - other.mcpCredentialIdsByThread - .get(threadId) - ?.has(mcpCredentialId) === true), - ); - return heldElsewhere - ? Effect.void - : clearMcpSession(threadId, mcpCredentialId); - }, + (mcpCredentialId) => + Effect.gen(function* () { + // Only holders of this credential may prevent its revocation; stale credentials must not leak it. + // An attached replacement holds only the thread's current one, which it may not have recorded yet. + const threadCurrent = yield* mcpSessions.read(threadId); + const isThreadCurrent = + threadCurrent !== undefined && + McpProviderSession.mcpCredentialIdOf(threadCurrent) === + mcpCredentialId; + const heldElsewhere = + isMcpCredentialReserved(threadId, mcpCredentialId) || + Array.from(current.values()).some( + (other) => + other !== entry && + ((isThreadCurrent && other.attachedThreadIds.has(threadId)) || + other.mcpCredentialIdsByThread + .get(threadId) + ?.has(mcpCredentialId) === true), + ); + if (!heldElsewhere) yield* clearMcpSession(threadId, mcpCredentialId); + }), { discard: true }, ), { discard: true }, @@ -2207,7 +2213,20 @@ export const layerWithOptions = ( input.requireRunScopedMcp !== undefined ? input.requireRunScopedMcp || (input.owedOutputRunId !== undefined && current?.runId !== input.owedOutputRunId) - : yield* threadRequiresRunScopedMcp(input.threadId, input.runId, current?.runId); + : yield* threadRequiresRunScopedMcp( + input.threadId, + input.runId, + current?.runId, + ).pipe( + Effect.mapError( + (cause) => + new ProviderSessionOpenError({ + instanceId: input.providerInstanceId, + providerSessionId: input.providerSessionId, + cause, + }), + ), + ); if (!rotateOnRunChange && current !== undefined) { yield* recordMcpTurnChecked(input.providerSessionId, input.threadId, turnKey); return; @@ -2664,43 +2683,72 @@ export const layerWithOptions = ( () => Effect.succeed(true), ), ); + // Keep the loaded thread on its credential and never mutate an issued bearer's run identity. + const rollBack = (detail: string) => + mcpPrepareLock + .withLock( + input.threadId, + Effect.gen(function* () { + const staged = yield* mcpSessions.read(input.threadId); + // A later open published its own credential; that one stays. + if ( + staged === undefined || + McpProviderSession.mcpCredentialIdOf(staged) !== currentCredentialId + ) { + return; + } + // Capability removals revoke immediately, so restore only a still-valid credential. + const loadedRawToken = loadedCredential.authorizationHeader.replace( + /^Bearer\s+/, + "", + ); + if ((yield* mcpSessionRegistry.resolve(loadedRawToken)) !== undefined) { + yield* mcpSessions.set(loadedCredential); + } else { + yield* mcpSessions.clear(input.threadId); + } + yield* mcpSessionRegistry.revokeCredential(currentCredentialId); + yield* removeSessionMcpCredential( + input.providerSessionId, + input.threadId, + currentCredentialId, + ); + yield* recordMcpTurnChecked( + input.providerSessionId, + input.threadId, + undefined, + ); + }), + ) + .pipe( + Effect.andThen( + Effect.fail( + new ProviderAdapter.ProviderAdapterMcpRotationBlockedError({ + driver: entry.runtime.driver, + providerSessionId: input.providerSessionId, + providerThreadId: input.providerThread.id, + detail, + }), + ), + ), + ); if (hasPendingWork) { - // Keep background work alive and never mutate an issued bearer's run identity. - // Restore the still-loaded credential only if still valid (capability removals revoke immediately). - const loadedRawToken = loadedCredential.authorizationHeader.replace( - /^Bearer\s+/, - "", - ); - if ((yield* mcpSessionRegistry.resolve(loadedRawToken)) !== undefined) { - yield* mcpSessions.set(loadedCredential); - } else { - yield* mcpSessions.clear(input.threadId); - } - yield* mcpSessionRegistry.revokeCredential(currentCredentialId); - yield* removeSessionMcpCredential( - input.providerSessionId, - input.threadId, - currentCredentialId, + return yield* rollBack( + "Cannot refresh MCP credentials while background work is running on this thread.", ); - yield* recordMcpTurnChecked(input.providerSessionId, input.threadId, undefined); - return yield* new ProviderAdapter.ProviderAdapterMcpRotationBlockedError({ - driver: entry.runtime.driver, - providerSessionId: input.providerSessionId, - providerThreadId: input.providerThread.id, - detail: - "Cannot refresh MCP credentials while background work is running on this thread.", - }); } - const unloading = yield* Ref.modify(sessions, (current) => { + const unloadingKey = yield* Ref.modify(sessions, (current) => { const latest = current.get(key); const latestLoaded = latest?.loadedMcpCredentialByThread.get(input.threadId); + const latestThreadKey = latest?.loadedProviderThreadKeyByThread.get(input.threadId); if ( latest?.runtime !== entry.runtime || latestLoaded === undefined || + latestThreadKey === undefined || McpProviderSession.mcpCredentialIdOf(latestLoaded) !== loadedCredentialId || hasBusyTurn(latest, input.providerThread.id) ) { - return [false, current] as const; + return [undefined, current] as const; } const loadedProviderThreadKeyByThread = new Map( latest.loadedProviderThreadKeyByThread, @@ -2709,7 +2757,7 @@ export const layerWithOptions = ( const loadedMcpCredentialByThread = new Map(latest.loadedMcpCredentialByThread); loadedMcpCredentialByThread.delete(input.threadId); return [ - true, + latestThreadKey, new Map(current).set(key, { ...latest, loadedProviderThreadKeyByThread, @@ -2717,20 +2765,30 @@ export const layerWithOptions = ( }), ] as const; }); - if (!unloading) return; - let unloaded = false; - yield* unloadThread({ providerThread: input.providerThread }).pipe( + if (unloadingKey === undefined) return; + const unloaded = yield* unloadThread({ providerThread: input.providerThread }).pipe( Effect.timeout(UNLOAD_THREAD_TIMEOUT_MS), - Effect.tap(() => Effect.sync(() => (unloaded = true))), + Effect.as(true), Effect.catchCause((cause) => Effect.logWarning("orchestration-v2.driver-session.mcp-unload-failed", { providerSessionId: input.providerSessionId, threadId: input.threadId, cause, - }), + }).pipe(Effect.as(false)), ), ); - if (unloaded && loadedCredential.runId === undefined) { + if (!unloaded) { + // A thread that may still be loaded ignores the new config on resume; keep it on the old one. + yield* markProviderThreadLoaded({ + providerSessionId: input.providerSessionId, + threadId: input.threadId, + providerThreadKey: unloadingKey, + linkedEnvironments: undefined, + mcpCredential: loadedCredential, + }); + return yield* rollBack("Could not reload the thread to refresh MCP credentials."); + } + if (loadedCredential.runId === undefined) { yield* mcpSessionRegistry.revokeCredential(loadedCredentialId); yield* removeSessionMcpCredential( input.providerSessionId, diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts index fb914278a3cb2..dfb1b988f88f1 100644 --- a/packages/provider-acp/src/server/adapter.ts +++ b/packages/provider-acp/src/server/adapter.ts @@ -8072,7 +8072,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( const syncMcpCredentialForSession = Effect.fnUntraced(function* ( sessionId: string, threadId: ThreadId | null, - options?: { readonly allowReload?: boolean }, + options: { readonly allowReload?: boolean; readonly providerThreadId: ProviderThreadId }, ) { const currentMcpContext = yield* readMcpContext(threadId); if (currentMcpContext.authorization === (yield* Ref.get(activeMcpAuthorization))) { @@ -8088,7 +8088,17 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( yield* Ref.set(activeMcpAuthorization, currentMcpContext.authorization); return false; } - if (options?.allowReload !== false && (canLoadSession || canResumeSession)) { + if (options.allowReload !== false && (canLoadSession || canResumeSession)) { + // Reloading resets native children and pending agent state the background work still owns. + if (yield* sessionRuntime.hasPendingBackgroundWork ?? Effect.succeed(false)) { + return yield* new ProviderAdapter.ProviderAdapterMcpRotationBlockedError({ + driver, + providerSessionId: input.providerSessionId, + providerThreadId: options.providerThreadId, + detail: + "Cannot refresh MCP credentials while background work is running on this thread.", + }); + } return true; } // Non-loadable agents or continuation wakes keep their active session; do not record as applied. @@ -9346,6 +9356,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( (yield* Ref.get(activeSessionId)) === requestedSessionId && (yield* syncMcpCredentialForSession(requestedSessionId, turnInput.threadId, { allowReload: !isContinuationTurn, + providerThreadId: turnInput.providerThread.id, })); const needsSessionActivation = (yield* Ref.get(activeSessionId)) !== requestedSessionId || @@ -10053,22 +10064,36 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( (yield* syncMcpCredentialForSession( sessionId, threadInput.providerThread.appThreadId, - )); + { providerThreadId: threadInput.providerThread.id }, + ).pipe(Effect.tapError(() => restorePreviousItemIdentity))); if ( (yield* Ref.get(activeSessionId)) !== sessionId || restartAfterInterrupt || mcpReloadRequired ) { yield* Ref.set(snapshot, emptySnapshotState()); + const nextSelection = threadInput.modelSelection ?? input.modelSelection; + const nextRuntimePolicy = threadInput.runtimePolicy ?? input.runtimePolicy; + // load/resume can invoke client methods; install the incoming policy before activation. + const previousRuntimePolicy = latestRuntimePolicy; + latestRuntimePolicy = nextRuntimePolicy; const activated = yield* activateSession( sessionId, threadInput.providerThread.appThreadId, - ).pipe(Effect.tapError(() => restorePreviousItemIdentity)); + ).pipe( + Effect.tapError(() => + restorePreviousItemIdentity.pipe( + Effect.andThen( + Effect.sync(() => { + latestRuntimePolicy = previousRuntimePolicy; + }), + ), + ), + ), + ); yield* Ref.set(activeSessionId, activated.sessionId); yield* Ref.set(loadingSessionId, null); yield* setActiveSessionSetup(activated); - const nextSelection = threadInput.modelSelection ?? input.modelSelection; - const nextRuntimePolicy = threadInput.runtimePolicy ?? input.runtimePolicy; yield* configureSession(activated, nextSelection, nextRuntimePolicy); yield* Ref.set(activeSelection, nextSelection); yield* Ref.set(activeInteractionMode, nextRuntimePolicy.interactionMode); @@ -10085,14 +10110,16 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( }, (effect, threadInput) => effect.pipe( - Effect.mapError( - (cause) => - new ProviderAdapter.ProviderAdapterResumeThreadError({ - driver, - providerSessionId: input.providerSessionId, - providerThreadId: threadInput.providerThread.id, - cause, - }), + // Keep the tag so the caller fails the run instead of opening a fresh native thread. + Effect.mapError((cause) => + cause._tag === "ProviderAdapterMcpRotationBlockedError" + ? cause + : new ProviderAdapter.ProviderAdapterResumeThreadError({ + driver, + providerSessionId: input.providerSessionId, + providerThreadId: threadInput.providerThread.id, + cause, + }), ), ), ), diff --git a/packages/provider-acp/src/server/mcpOverAcpBridge.ts b/packages/provider-acp/src/server/mcpOverAcpBridge.ts index d8b135393ef22..8f0af421b9e71 100644 --- a/packages/provider-acp/src/server/mcpOverAcpBridge.ts +++ b/packages/provider-acp/src/server/mcpOverAcpBridge.ts @@ -300,6 +300,8 @@ export const makeAcpMcpOverAcpBridge = Effect.fn("AcpMcpOverAcpBridge.make")(fun const connection = yield* connectionFor(request.connectionId); connections.delete(request.connectionId); const sessionId = connection.sessionId; + const disconnectAuthorization = authorization; + const disconnectGeneration = authorizationGeneration; if (sessionId !== null) { yield* Effect.gen(function* () { const response = yield* Effect.tryPromise({ @@ -308,7 +310,7 @@ export const makeAcpMcpOverAcpBridge = Effect.fn("AcpMcpOverAcpBridge.make")(fun method: "DELETE", signal, headers: { - authorization, + authorization: disconnectAuthorization, "mcp-session-id": sessionId, ...(connection.protocolVersion === null ? {} @@ -335,8 +337,17 @@ export const makeAcpMcpOverAcpBridge = Effect.fn("AcpMcpOverAcpBridge.make")(fun }), ), }), - // Restore a session that failed to close, so a retry or dispose can close it. - Effect.onError(() => Effect.sync(() => connections.set(request.connectionId, connection))), + // Restore a session that failed to close, so a retry or dispose can close it. A rotation + // during the DELETE missed this connection, so it reconnects instead of reusing the old session. + Effect.onError(() => + Effect.sync(() => { + if (disconnectGeneration !== authorizationGeneration) { + connection.sessionId = null; + connection.needsReconnect = connection.hasInitialized; + } + connections.set(request.connectionId, connection); + }), + ), ); } return {}; From 8b9b34cf4b59f1f5e79c4bf2f7e12ce961da1f47 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 21 Nov 2026 16:13:25 +0000 Subject: [PATCH 04/34] fix(acp): MCP credential rotation follows the installed agent's transport A replacement agent can negotiate a different MCP transport. Rotation mode and the live bridge update now read the installed runtime's capabilities, so a replacement without MCP-over-ACP reloads instead of recording a credential it never received. Co-Authored-By: Claude Opus 5.5 --- packages/provider-acp/src/server/adapter.ts | 26 +++++++++++++-------- 1 file changed, 16 insertions(+), 10 deletions(-) diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts index dfb1b988f88f1..b7c24e6d78c72 100644 --- a/packages/provider-acp/src/server/adapter.ts +++ b/packages/provider-acp/src/server/adapter.ts @@ -8029,8 +8029,13 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( const canLoadSession = started.initializeResult.agentCapabilities?.loadSession === true; const canResumeSession = started.initializeResult.agentCapabilities?.sessionCapabilities?.resume != null; - const usesMcpOverAcp = - started.initializeResult.agentCapabilities?.mcpCapabilities?.acp === true; + // A replacement agent can negotiate another MCP transport, so read the installed one. + const installedAgentCapabilities = () => + (Ref.getUnsafe(activeSessionSetup)?.initializeResult ?? started.initializeResult) + .agentCapabilities; + const usesMcpOverAcp = () => + installedAgentCapabilities()?.mcpCapabilities?.acp === true && + runtimeMcpBridge !== undefined; const supportsImagePrompts = acpSupportsImagePrompts({ flavorSupportsImagePrompts: flavor.supportsImagePrompts, negotiatedImage: @@ -8080,7 +8085,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( } rememberTerminalEnvironment(sessionId, currentMcpContext); if ( - usesMcpOverAcp && + usesMcpOverAcp() && runtimeMcpBridge !== undefined && currentMcpContext.authorization !== undefined ) { @@ -8088,7 +8093,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( yield* Ref.set(activeMcpAuthorization, currentMcpContext.authorization); return false; } - if (options.allowReload !== false && (canLoadSession || canResumeSession)) { + if (options.allowReload !== false && sessionRuntime.mcpCredentialRotation === "reload") { // Reloading resets native children and pending agent state the background work still owns. if (yield* sessionRuntime.hasPendingBackgroundWork ?? Effect.succeed(false)) { return yield* new ProviderAdapter.ProviderAdapterMcpRotationBlockedError({ @@ -9906,12 +9911,13 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( return providerSession; }, canResumeAfterRestart: canLoadSession || canResumeSession, - mcpCredentialRotation: - usesMcpOverAcp && runtimeMcpBridge !== undefined - ? "live" - : canLoadSession || canResumeSession - ? "reload" - : "none", + get mcpCredentialRotation() { + const agent = installedAgentCapabilities(); + if (usesMcpOverAcp()) return "live" as const; + return agent?.loadSession === true || agent?.sessionCapabilities?.resume != null + ? ("reload" as const) + : ("none" as const); + }, events: Stream.fromEffectRepeat(Queue.take(events)), ...(flavor.getModelContextWindow === undefined ? {} From 4662b0651172876a313e3eed16c9b61aa6351e4b Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 21 Nov 2026 16:30:18 +0000 Subject: [PATCH 05/34] fix(server): typed turns run again on providers that cannot rotate MCP credentials A session whose runtime cannot take a new MCP credential (an ACP agent with no session load/resume and no MCP-over-ACP) failed every typed turn after its first, because the credential stayed bound to the first run. It now keeps that credential and drops its run binding, and t3_submit_output no longer requires a caller run, so an unbound credential submits as before. The late-submission race stays open only on those runtimes. Co-Authored-By: Claude Opus 5.5 --- .../src/mcp/McpSessionRegistry.testkit.ts | 1 + apps/server/src/mcp/McpSessionRegistry.ts | 13 +++++++ apps/server/src/mcp/toolkits/core.test.ts | 7 +--- .../src/mcp/toolkits/thread/handlers.ts | 1 - .../ProviderSessionManager.test.ts | 38 +++++++++---------- .../ProviderSessionManager.ts | 18 +++++---- .../ThreadManagementService.ts | 7 ---- .../src/orchestration-v2/runtimeLayer.test.ts | 13 ------- .../orchestrator-mcp-server.md | 4 +- 9 files changed, 48 insertions(+), 54 deletions(-) diff --git a/apps/server/src/mcp/McpSessionRegistry.testkit.ts b/apps/server/src/mcp/McpSessionRegistry.testkit.ts index 8998d02d7fc6b..dc50a593ed971 100644 --- a/apps/server/src/mcp/McpSessionRegistry.testkit.ts +++ b/apps/server/src/mcp/McpSessionRegistry.testkit.ts @@ -23,6 +23,7 @@ export const layer = Layer.succeed( resolve: () => Effect.undefined, touch: () => Effect.void, revokeCredential: () => Effect.void, + releaseRunBinding: () => Effect.void, revokeProviderSession: () => Effect.void, revokeThread: () => Effect.void, revokeAll: Effect.void, diff --git a/apps/server/src/mcp/McpSessionRegistry.ts b/apps/server/src/mcp/McpSessionRegistry.ts index bd3b6f8a815fb..957b77214c397 100644 --- a/apps/server/src/mcp/McpSessionRegistry.ts +++ b/apps/server/src/mcp/McpSessionRegistry.ts @@ -37,6 +37,8 @@ export interface McpSessionRegistryShape { ) => Effect.Effect; readonly touch: (threadId: ThreadId) => Effect.Effect; readonly revokeCredential: (credentialId: string) => Effect.Effect; + /** For runtimes that cannot take a new credential: the token stays valid but answers for no run. */ + readonly releaseRunBinding: (credentialId: string) => Effect.Effect; readonly revokeProviderSession: (providerSessionId: string) => Effect.Effect; readonly revokeThread: (threadId: ThreadId) => Effect.Effect; readonly revokeAll: Effect.Effect; @@ -246,6 +248,17 @@ const makeWithOptions = Effect.fn("McpSessionRegistry.make")(function* ( revokeCredential: Effect.fn("McpSessionRegistry.revokeCredential")(function* (credentialId) { yield* revokeWhere((record) => record.credentialId === credentialId); }), + releaseRunBinding: Effect.fn("McpSessionRegistry.releaseRunBinding")(function* (credentialId) { + yield* SynchronizedRef.update(state, ({ records }) => { + const next = new Map(records); + for (const [tokenHash, record] of records) { + if (record.credentialId !== credentialId) continue; + const { runId: _runId, attemptId: _attemptId, ...thread } = record.scope.thread; + next.set(tokenHash, { ...record, scope: { ...record.scope, thread } }); + } + return { records: next }; + }); + }), revokeProviderSession: Effect.fn("McpSessionRegistry.revokeProviderSession")( function* (providerSessionId) { yield* revokeWhere((record) => record.scope.thread.providerSessionId === providerSessionId); diff --git a/apps/server/src/mcp/toolkits/core.test.ts b/apps/server/src/mcp/toolkits/core.test.ts index 00499bf31cf44..20e7ca6b45b36 100644 --- a/apps/server/src/mcp/toolkits/core.test.ts +++ b/apps/server/src/mcp/toolkits/core.test.ts @@ -1665,7 +1665,6 @@ it.effect("t3_submit_output forwards caller run and attempt identity and surface readonly json: string; readonly callerRunId?: RunId | undefined; readonly callerAttemptId?: RunAttemptId | undefined; - readonly requireCallerRunId?: boolean | undefined; }> = []; const runA = RunId.make("run-a"); const attemptA = RunAttemptId.make("attempt-a"); @@ -1685,7 +1684,6 @@ it.effect("t3_submit_output forwards caller run and attempt identity and surface json: input.json, callerRunId: input.callerRunId, callerAttemptId: input.callerAttemptId, - requireCallerRunId: input.requireCallerRunId, }); if (rejectNext !== undefined) { const problem = rejectNext; @@ -1724,7 +1722,7 @@ it.effect("t3_submit_output forwards caller run and attempt identity and surface ); }); - // Unbound MCP callers still pass requireCallerRunId: true and surface service rejections as invalid_request. + // Service rejections surface as invalid_request. rejectNext = "This output was submitted for a turn that is no longer active."; const unbound = yield* callWith(undefined, undefined, '{"ok":false}').pipe( Effect.provide(serverLayer), @@ -1754,21 +1752,18 @@ it.effect("t3_submit_output forwards caller run and attempt identity and surface json: '{"ok":false}', callerRunId: undefined, callerAttemptId: undefined, - requireCallerRunId: true, }, { threadId, json: '{"ok":false}', callerRunId: runA, callerAttemptId: attemptA, - requireCallerRunId: true, }, { threadId, json: '{"ok":true}', callerRunId: runB, callerAttemptId: attemptB, - requireCallerRunId: true, }, ]); }), diff --git a/apps/server/src/mcp/toolkits/thread/handlers.ts b/apps/server/src/mcp/toolkits/thread/handlers.ts index 258985159b9b4..0f66233aae961 100644 --- a/apps/server/src/mcp/toolkits/thread/handlers.ts +++ b/apps/server/src/mcp/toolkits/thread/handlers.ts @@ -292,7 +292,6 @@ export const layer = McpToolAccess.toLayer(ThreadToolkit, { threadId: scope.thread.threadId, commandId: yield* newCommandId(), json: input.json, - requireCallerRunId: true, ...(scope.thread.runId === undefined ? {} : { callerRunId: scope.thread.runId }), ...(scope.thread.attemptId === undefined ? {} diff --git a/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts b/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts index 3e69a5f8a3b70..e794a57a91f55 100644 --- a/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts +++ b/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts @@ -3299,7 +3299,7 @@ it.effect.each([ { scenario: "none" as const, description: - "ProviderSessionManagerV2 fails explicitly instead of mutating non-rotatable credentials on a second typed run", + "ProviderSessionManagerV2 keeps a non-rotatable runtime's credential, unbound, for a second typed run", }, { scenario: "reload-blocked" as const, @@ -3492,24 +3492,24 @@ it.effect.each([ ); assert.equal((yield* registry.resolve(token1))?.thread.runId, run1); - // A second typed run requires a new run-bound token, which a non-rotatable runtime cannot deliver. - const rejected = yield* manager - .open({ - threadId, - providerSessionId, - modelSelection, - runtimePolicy, - runId: run3, - attemptId: RunAttemptId.make("attempt-none-3"), - requireRunScopedMcp: true, - }) - .pipe(Effect.flip); - assert.equal(rejected._tag, "ProviderSessionOpenError"); - assert.equal((yield* registry.resolve(token1))?.thread.runId, run1); - assert.equal( - (yield* mcpSessions.read(threadId))?.authorizationHeader, - config1!.authorizationHeader, - ); + // A non-rotatable runtime cannot take a token for a second typed run: the turn still runs, + // and its token stops answering for run1 so the new run can submit. + yield* manager.open({ + threadId, + providerSessionId, + modelSelection, + runtimePolicy, + runId: run3, + attemptId: RunAttemptId.make("attempt-none-3"), + requireRunScopedMcp: true, + }); + const unbound = yield* registry.resolve(token1); + assert.isDefined(unbound); + assert.isUndefined(unbound!.thread.runId); + assert.isUndefined(unbound!.thread.attemptId); + const config3 = yield* mcpSessions.read(threadId); + assert.equal(config3?.authorizationHeader, config1!.authorizationHeader); + assert.isUndefined(config3?.runId); yield* manager.close(providerSessionId); }); diff --git a/apps/server/src/orchestration-v2/ProviderSessionManager.ts b/apps/server/src/orchestration-v2/ProviderSessionManager.ts index 85c9f60bd4d90..1ca2ba5fd3b5c 100644 --- a/apps/server/src/orchestration-v2/ProviderSessionManager.ts +++ b/apps/server/src/orchestration-v2/ProviderSessionManager.ts @@ -2231,14 +2231,18 @@ export const layerWithOptions = ( yield* recordMcpTurnChecked(input.providerSessionId, input.threadId, turnKey); return; } - if (input.runtime.mcpCredentialRotation === "none") { - if (current !== undefined) { - return yield* new ProviderSessionOpenError({ - instanceId: input.providerInstanceId, - providerSessionId: input.providerSessionId, - cause: `Provider ${input.runtime.driver} cannot rotate MCP credentials on a live session without session reload or MCP-over-ACP.`, - }); + // This runtime cannot take a new credential: keep it unbound so later typed turns still + // submit, leaving the late-submission race open only where rotation is impossible. + if (input.runtime.mcpCredentialRotation === "none" && current !== undefined) { + if (current.runId !== undefined || current.attemptId !== undefined) { + yield* mcpSessionRegistry.releaseRunBinding( + McpProviderSession.mcpCredentialIdOf(current), + ); + const { runId: _runId, attemptId: _attemptId, ...unbound } = current; + yield* mcpSessions.set(unbound); } + yield* recordMcpTurnChecked(input.providerSessionId, input.threadId, turnKey); + return; } const ownerSessionId = (yield* Ref.get(sessions)) .get(sessionKey(input.providerSessionId)) diff --git a/apps/server/src/orchestration-v2/ThreadManagementService.ts b/apps/server/src/orchestration-v2/ThreadManagementService.ts index a7df3d28f77fa..ff1356885813d 100644 --- a/apps/server/src/orchestration-v2/ThreadManagementService.ts +++ b/apps/server/src/orchestration-v2/ThreadManagementService.ts @@ -497,7 +497,6 @@ export interface ThreadManagementServiceShape { readonly json: string; readonly callerRunId?: RunId; readonly callerAttemptId?: RunAttemptId; - readonly requireCallerRunId?: boolean; }) => Effect.Effect<{ readonly runId: RunId }, ThreadManagementFailure>; readonly assertProviderInstanceEnabled: (input: { readonly projectId: ProjectId; @@ -1054,12 +1053,6 @@ const make = Effect.gen(function* () { problem: "This turn was not asked for a result. Reply in your message instead.", }); } - if (input.requireCallerRunId === true && input.callerRunId === undefined) { - return yield* new ThreadManagementRunOutputRejectedError({ - threadId: input.threadId, - problem: "This output was submitted for a turn that is no longer active.", - }); - } if (input.callerRunId !== undefined || input.callerAttemptId !== undefined) { const matchesRun = (candidate: OrchestrationV2Run | undefined) => candidate !== undefined && diff --git a/apps/server/src/orchestration-v2/runtimeLayer.test.ts b/apps/server/src/orchestration-v2/runtimeLayer.test.ts index 26907928d937a..a5940a0b3fa7f 100644 --- a/apps/server/src/orchestration-v2/runtimeLayer.test.ts +++ b/apps/server/src/orchestration-v2/runtimeLayer.test.ts @@ -12187,17 +12187,6 @@ it.layer(layerSharedApplicationDataPlaneTest)("run output after a stop", (it) => ], }); - const unboundOnTyped = yield* threadManagement - .submitRunOutput({ - threadId, - commandId: CommandId.make("runtime-layer-unbound-run-output"), - json: '{"from":"unbound"}', - requireCallerRunId: true, - }) - .pipe(Effect.flip); - assert.equal(unboundOnTyped._tag, "ThreadManagementRunOutputRejectedError"); - assert.include(unboundOnTyped.message, "no longer active"); - const lateFromA = yield* threadManagement .submitRunOutput({ threadId, @@ -12257,7 +12246,6 @@ it.layer(layerSharedApplicationDataPlaneTest)("run output after a stop", (it) => commandId: CommandId.make("runtime-layer-plain-run-output-stale"), json: "{}", callerRunId: runA.id, - requireCallerRunId: true, }) .pipe(Effect.flip); assert.equal(plainFromStale._tag, "ThreadManagementRunOutputRejectedError"); @@ -12267,7 +12255,6 @@ it.layer(layerSharedApplicationDataPlaneTest)("run output after a stop", (it) => threadId, commandId: CommandId.make("runtime-layer-plain-run-output-unbound"), json: "{}", - requireCallerRunId: true, }) .pipe(Effect.flip); assert.equal(plainFromUnbound._tag, "ThreadManagementRunOutputRejectedError"); diff --git a/docs/orchestration-v2/orchestrator-mcp-server.md b/docs/orchestration-v2/orchestrator-mcp-server.md index e2ff45093c599..b0c2b6753fbc0 100644 --- a/docs/orchestration-v2/orchestrator-mcp-server.md +++ b/docs/orchestration-v2/orchestrator-mcp-server.md @@ -469,7 +469,9 @@ that turn was sent with. A turn that was asked for nothing answers for the newest turn that was asked and has not answered yet, which is how an agent that ended its turn to wait gives its result after it is woken. A typed turn's MCP credential carries its run and attempt, so a late call from a stopped or -superseded turn is rejected instead of landing on the next one. A rejection names what did not fit, so the agent can +superseded turn is rejected instead of landing on the next one. A provider +session that cannot take a new credential keeps an unbound one, where that race +stays open. A rejection names what did not fit, so the agent can correct it and call again; a later accepted submission replaces an earlier one. ### `t3_thread_wait` From c37f8510dfa634f2cfb080c4d29e2469cb358ae8 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 21 Nov 2026 16:37:06 +0000 Subject: [PATCH 06/34] fix(server): MCP rotation fallbacks stay on the runtime and agent they belong to - A failed unload restores the thread's load record only on the runtime that attempted it, not on a replacement opened under the same session. - ACP activation picks session/load or session/resume from the installed agent. - A blocked ACP reload leaves the terminal environment on the old credential. Co-Authored-By: Claude Opus 5.5 --- .../ProviderSessionManager.ts | 20 +++++++++++++------ packages/provider-acp/src/server/adapter.ts | 7 ++++--- 2 files changed, 18 insertions(+), 9 deletions(-) diff --git a/apps/server/src/orchestration-v2/ProviderSessionManager.ts b/apps/server/src/orchestration-v2/ProviderSessionManager.ts index 1ca2ba5fd3b5c..579a8fda2ff73 100644 --- a/apps/server/src/orchestration-v2/ProviderSessionManager.ts +++ b/apps/server/src/orchestration-v2/ProviderSessionManager.ts @@ -2783,12 +2783,20 @@ export const layerWithOptions = ( ); if (!unloaded) { // A thread that may still be loaded ignores the new config on resume; keep it on the old one. - yield* markProviderThreadLoaded({ - providerSessionId: input.providerSessionId, - threadId: input.threadId, - providerThreadKey: unloadingKey, - linkedEnvironments: undefined, - mcpCredential: loadedCredential, + yield* Ref.update(sessions, (current) => { + const latest = current.get(key); + // A replacement runtime under the same session never loaded this thread. + if (latest?.runtime !== entry.runtime) return current; + return new Map(current).set(key, { + ...latest, + loadedProviderThreadKeyByThread: new Map( + latest.loadedProviderThreadKeyByThread, + ).set(input.threadId, unloadingKey), + loadedMcpCredentialByThread: new Map(latest.loadedMcpCredentialByThread).set( + input.threadId, + loadedCredential, + ), + }); }); return yield* rollBack("Could not reload the thread to refresh MCP credentials."); } diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts index b7c24e6d78c72..8b0b53650544b 100644 --- a/packages/provider-acp/src/server/adapter.ts +++ b/packages/provider-acp/src/server/adapter.ts @@ -8056,10 +8056,11 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( const activationOptions = acpMcpActivation(mcpContext); prepareTerminalEnvironment(mcpContext, sessionId); yield* Ref.set(loadingSessionId, sessionId); + const agent = installedAgentCapabilities(); const activated = yield* Effect.gen(function* () { - return canLoadSession + return agent?.loadSession === true ? yield* runtime.loadSession(sessionId, activationOptions) - : canResumeSession + : agent?.sessionCapabilities?.resume != null ? yield* runtime.resumeSession(sessionId, activationOptions) : yield* new ProviderAdapter.ProviderAdapterProtocolError({ driver, @@ -8083,12 +8084,12 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( if (currentMcpContext.authorization === (yield* Ref.get(activeMcpAuthorization))) { return false; } - rememberTerminalEnvironment(sessionId, currentMcpContext); if ( usesMcpOverAcp() && runtimeMcpBridge !== undefined && currentMcpContext.authorization !== undefined ) { + rememberTerminalEnvironment(sessionId, currentMcpContext); runtimeMcpBridge.setAuthorization(currentMcpContext.authorization); yield* Ref.set(activeMcpAuthorization, currentMcpContext.authorization); return false; From b3eef25232638146784a252786be13e09e715e12 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 21 Nov 2026 17:04:11 +0000 Subject: [PATCH 07/34] fix(server): typed results name their run when the credential cannot - t3_submit_output takes an optional runId, and a typed turn's instructions give it. A credential bound to its run still outranks it; a call with neither is rejected, so a stopped run's late call is turned down on providers that cannot rotate MCP credentials too. - A reload runtime with background work running no longer fails the typed turn: it keeps its loaded credential, unbound, and the turn starts as on main. A blocked or failed reload does the same. Co-Authored-By: Claude Opus 5.5 --- apps/server/src/mcp/toolkits/core.test.ts | 15 ++- .../src/mcp/toolkits/thread/handlers.ts | 4 +- apps/server/src/mcp/toolkits/thread/tools.ts | 7 +- .../ProviderSessionManager.test.ts | 70 ++++++------ .../ProviderSessionManager.ts | 101 +++++++++--------- .../ProviderTurnStartService.ts | 2 +- .../ThreadManagementService.ts | 31 +++--- apps/server/src/orchestration-v2/runOutput.ts | 4 +- .../src/orchestration-v2/runtimeLayer.test.ts | 13 +++ .../src/provider/agentContextBudget.json | 2 +- .../orchestrator-mcp-server.md | 10 +- 11 files changed, 140 insertions(+), 119 deletions(-) diff --git a/apps/server/src/mcp/toolkits/core.test.ts b/apps/server/src/mcp/toolkits/core.test.ts index 20e7ca6b45b36..7d4eb136da99a 100644 --- a/apps/server/src/mcp/toolkits/core.test.ts +++ b/apps/server/src/mcp/toolkits/core.test.ts @@ -1705,11 +1705,13 @@ it.effect("t3_submit_output forwards caller run and attempt identity and surface runId: RunId | undefined, attemptId: RunAttemptId | undefined, json: string, + argumentRunId?: RunId, ) => Effect.gen(function* () { const server = yield* McpServer.McpServer; const { runId: _r, attemptId: _a, ...baseThread } = scope.thread!; - return yield* server.callTool({ name: "t3_submit_output", arguments: { json } }).pipe( + const args = argumentRunId === undefined ? { json } : { json, runId: argumentRunId }; + return yield* server.callTool({ name: "t3_submit_output", arguments: args }).pipe( Effect.provideService(McpInvocationContext.McpInvocationContext, { ...scope, thread: { @@ -1722,9 +1724,9 @@ it.effect("t3_submit_output forwards caller run and attempt identity and surface ); }); - // Service rejections surface as invalid_request. + // An unbound credential names its run in the call; service rejections surface as invalid_request. rejectNext = "This output was submitted for a turn that is no longer active."; - const unbound = yield* callWith(undefined, undefined, '{"ok":false}').pipe( + const unbound = yield* callWith(undefined, undefined, '{"ok":false}', runA).pipe( Effect.provide(serverLayer), ); expect(unbound.isError).toBe(true); @@ -1743,14 +1745,17 @@ it.effect("t3_submit_output forwards caller run and attempt identity and surface message: "This output was submitted for a turn that is no longer active.", }); - const active = yield* callWith(runB, attemptB, '{"ok":true}').pipe(Effect.provide(serverLayer)); + // A bound credential outranks the argument. + const active = yield* callWith(runB, attemptB, '{"ok":true}', runA).pipe( + Effect.provide(serverLayer), + ); expect(active.isError).toBe(false); expect(active.structuredContent).toEqual({ runId: runB }); expect(calls).toEqual([ { threadId, json: '{"ok":false}', - callerRunId: undefined, + callerRunId: runA, callerAttemptId: undefined, }, { diff --git a/apps/server/src/mcp/toolkits/thread/handlers.ts b/apps/server/src/mcp/toolkits/thread/handlers.ts index 0f66233aae961..52423efd4fab7 100644 --- a/apps/server/src/mcp/toolkits/thread/handlers.ts +++ b/apps/server/src/mcp/toolkits/thread/handlers.ts @@ -287,12 +287,14 @@ export const layer = McpToolAccess.toLayer(ThreadToolkit, { Effect.gen(function* () { const { scope, threads } = yield* readCaller(); if (scope.thread === undefined) return yield* unavailable(); + // A credential bound to its run outranks the argument; an unbound one has only the argument. + const callerRunId = scope.thread.runId ?? input.runId; return yield* threads .submitRunOutput({ threadId: scope.thread.threadId, commandId: yield* newCommandId(), json: input.json, - ...(scope.thread.runId === undefined ? {} : { callerRunId: scope.thread.runId }), + ...(callerRunId === undefined ? {} : { callerRunId }), ...(scope.thread.attemptId === undefined ? {} : { callerAttemptId: scope.thread.attemptId }), diff --git a/apps/server/src/mcp/toolkits/thread/tools.ts b/apps/server/src/mcp/toolkits/thread/tools.ts index 9803e8b4fa690..051ea6995bdac 100644 --- a/apps/server/src/mcp/toolkits/thread/tools.ts +++ b/apps/server/src/mcp/toolkits/thread/tools.ts @@ -244,9 +244,12 @@ const ScheduledTaskRunTool = Tool.make("run_scheduled_task_now", { const SubmitOutputTool = Tool.make("t3_submit_output", { ...commandTool, description: - "Return this turn's result as data, when the message asked for one. `json`: JSON text matching the schema it gave. A rejection says what did not fit; fix it and call again.", + "Return this turn's result as data, when the message asked for one. `runId`: the run id the message gave. `json`: JSON text matching the schema it gave. A rejection says what did not fit; fix it and call again.", // Stored on the run, which every client of the thread holds. - parameters: Schema.Struct({ json: Schema.String.check(Schema.isMaxLength(200000)) }), + parameters: Schema.Struct({ + runId: Schema.optional(RunId), + json: Schema.String.check(Schema.isMaxLength(200000)), + }), success: Schema.Struct({ runId: RunId }), }) // It writes only the caller's own run, so a read-only or plan-mode agent can still answer. diff --git a/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts b/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts index e794a57a91f55..7a83bda3850f0 100644 --- a/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts +++ b/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts @@ -3304,7 +3304,7 @@ it.effect.each([ { scenario: "reload-blocked" as const, description: - "ProviderSessionManagerV2 fails reload explicitly without unloading or mutating the loaded token when background work is active", + "ProviderSessionManagerV2 keeps the loaded token, unbound, instead of reloading while background work is active", }, { scenario: "reload-when-required" as const, @@ -3615,20 +3615,19 @@ it.effect.each([ const rotatedToken = rotatedConfig!.authorizationHeader.replace(/^Bearer\s+/, ""); assert.notEqual(rotatedToken, loadedToken); - const failed = yield* runtime - .resumeThread({ - threadId, - providerThread, - modelSelection, - runtimePolicy, - }) - .pipe(Effect.flip); - assert.equal(failed._tag, "ProviderAdapterMcpRotationBlockedError"); - // Background work stayed alive (no unload), loaded token identity stayed immutable, and unused token was revoked. + yield* runtime.resumeThread({ + threadId, + providerThread, + modelSelection, + runtimePolicy, + }); + // Background work stayed alive (no unload): the turn runs on the loaded token, now unbound so + // its run can submit, and the unused token was revoked. assert.isTrue(Option.isNone(yield* Queue.poll(unloads))); const resolvedLoaded = yield* registry.resolve(loadedToken); - assert.equal(resolvedLoaded?.thread.runId, run1); - assert.equal(resolvedLoaded?.thread.attemptId, attempt1); + assert.isDefined(resolvedLoaded); + assert.isUndefined(resolvedLoaded?.thread.runId); + assert.isUndefined(resolvedLoaded?.thread.attemptId); assert.isUndefined(yield* registry.resolve(rotatedToken)); assert.equal( (yield* mcpSessions.read(threadId))?.authorizationHeader, @@ -3683,15 +3682,12 @@ it.effect.each([ ); assert.notEqual(unboundRotatedToken, unboundLoadedToken); - const unboundFailed = yield* runtime - .resumeThread({ - threadId: unboundThreadId, - providerThread: unboundProviderThread, - modelSelection, - runtimePolicy, - }) - .pipe(Effect.flip); - assert.equal(unboundFailed._tag, "ProviderAdapterMcpRotationBlockedError"); + yield* runtime.resumeThread({ + threadId: unboundThreadId, + providerThread: unboundProviderThread, + modelSelection, + runtimePolicy, + }); assert.isTrue(Option.isNone(yield* Queue.poll(unloads))); const resolvedUnboundLoaded = yield* registry.resolve(unboundLoadedToken); assert.isDefined(resolvedUnboundLoaded); @@ -3746,15 +3742,12 @@ it.effect.each([ assert.isDefined(widerRotatedConfig); assert.isTrue(widerRotatedConfig!.browserToolsAvailable); const widerRotatedToken = widerRotatedConfig!.authorizationHeader.replace(/^Bearer\s+/, ""); - const widenedFailed = yield* runtime - .resumeThread({ - threadId: widenedThreadId, - providerThread: widenedProviderThread, - modelSelection, - runtimePolicy, - }) - .pipe(Effect.flip); - assert.equal(widenedFailed._tag, "ProviderAdapterMcpRotationBlockedError"); + yield* runtime.resumeThread({ + threadId: widenedThreadId, + providerThread: widenedProviderThread, + modelSelection, + runtimePolicy, + }); const resolvedNarrow = yield* registry.resolve(narrowLoadedToken); assert.isDefined(resolvedNarrow); assert.isFalse(resolvedNarrow!.capabilities.has("preview")); @@ -3903,15 +3896,12 @@ it.effect.each([ unloadFailedThreadId, ))!.authorizationHeader.replace(/^Bearer\s+/, ""); yield* Ref.set(failUnload, true); - const unloadFailed = yield* runtime - .resumeThread({ - threadId: unloadFailedThreadId, - providerThread: unloadFailedProviderThread, - modelSelection, - runtimePolicy, - }) - .pipe(Effect.flip); - assert.equal(unloadFailed._tag, "ProviderAdapterMcpRotationBlockedError"); + yield* runtime.resumeThread({ + threadId: unloadFailedThreadId, + providerThread: unloadFailedProviderThread, + modelSelection, + runtimePolicy, + }); assert.isUndefined(yield* registry.resolve(stagedToken)); assert.equal( (yield* mcpSessions.read(unloadFailedThreadId))?.authorizationHeader, diff --git a/apps/server/src/orchestration-v2/ProviderSessionManager.ts b/apps/server/src/orchestration-v2/ProviderSessionManager.ts index 579a8fda2ff73..2fc8322791f02 100644 --- a/apps/server/src/orchestration-v2/ProviderSessionManager.ts +++ b/apps/server/src/orchestration-v2/ProviderSessionManager.ts @@ -2231,9 +2231,18 @@ export const layerWithOptions = ( yield* recordMcpTurnChecked(input.providerSessionId, input.threadId, turnKey); return; } - // This runtime cannot take a new credential: keep it unbound so later typed turns still - // submit, leaving the late-submission race open only where rotation is impossible. - if (input.runtime.mcpCredentialRotation === "none" && current !== undefined) { + // A runtime that cannot take a new credential now (no way to deliver one, or a reload that + // would end background work) keeps it unbound; the agent then names its run in the call. + const cannotRotate = + input.runtime.mcpCredentialRotation === "none" || + (input.runtime.mcpCredentialRotation !== "live" && + (yield* (input.runtime.hasPendingBackgroundWork ?? Effect.succeed(false)).pipe( + Effect.catchCauseIf( + (cause) => !Cause.hasInterruptsOnly(cause), + () => Effect.succeed(true), + ), + ))); + if (cannotRotate && current !== undefined) { if (current.runId !== undefined || current.attemptId !== undefined) { yield* mcpSessionRegistry.releaseRunBinding( McpProviderSession.mcpCredentialIdOf(current), @@ -2688,56 +2697,52 @@ export const layerWithOptions = ( ), ); // Keep the loaded thread on its credential and never mutate an issued bearer's run identity. - const rollBack = (detail: string) => - mcpPrepareLock - .withLock( - input.threadId, - Effect.gen(function* () { - const staged = yield* mcpSessions.read(input.threadId); - // A later open published its own credential; that one stays. - if ( - staged === undefined || - McpProviderSession.mcpCredentialIdOf(staged) !== currentCredentialId - ) { - return; - } - // Capability removals revoke immediately, so restore only a still-valid credential. - const loadedRawToken = loadedCredential.authorizationHeader.replace( - /^Bearer\s+/, - "", - ); - if ((yield* mcpSessionRegistry.resolve(loadedRawToken)) !== undefined) { - yield* mcpSessions.set(loadedCredential); - } else { - yield* mcpSessions.clear(input.threadId); - } - yield* mcpSessionRegistry.revokeCredential(currentCredentialId); - yield* removeSessionMcpCredential( - input.providerSessionId, - input.threadId, - currentCredentialId, - ); + // Without a reload the thread keeps its loaded credential, unbound so the turn's own + // run can still submit through it; the agent then names its run in the call. + const keepLoaded = (detail: string) => + mcpPrepareLock.withLock( + input.threadId, + Effect.gen(function* () { + const staged = yield* mcpSessions.read(input.threadId); + // A later open published its own credential; that one stays. + if ( + staged === undefined || + McpProviderSession.mcpCredentialIdOf(staged) !== currentCredentialId + ) { + return; + } + yield* mcpSessionRegistry.revokeCredential(currentCredentialId); + yield* removeSessionMcpCredential( + input.providerSessionId, + input.threadId, + currentCredentialId, + ); + const loadedRawToken = loadedCredential.authorizationHeader.replace( + /^Bearer\s+/, + "", + ); + // Capability removals revoke immediately; the thread then holds no working token. + if ((yield* mcpSessionRegistry.resolve(loadedRawToken)) === undefined) { + yield* mcpSessions.clear(input.threadId); yield* recordMcpTurnChecked( input.providerSessionId, input.threadId, undefined, ); - }), - ) - .pipe( - Effect.andThen( - Effect.fail( - new ProviderAdapter.ProviderAdapterMcpRotationBlockedError({ - driver: entry.runtime.driver, - providerSessionId: input.providerSessionId, - providerThreadId: input.providerThread.id, - detail, - }), - ), - ), - ); + return yield* new ProviderAdapter.ProviderAdapterMcpRotationBlockedError({ + driver: entry.runtime.driver, + providerSessionId: input.providerSessionId, + providerThreadId: input.providerThread.id, + detail, + }); + } + yield* mcpSessionRegistry.releaseRunBinding(loadedCredentialId); + const { runId: _runId, attemptId: _attemptId, ...unbound } = loadedCredential; + yield* mcpSessions.set(unbound); + }), + ); if (hasPendingWork) { - return yield* rollBack( + return yield* keepLoaded( "Cannot refresh MCP credentials while background work is running on this thread.", ); } @@ -2798,7 +2803,7 @@ export const layerWithOptions = ( ), }); }); - return yield* rollBack("Could not reload the thread to refresh MCP credentials."); + return yield* keepLoaded("Could not reload the thread to refresh MCP credentials."); } if (loadedCredential.runId === undefined) { yield* mcpSessionRegistry.revokeCredential(loadedCredentialId); diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts index aec6f399b825b..c862a95137193 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts @@ -1012,7 +1012,7 @@ export const layer: Layer.Layer< const userText = run.outputSchema === undefined || goalCommand || isProviderCommand(providerMessage) ? messageText - : `${messageText}\n\n${outputInstructions(run.outputSchema)}`; + : `${messageText}\n\n${outputInstructions(run.outputSchema, run.id)}`; // The provider turn marks cancellation work delivered; restart continuations use their own text or resume natively. const noteContinuation = isRestartNoteContinuation( run, diff --git a/apps/server/src/orchestration-v2/ThreadManagementService.ts b/apps/server/src/orchestration-v2/ThreadManagementService.ts index ff1356885813d..3c0d1da3d561a 100644 --- a/apps/server/src/orchestration-v2/ThreadManagementService.ts +++ b/apps/server/src/orchestration-v2/ThreadManagementService.ts @@ -1053,20 +1053,23 @@ const make = Effect.gen(function* () { problem: "This turn was not asked for a result. Reply in your message instead.", }); } - if (input.callerRunId !== undefined || input.callerAttemptId !== undefined) { - const matchesRun = (candidate: OrchestrationV2Run | undefined) => - candidate !== undefined && - (input.callerRunId === undefined || candidate.id === input.callerRunId) && - (input.callerAttemptId === undefined || - candidate.activeAttemptId === input.callerAttemptId); - // Accept the active run, or the un-stopped completed run whose own owed output is targeted. - const callerAllowed = matchesRun(active) || (run.id !== active.id && matchesRun(run)); - if (!callerAllowed) { - return yield* new ThreadManagementRunOutputRejectedError({ - threadId: input.threadId, - problem: "This output was submitted for a turn that is no longer active.", - }); - } + // Without it a stopped run's late call cannot be told from the active run's. + if (input.callerRunId === undefined) { + return yield* new ThreadManagementRunOutputRejectedError({ + threadId: input.threadId, + problem: "Pass `runId` as this turn's instructions gave it.", + }); + } + const callerRunId = input.callerRunId; + const matchesRun = (candidate: OrchestrationV2Run) => + candidate.id === callerRunId && + (input.callerAttemptId === undefined || candidate.activeAttemptId === input.callerAttemptId); + // Accept the active run, or the un-stopped completed run whose own owed output is targeted. + if (!matchesRun(active) && !(run.id !== active.id && matchesRun(run))) { + return yield* new ThreadManagementRunOutputRejectedError({ + threadId: input.threadId, + problem: "This output was submitted for a turn that is no longer active.", + }); } const checked = yield* checkOutput(run.outputSchema, input.json); if (Result.isFailure(checked)) { diff --git a/apps/server/src/orchestration-v2/runOutput.ts b/apps/server/src/orchestration-v2/runOutput.ts index a583b7f6527da..1e3363b7bc98f 100644 --- a/apps/server/src/orchestration-v2/runOutput.ts +++ b/apps/server/src/orchestration-v2/runOutput.ts @@ -88,10 +88,10 @@ export const outputRequestProblem = ( : outputSchemaProblem(schema); /** Appended to the turn's prompt: the agent learns the shape and how to hand the result back. */ -export const outputInstructions = (schema: OutputSchema): string => +export const outputInstructions = (schema: OutputSchema, runId: RunId): string => [ "A program reads the result of this turn, not a person.", - "When the work is done, call the `t3_submit_output` tool once with `json` set to JSON text matching this JSON Schema:", + `When the work is done, call the \`t3_submit_output\` tool once with \`runId\` set to \`${runId}\` and \`json\` set to JSON text matching this JSON Schema:`, JSON.stringify(schema), "If you could not finish, still submit, with the fields that say so. A rejected submission names what did not fit: correct it and submit again.", ].join("\n"); diff --git a/apps/server/src/orchestration-v2/runtimeLayer.test.ts b/apps/server/src/orchestration-v2/runtimeLayer.test.ts index a5940a0b3fa7f..d2d67cf2b439d 100644 --- a/apps/server/src/orchestration-v2/runtimeLayer.test.ts +++ b/apps/server/src/orchestration-v2/runtimeLayer.test.ts @@ -11907,6 +11907,7 @@ it.layer(layerSharedApplicationDataPlaneTest)("run output after a stop", (it) => threadId, commandId: CommandId.make("runtime-layer-owed-output-submit"), json: '{"head":"abc"}', + callerRunId: asked.id, }); assert.equal(accepted.runId, asked.id); const after = yield* orchestrator.getThreadProjection(threadId); @@ -12075,6 +12076,7 @@ it.layer(layerSharedApplicationDataPlaneTest)("run output after a stop", (it) => threadId, commandId: CommandId.make("runtime-layer-stopped-output-submit"), json: "{}", + callerRunId: run.id, }) .pipe(Effect.flip); assert.equal(rejected._tag, "ThreadManagementRunOutputRejectedError"); @@ -12187,6 +12189,17 @@ it.layer(layerSharedApplicationDataPlaneTest)("run output after a stop", (it) => ], }); + // A caller that names no run cannot be told from a stopped run's late call. + const anonymous = yield* threadManagement + .submitRunOutput({ + threadId, + commandId: CommandId.make("runtime-layer-anonymous-run-output"), + json: '{"from":"anonymous"}', + }) + .pipe(Effect.flip); + assert.equal(anonymous._tag, "ThreadManagementRunOutputRejectedError"); + assert.include(anonymous.message, "runId"); + const lateFromA = yield* threadManagement .submitRunOutput({ threadId, diff --git a/apps/server/src/provider/agentContextBudget.json b/apps/server/src/provider/agentContextBudget.json index 139eba175bc8a..af8f02d331fa2 100644 --- a/apps/server/src/provider/agentContextBudget.json +++ b/apps/server/src/provider/agentContextBudget.json @@ -1,5 +1,5 @@ { "claudeSystemAppendBytes": 6245, "codexAdditionalContextBytes": 7639, - "mcpToolListJsonBytes": 59052 + "mcpToolListJsonBytes": 59116 } diff --git a/docs/orchestration-v2/orchestrator-mcp-server.md b/docs/orchestration-v2/orchestrator-mcp-server.md index b0c2b6753fbc0..92c4df7a43dc2 100644 --- a/docs/orchestration-v2/orchestrator-mcp-server.md +++ b/docs/orchestration-v2/orchestrator-mcp-server.md @@ -467,11 +467,11 @@ with no `output`. Stores the calling thread's result on its running turn, once it fits the schema that turn was sent with. A turn that was asked for nothing answers for the newest turn that was asked and has not answered yet, which is how an agent that -ended its turn to wait gives its result after it is woken. A typed turn's MCP -credential carries its run and attempt, so a late call from a stopped or -superseded turn is rejected instead of landing on the next one. A provider -session that cannot take a new credential keeps an unbound one, where that race -stays open. A rejection names what did not fit, so the agent can +ended its turn to wait gives its result after it is woken. The call names its run: a typed turn's MCP +credential carries its run and attempt, and where a provider session cannot +take a new credential the agent passes the `runId` its instructions give. A +late call from a stopped or superseded turn is rejected instead of landing on +the next one. A rejection names what did not fit, so the agent can correct it and call again; a later accepted submission replaces an earlier one. ### `t3_thread_wait` From f37095040fb6058eb07e926df6e4184e0c65d51f Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 21 Nov 2026 17:09:11 +0000 Subject: [PATCH 08/34] fix(server): t3_submit_output's description fits the agent context budget The runId parameter grew the MCP tool list past main's; a shorter description brings it back under. Co-Authored-By: Claude Opus 5.5 --- apps/server/src/mcp/toolkits/thread/tools.ts | 2 +- apps/server/src/provider/agentContextBudget.json | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/apps/server/src/mcp/toolkits/thread/tools.ts b/apps/server/src/mcp/toolkits/thread/tools.ts index 051ea6995bdac..177cabe22482b 100644 --- a/apps/server/src/mcp/toolkits/thread/tools.ts +++ b/apps/server/src/mcp/toolkits/thread/tools.ts @@ -244,7 +244,7 @@ const ScheduledTaskRunTool = Tool.make("run_scheduled_task_now", { const SubmitOutputTool = Tool.make("t3_submit_output", { ...commandTool, description: - "Return this turn's result as data, when the message asked for one. `runId`: the run id the message gave. `json`: JSON text matching the schema it gave. A rejection says what did not fit; fix it and call again.", + "Return the result the message asked for, with the `runId` it gave. `json`: JSON text matching its schema. A rejection says what to fix; retry.", // Stored on the run, which every client of the thread holds. parameters: Schema.Struct({ runId: Schema.optional(RunId), diff --git a/apps/server/src/provider/agentContextBudget.json b/apps/server/src/provider/agentContextBudget.json index af8f02d331fa2..e99c98d67f329 100644 --- a/apps/server/src/provider/agentContextBudget.json +++ b/apps/server/src/provider/agentContextBudget.json @@ -1,5 +1,5 @@ { "claudeSystemAppendBytes": 6245, "codexAdditionalContextBytes": 7639, - "mcpToolListJsonBytes": 59116 + "mcpToolListJsonBytes": 59049 } From e4d0fea90b4aa7becf54b16a18fe0cf14a03bd78 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 21 Nov 2026 17:11:48 +0000 Subject: [PATCH 09/34] test(server): the launch result test names the run it submits for Co-Authored-By: Claude Opus 5.5 --- apps/server/src/orchestration-v2/ThreadLaunchService.test.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts b/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts index 73eaabdde2016..9e79f578468a3 100644 --- a/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts +++ b/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts @@ -659,11 +659,13 @@ it.effect("a run asked for a result stores what its agent submits once it fits t ...input, initialMessage: { ...input.initialMessage!, outputSchema }, }); + const askedRunId = launched.projection.runs.at(-1)!.id; const submit = (command: string, json: string) => threads.submitRunOutput({ threadId: launched.threadId, commandId: CommandId.make(command), json, + callerRunId: askedRunId, }); const rejected = yield* submit("command:output:bad", '{"verdict":"maybe"}').pipe(Effect.flip); From e8ce63ef76061a1b2bb3dc03947ca94a555169e1 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 21 Nov 2026 17:23:20 +0000 Subject: [PATCH 10/34] fix(server): an unconfirmed unload resumes natively, and continuations take their run's result - After an unload that failed or timed out the thread stays marked unloaded, so the next step resumes it natively on the old credential instead of trusting a load record for a thread that may have unsubscribed. - A continuation gets no new instructions, so a caller naming the run it continues is accepted for the continuation. Co-Authored-By: Claude Opus 5.5 --- .../ProviderSessionManager.ts | 18 ++------------ .../ThreadManagementService.ts | 21 +++++++++++++--- .../src/orchestration-v2/runtimeLayer.test.ts | 24 +++++++++++++++++++ 3 files changed, 44 insertions(+), 19 deletions(-) diff --git a/apps/server/src/orchestration-v2/ProviderSessionManager.ts b/apps/server/src/orchestration-v2/ProviderSessionManager.ts index 2fc8322791f02..f2f345b771ae2 100644 --- a/apps/server/src/orchestration-v2/ProviderSessionManager.ts +++ b/apps/server/src/orchestration-v2/ProviderSessionManager.ts @@ -2787,22 +2787,8 @@ export const layerWithOptions = ( ), ); if (!unloaded) { - // A thread that may still be loaded ignores the new config on resume; keep it on the old one. - yield* Ref.update(sessions, (current) => { - const latest = current.get(key); - // A replacement runtime under the same session never loaded this thread. - if (latest?.runtime !== entry.runtime) return current; - return new Map(current).set(key, { - ...latest, - loadedProviderThreadKeyByThread: new Map( - latest.loadedProviderThreadKeyByThread, - ).set(input.threadId, unloadingKey), - loadedMcpCredentialByThread: new Map(latest.loadedMcpCredentialByThread).set( - input.threadId, - loadedCredential, - ), - }); - }); + // The thread may or may not have unloaded, so it stays marked unloaded and the next + // step resumes it natively, on the old credential either way. return yield* keepLoaded("Could not reload the thread to refresh MCP credentials."); } if (loadedCredential.runId === undefined) { diff --git a/apps/server/src/orchestration-v2/ThreadManagementService.ts b/apps/server/src/orchestration-v2/ThreadManagementService.ts index 3c0d1da3d561a..1e99885230ed5 100644 --- a/apps/server/src/orchestration-v2/ThreadManagementService.ts +++ b/apps/server/src/orchestration-v2/ThreadManagementService.ts @@ -1061,9 +1061,23 @@ const make = Effect.gen(function* () { }); } const callerRunId = input.callerRunId; + // A continuation finishes the run it continues and gets no new instructions, so its agent can + // only name that earlier run. + const continues = (candidate: OrchestrationV2Run): boolean => { + const previousId = + candidate.restartContinuationOfRunId ?? + candidate.usageLimitContinuationOfRunId ?? + candidate.manualContinuationOfRunId; + if (previousId === undefined) return false; + if (previousId === callerRunId) return true; + const previous = records.runs.find((other) => other.id === previousId); + return previous !== undefined && continues(previous); + }; const matchesRun = (candidate: OrchestrationV2Run) => - candidate.id === callerRunId && - (input.callerAttemptId === undefined || candidate.activeAttemptId === input.callerAttemptId); + (candidate.id === callerRunId && + (input.callerAttemptId === undefined || + candidate.activeAttemptId === input.callerAttemptId)) || + (input.callerAttemptId === undefined && continues(candidate)); // Accept the active run, or the un-stopped completed run whose own owed output is targeted. if (!matchesRun(active) && !(run.id !== active.id && matchesRun(run))) { return yield* new ThreadManagementRunOutputRejectedError({ @@ -1084,7 +1098,8 @@ const make = Effect.gen(function* () { commandId: input.commandId, threadId: input.threadId, runId: run.id, - ...(input.callerRunId === undefined ? {} : { callerRunId: input.callerRunId }), + // A caller accepted through a continuation answers for the run that continues it. + callerRunId: callerRunId === active.id || callerRunId === run.id ? callerRunId : active.id, ...(input.callerAttemptId === undefined ? {} : { callerAttemptId: input.callerAttemptId }), value: checked.success, }).pipe( diff --git a/apps/server/src/orchestration-v2/runtimeLayer.test.ts b/apps/server/src/orchestration-v2/runtimeLayer.test.ts index d2d67cf2b439d..45be2168097bd 100644 --- a/apps/server/src/orchestration-v2/runtimeLayer.test.ts +++ b/apps/server/src/orchestration-v2/runtimeLayer.test.ts @@ -12239,6 +12239,30 @@ it.layer(layerSharedApplicationDataPlaneTest)("run output after a stop", (it) => from: "run-b", }); + // A continuation gets no new instructions, so its agent names the run it continues. + yield* eventSink.write({ + events: [ + { + id: EventId.make(`${threadId}-run-b-continues-a`), + type: "run.updated", + threadId, + runId: runB.id, + occurredAt: runB.requestedAt, + payload: { + ...afterB.runs.find((run) => run.id === runB.id)!, + manualContinuationOfRunId: runA.id, + }, + }, + ], + }); + const acceptedViaContinuation = yield* threadManagement.submitRunOutput({ + threadId, + commandId: CommandId.make("runtime-layer-run-output-via-continuation"), + json: '{"from":"continued"}', + callerRunId: runA.id, + }); + assert.equal(acceptedViaContinuation.runId, runB.id); + // A plain turn with no schema preserves the plain-turn guidance even for stale/unbound MCP callers. yield* eventSink.write({ events: [ From f83b0467f7636f19aaa54e12df4d48c2a83537be Mon Sep 17 00:00:00 2001 From: Victor Vogel Date: Sat, 21 Nov 2026 18:37:11 +0000 Subject: [PATCH 11/34] fix(server): harden MCP credential fallback, reload retirement, and ACP initialize validation - Sync retained credential capabilities in ensureTurnMcpSession when a runtime cannot rotate, revoking disabled access across the thread and restoring it on the active credential when re-enabled. - Re-read mcpSessions under mcpPrepareLock after the background-work probe before unbinding or writing, re-evaluating against the newer credential if it changed during the await. - Keep loadedMcpCredentialByThread synchronized when releaseRunBinding unbinds a credential and read the latest loaded record on unload so later reloads retire credentials that became unbound after native load. - Validate explicit ACP initialize responses for a valid protocolVersion and reject malformed envelopes with AcpMcpOverAcpError instead of returning null. - Assert token3 is defined and native resumeCount increments from 1 to 2 in the shared-runtime rotation test. --- .../src/mcp/McpSessionRegistry.testkit.ts | 1 + apps/server/src/mcp/McpSessionRegistry.ts | 48 ++++ .../ProviderSessionManager.test.ts | 178 ++++++++++++- .../ProviderSessionManager.ts | 250 +++++++++++++----- .../src/server/mcpOverAcpBridge.test.ts | 10 +- .../src/server/mcpOverAcpBridge.ts | 5 + 6 files changed, 411 insertions(+), 81 deletions(-) diff --git a/apps/server/src/mcp/McpSessionRegistry.testkit.ts b/apps/server/src/mcp/McpSessionRegistry.testkit.ts index dc50a593ed971..34ec6e63632d2 100644 --- a/apps/server/src/mcp/McpSessionRegistry.testkit.ts +++ b/apps/server/src/mcp/McpSessionRegistry.testkit.ts @@ -24,6 +24,7 @@ export const layer = Layer.succeed( touch: () => Effect.void, revokeCredential: () => Effect.void, releaseRunBinding: () => Effect.void, + syncCapabilities: () => Effect.undefined, revokeProviderSession: () => Effect.void, revokeThread: () => Effect.void, revokeAll: Effect.void, diff --git a/apps/server/src/mcp/McpSessionRegistry.ts b/apps/server/src/mcp/McpSessionRegistry.ts index 957b77214c397..880d166c2d9b5 100644 --- a/apps/server/src/mcp/McpSessionRegistry.ts +++ b/apps/server/src/mcp/McpSessionRegistry.ts @@ -39,6 +39,15 @@ export interface McpSessionRegistryShape { readonly revokeCredential: (credentialId: string) => Effect.Effect; /** For runtimes that cannot take a new credential: the token stays valid but answers for no run. */ readonly releaseRunBinding: (credentialId: string) => Effect.Effect; + /** Syncs dynamic access capabilities on a retained credential (revokes apply across the thread). */ + readonly syncCapabilities: ( + credentialId: string, + changes: { + readonly threadId: ThreadId; + readonly grant?: ReadonlyArray; + readonly revoke?: ReadonlyArray; + }, + ) => Effect.Effect | undefined>; readonly revokeProviderSession: (providerSessionId: string) => Effect.Effect; readonly revokeThread: (threadId: ThreadId) => Effect.Effect; readonly revokeAll: Effect.Effect; @@ -259,6 +268,45 @@ const makeWithOptions = Effect.fn("McpSessionRegistry.make")(function* ( return { records: next }; }); }), + syncCapabilities: Effect.fn("McpSessionRegistry.syncCapabilities")( + function* (credentialId, changes) { + const grant = changes.grant ?? []; + const revoke = changes.revoke ?? []; + return yield* SynchronizedRef.modify(state, ({ records }) => { + let updatedCapabilities: ReadonlySet | undefined; + let next: Map | undefined; + for (const [tokenHash, record] of records) { + const isTarget = record.credentialId === credentialId; + const isThreadRevoke = + revoke.length > 0 && record.scope.thread.threadId === changes.threadId; + if (!isTarget && !isThreadRevoke) continue; + const remaining = new Set(record.scope.capabilities); + let changed = false; + if (isThreadRevoke) { + for (const capability of revoke) { + if (remaining.delete(capability)) changed = true; + } + } + if (isTarget) { + for (const capability of grant) { + if (!remaining.has(capability)) { + remaining.add(capability); + changed = true; + } + } + updatedCapabilities = changed ? remaining : record.scope.capabilities; + } + if (!changed) continue; + next ??= new Map(records); + next.set(tokenHash, { ...record, scope: { ...record.scope, capabilities: remaining } }); + } + return [ + updatedCapabilities, + next === undefined ? { records } : { records: next }, + ] as const; + }); + }, + ), revokeProviderSession: Effect.fn("McpSessionRegistry.revokeProviderSession")( function* (providerSessionId) { yield* revokeWhere((record) => record.scope.thread.providerSessionId === providerSessionId); diff --git a/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts b/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts index 7a83bda3850f0..53c5c70a15991 100644 --- a/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts +++ b/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts @@ -3413,6 +3413,7 @@ it.effect.each([ const manager = yield* ProviderSessionManager.ProviderSessionManagerV2; const registry = yield* McpSessionRegistry.McpSessionRegistry; const mcpSessions = yield* McpProviderSessions.McpProviderSessions; + const settings = yield* ServerSettings.ServerSettingsService; const now = yield* DateTime.now; const threadId = ThreadId.make("thread-provider-session-manager-no-rotation"); const providerSessionId = yield* idAllocator.allocate.providerSession({ @@ -3422,6 +3423,7 @@ it.effect.each([ const run1 = RunId.make("run-none-1"); const run2 = RunId.make("run-none-2"); const run3 = RunId.make("run-none-3"); + const run4 = RunId.make("run-none-4"); const rootNode1 = NodeId.make("node-none-1"); const providerThread = makeProviderThread({ idAllocator, @@ -3507,19 +3509,66 @@ it.effect.each([ assert.isDefined(unbound); assert.isUndefined(unbound!.thread.runId); assert.isUndefined(unbound!.thread.attemptId); + assert.isTrue(unbound!.capabilities.has("preview")); const config3 = yield* mcpSessions.read(threadId); assert.equal(config3?.authorizationHeader, config1!.authorizationHeader); assert.isUndefined(config3?.runId); + assert.isTrue(config3?.browserToolsAvailable); + + // Disabling browser access drops preview from the retained credential without breaking typed runs. + yield* settings.updateSettings({ enableAgentBrowserAccess: false }); + yield* manager.open({ + threadId, + providerSessionId, + modelSelection, + runtimePolicy, + runId: run4, + attemptId: RunAttemptId.make("attempt-none-4"), + requireRunScopedMcp: true, + }); + const narrowed = yield* registry.resolve(token1); + assert.isDefined(narrowed); + assert.isUndefined(narrowed!.thread.runId); + assert.isFalse(narrowed!.capabilities.has("preview")); + const config4 = yield* mcpSessions.read(threadId); + assert.equal(config4?.authorizationHeader, config1!.authorizationHeader); + assert.isFalse(config4?.browserToolsAvailable); + assert.isFalse(config4?.capabilities?.has("preview") ?? false); + + // Re-enabling browser access restores preview on the retained credential. + yield* settings.updateSettings({ enableAgentBrowserAccess: true }); + yield* manager.open({ + threadId, + providerSessionId, + modelSelection, + runtimePolicy, + runId: RunId.make("run-none-5"), + attemptId: RunAttemptId.make("attempt-none-5"), + requireRunScopedMcp: true, + }); + const restored = yield* registry.resolve(token1); + assert.isDefined(restored); + assert.isUndefined(restored!.thread.runId); + assert.isTrue(restored!.capabilities.has("preview")); + const config5 = yield* mcpSessions.read(threadId); + assert.equal(config5?.authorizationHeader, config1!.authorizationHeader); + assert.isTrue(config5?.browserToolsAvailable); + assert.isTrue(config5?.capabilities?.has("preview") ?? false); yield* manager.close(providerSessionId); }); + const serverSettingsLayer = ServerSettings.layerTest().pipe(Layer.orDie); yield* effect.pipe( Effect.provide( - layerTest({ - state, - idleTimeoutMs: 1_000, - mcpCredentialRotation: "none", - }), + Layer.merge( + layerTest({ + state, + idleTimeoutMs: 1_000, + mcpCredentialRotation: "none", + serverSettingsLayer, + }), + serverSettingsLayer, + ), ), ); return; @@ -3528,6 +3577,9 @@ it.effect.each([ if (scenario === "reload-blocked") { const unloads = yield* Queue.unbounded(); const pendingBackgroundWork = yield* Ref.make(true); + const sessionBackgroundWorkProbe = yield* Ref.make>( + Effect.succeed(false), + ); const failUnload = yield* Ref.make(false); const effect = Effect.gen(function* () { const eventSink = yield* EventSink.EventSinkV2; @@ -3908,6 +3960,118 @@ it.effect.each([ beforeFailedUnload!.authorizationHeader, ); + // Once background work finishes, reloading a thread whose loaded credential became unbound + // during keepLoaded retires that old unbound credential. + yield* Ref.set(failUnload, false); + yield* manager.open({ + threadId, + providerSessionId, + modelSelection, + runtimePolicy, + runId: RunId.make("run-bg-3-retire"), + attemptId: RunAttemptId.make("attempt-bg-3-retire"), + requireRunScopedMcp: true, + }); + yield* runtime.resumeThread({ + threadId, + providerThread, + modelSelection, + runtimePolicy, + }); + assert.isTrue(Option.isSome(yield* Queue.poll(unloads))); + assert.isUndefined(yield* registry.resolve(loadedToken)); + + // If a newer credential is published while the background-work probe awaits, the fallback + // skips releasing and overwriting it. + const probeRaceThreadId = ThreadId.make("thread-provider-session-manager-probe-race"); + yield* eventSink.write({ + events: [ + yield* makeThreadCreatedEvent({ idAllocator, threadId: probeRaceThreadId, now }), + ], + }); + const raceRun1 = RunId.make("run-probe-race-1"); + yield* manager.open({ + threadId: probeRaceThreadId, + providerSessionId, + modelSelection, + runtimePolicy, + runId: raceRun1, + attemptId: RunAttemptId.make("attempt-probe-race-1"), + requireRunScopedMcp: true, + }); + const originalRaceConfig = yield* mcpSessions.read(probeRaceThreadId); + assert.isDefined(originalRaceConfig); + const originalRaceToken = originalRaceConfig!.authorizationHeader.replace(/^Bearer\s+/, ""); + const probeStarted = yield* Deferred.make(); + const releaseProbe = yield* Deferred.make(); + yield* Ref.set( + sessionBackgroundWorkProbe, + Deferred.succeed(probeStarted, undefined).pipe( + Effect.andThen(Deferred.await(releaseProbe)), + ), + ); + const racingOpen = yield* manager + .open({ + threadId: probeRaceThreadId, + providerSessionId, + modelSelection, + runtimePolicy, + runId: RunId.make("run-probe-race-2"), + attemptId: RunAttemptId.make("attempt-probe-race-2"), + requireRunScopedMcp: true, + }) + .pipe(Effect.forkChild); + yield* Deferred.await(probeStarted); + const newerIssued = yield* registry.issue({ + threadId: probeRaceThreadId, + providerInstanceId: modelSelection.instanceId, + providerSessionId: originalRaceConfig!.providerSessionId, + runId: RunId.make("run-probe-race-3"), + attemptId: RunAttemptId.make("attempt-probe-race-3"), + }); + yield* mcpSessions.set(newerIssued.config); + yield* Deferred.succeed(releaseProbe, true); + yield* Fiber.join(racingOpen); + const afterRace = yield* mcpSessions.read(probeRaceThreadId); + assert.equal(afterRace?.authorizationHeader, newerIssued.config.authorizationHeader); + assert.isUndefined(afterRace?.runId); + // The older credential was not released or written back; the newer one became unbound for run 2. + assert.equal((yield* registry.resolve(originalRaceToken))?.thread.runId, raceRun1); + const newerToken = newerIssued.config.authorizationHeader.replace(/^Bearer\s+/, ""); + const resolvedNewer = yield* registry.resolve(newerToken); + assert.isDefined(resolvedNewer); + assert.isUndefined(resolvedNewer!.thread.runId); + // Narrowing on a non-rotating turn strips preview from older retained thread tokens too, + // while re-enabling restores it only on the active credential. + yield* settings.updateSettings({ enableAgentBrowserAccess: false }); + yield* manager.open({ + threadId: probeRaceThreadId, + providerSessionId, + modelSelection, + runtimePolicy, + runId: RunId.make("run-probe-race-4"), + attemptId: RunAttemptId.make("attempt-probe-race-4"), + requireRunScopedMcp: true, + }); + assert.isFalse((yield* registry.resolve(newerToken))?.capabilities.has("preview") ?? true); + assert.isFalse( + (yield* registry.resolve(originalRaceToken))?.capabilities.has("preview") ?? true, + ); + yield* settings.updateSettings({ enableAgentBrowserAccess: true }); + yield* manager.open({ + threadId: probeRaceThreadId, + providerSessionId, + modelSelection, + runtimePolicy, + runId: RunId.make("run-probe-race-5"), + attemptId: RunAttemptId.make("attempt-probe-race-5"), + requireRunScopedMcp: true, + }); + assert.isTrue((yield* registry.resolve(newerToken))?.capabilities.has("preview") ?? false); + assert.isFalse( + (yield* registry.resolve(originalRaceToken))?.capabilities.has("preview") ?? true, + ); + yield* manager.close(providerSessionId); }); @@ -3919,6 +4083,7 @@ it.effect.each([ state, idleTimeoutMs: 1_000, unloads, + hasPendingBackgroundWork: Ref.get(sessionBackgroundWorkProbe).pipe(Effect.flatten), hasPendingBackgroundWorkForThread: Ref.get(pendingBackgroundWork), beforeUnload: Ref.get(failUnload).pipe( Effect.flatMap((fail) => (fail ? Effect.die("unload failed") : Effect.void)), @@ -3971,6 +4136,7 @@ it.effect.each([ }); const token1 = (yield* mcpSessions.read(threadId))?.authorizationHeader; assert.isDefined(token1); + assert.equal((yield* Ref.get(state)).resumeCount, 1); assert.isTrue(Option.isNone(yield* Queue.poll(unloads))); // Plain turn on a shared runtime without live MCP updates keeps the loaded credential. @@ -3998,6 +4164,7 @@ it.effect.each([ requireRunScopedMcp: true, }); const token3 = (yield* mcpSessions.read(threadId))?.authorizationHeader; + assert.isDefined(token3); assert.notEqual(token3, token1); yield* runtime.resumeThread({ threadId, @@ -4006,6 +4173,7 @@ it.effect.each([ runtimePolicy, }); assert.deepEqual([...(yield* Queue.takeAll(unloads))], ["unload:native-thread"]); + assert.equal((yield* Ref.get(state)).resumeCount, 2); yield* manager.close(providerSessionId); }); diff --git a/apps/server/src/orchestration-v2/ProviderSessionManager.ts b/apps/server/src/orchestration-v2/ProviderSessionManager.ts index f2f345b771ae2..a2de2538854af 100644 --- a/apps/server/src/orchestration-v2/ProviderSessionManager.ts +++ b/apps/server/src/orchestration-v2/ProviderSessionManager.ts @@ -663,6 +663,28 @@ export const layerWithOptions = ( } return new Map(current).set(key, { ...entry, mcpCredentialIdsByThread }); }); + const syncLoadedMcpCredential = ( + threadId: ThreadId, + credentialId: string, + updatedCredential: McpProviderSession.McpProviderSessionConfig, + ) => + Ref.update(sessions, (current) => { + let next: Map | undefined; + for (const [key, entry] of current) { + const loaded = entry.loadedMcpCredentialByThread.get(threadId); + if ( + loaded === undefined || + McpProviderSession.mcpCredentialIdOf(loaded) !== credentialId + ) { + continue; + } + next ??= new Map(current); + const loadedMcpCredentialByThread = new Map(entry.loadedMcpCredentialByThread); + loadedMcpCredentialByThread.set(threadId, updatedCredential); + next.set(key, { ...entry, loadedMcpCredentialByThread }); + } + return next ?? current; + }); const mcpTurnKey = (runId: RunId, attemptId?: RunAttemptId) => `${runId}:${attemptId ?? ""}`; const recordMcpTurnChecked = ( providerSessionId: ProviderSessionId, @@ -2200,78 +2222,151 @@ export const layerWithOptions = ( ?.mcpTurnCheckedKeyByThread.get(input.threadId) === turnKey; if (alreadyChecked) return; } - const current = yield* mcpSessions.read(input.threadId); - if ( - current !== undefined && - current.runId === input.runId && - (input.attemptId === undefined || current.attemptId === input.attemptId) - ) { - yield* recordMcpTurnChecked(input.providerSessionId, input.threadId, turnKey); - return; - } - const rotateOnRunChange = - input.requireRunScopedMcp !== undefined - ? input.requireRunScopedMcp || - (input.owedOutputRunId !== undefined && current?.runId !== input.owedOutputRunId) - : yield* threadRequiresRunScopedMcp( - input.threadId, - input.runId, - current?.runId, - ).pipe( - Effect.mapError( - (cause) => - new ProviderSessionOpenError({ - instanceId: input.providerInstanceId, - providerSessionId: input.providerSessionId, - cause, - }), + for (let attempt = 0; attempt < 3; attempt += 1) { + const current = yield* mcpSessions.read(input.threadId); + if ( + current !== undefined && + current.runId === input.runId && + (input.attemptId === undefined || current.attemptId === input.attemptId) + ) { + yield* recordMcpTurnChecked(input.providerSessionId, input.threadId, turnKey); + return; + } + const rotateOnRunChange = + input.requireRunScopedMcp !== undefined + ? input.requireRunScopedMcp || + (input.owedOutputRunId !== undefined && + current?.runId !== input.owedOutputRunId) + : yield* threadRequiresRunScopedMcp( + input.threadId, + input.runId, + current?.runId, + ).pipe( + Effect.mapError( + (cause) => + new ProviderSessionOpenError({ + instanceId: input.providerInstanceId, + providerSessionId: input.providerSessionId, + cause, + }), + ), + ); + if (!rotateOnRunChange && current !== undefined) { + yield* recordMcpTurnChecked(input.providerSessionId, input.threadId, turnKey); + return; + } + // A runtime that cannot take a new credential now (no way to deliver one, or a reload that + // would end background work) keeps it unbound; the agent then names its run in the call. + const cannotRotate = + input.runtime.mcpCredentialRotation === "none" || + (input.runtime.mcpCredentialRotation !== "live" && + (yield* (input.runtime.hasPendingBackgroundWork ?? Effect.succeed(false)).pipe( + Effect.catchCauseIf( + (cause) => !Cause.hasInterruptsOnly(cause), + () => Effect.succeed(true), ), - ); - if (!rotateOnRunChange && current !== undefined) { - yield* recordMcpTurnChecked(input.providerSessionId, input.threadId, turnKey); - return; - } - // A runtime that cannot take a new credential now (no way to deliver one, or a reload that - // would end background work) keeps it unbound; the agent then names its run in the call. - const cannotRotate = - input.runtime.mcpCredentialRotation === "none" || - (input.runtime.mcpCredentialRotation !== "live" && - (yield* (input.runtime.hasPendingBackgroundWork ?? Effect.succeed(false)).pipe( - Effect.catchCauseIf( - (cause) => !Cause.hasInterruptsOnly(cause), - () => Effect.succeed(true), - ), - ))); - if (cannotRotate && current !== undefined) { - if (current.runId !== undefined || current.attemptId !== undefined) { - yield* mcpSessionRegistry.releaseRunBinding( - McpProviderSession.mcpCredentialIdOf(current), + ))); + if (cannotRotate && current !== undefined) { + const currentCredentialId = McpProviderSession.mcpCredentialIdOf(current); + const retained = yield* mcpPrepareLock.withLock( + input.threadId, + Effect.gen(function* () { + // Re-read after the async probe so an overlapping turn start's credential is never overwritten. + const latest = yield* mcpSessions.read(input.threadId); + if ( + latest === undefined || + McpProviderSession.mcpCredentialIdOf(latest) !== currentCredentialId + ) { + return false; + } + const { browser: browserToolsAvailable, device: deviceToolsAvailable } = + yield* agentAccessSettings(input.threadId); + const rawToken = latest.authorizationHeader.replace(/^Bearer\s+/, ""); + const resolved = yield* mcpSessionRegistry.resolve(rawToken); + const hasPreview = + resolved !== undefined + ? resolved.capabilities.has("preview") + : latest.browserToolsAvailable || + latest.capabilities?.has("preview") === true; + const hasDevice = + resolved !== undefined + ? resolved.capabilities.has("device") + : latest.capabilities?.has("device") === true; + const grant: Array = []; + const revoke: Array = + []; + if (browserToolsAvailable && !hasPreview) grant.push("preview"); + else if (!browserToolsAvailable && hasPreview) revoke.push("preview"); + if (deviceToolsAvailable && !hasDevice) grant.push("device"); + else if (!deviceToolsAvailable && hasDevice) revoke.push("device"); + const capabilitiesChanged = grant.length > 0 || revoke.length > 0; + const syncedCapabilities = capabilitiesChanged + ? yield* mcpSessionRegistry.syncCapabilities(currentCredentialId, { + threadId: input.threadId, + grant, + revoke, + }) + : resolved?.capabilities; + const needsUnbind = + latest.runId !== undefined || latest.attemptId !== undefined; + if (needsUnbind) { + yield* mcpSessionRegistry.releaseRunBinding(currentCredentialId); + } + if (capabilitiesChanged || needsUnbind) { + const { runId: _runId, attemptId: _attemptId, ...withoutRun } = latest; + const nextCapabilities = + syncedCapabilities ?? + (latest.capabilities === undefined + ? undefined + : (() => { + const next = new Set(latest.capabilities); + for (const capability of grant) next.add(capability); + for (const capability of revoke) next.delete(capability); + return next; + })()); + const updated: McpProviderSession.McpProviderSessionConfig = { + ...withoutRun, + browserToolsAvailable: + syncedCapabilities !== undefined + ? syncedCapabilities.has("preview") + : browserToolsAvailable, + ...(nextCapabilities === undefined + ? {} + : { capabilities: nextCapabilities }), + }; + yield* mcpSessions.set(updated); + yield* syncLoadedMcpCredential(input.threadId, currentCredentialId, updated); + } + return true; + }), + ); + if (retained) { + yield* recordMcpTurnChecked(input.providerSessionId, input.threadId, turnKey); + return; + } + continue; + } + const ownerSessionId = (yield* Ref.get(sessions)) + .get(sessionKey(input.providerSessionId)) + ?.mcpOwnerSessionIdByThread.get(input.threadId); + const prepared = yield* prepareMcpSession(input.threadId, input.providerInstanceId, { + runId: input.runId, + ...(input.attemptId === undefined ? {} : { attemptId: input.attemptId }), + ...(ownerSessionId === undefined ? {} : { ownerSessionId }), + rotateOnRunChange, + }); + reservedCredentialId = prepared.mcpCredentialId; + if (prepared.mcpCredentialId !== undefined) { + yield* recordSessionMcpCredential( + input.providerSessionId, + input.threadId, + prepared.mcpCredentialId, + prepared.mcpOwnerSessionId, ); - const { runId: _runId, attemptId: _attemptId, ...unbound } = current; - yield* mcpSessions.set(unbound); } yield* recordMcpTurnChecked(input.providerSessionId, input.threadId, turnKey); return; } - const ownerSessionId = (yield* Ref.get(sessions)) - .get(sessionKey(input.providerSessionId)) - ?.mcpOwnerSessionIdByThread.get(input.threadId); - const prepared = yield* prepareMcpSession(input.threadId, input.providerInstanceId, { - runId: input.runId, - ...(input.attemptId === undefined ? {} : { attemptId: input.attemptId }), - ...(ownerSessionId === undefined ? {} : { ownerSessionId }), - rotateOnRunChange, - }); - reservedCredentialId = prepared.mcpCredentialId; - if (prepared.mcpCredentialId !== undefined) { - yield* recordSessionMcpCredential( - input.providerSessionId, - input.threadId, - prepared.mcpCredentialId, - prepared.mcpOwnerSessionId, - ); - } - yield* recordMcpTurnChecked(input.providerSessionId, input.threadId, turnKey); }).pipe(Effect.ensuring(Effect.sync(dropReservation))); }, ); @@ -2721,8 +2816,9 @@ export const layerWithOptions = ( /^Bearer\s+/, "", ); + const resolvedLoaded = yield* mcpSessionRegistry.resolve(loadedRawToken); // Capability removals revoke immediately; the thread then holds no working token. - if ((yield* mcpSessionRegistry.resolve(loadedRawToken)) === undefined) { + if (resolvedLoaded === undefined) { yield* mcpSessions.clear(input.threadId); yield* recordMcpTurnChecked( input.providerSessionId, @@ -2737,8 +2833,18 @@ export const layerWithOptions = ( }); } yield* mcpSessionRegistry.releaseRunBinding(loadedCredentialId); - const { runId: _runId, attemptId: _attemptId, ...unbound } = loadedCredential; + const { + runId: _runId, + attemptId: _attemptId, + ...withoutRun + } = loadedCredential; + const unbound: McpProviderSession.McpProviderSessionConfig = { + ...withoutRun, + browserToolsAvailable: resolvedLoaded.capabilities.has("preview"), + capabilities: resolvedLoaded.capabilities, + }; yield* mcpSessions.set(unbound); + yield* syncLoadedMcpCredential(input.threadId, loadedCredentialId, unbound); }), ); if (hasPendingWork) { @@ -2746,7 +2852,7 @@ export const layerWithOptions = ( "Cannot refresh MCP credentials while background work is running on this thread.", ); } - const unloadingKey = yield* Ref.modify(sessions, (current) => { + const unloadingCredential = yield* Ref.modify(sessions, (current) => { const latest = current.get(key); const latestLoaded = latest?.loadedMcpCredentialByThread.get(input.threadId); const latestThreadKey = latest?.loadedProviderThreadKeyByThread.get(input.threadId); @@ -2766,7 +2872,7 @@ export const layerWithOptions = ( const loadedMcpCredentialByThread = new Map(latest.loadedMcpCredentialByThread); loadedMcpCredentialByThread.delete(input.threadId); return [ - latestThreadKey, + latestLoaded, new Map(current).set(key, { ...latest, loadedProviderThreadKeyByThread, @@ -2774,7 +2880,7 @@ export const layerWithOptions = ( }), ] as const; }); - if (unloadingKey === undefined) return; + if (unloadingCredential === undefined) return; const unloaded = yield* unloadThread({ providerThread: input.providerThread }).pipe( Effect.timeout(UNLOAD_THREAD_TIMEOUT_MS), Effect.as(true), @@ -2791,7 +2897,7 @@ export const layerWithOptions = ( // step resumes it natively, on the old credential either way. return yield* keepLoaded("Could not reload the thread to refresh MCP credentials."); } - if (loadedCredential.runId === undefined) { + if (unloadingCredential.runId === undefined) { yield* mcpSessionRegistry.revokeCredential(loadedCredentialId); yield* removeSessionMcpCredential( input.providerSessionId, diff --git a/packages/provider-acp/src/server/mcpOverAcpBridge.test.ts b/packages/provider-acp/src/server/mcpOverAcpBridge.test.ts index 00001e0db9a49..53fcdfa6a904a 100644 --- a/packages/provider-acp/src/server/mcpOverAcpBridge.test.ts +++ b/packages/provider-acp/src/server/mcpOverAcpBridge.test.ts @@ -563,8 +563,8 @@ describe("AcpMcpOverAcpBridge", () => { .pipe(Effect.flip); expect(explicitError.message).toContain("initialize rejected"); nextInitMode = "malformed"; - expect( - yield* bridge.message({ + const explicitMalformed = yield* bridge + .message({ connectionId, method: "initialize", params: { @@ -572,8 +572,10 @@ describe("AcpMcpOverAcpBridge", () => { capabilities: {}, clientInfo: { name: "acp" }, }, - }), - ).toBeNull(); + }) + .pipe(Effect.flip); + expect(explicitMalformed._tag).toBe("AcpMcpOverAcpError"); + expect(explicitMalformed.message).toContain("valid initialize response"); const methodsBeforeRecovery = methods.length; expect( yield* bridge.message({ diff --git a/packages/provider-acp/src/server/mcpOverAcpBridge.ts b/packages/provider-acp/src/server/mcpOverAcpBridge.ts index 8f0af421b9e71..3b516941c0e87 100644 --- a/packages/provider-acp/src/server/mcpOverAcpBridge.ts +++ b/packages/provider-acp/src/server/mcpOverAcpBridge.ts @@ -397,6 +397,11 @@ export const makeAcpMcpOverAcpBridge = Effect.fn("AcpMcpOverAcpBridge.make")(fun if (envelope.error !== undefined) { return yield* new AcpMcpOverAcpError({ message: errorMessage(envelope.error) }); } + if (request.method === "initialize" && protocolVersionOf(envelope) === null) { + return yield* new AcpMcpOverAcpError({ + message: "MCP server did not return a valid initialize response.", + }); + } return (envelope.result ?? null) as AcpSchema.MessageMcpResponse; }), notification: Effect.fn("mcpOverAcpBridge.notification")(function* (request) { From 602806f418bf42aa63101ce2190aa27f8c1e05e5 Mon Sep 17 00:00:00 2001 From: Victor Vogel Date: Sat, 21 Nov 2026 19:32:42 +0000 Subject: [PATCH 12/34] fix(server): close MCP capability sync, ACP restart, continuation runId, and Claude refresh gaps - Sync preview/device capabilities on retained credentials in ensureTurnMcpSession for untyped next runs and same-run re-opens without dropping active run bindings. - Negotiate runtime.initialize() on ACP teardown restarts and read installed capabilities in activateSession, readThreadSnapshot, forkThread, canResumeAfterRestart, and mcpCredentialRotation. - Prompt unbound typed manual and restart continuations with their own runId in ProviderTurnStartService and remove the continuation ancestry bypass in ThreadManagementService.submitRunOutput so a stopped ancestor's delayed submission is rejected on its continuation. - Track mcpAuthorization on retained Claude queries and fail provider-origin continuations with ProviderAdapterMcpRotationBlockedError when live setMcpServers is unavailable or fails, keeping the process and buffered wake intact for retry. --- .../Adapters/AcpAdapterV2.test.ts | 83 +++++++-- .../Adapters/ClaudeAdapterV2.test.ts | 111 +++++++++-- .../Adapters/ClaudeAdapterV2.ts | 27 ++- .../ProviderSessionManager.test.ts | 65 +++++++ .../ProviderSessionManager.ts | 176 ++++++++++-------- .../ProviderTurnStartService.test.ts | 81 +++++++- .../ProviderTurnStartService.ts | 40 +++- .../ThreadManagementService.ts | 21 +-- .../src/orchestration-v2/runtimeLayer.test.ts | 58 +++++- packages/provider-acp/src/server/adapter.ts | 39 ++-- 10 files changed, 539 insertions(+), 162 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts index d79fd62826e61..e7e7009fa476a 100644 --- a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts @@ -1376,6 +1376,7 @@ describe("AcpAdapterV2", () => { const promptRuntimes: Array = []; const promptTexts: Array = []; const watchedSessions: Array = []; + const restartedActivationCalls: Array = []; const adapter = yield* makeAcpAdapterV2({ instanceId, selfInvocation: yield* resolveSelfInvocation(), @@ -1403,20 +1404,69 @@ describe("AcpAdapterV2", () => { makeRuntime: makeMockRuntime({ childProcessSpawner: yield* ChildProcessSpawner.ChildProcessSpawner, mockAgentPath: yield* bundledMockAgentPath, - wrapRuntime: (runtime, runtimeOrdinal) => ({ - ...runtime, - cancel: Deferred.succeed(cancelled, undefined).pipe(Effect.asVoid), - prompt: (payload) => - Effect.sync(() => { - promptRuntimes.push(runtimeOrdinal); - promptTexts.push( - payload.prompt - .flatMap((block) => (block.type === "text" ? [block.text] : [])) - .join("\n"), - ); - return { stopReason: "end_turn" as const }; - }), - }), + wrapRuntime: (runtime, runtimeOrdinal) => { + const resumeOnlyCapabilities = ( + init: Effect.Success>, + ) => ({ + ...init, + agentCapabilities: { + ...init.agentCapabilities, + loadSession: false, + sessionCapabilities: { + ...init.agentCapabilities?.sessionCapabilities, + resume: {}, + }, + }, + }); + return { + ...runtime, + ...(runtimeOrdinal === 2 + ? { + initialize: () => + runtime.initialize().pipe( + Effect.map((init) => { + restartedActivationCalls.push("initialize"); + return resumeOnlyCapabilities(init); + }), + ), + loadSession: () => + Effect.sync(() => { + restartedActivationCalls.push("loadSession"); + }).pipe( + Effect.andThen( + Effect.fail( + new EffectAcpErrors.AcpRequestError({ + code: -32601, + errorMessage: "restarted agent does not support session/load", + }), + ), + ), + ), + resumeSession: (sessionId, activationOptions) => + Effect.sync(() => { + restartedActivationCalls.push("resumeSession"); + }).pipe( + Effect.andThen(runtime.loadSession(sessionId, activationOptions)), + Effect.map((loaded) => ({ + ...loaded, + initializeResult: resumeOnlyCapabilities(loaded.initializeResult), + })), + ), + } + : {}), + cancel: Deferred.succeed(cancelled, undefined).pipe(Effect.asVoid), + prompt: (payload) => + Effect.sync(() => { + promptRuntimes.push(runtimeOrdinal); + promptTexts.push( + payload.prompt + .flatMap((block) => (block.type === "text" ? [block.text] : [])) + .join("\n"), + ); + return { stopReason: "end_turn" as const }; + }), + }; + }, }), }, }); @@ -1465,6 +1515,11 @@ describe("AcpAdapterV2", () => { const completed = (yield* runTurn(2)).at(-1); assert.equal(completed?.type === "turn.terminal" ? completed.status : null, "completed"); assert.deepEqual(promptRuntimes, [1, 2], "the next turn runs on a fresh runtime"); + assert.deepEqual( + restartedActivationCalls, + ["initialize", "resumeSession"], + "restarted runtime negotiates capabilities before choosing loadSession vs resumeSession", + ); // The fresh runtime has no record of what reached the agent, so it sends T3's notes again. assert.include(promptTexts[1] ?? "", ""); assert.include(promptTexts[1] ?? "", "T3 Code interaction mode: Default"); diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts index 6ecca5421a958..98685d4150051 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts @@ -3756,6 +3756,7 @@ describe("ClaudeAdapterV2 background wake turns", () => { ) => Effect.Effect; readonly renameSession?: ClaudeAdapterV2.ClaudeAgentSdkQuerySession["renameSession"]; readonly setMcpServers?: ClaudeAdapterV2.ClaudeAgentSdkQuerySession["setMcpServers"]; + readonly omitSetMcpServers?: boolean; readonly applyFlagSettings?: ClaudeAdapterV2.ClaudeAgentSdkQuerySession["applyFlagSettings"]; readonly stopTask?: ( taskId: string, @@ -3947,10 +3948,18 @@ describe("ClaudeAdapterV2 background wake turns", () => { Effect.sync(() => { renameCalls.push(title); }).pipe(Effect.andThen(() => options?.renameSession?.(title) ?? Effect.void)), - setMcpServers: (servers) => - Effect.sync(() => { - setMcpServersCalls.push(servers); - }).pipe(Effect.andThen(() => options?.setMcpServers?.(servers) ?? Effect.void)), + ...(options?.omitSetMcpServers === true + ? {} + : { + setMcpServers: ((servers) => + Effect.sync(() => { + setMcpServersCalls.push(servers); + }).pipe( + Effect.andThen(() => options?.setMcpServers?.(servers) ?? Effect.void), + )) satisfies NonNullable< + ClaudeAdapterV2.ClaudeAgentSdkQuerySession["setMcpServers"] + >, + }), backgroundTasks: options?.backgroundTasks ?? (() => Effect.succeed(false)), mcpServerStatus: options?.mcp?.mcpServerStatus ?? Effect.succeed([]), readMcpResource: @@ -25267,28 +25276,54 @@ describe("ClaudeAdapterV2 background wake turns", () => { description: "fails explicitly when live setMcpServers fails on token rotation while background work is active", }, + { + mode: "continuation-refresh-failed" as const, + description: + "fails explicitly when live setMcpServers fails on a provider-origin continuation with a rotated credential", + }, + { + mode: "continuation-no-live-refresh" as const, + description: + "fails explicitly when setMcpServers is unavailable on a provider-origin continuation with a rotated credential", + }, ])("$description", ({ mode }) => Effect.gen(function* () { const mcpSessions = yield* McpProviderSessions.McpProviderSessions; + let failRefreshCount = + mode === "continuation-refresh-failed" ? 1 : Number.POSITIVE_INFINITY; const harness = mode === "live-refresh" ? yield* makeWakeHarness : yield* makeWakeHarnessWithOptions({ freshQueueOnReopen: true, - setMcpServers: () => - Effect.fail( - new ClaudeAdapterV2.ClaudeAgentSdkQueryRunnerError({ - method: "setMcpServers", - cause: new Error("setMcpServers rejected"), + ...(mode === "continuation-no-live-refresh" + ? { omitSetMcpServers: true } + : { + setMcpServers: () => + Effect.suspend(() => { + if (failRefreshCount > 0) { + failRefreshCount -= 1; + return Effect.fail( + new ClaudeAdapterV2.ClaudeAgentSdkQueryRunnerError({ + method: "setMcpServers", + cause: new Error("setMcpServers rejected"), + }), + ); + } + return Effect.void; + }), }), - ), }); + const isContinuationMode = + mode === "continuation-refresh-failed" || mode === "continuation-no-live-refresh"; const envSlug = `environment-claude-mcp-${mode}`; yield* mcpSessions.set({ environmentId: EnvironmentId.make(envSlug), threadId: harness.threadId, providerSessionId: `mcp-session-claude-${mode}-1`, providerInstanceId: ProviderInstanceId.make("claudeAgent"), + runId: RunId.make(`claude-mcp-${mode}-run-1`), + attemptId: RunAttemptId.make(`claude-mcp-${mode}-attempt-1`), endpoint: "http://127.0.0.1:43123/mcp", authorizationHeader: `Bearer claude-${mode}-run-1`, browserToolsAvailable: false, @@ -25304,7 +25339,7 @@ describe("ClaudeAdapterV2 background wake turns", () => { attachments: [], }), ); - if (mode === "blocked-by-background-work") { + if (mode === "blocked-by-background-work" || isContinuationMode) { yield* harness.offerAndWait(wakeTaskStarted); } const firstQueue = @@ -25314,20 +25349,72 @@ describe("ClaudeAdapterV2 background wake turns", () => { makeResultFrame({ uuid: `claude-mcp-${mode}-result-1`, result: "Done 1." }), ); yield* Queue.take(harness.terminalReceipts); - if (mode === "blocked-by-background-work") { + if (mode === "blocked-by-background-work" || isContinuationMode) { assert.isTrue(yield* harness.hasPendingBackgroundWork); } + if (isContinuationMode) { + yield* harness.offerAndWait( + makeSubagentNotificationFrame({ + taskId: WAKE_TASK_ID, + toolUseId: WAKE_TOOL_USE_ID, + summary: "Background task done.", + uuid: `claude-mcp-${mode}-wake-done`, + }), + ); + yield* harness.offerAndWait(wakeTurnInit); + yield* Queue.take(harness.continuationReceipts); + } yield* mcpSessions.set({ environmentId: EnvironmentId.make(envSlug), threadId: harness.threadId, providerSessionId: `mcp-session-claude-${mode}-2`, providerInstanceId: ProviderInstanceId.make("claudeAgent"), + runId: RunId.make(`claude-mcp-${mode}-run-2`), + attemptId: RunAttemptId.make(`claude-mcp-${mode}-attempt-2`), endpoint: "http://127.0.0.1:43123/mcp", authorizationHeader: `Bearer claude-${mode}-run-2`, browserToolsAvailable: false, }); + if (isContinuationMode) { + const continuationTurn = makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now: yield* DateTime.now, + attemptId: RunAttemptId.make(`claude-mcp-${mode}-attempt-2`), + text: "Background task completed.", + attachments: [], + providerTurnOrdinal: 2, + messageCreatedBy: "agent", + messageCreationSource: "provider", + }); + const rejected = yield* harness.runtime.startTurn(continuationTurn).pipe(Effect.flip); + assert.instanceOf(rejected.cause, ProviderAdapter.ProviderAdapterMcpRotationBlockedError); + assert.equal(harness.processQueues.length, 1); + if (mode === "continuation-no-live-refresh") { + assert.equal(harness.setMcpServersCalls.length, 0); + return; + } + assert.equal(harness.setMcpServersCalls.length, 1); + // The buffered wake stayed intact: once live refresh recovers, the retry delivers it. + yield* harness.runtime.startTurn({ + ...continuationTurn, + attemptId: RunAttemptId.make(`claude-mcp-${mode}-attempt-3`), + }); + yield* harness.offerAndWait( + makeResultFrame({ + uuid: `claude-mcp-${mode}-wake-result`, + result: "Done wake.", + origin: { kind: "task-notification" }, + }), + ); + assert.equal((yield* Queue.take(harness.terminalReceipts)).status, "completed"); + assert.equal(harness.processQueues.length, 1); + assert.equal(harness.setMcpServersCalls.length, 2); + return; + } + if (mode === "blocked-by-background-work") { const rejected = yield* harness.runtime .startTurn( diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts index 825cc56d7f097..666041f76d097 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts @@ -5371,6 +5371,7 @@ interface ClaudeLiveQueryContext { readonly query: ClaudeAgentSdkQuerySession; queryPolicyKey: string; readonly queryPolicyKeyWithoutMcpAuth: string; + mcpAuthorization: string | undefined; selection: CompiledClaudeModelSelection; readonly closed: Deferred.Deferred; lastTurn: ActiveClaudeTurnContext | null; @@ -13215,7 +13216,10 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( ) return; yield* candidate.query.setMcpServers(mcpOverrides.mcpServers); - candidate.queryPolicyKey = queryPolicyKey; + candidate.mcpAuthorization = mcpSession?.authorizationHeader; + if (candidate.queryPolicyKeyWithoutMcpAuth === queryPolicyKeyWithoutMcpAuth) { + candidate.queryPolicyKey = queryPolicyKey; + } }); // Continuations drain existing output without prompting; retain the live process regardless of selection. if ( @@ -13224,9 +13228,21 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( !existing.stopping && isClaudeProviderContinuationTurn(turnInput) ) { - // The turn's run may have rotated the credential; the retained query must carry it. - // Reopening would end the wake, so a failed refresh keeps the query and is logged. - if (canUpdateMcpLive(existing)) { + // Refuse to run on a stale credential, keeping the process and its buffered wake for retry. + if (existing.mcpAuthorization !== mcpSession?.authorizationHeader) { + const rotationBlocked = () => + new ProviderAdapter.ProviderAdapterMcpRotationBlockedError({ + driver: CLAUDE_PROVIDER, + providerSessionId: input.providerSessionId, + providerThreadId: turnInput.providerThread.id, + detail: "Cannot refresh MCP credentials on a retained Claude continuation query.", + }); + if ( + mcpOverrides.mcpServers === undefined || + existing.query.setMcpServers === undefined + ) { + return yield* rotationBlocked(); + } yield* syncMcpServersLive(existing).pipe( Effect.catchCauseIf( (cause) => !Cause.hasInterruptsOnly(cause), @@ -13234,7 +13250,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( Effect.logWarning("orchestration-v2.claude-live-mcp-refresh-failed", { threadId: turnInput.threadId, reason: "continuation", - }), + }).pipe(Effect.andThen(Effect.fail(rotationBlocked()))), ), ); } @@ -13473,6 +13489,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( query: querySession, queryPolicyKey, queryPolicyKeyWithoutMcpAuth, + mcpAuthorization: mcpSession?.authorizationHeader, selection: compiledSelection, closed, lastTurn: null, diff --git a/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts b/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts index 53c5c70a15991..dbb4079e1bc19 100644 --- a/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts +++ b/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts @@ -3478,6 +3478,34 @@ it.effect.each([ const token1 = config1!.authorizationHeader.replace(/^Bearer\s+/, ""); assert.equal((yield* registry.resolve(token1))?.thread.runId, run1); + // Re-opening the same run/attempt after toggling browser access syncs preview while keeping run1 bound. + yield* settings.updateSettings({ enableAgentBrowserAccess: false }); + yield* manager.open({ + threadId, + providerSessionId, + modelSelection, + runtimePolicy, + runId: run1, + attemptId: RunAttemptId.make("attempt-none-1"), + requireRunScopedMcp: true, + }); + assert.isFalse((yield* registry.resolve(token1))?.capabilities.has("preview") ?? true); + assert.equal((yield* registry.resolve(token1))?.thread.runId, run1); + assert.isFalse((yield* mcpSessions.read(threadId))?.browserToolsAvailable); + yield* settings.updateSettings({ enableAgentBrowserAccess: true }); + yield* manager.open({ + threadId, + providerSessionId, + modelSelection, + runtimePolicy, + runId: run1, + attemptId: RunAttemptId.make("attempt-none-1"), + requireRunScopedMcp: true, + }); + assert.isTrue((yield* registry.resolve(token1))?.capabilities.has("preview") ?? false); + assert.equal((yield* registry.resolve(token1))?.thread.runId, run1); + assert.isTrue((yield* mcpSessions.read(threadId))?.browserToolsAvailable); + // Plain turns and owed wakes for run1 succeed without rotating or mutating token1. yield* manager.open({ threadId, @@ -3554,6 +3582,43 @@ it.effect.each([ assert.equal(config5?.authorizationHeader, config1!.authorizationHeader); assert.isTrue(config5?.browserToolsAvailable); assert.isTrue(config5?.capabilities?.has("preview") ?? false); + + // Disabling and re-enabling browser access also syncs on untyped next runs with no owed output. + yield* settings.updateSettings({ enableAgentBrowserAccess: false }); + yield* manager.open({ + threadId, + providerSessionId, + modelSelection, + runtimePolicy, + runId: RunId.make("run-none-6"), + attemptId: RunAttemptId.make("attempt-none-6"), + requireRunScopedMcp: false, + }); + const narrowedUntyped = yield* registry.resolve(token1); + assert.isDefined(narrowedUntyped); + assert.isFalse(narrowedUntyped!.capabilities.has("preview")); + const config6 = yield* mcpSessions.read(threadId); + assert.equal(config6?.authorizationHeader, config1!.authorizationHeader); + assert.isFalse(config6?.browserToolsAvailable); + assert.isFalse(config6?.capabilities?.has("preview") ?? false); + + yield* settings.updateSettings({ enableAgentBrowserAccess: true }); + yield* manager.open({ + threadId, + providerSessionId, + modelSelection, + runtimePolicy, + runId: RunId.make("run-none-7"), + attemptId: RunAttemptId.make("attempt-none-7"), + requireRunScopedMcp: false, + }); + const restoredUntyped = yield* registry.resolve(token1); + assert.isDefined(restoredUntyped); + assert.isTrue(restoredUntyped!.capabilities.has("preview")); + const config7 = yield* mcpSessions.read(threadId); + assert.equal(config7?.authorizationHeader, config1!.authorizationHeader); + assert.isTrue(config7?.browserToolsAvailable); + assert.isTrue(config7?.capabilities?.has("preview") ?? false); yield* manager.close(providerSessionId); }); diff --git a/apps/server/src/orchestration-v2/ProviderSessionManager.ts b/apps/server/src/orchestration-v2/ProviderSessionManager.ts index a2de2538854af..bf58b987cfe8b 100644 --- a/apps/server/src/orchestration-v2/ProviderSessionManager.ts +++ b/apps/server/src/orchestration-v2/ProviderSessionManager.ts @@ -45,6 +45,7 @@ import * as Semaphore from "effect/Semaphore"; import * as Stream from "effect/Stream"; import * as SubscriptionRef from "effect/SubscriptionRef"; +import type { McpCapability } from "../mcp/McpInvocationContext.ts"; import { normalizeModelMetricLabel } from "../observability/Attributes.ts"; import { providerSessionsTotal, @@ -740,9 +741,12 @@ export const layerWithOptions = ( // Live providers build MCP clients once; reuse credentials across workspace handoffs. const { browser: browserToolsAvailable, device: deviceToolsAvailable } = yield* agentAccessSettings(threadId); - const capabilities = new Set< - import("../mcp/McpInvocationContext.ts").McpCapability - >(["orchestration", "worktree", "pull-requests", "issues"]); + const capabilities = new Set([ + "orchestration", + "worktree", + "pull-requests", + "issues", + ]); if (browserToolsAvailable) capabilities.add("preview"); if (deviceToolsAvailable) capabilities.add("device"); const backgroundWait = yield* registry.get(providerInstanceId).pipe( @@ -2222,6 +2226,83 @@ export const layerWithOptions = ( ?.mcpTurnCheckedKeyByThread.get(input.threadId) === turnKey; if (alreadyChecked) return; } + const retainCurrentMcpCredential = ( + current: McpProviderSession.McpProviderSessionConfig, + opts: { readonly unbindRun: boolean }, + ) => { + const currentCredentialId = McpProviderSession.mcpCredentialIdOf(current); + return mcpPrepareLock.withLock( + input.threadId, + Effect.gen(function* () { + // Re-read under lock so an overlapping turn start's credential is never overwritten. + const latest = yield* mcpSessions.read(input.threadId); + if ( + latest === undefined || + McpProviderSession.mcpCredentialIdOf(latest) !== currentCredentialId + ) { + return false; + } + const { browser: browserToolsAvailable, device: deviceToolsAvailable } = + yield* agentAccessSettings(input.threadId); + const rawToken = latest.authorizationHeader.replace(/^Bearer\s+/, ""); + const resolved = yield* mcpSessionRegistry.resolve(rawToken); + const hasPreview = + resolved !== undefined + ? resolved.capabilities.has("preview") + : latest.browserToolsAvailable || + latest.capabilities?.has("preview") === true; + const hasDevice = + resolved !== undefined + ? resolved.capabilities.has("device") + : latest.capabilities?.has("device") === true; + const grant: Array = []; + const revoke: Array = []; + if (browserToolsAvailable && !hasPreview) grant.push("preview"); + else if (!browserToolsAvailable && hasPreview) revoke.push("preview"); + if (deviceToolsAvailable && !hasDevice) grant.push("device"); + else if (!deviceToolsAvailable && hasDevice) revoke.push("device"); + const capabilitiesChanged = grant.length > 0 || revoke.length > 0; + const syncedCapabilities = capabilitiesChanged + ? yield* mcpSessionRegistry.syncCapabilities(currentCredentialId, { + threadId: input.threadId, + grant, + revoke, + }) + : resolved?.capabilities; + const needsUnbind = + opts.unbindRun && + (latest.runId !== undefined || latest.attemptId !== undefined); + if (needsUnbind) { + yield* mcpSessionRegistry.releaseRunBinding(currentCredentialId); + } + if (capabilitiesChanged || needsUnbind) { + const { runId: _runId, attemptId: _attemptId, ...withoutRun } = latest; + const base = needsUnbind ? withoutRun : latest; + const nextCapabilities = + syncedCapabilities ?? + (latest.capabilities === undefined + ? undefined + : (() => { + const next = new Set(latest.capabilities); + for (const capability of grant) next.add(capability); + for (const capability of revoke) next.delete(capability); + return next; + })()); + const updated: McpProviderSession.McpProviderSessionConfig = { + ...base, + browserToolsAvailable: + syncedCapabilities !== undefined + ? syncedCapabilities.has("preview") + : browserToolsAvailable, + ...(nextCapabilities === undefined ? {} : { capabilities: nextCapabilities }), + }; + yield* mcpSessions.set(updated); + yield* syncLoadedMcpCredential(input.threadId, currentCredentialId, updated); + } + return true; + }), + ); + }; for (let attempt = 0; attempt < 3; attempt += 1) { const current = yield* mcpSessions.read(input.threadId); if ( @@ -2229,8 +2310,11 @@ export const layerWithOptions = ( current.runId === input.runId && (input.attemptId === undefined || current.attemptId === input.attemptId) ) { - yield* recordMcpTurnChecked(input.providerSessionId, input.threadId, turnKey); - return; + if (yield* retainCurrentMcpCredential(current, { unbindRun: false })) { + yield* recordMcpTurnChecked(input.providerSessionId, input.threadId, turnKey); + return; + } + continue; } const rotateOnRunChange = input.requireRunScopedMcp !== undefined @@ -2252,8 +2336,11 @@ export const layerWithOptions = ( ), ); if (!rotateOnRunChange && current !== undefined) { - yield* recordMcpTurnChecked(input.providerSessionId, input.threadId, turnKey); - return; + if (yield* retainCurrentMcpCredential(current, { unbindRun: false })) { + yield* recordMcpTurnChecked(input.providerSessionId, input.threadId, turnKey); + return; + } + continue; } // A runtime that cannot take a new credential now (no way to deliver one, or a reload that // would end background work) keeps it unbound; the agent then names its run in the call. @@ -2267,80 +2354,7 @@ export const layerWithOptions = ( ), ))); if (cannotRotate && current !== undefined) { - const currentCredentialId = McpProviderSession.mcpCredentialIdOf(current); - const retained = yield* mcpPrepareLock.withLock( - input.threadId, - Effect.gen(function* () { - // Re-read after the async probe so an overlapping turn start's credential is never overwritten. - const latest = yield* mcpSessions.read(input.threadId); - if ( - latest === undefined || - McpProviderSession.mcpCredentialIdOf(latest) !== currentCredentialId - ) { - return false; - } - const { browser: browserToolsAvailable, device: deviceToolsAvailable } = - yield* agentAccessSettings(input.threadId); - const rawToken = latest.authorizationHeader.replace(/^Bearer\s+/, ""); - const resolved = yield* mcpSessionRegistry.resolve(rawToken); - const hasPreview = - resolved !== undefined - ? resolved.capabilities.has("preview") - : latest.browserToolsAvailable || - latest.capabilities?.has("preview") === true; - const hasDevice = - resolved !== undefined - ? resolved.capabilities.has("device") - : latest.capabilities?.has("device") === true; - const grant: Array = []; - const revoke: Array = - []; - if (browserToolsAvailable && !hasPreview) grant.push("preview"); - else if (!browserToolsAvailable && hasPreview) revoke.push("preview"); - if (deviceToolsAvailable && !hasDevice) grant.push("device"); - else if (!deviceToolsAvailable && hasDevice) revoke.push("device"); - const capabilitiesChanged = grant.length > 0 || revoke.length > 0; - const syncedCapabilities = capabilitiesChanged - ? yield* mcpSessionRegistry.syncCapabilities(currentCredentialId, { - threadId: input.threadId, - grant, - revoke, - }) - : resolved?.capabilities; - const needsUnbind = - latest.runId !== undefined || latest.attemptId !== undefined; - if (needsUnbind) { - yield* mcpSessionRegistry.releaseRunBinding(currentCredentialId); - } - if (capabilitiesChanged || needsUnbind) { - const { runId: _runId, attemptId: _attemptId, ...withoutRun } = latest; - const nextCapabilities = - syncedCapabilities ?? - (latest.capabilities === undefined - ? undefined - : (() => { - const next = new Set(latest.capabilities); - for (const capability of grant) next.add(capability); - for (const capability of revoke) next.delete(capability); - return next; - })()); - const updated: McpProviderSession.McpProviderSessionConfig = { - ...withoutRun, - browserToolsAvailable: - syncedCapabilities !== undefined - ? syncedCapabilities.has("preview") - : browserToolsAvailable, - ...(nextCapabilities === undefined - ? {} - : { capabilities: nextCapabilities }), - }; - yield* mcpSessions.set(updated); - yield* syncLoadedMcpCredential(input.threadId, currentCredentialId, updated); - } - return true; - }), - ); - if (retained) { + if (yield* retainCurrentMcpCredential(current, { unbindRun: true })) { yield* recordMcpTurnChecked(input.providerSessionId, input.threadId, turnKey); return; } diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts index efe3184958f90..3abe7392ddebe 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts @@ -81,6 +81,7 @@ import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator"; import { CodexProviderCapabilitiesV2 } from "./Adapters/CodexAdapterV2.ts"; import * as ProjectionStore from "./ProjectionStore.ts"; import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter"; +import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions"; import * as ProviderSessionManager from "./ProviderSessionManager.ts"; import * as ProviderTurnStart from "./ProviderTurnStartService.ts"; import * as RunExecutionService from "./RunExecutionService.ts"; @@ -458,6 +459,9 @@ it.each([ function makeLocalCommandHarness(input: { readonly text: string; readonly manualContinuation?: boolean; + readonly restartContinuation?: boolean; + readonly outputSchema?: Readonly>; + readonly mcpSession?: "unbound" | "bound"; readonly nativeResumeUnsupported?: boolean; readonly steeringRestart?: boolean; readonly nativeGoals?: boolean; @@ -527,6 +531,8 @@ function makeLocalCommandHarness(input: { const messageId = MessageId.make("message-native-account-command"); const run: OrchestrationV2ThreadProjection["runs"][number] = { ...(input.manualContinuation ? { manualContinuationOfRunId: RunId.make("stopped-run") } : {}), + ...(input.restartContinuation ? { restartContinuationOfRunId: RunId.make("stopped-run") } : {}), + ...(input.outputSchema === undefined ? {} : { outputSchema: input.outputSchema }), id: runId, threadId, ordinal: 2, @@ -1215,7 +1221,12 @@ function makeLocalCommandHarness(input: { ...runInput, messageId: runInput.message.messageId, } as never) - : runInput.session.startTurn(runInput as never) + : runInput.session.startTurn({ + ...runInput, + ...(runInput.run.restartContinuationOfRunId === undefined + ? {} + : { restartContinuationOfRunId: runInput.run.restartContinuationOfRunId }), + } as never) ).pipe(Effect.orDie) : input.failReadsAfterRunning === true || input.previousTurn !== undefined ? Effect.suspend(() => @@ -1408,6 +1419,23 @@ function makeLocalCommandHarness(input: { Layer.mock(RuntimePolicy.RuntimePolicyV2)({ resolve: resolveRuntimePolicy, }), + ...(input.mcpSession === undefined + ? [] + : [ + Layer.mock(McpProviderSessions.McpProviderSessions)({ + read: () => + Effect.succeed({ + environmentId: EnvironmentId.make("env-native-account-command"), + threadId, + providerSessionId: "mcp-session-native-account-command", + providerInstanceId: newInstanceId, + ...(input.mcpSession === "bound" ? { runId, attemptId } : {}), + endpoint: "http://127.0.0.1:43123/mcp", + authorizationHeader: "Bearer test-token", + browserToolsAvailable: false, + }), + }), + ]), ), ), ); @@ -2260,6 +2288,57 @@ effectIt.effect("sends new steering text when restarting a manual continuation", yield* harness.start; expect(harness.startTurn.mock.calls[0]?.[0].message.text).toBe("New steering instruction"); expect(harness.startRootRun.mock.calls[0]?.[0].resume).toBe(false); + + // An unbound MCP credential cannot supply runId, so typed continuations prompt with their own runId. + const unboundManual = makeLocalCommandHarness({ + text: "", + manualContinuation: true, + outputSchema: { type: "object" }, + mcpSession: "unbound", + sideChat: { contextRun: "delivered" }, + }); + yield* unboundManual.start; + const unboundManualTurn = unboundManual.startTurn.mock.calls[0]?.[0]; + expect(unboundManualTurn?.resume).toBeUndefined(); + expect(unboundManualTurn?.message.text).toContain("Continue where you left off."); + expect(unboundManualTurn?.message.text).toContain("run-native-account-command"); + expect(unboundManualTurn?.inlineContextLength).toBeUndefined(); + + // A bound MCP credential supplies runId itself, so native resume keeps sending no prompt text. + const boundManual = makeLocalCommandHarness({ + text: "", + manualContinuation: true, + outputSchema: { type: "object" }, + mcpSession: "bound", + sideChat: { contextRun: "delivered" }, + }); + yield* boundManual.start; + const boundManualTurn = boundManual.startTurn.mock.calls[0]?.[0]; + expect(boundManualTurn?.resume).toBe(true); + expect(boundManualTurn?.message.text).toBe(""); + + // An unbound typed restart continuation strips restartContinuationOfRunId; a bound one keeps it. + const unboundRestart = makeLocalCommandHarness({ + text: "Continue where you left off.", + restartContinuation: true, + outputSchema: { type: "object" }, + mcpSession: "unbound", + sideChat: { contextRun: "delivered" }, + }); + yield* unboundRestart.start; + expect(unboundRestart.startTurn.mock.calls[0]?.[0].restartContinuationOfRunId).toBeUndefined(); + + const boundRestart = makeLocalCommandHarness({ + text: "Continue where you left off.", + restartContinuation: true, + outputSchema: { type: "object" }, + mcpSession: "bound", + sideChat: { contextRun: "delivered" }, + }); + yield* boundRestart.start; + expect(boundRestart.startTurn.mock.calls[0]?.[0].restartContinuationOfRunId).toBe( + "stopped-run", + ); }), ); diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts index c862a95137193..7bb4838438b03 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts @@ -63,6 +63,7 @@ import { import { deliverContextHandoffs, withInlineContext } from "./ContextHandoffDelivery.ts"; import { isProviderCommand, latestOwedOutputRun, outputInstructions } from "./runOutput.ts"; import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter"; +import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions"; import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator"; import * as ProjectionStore from "./ProjectionStore.ts"; import { unsentManualContinuationSource } from "@t3tools/shared/orchestrationV2ManualContinuation"; @@ -149,6 +150,7 @@ const PROMPT_REFUSAL_TAGS = [ "ClaudeAppendSystemPromptMissingValueError", "ClaudeSettingsLaunchArgError", "ClaudeMcpRegistrationTimeoutError", + "ProviderAdapterMcpRotationBlockedError", ] as const; const refusedBeforePrompt = (error: unknown): boolean => @@ -284,6 +286,7 @@ export const layer: Layer.Layer< const projects = yield* ProjectService.ProjectService; const providerAuth = yield* ProviderAuthService.ProviderAuthService; const projectionStore = yield* ProjectionStore.ProjectionStoreV2; + const mcpSessions = yield* Effect.serviceOption(McpProviderSessions.McpProviderSessions); const providerSessions = yield* ProviderSessionManager.ProviderSessionManagerV2; const runExecution = yield* RunExecutionService.RunExecutionServiceV2; const runtimePolicy = yield* RuntimePolicy.RuntimePolicyV2; @@ -1009,10 +1012,11 @@ export const layer: Layer.Layer< session.providerSession.capabilities.turns.supportsNativeGoals === true; const goalCommand = goalDriver && parseGoalCommand(providerMessage) !== null; // Part of the user text, so every way a turn starts carries it, after the user's own words. - const userText = + const outputNote = run.outputSchema === undefined || goalCommand || isProviderCommand(providerMessage) - ? messageText - : `${messageText}\n\n${outputInstructions(run.outputSchema, run.id)}`; + ? "" + : outputInstructions(run.outputSchema, run.id); + const userText = [messageText, outputNote].filter((part) => part !== "").join("\n\n"); // The provider turn marks cancellation work delivered; restart continuations use their own text or resume natively. const noteContinuation = isRestartNoteContinuation( run, @@ -1861,6 +1865,17 @@ export const layer: Layer.Layer< }); return; } + const needsOutputRunIdCheck = + outputNote !== "" && + ((manualResume && unsentResumeMessage === undefined) || + (run.restartContinuationOfRunId !== undefined && !noteContinuation)); + const mcpSession = + needsOutputRunIdCheck && Option.isSome(mcpSessions) + ? yield* mcpSessions.value.read(projection.thread.id) + : undefined; + // An unbound MCP credential cannot supply run.id, so a typed continuation must prompt with it. + const needsPromptedOutputRunId = + needsOutputRunIdCheck && mcpSession !== undefined && mcpSession.runId !== run.id; const retryHandoff = resumedRetryHandoff ?? (yield* prepareRetryHandoff(handoffContext)); const runningProviderThread: OrchestrationV2ProviderThread = { ...loadedProviderThread, @@ -2061,7 +2076,8 @@ export const layer: Layer.Layer< .filter((part) => part !== "") .join("\n\n"); const { restartContinuationOfRunId: _resumedRunId, ...promptedInput } = turnInput; - const startInput = noteContinuation ? promptedInput : turnInput; + const startInput = + noteContinuation || needsPromptedOutputRunId ? promptedInput : turnInput; const { resume: _resume, ...contextInput } = startInput; const { message: resumeMessage, resume: _resumeIntent, ...resumeInput } = startInput; const missedAttachments = @@ -2072,10 +2088,15 @@ export const layer: Layer.Layer< !turnInput.message.attachments.some((current) => current.id === missed.id), ); // Like pending history, pending images need a prompt; native resume carries none. - const prompted = context !== "" || missedAttachments.length > 0; + const prompted = + context !== "" || missedAttachments.length > 0 || needsPromptedOutputRunId; // A resume that must be prompted still needs a request, or the agent has nothing to do. const requestText = - turnInput.resume && prompted && userText === "" ? RESUME_PROMPT : userText; + turnInput.resume && prompted && messageText === "" + ? outputNote === "" + ? RESUME_PROMPT + : `${RESUME_PROMPT}\n\n${outputNote}` + : userText; const text = goalCommand ? userText : withInlineContext(context, requestText); const operation = turnInput.resume && !prompted && session.resumeTurn !== undefined @@ -2089,9 +2110,9 @@ export const layer: Layer.Layer< ? {} : { attachments: [...missedAttachments, ...turnInput.message.attachments] }), }, - ...(text === userText + ...(text === requestText ? {} - : { inlineContextLength: text.length - userText.length }), + : { inlineContextLength: text.length - requestText.length }), }); yield* operation.pipe( // Clear pending handoff markers for refused prompts so the next turn retains the native session. @@ -2152,7 +2173,8 @@ export const layer: Layer.Layer< retryHandoff.attachments.length === 0 && sideChatHandoff === undefined && restartNote === "" && - !noteContinuation + !noteContinuation && + !needsPromptedOutputRunId ? session : makeDeliverySession(session, startWithHandoffs); return runExecution.startRootRun({ diff --git a/apps/server/src/orchestration-v2/ThreadManagementService.ts b/apps/server/src/orchestration-v2/ThreadManagementService.ts index 1e99885230ed5..c7b590f054f85 100644 --- a/apps/server/src/orchestration-v2/ThreadManagementService.ts +++ b/apps/server/src/orchestration-v2/ThreadManagementService.ts @@ -1061,23 +1061,9 @@ const make = Effect.gen(function* () { }); } const callerRunId = input.callerRunId; - // A continuation finishes the run it continues and gets no new instructions, so its agent can - // only name that earlier run. - const continues = (candidate: OrchestrationV2Run): boolean => { - const previousId = - candidate.restartContinuationOfRunId ?? - candidate.usageLimitContinuationOfRunId ?? - candidate.manualContinuationOfRunId; - if (previousId === undefined) return false; - if (previousId === callerRunId) return true; - const previous = records.runs.find((other) => other.id === previousId); - return previous !== undefined && continues(previous); - }; const matchesRun = (candidate: OrchestrationV2Run) => - (candidate.id === callerRunId && - (input.callerAttemptId === undefined || - candidate.activeAttemptId === input.callerAttemptId)) || - (input.callerAttemptId === undefined && continues(candidate)); + candidate.id === callerRunId && + (input.callerAttemptId === undefined || candidate.activeAttemptId === input.callerAttemptId); // Accept the active run, or the un-stopped completed run whose own owed output is targeted. if (!matchesRun(active) && !(run.id !== active.id && matchesRun(run))) { return yield* new ThreadManagementRunOutputRejectedError({ @@ -1098,8 +1084,7 @@ const make = Effect.gen(function* () { commandId: input.commandId, threadId: input.threadId, runId: run.id, - // A caller accepted through a continuation answers for the run that continues it. - callerRunId: callerRunId === active.id || callerRunId === run.id ? callerRunId : active.id, + callerRunId, ...(input.callerAttemptId === undefined ? {} : { callerAttemptId: input.callerAttemptId }), value: checked.success, }).pipe( diff --git a/apps/server/src/orchestration-v2/runtimeLayer.test.ts b/apps/server/src/orchestration-v2/runtimeLayer.test.ts index 45be2168097bd..76a583d3d0511 100644 --- a/apps/server/src/orchestration-v2/runtimeLayer.test.ts +++ b/apps/server/src/orchestration-v2/runtimeLayer.test.ts @@ -12239,40 +12239,82 @@ it.layer(layerSharedApplicationDataPlaneTest)("run output after a stop", (it) => from: "run-b", }); - // A continuation gets no new instructions, so its agent names the run it continues. + // A continuation of stopped run A rejects A's delayed unbound submission and accepts C's own runId. yield* eventSink.write({ events: [ { - id: EventId.make(`${threadId}-run-b-continues-a`), + id: EventId.make(`${threadId}-run-b-completed`), type: "run.updated", threadId, runId: runB.id, occurredAt: runB.requestedAt, payload: { ...afterB.runs.find((run) => run.id === runB.id)!, + status: "completed", + completedAt: runB.requestedAt, + }, + }, + ], + }); + yield* send("run-c", { type: "object" }); + const runC = (yield* orchestrator.getThreadProjection(threadId)).runs.find( + (run) => run.id !== runA.id && run.id !== runB.id, + )!; + yield* eventSink.write({ + events: [ + { + id: EventId.make(`${threadId}-run-c-continues-a`), + type: "run.updated", + threadId, + runId: runC.id, + occurredAt: runC.requestedAt, + payload: { + ...runC, manualContinuationOfRunId: runA.id, }, }, ], }); + const lateFromStoppedAncestor = yield* threadManagement + .submitRunOutput({ + threadId, + commandId: CommandId.make("runtime-layer-run-output-from-stopped-ancestor"), + json: '{"from":"late-ancestor"}', + callerRunId: runA.id, + }) + .pipe(Effect.flip); + assert.equal(lateFromStoppedAncestor._tag, "ThreadManagementRunOutputRejectedError"); + assert.include(lateFromStoppedAncestor.message, "no longer active"); + assert.isUndefined( + (yield* orchestrator.getThreadProjection(threadId)).runs.find((run) => run.id === runC.id) + ?.output, + ); const acceptedViaContinuation = yield* threadManagement.submitRunOutput({ threadId, commandId: CommandId.make("runtime-layer-run-output-via-continuation"), json: '{"from":"continued"}', - callerRunId: runA.id, + callerRunId: runC.id, + }); + assert.equal(acceptedViaContinuation.runId, runC.id); + const afterC = yield* orchestrator.getThreadProjection(threadId); + assert.deepEqual(afterC.runs.find((run) => run.id === runC.id)?.output?.value, { + from: "continued", }); - assert.equal(acceptedViaContinuation.runId, runB.id); // A plain turn with no schema preserves the plain-turn guidance even for stale/unbound MCP callers. yield* eventSink.write({ events: [ { - id: EventId.make(`${threadId}-run-b-completed`), + id: EventId.make(`${threadId}-run-c-completed`), type: "run.updated", threadId, - runId: runB.id, - occurredAt: runB.requestedAt, - payload: { ...runB, status: "completed", completedAt: runB.requestedAt }, + runId: runC.id, + occurredAt: runC.requestedAt, + payload: { + ...afterC.runs.find((run) => run.id === runC.id)!, + status: "completed", + completedAt: runC.requestedAt, + }, }, ], }); diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts index 8b0b53650544b..33d1cf568e50b 100644 --- a/packages/provider-acp/src/server/adapter.ts +++ b/packages/provider-acp/src/server/adapter.ts @@ -2285,6 +2285,8 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( } | null>(null); const activeSessionSetup = yield* Ref.make(null); + const installedInitializeResult = + yield* Ref.make(null); const setActiveSessionSetup = Effect.fnUntraced(function* ( setup: AcpSessionRuntime.AcpSessionRuntimeStartResult, ) { @@ -2304,6 +2306,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( agentRequests.clear(); nativeChildren.clear(); yield* Ref.set(activeSessionSetup, setup); + yield* Ref.set(installedInitializeResult, setup.initializeResult); }); const activeSelection = yield* Ref.make(null); const activeInteractionMode = yield* Ref.make(null); @@ -7771,8 +7774,12 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( }); const restartAcpRuntime = Effect.fnUntraced(function* (threadId: ThreadId | null) { - yield* spawnAcpRuntime(threadId); - yield* wireAcpRuntimeHandlers(runtime, yield* Ref.get(runtimeCallbackGeneration)); + const startup = Effect.gen(function* () { + yield* spawnAcpRuntime(threadId); + yield* wireAcpRuntimeHandlers(runtime, yield* Ref.get(runtimeCallbackGeneration)); + return yield* runtime.initialize(); + }); + return yield* flavor.withRuntimeStartup?.(startup) ?? startup; }); const startReplacementAcpRuntime = Effect.fnUntraced(function* ( @@ -8026,13 +8033,12 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( flavor.forkFromTurn?.supported(started.initializeResult) === true, steersWithPrompt, ); - const canLoadSession = started.initializeResult.agentCapabilities?.loadSession === true; - const canResumeSession = - started.initializeResult.agentCapabilities?.sessionCapabilities?.resume != null; - // A replacement agent can negotiate another MCP transport, so read the installed one. - const installedAgentCapabilities = () => - (Ref.getUnsafe(activeSessionSetup)?.initializeResult ?? started.initializeResult) - .agentCapabilities; + // A replacement or restarted agent can negotiate different capabilities, so read the installed one. + const installedInitialize = () => + Ref.getUnsafe(activeSessionSetup)?.initializeResult ?? + Ref.getUnsafe(installedInitializeResult) ?? + started.initializeResult; + const installedAgentCapabilities = () => installedInitialize().agentCapabilities; const usesMcpOverAcp = () => installedAgentCapabilities()?.mcpCapabilities?.acp === true && runtimeMcpBridge !== undefined; @@ -9076,7 +9082,8 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( ) { const restartRequired = yield* Ref.get(runtimeRestartRequired); if (!restartRequired) return false; - yield* restartAcpRuntime(threadId); + const initializeResult = yield* restartAcpRuntime(threadId); + yield* Ref.set(installedInitializeResult, initializeResult); yield* Ref.set(runtimeRestartRequired, false); yield* Ref.set(activeSessionId, null); yield* Ref.set(activeMcpAuthorization, undefined); @@ -9911,7 +9918,10 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( get providerSession() { return providerSession; }, - canResumeAfterRestart: canLoadSession || canResumeSession, + get canResumeAfterRestart() { + const agent = installedAgentCapabilities(); + return agent?.loadSession === true || agent?.sessionCapabilities?.resume != null; + }, get mcpCredentialRotation() { const agent = installedAgentCapabilities(); if (usesMcpOverAcp()) return "live" as const; @@ -10626,7 +10636,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( ); const sessionId = yield* nativeThreadId(driver, snapshotInput.providerThread); if ((yield* Ref.get(activeSessionId)) !== sessionId) { - if (!capabilities.threads.canReadThreadSnapshot) { + if (installedAgentCapabilities()?.loadSession !== true) { return yield* new ProviderAdapter.ProviderAdapterProtocolError({ driver, detail: "ACP driver does not support session/load snapshots", @@ -10752,7 +10762,8 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( yield* restartRuntimeAfterTeardownIfRequired( forkInput.sourceProviderThread.appThreadId, ); - if (!capabilities.threads.canForkThread) { + const initResult = installedInitialize(); + if (initResult.agentCapabilities?.sessionCapabilities?.fork == null) { return yield* new ProviderAdapter.ProviderAdapterProtocolError({ driver, detail: "ACP driver did not negotiate session/fork", @@ -10761,7 +10772,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( const forkMeta = forkFromTurnMetaFor({ driver, flavor, - canForkFromTurn: capabilities.threads.canForkFromTurn, + canForkFromTurn: flavor.forkFromTurn?.supported(initResult) === true, forkInput, }); if (forkMeta === null) { From 7ec208833c6a881f5552ac448ef5e62f80cc89fd Mon Sep 17 00:00:00 2001 From: Victor Vogel Date: Sun, 22 Nov 2026 18:22:41 +0000 Subject: [PATCH 13/34] refactor(server): tighten MCP credential rotation paths and tests Remove redundant credential eviction and reconnect guards, compute the Claude MCP-auth-stripped policy key lazily on rotation, avoid extra allocations when scanning runs and tracking thread credentials, and deduplicate repeated MCP session setup and assertions across the new tests. --- apps/server/src/mcp/McpSessionRegistry.ts | 7 +- .../Adapters/ClaudeAdapterV2.test.ts | 96 ++-- .../Adapters/ClaudeAdapterV2.ts | 18 +- .../Adapters/CodexAdapterV2.test.ts | 65 +-- .../src/orchestration-v2/Orchestrator.ts | 12 +- .../ProviderSessionManager.test.ts | 501 ++++++------------ .../ProviderSessionManager.ts | 96 ++-- apps/server/src/orchestration-v2/runOutput.ts | 20 +- .../src/orchestration-v2/runtimeLayer.test.ts | 286 ++++------ apps/server/src/preview/ServerBrowser.test.ts | 58 +- packages/provider-acp/src/server/adapter.ts | 12 +- .../src/server/mcpOverAcpBridge.test.ts | 347 +++++------- .../src/server/mcpOverAcpBridge.ts | 13 +- packages/provider-muse/src/server/adapter.ts | 7 +- .../src/server/mcpBridge.testkit.ts | 7 +- .../src/server/mcpExtensionSource.test.ts | 51 +- .../src/server/mcpExtensionSource.ts | 30 +- 17 files changed, 591 insertions(+), 1035 deletions(-) diff --git a/apps/server/src/mcp/McpSessionRegistry.ts b/apps/server/src/mcp/McpSessionRegistry.ts index 880d166c2d9b5..f2569bbe5ff99 100644 --- a/apps/server/src/mcp/McpSessionRegistry.ts +++ b/apps/server/src/mcp/McpSessionRegistry.ts @@ -178,17 +178,14 @@ const makeWithOptions = Effect.fn("McpSessionRegistry.make")(function* ( lastAlive: issuedAlive, expired: false, }); - let retainedForThread = 0; const threadTokens: Array = []; for (const [hash, record] of next) { if (record.scope.thread.threadId === scope.thread.threadId) { - retainedForThread += 1; threadTokens.push(hash); } } - for (let index = 0; index < retainedForThread - MAX_CREDENTIALS_PER_THREAD; index += 1) { - const evicted = threadTokens[index]; - if (evicted !== undefined) next.delete(evicted); + for (let index = 0; index < threadTokens.length - MAX_CREDENTIALS_PER_THREAD; index += 1) { + next.delete(threadTokens[index]!); } return { records: next }; }); diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts index eb041fa8b2915..43c6e9a6606b9 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts @@ -25425,29 +25425,39 @@ describe("ClaudeAdapterV2 background wake turns", () => { }); const isContinuationMode = mode === "continuation-refresh-failed" || mode === "continuation-no-live-refresh"; - const envSlug = `environment-claude-mcp-${mode}`; - yield* mcpSessions.set({ - environmentId: EnvironmentId.make(envSlug), - threadId: harness.threadId, - providerSessionId: `mcp-session-claude-${mode}-1`, - providerInstanceId: ProviderInstanceId.make("claudeAgent"), - runId: RunId.make(`claude-mcp-${mode}-run-1`), - attemptId: RunAttemptId.make(`claude-mcp-${mode}-attempt-1`), - endpoint: "http://127.0.0.1:43123/mcp", - authorizationHeader: `Bearer claude-${mode}-run-1`, - browserToolsAvailable: false, - }); - - yield* harness.runtime.startTurn( - makeClaudeTestTurnInput({ + const setMcp = (ordinal: number) => + mcpSessions.set({ + environmentId: EnvironmentId.make(`environment-claude-mcp-${mode}`), threadId: harness.threadId, - providerThread: harness.providerThread, - now: yield* DateTime.now, - attemptId: RunAttemptId.make(`claude-mcp-${mode}-attempt-1`), - text: "First turn.", - attachments: [], - }), - ); + providerSessionId: `mcp-session-claude-${mode}-${ordinal}`, + providerInstanceId: ProviderInstanceId.make("claudeAgent"), + runId: RunId.make(`claude-mcp-${mode}-run-${ordinal}`), + attemptId: RunAttemptId.make(`claude-mcp-${mode}-attempt-${ordinal}`), + endpoint: "http://127.0.0.1:43123/mcp", + authorizationHeader: `Bearer claude-${mode}-run-${ordinal}`, + browserToolsAvailable: false, + }); + const turnInput = ( + ordinal: number, + text: string, + extra?: Partial[0]>, + ) => + DateTime.now.pipe( + Effect.map((now) => + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now, + attemptId: RunAttemptId.make(`claude-mcp-${mode}-attempt-${ordinal}`), + text, + attachments: [], + ...extra, + }), + ), + ); + + yield* setMcp(1); + yield* harness.runtime.startTurn(yield* turnInput(1, "First turn.")); if (mode === "blocked-by-background-work" || isContinuationMode) { yield* harness.offerAndWait(wakeTaskStarted); } @@ -25474,26 +25484,10 @@ describe("ClaudeAdapterV2 background wake turns", () => { yield* Queue.take(harness.continuationReceipts); } - yield* mcpSessions.set({ - environmentId: EnvironmentId.make(envSlug), - threadId: harness.threadId, - providerSessionId: `mcp-session-claude-${mode}-2`, - providerInstanceId: ProviderInstanceId.make("claudeAgent"), - runId: RunId.make(`claude-mcp-${mode}-run-2`), - attemptId: RunAttemptId.make(`claude-mcp-${mode}-attempt-2`), - endpoint: "http://127.0.0.1:43123/mcp", - authorizationHeader: `Bearer claude-${mode}-run-2`, - browserToolsAvailable: false, - }); + yield* setMcp(2); if (isContinuationMode) { - const continuationTurn = makeClaudeTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now: yield* DateTime.now, - attemptId: RunAttemptId.make(`claude-mcp-${mode}-attempt-2`), - text: "Background task completed.", - attachments: [], + const continuationTurn = yield* turnInput(2, "Background task completed.", { providerTurnOrdinal: 2, messageCreatedBy: "agent", messageCreationSource: "provider", @@ -25526,16 +25520,7 @@ describe("ClaudeAdapterV2 background wake turns", () => { if (mode === "blocked-by-background-work") { const rejected = yield* harness.runtime - .startTurn( - makeClaudeTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now: yield* DateTime.now, - attemptId: RunAttemptId.make(`claude-mcp-${mode}-attempt-2`), - text: "Second turn.", - attachments: [], - }), - ) + .startTurn(yield* turnInput(2, "Second turn.")) .pipe(Effect.flip); assert.instanceOf( rejected.cause, @@ -25546,16 +25531,7 @@ describe("ClaudeAdapterV2 background wake turns", () => { return; } - yield* harness.runtime.startTurn( - makeClaudeTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now: yield* DateTime.now, - attemptId: RunAttemptId.make(`claude-mcp-${mode}-attempt-2`), - text: "Second turn.", - attachments: [], - }), - ); + yield* harness.runtime.startTurn(yield* turnInput(2, "Second turn.")); if (mode === "fallback-replace") { assert.equal(harness.processQueues.length, 2); yield* Queue.offer( diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts index 04fef07dae755..f34ae5e47d4cb 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts @@ -13242,16 +13242,18 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( mcpOverrides, turnInput.runtimePolicy.workspace, ); - const queryPolicyKeyWithoutMcpAuth = claudeEffectiveQueryPolicyKeyWithoutMcpAuth( - queryPolicy, - mcpOverrides, - turnInput.runtimePolicy.workspace, - ); + let cachedQueryPolicyKeyWithoutMcpAuth: string | undefined; + const getQueryPolicyKeyWithoutMcpAuth = () => + (cachedQueryPolicyKeyWithoutMcpAuth ??= claudeEffectiveQueryPolicyKeyWithoutMcpAuth( + queryPolicy, + mcpOverrides, + turnInput.runtimePolicy.workspace, + )); const resumeSessionAt = yield* getNativeConversationHeadId(turnInput.providerThread); const existing = yield* Ref.get(queryContext); const canUpdateMcpLive = (candidate: ClaudeLiveQueryContext) => candidate.queryPolicyKey !== queryPolicyKey && - candidate.queryPolicyKeyWithoutMcpAuth === queryPolicyKeyWithoutMcpAuth && + candidate.queryPolicyKeyWithoutMcpAuth === getQueryPolicyKeyWithoutMcpAuth() && mcpOverrides.mcpServers !== undefined && candidate.query.setMcpServers !== undefined; const syncMcpServersLive = Effect.fnUntraced(function* ( @@ -13264,7 +13266,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( return; yield* candidate.query.setMcpServers(mcpOverrides.mcpServers); candidate.mcpAuthorization = mcpSession?.authorizationHeader; - if (candidate.queryPolicyKeyWithoutMcpAuth === queryPolicyKeyWithoutMcpAuth) { + if (candidate.queryPolicyKeyWithoutMcpAuth === getQueryPolicyKeyWithoutMcpAuth()) { candidate.queryPolicyKey = queryPolicyKey; } }); @@ -13536,7 +13538,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( launchArgSettings, query: querySession, queryPolicyKey, - queryPolicyKeyWithoutMcpAuth, + queryPolicyKeyWithoutMcpAuth: getQueryPolicyKeyWithoutMcpAuth(), mcpAuthorization: mcpSession?.authorizationHeader, selection: compiledSelection, closed, diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts index c5c4b33415b88..2df8cf9f2541c 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts @@ -2730,15 +2730,30 @@ describe("CodexAdapterV2 post-settle continuation", () => { const nativeThreadId = "rotate-mcp-thread"; const threadId = ThreadId.make(`thread-${scenario}`); const mcpSessions = yield* McpProviderSessions.McpProviderSessions; - yield* mcpSessions.set({ - environmentId: EnvironmentId.make("environment-codex-mcp-rotate"), - threadId, - providerSessionId: "provider-session-rotate-1", - providerInstanceId: ProviderInstanceId.make("codex"), - endpoint: "http://127.0.0.1:43123/mcp", - authorizationHeader: "Bearer codex-run-1-token", - browserToolsAvailable: false, - }); + const setMcp = (ordinal: number) => + mcpSessions.set({ + environmentId: EnvironmentId.make("environment-codex-mcp-rotate"), + threadId, + providerSessionId: `provider-session-rotate-${ordinal}`, + providerInstanceId: ProviderInstanceId.make("codex"), + endpoint: "http://127.0.0.1:43123/mcp", + authorizationHeader: `Bearer codex-run-${ordinal}-token`, + browserToolsAvailable: false, + }); + const configRead = (id: number, label: string) => + [ + { + type: "expect_outbound", + label, + frame: { id, method: "config/read", params: { includeLayers: false } }, + }, + { + type: "emit_inbound", + label, + frame: { id, result: { config: {}, origins: {} } }, + }, + ] as const; + yield* setMcp(1); const resumedConfigs: Array = []; const preamble = codexReplayPreamble({ nativeThreadId, @@ -2758,16 +2773,7 @@ describe("CodexAdapterV2 post-settle continuation", () => { scenario, entries: [ ...preamble.slice(0, 3), - { - type: "expect_outbound", - label: "config/read initial", - frame: { id: 2, method: "config/read", params: { includeLayers: false } }, - }, - { - type: "emit_inbound", - label: "config/read initial", - frame: { id: 2, result: { config: {}, origins: {} } }, - }, + ...configRead(2, "config/read initial"), ...preamble.slice(3, 5).map((entry) => withReplayRequestId(entry, 3)), { type: "expect_outbound", @@ -2783,16 +2789,7 @@ describe("CodexAdapterV2 post-settle continuation", () => { label: "thread/unsubscribe result", frame: { id: 4, result: { status: "unsubscribed" } }, }, - { - type: "expect_outbound", - label: "config/read reload", - frame: { id: 5, method: "config/read", params: { includeLayers: false } }, - }, - { - type: "emit_inbound", - label: "config/read reload", - frame: { id: 5, result: { config: {}, origins: {} } }, - }, + ...configRead(5, "config/read reload"), { type: "expect_outbound", label: "thread/resume with rotated token", @@ -2863,15 +2860,7 @@ describe("CodexAdapterV2 post-settle continuation", () => { }), ); - yield* mcpSessions.set({ - environmentId: EnvironmentId.make("environment-codex-mcp-rotate"), - threadId, - providerSessionId: "provider-session-rotate-2", - providerInstanceId: ProviderInstanceId.make("codex"), - endpoint: "http://127.0.0.1:43123/mcp", - authorizationHeader: "Bearer codex-run-2-token", - browserToolsAvailable: false, - }); + yield* setMcp(2); yield* harness.runtime.unloadThread!({ providerThread: harness.providerThread }); const resumedThread = yield* harness.runtime.resumeThread({ threadId, diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 5c2ddc0a88d70..993faef203b6d 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -12236,9 +12236,15 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio }); } if (command.callerRunId !== undefined || command.callerAttemptId !== undefined) { - const active = projection.runs - .filter(isActiveRun) - .toSorted((left, right) => right.ordinal - left.ordinal)[0]; + let active: OrchestrationV2Run | undefined; + for (const candidate of projection.runs) { + if ( + isActiveRun(candidate) && + (active === undefined || candidate.ordinal > active.ordinal) + ) { + active = candidate; + } + } const matchesRun = (candidate: OrchestrationV2Run | undefined) => candidate !== undefined && (command.callerRunId === undefined || candidate.id === command.callerRunId) && diff --git a/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts b/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts index dbb4079e1bc19..dd97f5c930bbb 100644 --- a/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts +++ b/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts @@ -3314,6 +3314,27 @@ it.effect.each([ ])("$description", ({ scenario }) => Effect.gen(function* () { const state = yield* Ref.make(emptyState); + const rawBearer = (config: { readonly authorizationHeader: string } | undefined) => { + assert.isDefined(config); + return config!.authorizationHeader.replace(/^Bearer\s+/, ""); + }; + const openFor = ( + manager: ProviderSessionManager.ProviderSessionManagerV2Shape, + providerSessionId: ProviderSessionId, + threadId: ThreadId, + turn?: { + readonly runId?: RunId; + readonly attemptId?: RunAttemptId; + readonly requireRunScopedMcp?: boolean; + }, + ) => + manager.open({ + threadId, + providerSessionId, + modelSelection, + runtimePolicy, + ...turn, + }); if (scenario === "live") { const effect = Effect.gen(function* () { const eventSink = yield* EventSink.EventSinkV2; @@ -3333,27 +3354,18 @@ it.effect.each([ const run1 = RunId.make("run-live-1"); const attempt1 = RunAttemptId.make("attempt-live-1"); - yield* manager.open({ - threadId, - providerSessionId, - modelSelection, - runtimePolicy, + yield* openFor(manager, providerSessionId, threadId, { runId: run1, attemptId: attempt1, requireRunScopedMcp: true, }); const config1 = yield* mcpSessions.read(threadId); - assert.isDefined(config1); - const token1 = config1!.authorizationHeader.replace(/^Bearer\s+/, ""); + const token1 = rawBearer(config1); assert.equal((yield* registry.resolve(token1))?.thread.runId, run1); assert.equal((yield* registry.resolve(token1))?.thread.attemptId, attempt1); // Plain turns skip rotation to avoid unnecessary reconnect churn. - yield* manager.open({ - threadId, - providerSessionId, - modelSelection, - runtimePolicy, + yield* openFor(manager, providerSessionId, threadId, { runId: RunId.make("run-live-plain"), attemptId: RunAttemptId.make("attempt-live-plain"), requireRunScopedMcp: false, @@ -3365,18 +3377,13 @@ it.effect.each([ const run2 = RunId.make("run-live-2"); const attempt2 = RunAttemptId.make("attempt-live-2"); - yield* manager.open({ - threadId, - providerSessionId, - modelSelection, - runtimePolicy, + yield* openFor(manager, providerSessionId, threadId, { runId: run2, attemptId: attempt2, requireRunScopedMcp: true, }); const config2 = yield* mcpSessions.read(threadId); - assert.isDefined(config2); - const token2 = config2!.authorizationHeader.replace(/^Bearer\s+/, ""); + const token2 = rawBearer(config2); assert.notEqual(token2, token1); assert.equal(config2!.providerSessionId, config1!.providerSessionId); assert.notEqual(config2!.credentialId, config1!.credentialId); @@ -3464,54 +3471,45 @@ it.effect.each([ ], }); - yield* manager.open({ - threadId, - providerSessionId, - modelSelection, - runtimePolicy, + yield* openFor(manager, providerSessionId, threadId, { runId: run1, attemptId: RunAttemptId.make("attempt-none-1"), requireRunScopedMcp: true, }); const config1 = yield* mcpSessions.read(threadId); - assert.isDefined(config1); - const token1 = config1!.authorizationHeader.replace(/^Bearer\s+/, ""); + const token1 = rawBearer(config1); assert.equal((yield* registry.resolve(token1))?.thread.runId, run1); + const expectPreviewSync = ( + enabled: boolean, + runId: RunId, + attempt: string, + requireRunScopedMcp: boolean, + expectedRunId: RunId | undefined, + ) => + Effect.gen(function* () { + yield* settings.updateSettings({ enableAgentBrowserAccess: enabled }); + yield* openFor(manager, providerSessionId, threadId, { + runId, + attemptId: RunAttemptId.make(attempt), + requireRunScopedMcp, + }); + const resolved = yield* registry.resolve(token1); + assert.isDefined(resolved); + assert.equal(resolved!.thread.runId, expectedRunId); + assert.equal(resolved!.capabilities.has("preview"), enabled); + const config = yield* mcpSessions.read(threadId); + assert.equal(config?.authorizationHeader, config1!.authorizationHeader); + assert.equal(config?.browserToolsAvailable, enabled); + assert.equal(config?.capabilities?.has("preview") ?? false, enabled); + }); + // Re-opening the same run/attempt after toggling browser access syncs preview while keeping run1 bound. - yield* settings.updateSettings({ enableAgentBrowserAccess: false }); - yield* manager.open({ - threadId, - providerSessionId, - modelSelection, - runtimePolicy, - runId: run1, - attemptId: RunAttemptId.make("attempt-none-1"), - requireRunScopedMcp: true, - }); - assert.isFalse((yield* registry.resolve(token1))?.capabilities.has("preview") ?? true); - assert.equal((yield* registry.resolve(token1))?.thread.runId, run1); - assert.isFalse((yield* mcpSessions.read(threadId))?.browserToolsAvailable); - yield* settings.updateSettings({ enableAgentBrowserAccess: true }); - yield* manager.open({ - threadId, - providerSessionId, - modelSelection, - runtimePolicy, - runId: run1, - attemptId: RunAttemptId.make("attempt-none-1"), - requireRunScopedMcp: true, - }); - assert.isTrue((yield* registry.resolve(token1))?.capabilities.has("preview") ?? false); - assert.equal((yield* registry.resolve(token1))?.thread.runId, run1); - assert.isTrue((yield* mcpSessions.read(threadId))?.browserToolsAvailable); + yield* expectPreviewSync(false, run1, "attempt-none-1", true, run1); + yield* expectPreviewSync(true, run1, "attempt-none-1", true, run1); // Plain turns and owed wakes for run1 succeed without rotating or mutating token1. - yield* manager.open({ - threadId, - providerSessionId, - modelSelection, - runtimePolicy, + yield* openFor(manager, providerSessionId, threadId, { runId: run2, attemptId: RunAttemptId.make("attempt-none-2"), requireRunScopedMcp: false, @@ -3543,82 +3541,23 @@ it.effect.each([ assert.isUndefined(config3?.runId); assert.isTrue(config3?.browserToolsAvailable); - // Disabling browser access drops preview from the retained credential without breaking typed runs. - yield* settings.updateSettings({ enableAgentBrowserAccess: false }); - yield* manager.open({ - threadId, - providerSessionId, - modelSelection, - runtimePolicy, - runId: run4, - attemptId: RunAttemptId.make("attempt-none-4"), - requireRunScopedMcp: true, - }); - const narrowed = yield* registry.resolve(token1); - assert.isDefined(narrowed); - assert.isUndefined(narrowed!.thread.runId); - assert.isFalse(narrowed!.capabilities.has("preview")); - const config4 = yield* mcpSessions.read(threadId); - assert.equal(config4?.authorizationHeader, config1!.authorizationHeader); - assert.isFalse(config4?.browserToolsAvailable); - assert.isFalse(config4?.capabilities?.has("preview") ?? false); - - // Re-enabling browser access restores preview on the retained credential. - yield* settings.updateSettings({ enableAgentBrowserAccess: true }); - yield* manager.open({ - threadId, - providerSessionId, - modelSelection, - runtimePolicy, - runId: RunId.make("run-none-5"), - attemptId: RunAttemptId.make("attempt-none-5"), - requireRunScopedMcp: true, - }); - const restored = yield* registry.resolve(token1); - assert.isDefined(restored); - assert.isUndefined(restored!.thread.runId); - assert.isTrue(restored!.capabilities.has("preview")); - const config5 = yield* mcpSessions.read(threadId); - assert.equal(config5?.authorizationHeader, config1!.authorizationHeader); - assert.isTrue(config5?.browserToolsAvailable); - assert.isTrue(config5?.capabilities?.has("preview") ?? false); - - // Disabling and re-enabling browser access also syncs on untyped next runs with no owed output. - yield* settings.updateSettings({ enableAgentBrowserAccess: false }); - yield* manager.open({ - threadId, - providerSessionId, - modelSelection, - runtimePolicy, - runId: RunId.make("run-none-6"), - attemptId: RunAttemptId.make("attempt-none-6"), - requireRunScopedMcp: false, - }); - const narrowedUntyped = yield* registry.resolve(token1); - assert.isDefined(narrowedUntyped); - assert.isFalse(narrowedUntyped!.capabilities.has("preview")); - const config6 = yield* mcpSessions.read(threadId); - assert.equal(config6?.authorizationHeader, config1!.authorizationHeader); - assert.isFalse(config6?.browserToolsAvailable); - assert.isFalse(config6?.capabilities?.has("preview") ?? false); - - yield* settings.updateSettings({ enableAgentBrowserAccess: true }); - yield* manager.open({ - threadId, - providerSessionId, - modelSelection, - runtimePolicy, - runId: RunId.make("run-none-7"), - attemptId: RunAttemptId.make("attempt-none-7"), - requireRunScopedMcp: false, - }); - const restoredUntyped = yield* registry.resolve(token1); - assert.isDefined(restoredUntyped); - assert.isTrue(restoredUntyped!.capabilities.has("preview")); - const config7 = yield* mcpSessions.read(threadId); - assert.equal(config7?.authorizationHeader, config1!.authorizationHeader); - assert.isTrue(config7?.browserToolsAvailable); - assert.isTrue(config7?.capabilities?.has("preview") ?? false); + // Disabling and re-enabling browser access syncs preview on both typed and untyped retained runs. + yield* expectPreviewSync(false, run4, "attempt-none-4", true, undefined); + yield* expectPreviewSync(true, RunId.make("run-none-5"), "attempt-none-5", true, undefined); + yield* expectPreviewSync( + false, + RunId.make("run-none-6"), + "attempt-none-6", + false, + undefined, + ); + yield* expectPreviewSync( + true, + RunId.make("run-none-7"), + "attempt-none-7", + false, + undefined, + ); yield* manager.close(providerSessionId); }); @@ -3700,36 +3639,53 @@ it.effect.each([ }, ], }); - const runtime = yield* manager.open({ - threadId, - providerSessionId, - modelSelection, - runtimePolicy, + const runtime = yield* openFor(manager, providerSessionId, threadId, { runId: run1, attemptId: attempt1, requireRunScopedMcp: true, }); + const attachLoadedThread = (name: string) => + Effect.gen(function* () { + const nextThreadId = ThreadId.make(`thread-provider-session-manager-${name}`); + const nextProviderThread = makeProviderThread({ + idAllocator, + threadId: nextThreadId, + providerSessionId, + now, + }); + yield* eventSink.write({ + events: [yield* makeThreadCreatedEvent({ idAllocator, threadId: nextThreadId, now })], + }); + yield* openFor(manager, providerSessionId, nextThreadId); + const loadedConfig = yield* mcpSessions.read(nextThreadId); + const loadedToken = rawBearer(loadedConfig); + yield* runtime.resumeThread({ + threadId: nextThreadId, + providerThread: nextProviderThread, + modelSelection, + runtimePolicy, + }); + return { + threadId: nextThreadId, + providerThread: nextProviderThread, + loadedConfig: loadedConfig!, + loadedToken, + }; + }); const loadedConfig = yield* mcpSessions.read(threadId); - assert.isDefined(loadedConfig); - const loadedToken = loadedConfig!.authorizationHeader.replace(/^Bearer\s+/, ""); + const loadedToken = rawBearer(loadedConfig); yield* runtime.resumeThread({ threadId, providerThread, modelSelection, runtimePolicy, }); - yield* manager.open({ - threadId, - providerSessionId, - modelSelection, - runtimePolicy, + yield* openFor(manager, providerSessionId, threadId, { runId: run2, attemptId: attempt2, requireRunScopedMcp: true, }); - const rotatedConfig = yield* mcpSessions.read(threadId); - assert.isDefined(rotatedConfig); - const rotatedToken = rotatedConfig!.authorizationHeader.replace(/^Bearer\s+/, ""); + const rotatedToken = rawBearer(yield* mcpSessions.read(threadId)); assert.notEqual(rotatedToken, loadedToken); yield* runtime.resumeThread({ @@ -3753,50 +3709,19 @@ it.effect.each([ // Also cover a thread initially attached to the shared session with an unbound (run-less) bearer: // rolling back on blocked reload must keep that run-less bearer valid for running background work. - const unboundThreadId = ThreadId.make("thread-provider-session-manager-bg-unbound"); - const unboundProviderThread = makeProviderThread({ - idAllocator, - threadId: unboundThreadId, - providerSessionId, - now, - }); - yield* eventSink.write({ - events: [yield* makeThreadCreatedEvent({ idAllocator, threadId: unboundThreadId, now })], - }); - yield* manager.open({ - threadId: unboundThreadId, - providerSessionId, - modelSelection, - runtimePolicy, - }); - const unboundLoadedConfig = yield* mcpSessions.read(unboundThreadId); - assert.isDefined(unboundLoadedConfig); - assert.isUndefined(unboundLoadedConfig!.runId); - const unboundLoadedToken = unboundLoadedConfig!.authorizationHeader.replace( - /^Bearer\s+/, - "", - ); - yield* runtime.resumeThread({ + const { threadId: unboundThreadId, providerThread: unboundProviderThread, - modelSelection, - runtimePolicy, - }); - yield* manager.open({ - threadId: unboundThreadId, - providerSessionId, - modelSelection, - runtimePolicy, + loadedConfig: unboundLoadedConfig, + loadedToken: unboundLoadedToken, + } = yield* attachLoadedThread("bg-unbound"); + assert.isUndefined(unboundLoadedConfig.runId); + yield* openFor(manager, providerSessionId, unboundThreadId, { runId: RunId.make("run-bg-unbound-typed"), attemptId: RunAttemptId.make("attempt-bg-unbound-typed"), requireRunScopedMcp: true, }); - const unboundRotatedConfig = yield* mcpSessions.read(unboundThreadId); - assert.isDefined(unboundRotatedConfig); - const unboundRotatedToken = unboundRotatedConfig!.authorizationHeader.replace( - /^Bearer\s+/, - "", - ); + const unboundRotatedToken = rawBearer(yield* mcpSessions.read(unboundThreadId)); assert.notEqual(unboundRotatedToken, unboundLoadedToken); yield* runtime.resumeThread({ @@ -3819,46 +3744,22 @@ it.effect.each([ // loaded bearer valid on rollback, whereas disabling browser access (capability removal) revokes it. const settings = yield* ServerSettings.ServerSettingsService; yield* settings.updateSettings({ enableAgentBrowserAccess: false }); - const widenedThreadId = ThreadId.make("thread-provider-session-manager-bg-widened"); - const widenedProviderThread = makeProviderThread({ - idAllocator, - threadId: widenedThreadId, - providerSessionId, - now, - }); - yield* eventSink.write({ - events: [yield* makeThreadCreatedEvent({ idAllocator, threadId: widenedThreadId, now })], - }); - yield* manager.open({ - threadId: widenedThreadId, - providerSessionId, - modelSelection, - runtimePolicy, - }); - const narrowLoadedConfig = yield* mcpSessions.read(widenedThreadId); - assert.isDefined(narrowLoadedConfig); - assert.isFalse(narrowLoadedConfig!.browserToolsAvailable); - const narrowLoadedToken = narrowLoadedConfig!.authorizationHeader.replace(/^Bearer\s+/, ""); - yield* runtime.resumeThread({ + const { threadId: widenedThreadId, providerThread: widenedProviderThread, - modelSelection, - runtimePolicy, - }); + loadedConfig: narrowLoadedConfig, + loadedToken: narrowLoadedToken, + } = yield* attachLoadedThread("bg-widened"); + assert.isFalse(narrowLoadedConfig.browserToolsAvailable); yield* settings.updateSettings({ enableAgentBrowserAccess: true }); - yield* manager.open({ - threadId: widenedThreadId, - providerSessionId, - modelSelection, - runtimePolicy, + yield* openFor(manager, providerSessionId, widenedThreadId, { runId: RunId.make("run-bg-widened-typed"), attemptId: RunAttemptId.make("attempt-bg-widened-typed"), requireRunScopedMcp: true, }); const widerRotatedConfig = yield* mcpSessions.read(widenedThreadId); - assert.isDefined(widerRotatedConfig); - assert.isTrue(widerRotatedConfig!.browserToolsAvailable); - const widerRotatedToken = widerRotatedConfig!.authorizationHeader.replace(/^Bearer\s+/, ""); + assert.isTrue(widerRotatedConfig?.browserToolsAvailable); + const widerRotatedToken = rawBearer(widerRotatedConfig); yield* runtime.resumeThread({ threadId: widenedThreadId, providerThread: widenedProviderThread, @@ -3875,48 +3776,20 @@ it.effect.each([ ); // Capability removal revokes the previously wider bearer immediately and does not restore a dead token. - const narrowedThreadId = ThreadId.make("thread-provider-session-manager-bg-narrowed"); - const narrowedProviderThread = makeProviderThread({ - idAllocator, - threadId: narrowedThreadId, - providerSessionId, - now, - }); - yield* eventSink.write({ - events: [yield* makeThreadCreatedEvent({ idAllocator, threadId: narrowedThreadId, now })], - }); - yield* manager.open({ - threadId: narrowedThreadId, - providerSessionId, - modelSelection, - runtimePolicy, - }); - const broadLoadedConfig = yield* mcpSessions.read(narrowedThreadId); - assert.isDefined(broadLoadedConfig); - assert.isTrue(broadLoadedConfig!.browserToolsAvailable); - const broadLoadedToken = broadLoadedConfig!.authorizationHeader.replace(/^Bearer\s+/, ""); - yield* runtime.resumeThread({ + const { threadId: narrowedThreadId, providerThread: narrowedProviderThread, - modelSelection, - runtimePolicy, - }); + loadedConfig: broadLoadedConfig, + loadedToken: broadLoadedToken, + } = yield* attachLoadedThread("bg-narrowed"); + assert.isTrue(broadLoadedConfig.browserToolsAvailable); yield* settings.updateSettings({ enableAgentBrowserAccess: false }); - yield* manager.open({ - threadId: narrowedThreadId, - providerSessionId, - modelSelection, - runtimePolicy, + yield* openFor(manager, providerSessionId, narrowedThreadId, { runId: RunId.make("run-bg-narrowed-typed"), attemptId: RunAttemptId.make("attempt-bg-narrowed-typed"), requireRunScopedMcp: true, }); - const narrowedRotatedConfig = yield* mcpSessions.read(narrowedThreadId); - assert.isDefined(narrowedRotatedConfig); - const narrowedRotatedToken = narrowedRotatedConfig!.authorizationHeader.replace( - /^Bearer\s+/, - "", - ); + const narrowedRotatedToken = rawBearer(yield* mcpSessions.read(narrowedThreadId)); const narrowedFailed = yield* runtime .resumeThread({ threadId: narrowedThreadId, @@ -3934,11 +3807,7 @@ it.effect.each([ // MCP credential with browser access still disabled and reloads the thread cleanly. yield* Ref.set(pendingBackgroundWork, false); const nextPlainRun = RunId.make("run-bg-narrowed-next-plain"); - yield* manager.open({ - threadId: narrowedThreadId, - providerSessionId, - modelSelection, - runtimePolicy, + yield* openFor(manager, providerSessionId, narrowedThreadId, { runId: nextPlainRun, attemptId: RunAttemptId.make("attempt-bg-narrowed-next-plain"), requireRunScopedMcp: false, @@ -3951,27 +3820,20 @@ it.effect.each([ }); assert.isTrue(Option.isSome(yield* Queue.poll(unloads))); const recoveredConfig = yield* mcpSessions.read(narrowedThreadId); - assert.isDefined(recoveredConfig); - assert.isFalse(recoveredConfig!.browserToolsAvailable); - const recoveredToken = recoveredConfig!.authorizationHeader.replace(/^Bearer\s+/, ""); - const resolvedRecovered = yield* registry.resolve(recoveredToken); + assert.isFalse(recoveredConfig?.browserToolsAvailable); + const resolvedRecovered = yield* registry.resolve(rawBearer(recoveredConfig)); assert.isDefined(resolvedRecovered); assert.isFalse(resolvedRecovered!.capabilities.has("preview")); assert.equal(resolvedRecovered!.thread.runId, nextPlainRun); - assert.equal(recoveredConfig!.providerSessionId, broadLoadedConfig!.providerSessionId); - assert.notEqual(recoveredConfig!.credentialId, broadLoadedConfig!.credentialId); + assert.equal(recoveredConfig!.providerSessionId, broadLoadedConfig.providerSessionId); + assert.notEqual(recoveredConfig!.credentialId, broadLoadedConfig.credentialId); // Also cover run-less open recovery after a cleared capability-removal rollback. yield* mcpSessions.clear(narrowedThreadId); - yield* manager.open({ - threadId: narrowedThreadId, - providerSessionId, - modelSelection, - runtimePolicy, - }); + yield* openFor(manager, providerSessionId, narrowedThreadId); const runlessRecovered = yield* mcpSessions.read(narrowedThreadId); assert.isDefined(runlessRecovered); - assert.equal(runlessRecovered!.providerSessionId, broadLoadedConfig!.providerSessionId); + assert.equal(runlessRecovered!.providerSessionId, broadLoadedConfig.providerSessionId); assert.isFalse(runlessRecovered!.browserToolsAvailable); // A failed unload may leave the thread loaded, where a resume ignores new config: keep the old credential. @@ -4028,11 +3890,7 @@ it.effect.each([ // Once background work finishes, reloading a thread whose loaded credential became unbound // during keepLoaded retires that old unbound credential. yield* Ref.set(failUnload, false); - yield* manager.open({ - threadId, - providerSessionId, - modelSelection, - runtimePolicy, + yield* openFor(manager, providerSessionId, threadId, { runId: RunId.make("run-bg-3-retire"), attemptId: RunAttemptId.make("attempt-bg-3-retire"), requireRunScopedMcp: true, @@ -4055,18 +3913,13 @@ it.effect.each([ ], }); const raceRun1 = RunId.make("run-probe-race-1"); - yield* manager.open({ - threadId: probeRaceThreadId, - providerSessionId, - modelSelection, - runtimePolicy, + yield* openFor(manager, providerSessionId, probeRaceThreadId, { runId: raceRun1, attemptId: RunAttemptId.make("attempt-probe-race-1"), requireRunScopedMcp: true, }); const originalRaceConfig = yield* mcpSessions.read(probeRaceThreadId); - assert.isDefined(originalRaceConfig); - const originalRaceToken = originalRaceConfig!.authorizationHeader.replace(/^Bearer\s+/, ""); + const originalRaceToken = rawBearer(originalRaceConfig); const probeStarted = yield* Deferred.make(); const releaseProbe = yield* Deferred.make(); yield* Ref.set( @@ -4075,17 +3928,11 @@ it.effect.each([ Effect.andThen(Deferred.await(releaseProbe)), ), ); - const racingOpen = yield* manager - .open({ - threadId: probeRaceThreadId, - providerSessionId, - modelSelection, - runtimePolicy, - runId: RunId.make("run-probe-race-2"), - attemptId: RunAttemptId.make("attempt-probe-race-2"), - requireRunScopedMcp: true, - }) - .pipe(Effect.forkChild); + const racingOpen = yield* openFor(manager, providerSessionId, probeRaceThreadId, { + runId: RunId.make("run-probe-race-2"), + attemptId: RunAttemptId.make("attempt-probe-race-2"), + requireRunScopedMcp: true, + }).pipe(Effect.forkChild); yield* Deferred.await(probeStarted); const newerIssued = yield* registry.issue({ threadId: probeRaceThreadId, @@ -4102,40 +3949,27 @@ it.effect.each([ assert.isUndefined(afterRace?.runId); // The older credential was not released or written back; the newer one became unbound for run 2. assert.equal((yield* registry.resolve(originalRaceToken))?.thread.runId, raceRun1); - const newerToken = newerIssued.config.authorizationHeader.replace(/^Bearer\s+/, ""); + const newerToken = rawBearer(newerIssued.config); const resolvedNewer = yield* registry.resolve(newerToken); assert.isDefined(resolvedNewer); assert.isUndefined(resolvedNewer!.thread.runId); // Narrowing on a non-rotating turn strips preview from older retained thread tokens too, // while re-enabling restores it only on the active credential. - yield* settings.updateSettings({ enableAgentBrowserAccess: false }); - yield* manager.open({ - threadId: probeRaceThreadId, - providerSessionId, - modelSelection, - runtimePolicy, - runId: RunId.make("run-probe-race-4"), - attemptId: RunAttemptId.make("attempt-probe-race-4"), - requireRunScopedMcp: true, - }); - assert.isFalse((yield* registry.resolve(newerToken))?.capabilities.has("preview") ?? true); - assert.isFalse( - (yield* registry.resolve(originalRaceToken))?.capabilities.has("preview") ?? true, - ); - yield* settings.updateSettings({ enableAgentBrowserAccess: true }); - yield* manager.open({ - threadId: probeRaceThreadId, - providerSessionId, - modelSelection, - runtimePolicy, - runId: RunId.make("run-probe-race-5"), - attemptId: RunAttemptId.make("attempt-probe-race-5"), - requireRunScopedMcp: true, - }); - assert.isTrue((yield* registry.resolve(newerToken))?.capabilities.has("preview") ?? false); - assert.isFalse( - (yield* registry.resolve(originalRaceToken))?.capabilities.has("preview") ?? true, - ); + for (const [enabled, ordinal] of [ + [false, 4], + [true, 5], + ] as const) { + yield* settings.updateSettings({ enableAgentBrowserAccess: enabled }); + yield* openFor(manager, providerSessionId, probeRaceThreadId, { + runId: RunId.make(`run-probe-race-${ordinal}`), + attemptId: RunAttemptId.make(`attempt-probe-race-${ordinal}`), + requireRunScopedMcp: true, + }); + assert.equal((yield* registry.resolve(newerToken))?.capabilities.has("preview"), enabled); + assert.isFalse( + (yield* registry.resolve(originalRaceToken))?.capabilities.has("preview") ?? true, + ); + } yield* manager.close(providerSessionId); }); @@ -4179,11 +4013,7 @@ it.effect.each([ }); const run1 = RunId.make("run-shared-1"); - const runtime = yield* manager.open({ - threadId, - providerSessionId, - modelSelection, - runtimePolicy, + const runtime = yield* openFor(manager, providerSessionId, threadId, { runId: run1, attemptId: RunAttemptId.make("attempt-shared-1"), }); @@ -4205,11 +4035,7 @@ it.effect.each([ assert.isTrue(Option.isNone(yield* Queue.poll(unloads))); // Plain turn on a shared runtime without live MCP updates keeps the loaded credential. - yield* manager.open({ - threadId, - providerSessionId, - modelSelection, - runtimePolicy, + yield* openFor(manager, providerSessionId, threadId, { runId: RunId.make("run-shared-2"), attemptId: RunAttemptId.make("attempt-shared-2"), requireRunScopedMcp: false, @@ -4218,13 +4044,8 @@ it.effect.each([ assert.isTrue(Option.isNone(yield* Queue.poll(unloads))); // Typed-output turn rotates the credential and reloads the thread via unloadThread + resumeThread. - const run3 = RunId.make("run-shared-3"); - yield* manager.open({ - threadId, - providerSessionId, - modelSelection, - runtimePolicy, - runId: run3, + yield* openFor(manager, providerSessionId, threadId, { + runId: RunId.make("run-shared-3"), attemptId: RunAttemptId.make("attempt-shared-3"), requireRunScopedMcp: true, }); diff --git a/apps/server/src/orchestration-v2/ProviderSessionManager.ts b/apps/server/src/orchestration-v2/ProviderSessionManager.ts index 85e31281e1ebb..88293af8276c2 100644 --- a/apps/server/src/orchestration-v2/ProviderSessionManager.ts +++ b/apps/server/src/orchestration-v2/ProviderSessionManager.ts @@ -607,7 +607,8 @@ export const layerWithOptions = ( ): ReadonlyMap> => { const existing = current.get(threadId); if (existing?.has(mcpCredentialId) === true) return current; - const ids = new Set([...(existing ?? []), mcpCredentialId]); + const ids = new Set(existing); + ids.add(mcpCredentialId); for (const oldest of ids) { if (ids.size <= McpSessionRegistry.MAX_CREDENTIALS_PER_THREAD) break; ids.delete(oldest); @@ -2083,10 +2084,10 @@ export const layerWithOptions = ( } const loadedProviderThreadKeyByThread = new Map(entry.loadedProviderThreadKeyByThread); loadedProviderThreadKeyByThread.set(input.threadId, input.providerThreadKey); - const loadedMcpCredentialByThread = new Map(entry.loadedMcpCredentialByThread); - if (input.mcpCredential !== undefined) { - loadedMcpCredentialByThread.set(input.threadId, input.mcpCredential); - } + const loadedMcpCredentialByThread = + input.mcpCredential === undefined + ? entry.loadedMcpCredentialByThread + : new Map(entry.loadedMcpCredentialByThread).set(input.threadId, input.mcpCredential); const linkedEnvironmentsByThread = new Map(entry.linkedEnvironmentsByThread); if ( input.linkedEnvironments !== undefined && @@ -2304,6 +2305,7 @@ export const layerWithOptions = ( yield* mcpSessions.set(updated); yield* syncLoadedMcpCredential(input.threadId, currentCredentialId, updated); } + yield* recordMcpTurnChecked(input.providerSessionId, input.threadId, turnKey); return true; }), ); @@ -2315,10 +2317,7 @@ export const layerWithOptions = ( current.runId === input.runId && (input.attemptId === undefined || current.attemptId === input.attemptId) ) { - if (yield* retainCurrentMcpCredential(current, { unbindRun: false })) { - yield* recordMcpTurnChecked(input.providerSessionId, input.threadId, turnKey); - return; - } + if (yield* retainCurrentMcpCredential(current, { unbindRun: false })) return; continue; } const rotateOnRunChange = @@ -2341,10 +2340,7 @@ export const layerWithOptions = ( ), ); if (!rotateOnRunChange && current !== undefined) { - if (yield* retainCurrentMcpCredential(current, { unbindRun: false })) { - yield* recordMcpTurnChecked(input.providerSessionId, input.threadId, turnKey); - return; - } + if (yield* retainCurrentMcpCredential(current, { unbindRun: false })) return; continue; } // A runtime that cannot take a new credential now (no way to deliver one, or a reload that @@ -2359,10 +2355,7 @@ export const layerWithOptions = ( ), ))); if (cannotRotate && current !== undefined) { - if (yield* retainCurrentMcpCredential(current, { unbindRun: true })) { - yield* recordMcpTurnChecked(input.providerSessionId, input.threadId, turnKey); - return; - } + if (yield* retainCurrentMcpCredential(current, { unbindRun: true })) return; continue; } const ownerSessionId = (yield* Ref.get(sessions)) @@ -3068,6 +3061,31 @@ export const layerWithOptions = ( modelFamily: normalizeModelMetricLabel(model), }, }); + const ensureTurnMcp = ( + input: Pick< + ProviderAdapter.ProviderAdapterV2TurnInput, + "threadId" | "providerThread" | "runId" | "attemptId" + >, + ) => + ensureTurnMcpSession({ + providerSessionId, + threadId: input.threadId, + providerInstanceId: runtime.instanceId, + runtime, + runId: input.runId, + attemptId: input.attemptId, + }).pipe( + Effect.mapError( + (cause) => + new ProviderAdapter.ProviderAdapterTurnStartError({ + driver: runtime.driver, + threadId: input.threadId, + providerThreadId: input.providerThread.id, + runId: input.runId, + cause, + }), + ), + ); return { ...runtime, // Pi replaces its session snapshot as metadata changes. @@ -3218,27 +3236,7 @@ export const layerWithOptions = ( providerInstanceId: runtime.instanceId, }), ).pipe( - Effect.andThen( - ensureTurnMcpSession({ - providerSessionId, - threadId: input.threadId, - providerInstanceId: runtime.instanceId, - runtime, - runId: input.runId, - attemptId: input.attemptId, - }).pipe( - Effect.mapError( - (cause) => - new ProviderAdapter.ProviderAdapterTurnStartError({ - driver: runtime.driver, - threadId: input.threadId, - providerThreadId: input.providerThread.id, - runId: input.runId, - cause, - }), - ), - ), - ), + Effect.andThen(ensureTurnMcp(input)), // Failed or stopped starts may omit turn.terminal; clear their turns so sessions can idle. Effect.andThen( holdThreadLoaded({ @@ -3310,27 +3308,7 @@ export const layerWithOptions = ( providerInstanceId: runtime.instanceId, }), ).pipe( - Effect.andThen( - ensureTurnMcpSession({ - providerSessionId, - threadId: input.threadId, - providerInstanceId: runtime.instanceId, - runtime, - runId: input.runId, - attemptId: input.attemptId, - }).pipe( - Effect.mapError( - (cause) => - new ProviderAdapter.ProviderAdapterTurnStartError({ - driver: runtime.driver, - threadId: input.threadId, - providerThreadId: input.providerThread.id, - runId: input.runId, - cause, - }), - ), - ), - ), + Effect.andThen(ensureTurnMcp(input)), Effect.andThen( holdThreadLoaded({ providerSessionId, diff --git a/apps/server/src/orchestration-v2/runOutput.ts b/apps/server/src/orchestration-v2/runOutput.ts index 1e3363b7bc98f..df879a401248e 100644 --- a/apps/server/src/orchestration-v2/runOutput.ts +++ b/apps/server/src/orchestration-v2/runOutput.ts @@ -15,14 +15,18 @@ export function latestOwedOutputRun< readonly output?: unknown; }, >(runs: ReadonlyArray): TRun | undefined { - return runs - .filter( - (candidate) => - candidate.outputSchema !== undefined && - candidate.output === undefined && - candidate.status === "completed", - ) - .toSorted((left, right) => right.ordinal - left.ordinal)[0]; + let latest: TRun | undefined; + for (const candidate of runs) { + if ( + candidate.outputSchema !== undefined && + candidate.output === undefined && + candidate.status === "completed" && + (latest === undefined || candidate.ordinal > latest.ordinal) + ) { + latest = candidate; + } + } + return latest; } /** Whether a turn needs its MCP credential rotated to match its run/attempt identity. */ diff --git a/apps/server/src/orchestration-v2/runtimeLayer.test.ts b/apps/server/src/orchestration-v2/runtimeLayer.test.ts index 8411acd1a4957..db35a88de5a43 100644 --- a/apps/server/src/orchestration-v2/runtimeLayer.test.ts +++ b/apps/server/src/orchestration-v2/runtimeLayer.test.ts @@ -12150,7 +12150,48 @@ it.layer(layerSharedApplicationDataPlaneTest)("run output after a stop", (it) => ...(outputSchema === undefined ? {} : { outputSchema }), dispatchMode: { type: "start_immediately" }, }); - return { orchestrator, eventSink, threadManagement, threadId, send }; + const latestRun = () => + orchestrator + .getThreadProjection(threadId) + .pipe(Effect.map((projection) => projection.runs.at(-1)!)); + const updateRun = ( + run: Effect.Success>, + suffix: string, + patch: Partial>>, + ) => + eventSink.write({ + events: [ + { + id: EventId.make(`${threadId}-${suffix}`), + type: "run.updated", + threadId, + runId: run.id, + occurredAt: run.requestedAt, + payload: { ...run, ...patch }, + }, + ], + }); + const submit = ( + command: string, + json: string, + caller?: { readonly callerRunId?: RunId; readonly callerAttemptId?: RunAttemptId }, + ) => + threadManagement.submitRunOutput({ + threadId, + commandId: CommandId.make(`runtime-layer-${command}`), + json, + ...caller, + }); + return { + orchestrator, + eventSink, + threadManagement, + threadId, + send, + latestRun, + updateRun, + submit, + }; }); it.effect.each([ @@ -12172,44 +12213,31 @@ it.layer(layerSharedApplicationDataPlaneTest)("run output after a stop", (it) => ])("$description", ({ scenario }) => Effect.gen(function* () { if (scenario === "stopped-run-or-stale-attempt") { - const { orchestrator, eventSink, threadManagement, threadId, send } = - yield* setupOutputThread("late-stopped-run"); + const { + orchestrator, + eventSink, + threadManagement, + threadId, + send, + latestRun, + updateRun, + submit, + } = yield* setupOutputThread("late-stopped-run"); // Run A starts with a schema, then is stopped while its submission is in flight. yield* send("run-a", { type: "object" }); - const runA = (yield* orchestrator.getThreadProjection(threadId)).runs[0]!; - yield* eventSink.write({ - events: [ - { - id: EventId.make(`${threadId}-run-a-interrupted`), - type: "run.updated", - threadId, - runId: runA.id, - occurredAt: runA.requestedAt, - payload: { ...runA, status: "interrupted", completedAt: runA.requestedAt }, - }, - ], + const runA = yield* latestRun(); + yield* updateRun(runA, "run-a-interrupted", { + status: "interrupted", + completedAt: runA.requestedAt, }); // Run B starts with a compatible schema and attempt 2 active. yield* send("run-b", { type: "object" }); - const runB = (yield* orchestrator.getThreadProjection(threadId)).runs.find( - (run) => run.id !== runA.id, - )!; + const runB = yield* latestRun(); const attempt1 = RunAttemptId.make(`${runB.id}:attempt:1`); const attempt2 = RunAttemptId.make(`${runB.id}:attempt:2`); - yield* eventSink.write({ - events: [ - { - id: EventId.make(`${threadId}-run-b-attempt-2`), - type: "run.updated", - threadId, - runId: runB.id, - occurredAt: runB.requestedAt, - payload: { ...runB, activeAttemptId: attempt2 }, - }, - ], - }); + yield* updateRun(runB, "run-b-attempt-2", { activeAttemptId: attempt2 }); // A caller that names no run cannot be told from a stopped run's late call. const anonymous = yield* threadManagement @@ -12222,36 +12250,26 @@ it.layer(layerSharedApplicationDataPlaneTest)("run output after a stop", (it) => assert.equal(anonymous._tag, "ThreadManagementRunOutputRejectedError"); assert.include(anonymous.message, "runId"); - const lateFromA = yield* threadManagement - .submitRunOutput({ - threadId, - commandId: CommandId.make("runtime-layer-late-run-output-from-a"), - json: '{"from":"run-a"}', - callerRunId: runA.id, - }) - .pipe(Effect.flip); + const lateFromA = yield* submit("late-run-output-from-a", '{"from":"run-a"}', { + callerRunId: runA.id, + }).pipe(Effect.flip); assert.equal(lateFromA._tag, "ThreadManagementRunOutputRejectedError"); assert.include(lateFromA.message, "no longer active"); - const lateFromAttempt1 = yield* threadManagement - .submitRunOutput({ - threadId, - commandId: CommandId.make("runtime-layer-late-run-output-from-attempt-1"), - json: '{"from":"attempt-1"}', + const lateFromAttempt1 = yield* submit( + "late-run-output-from-attempt-1", + '{"from":"attempt-1"}', + { callerRunId: runB.id, callerAttemptId: attempt1, - }) - .pipe(Effect.flip); + }, + ).pipe(Effect.flip); assert.equal(lateFromAttempt1._tag, "ThreadManagementRunOutputRejectedError"); assert.include(lateFromAttempt1.message, "no longer active"); - const mid = yield* orchestrator.getThreadProjection(threadId); - assert.isUndefined(mid.runs.find((run) => run.id === runB.id)?.output); + assert.isUndefined((yield* latestRun()).output); - const acceptedB = yield* threadManagement.submitRunOutput({ - threadId, - commandId: CommandId.make("runtime-layer-late-run-output-from-b"), - json: '{"from":"run-b"}', + const acceptedB = yield* submit("late-run-output-from-b", '{"from":"run-b"}', { callerRunId: runB.id, callerAttemptId: attempt2, }); @@ -12324,98 +12342,53 @@ it.layer(layerSharedApplicationDataPlaneTest)("run output after a stop", (it) => }); // A plain turn with no schema preserves the plain-turn guidance even for stale/unbound MCP callers. - yield* eventSink.write({ - events: [ - { - id: EventId.make(`${threadId}-run-c-completed`), - type: "run.updated", - threadId, - runId: runC.id, - occurredAt: runC.requestedAt, - payload: { - ...afterC.runs.find((run) => run.id === runC.id)!, - status: "completed", - completedAt: runC.requestedAt, - }, - }, - ], - }); + yield* updateRun( + afterC.runs.find((run) => run.id === runC.id)!, + "run-c-completed", + { + status: "completed", + completedAt: runC.requestedAt, + }, + ); yield* send("run-plain"); - const plainFromStale = yield* threadManagement - .submitRunOutput({ - threadId, - commandId: CommandId.make("runtime-layer-plain-run-output-stale"), - json: "{}", - callerRunId: runA.id, - }) - .pipe(Effect.flip); + const plainFromStale = yield* submit("plain-run-output-stale", "{}", { + callerRunId: runA.id, + }).pipe(Effect.flip); assert.equal(plainFromStale._tag, "ThreadManagementRunOutputRejectedError"); assert.include(plainFromStale.message, "not asked for a result"); - const plainFromUnbound = yield* threadManagement - .submitRunOutput({ - threadId, - commandId: CommandId.make("runtime-layer-plain-run-output-unbound"), - json: "{}", - }) - .pipe(Effect.flip); + const plainFromUnbound = yield* submit("plain-run-output-unbound", "{}").pipe(Effect.flip); assert.equal(plainFromUnbound._tag, "ThreadManagementRunOutputRejectedError"); assert.include(plainFromUnbound.message, "not asked for a result"); return; } if (scenario === "owed-run-and-wake") { - const { orchestrator, eventSink, threadManagement, threadId, send } = + const { orchestrator, threadId, send, latestRun, updateRun, submit } = yield* setupOutputThread("owed-wake-output"); yield* send("run-a", { type: "object" }); - const runA = (yield* orchestrator.getThreadProjection(threadId)).runs[0]!; - yield* eventSink.write({ - events: [ - { - id: EventId.make(`${threadId}-run-a-interrupted`), - type: "run.updated", - threadId, - runId: runA.id, - occurredAt: runA.requestedAt, - payload: { ...runA, status: "interrupted", completedAt: runA.requestedAt }, - }, - ], + const runA = yield* latestRun(); + yield* updateRun(runA, "run-a-interrupted", { + status: "interrupted", + completedAt: runA.requestedAt, }); yield* send("run-c", { type: "object" }); - const runC = (yield* orchestrator.getThreadProjection(threadId)).runs.find( - (run) => run.id !== runA.id, - )!; - yield* eventSink.write({ - events: [ - { - id: EventId.make(`${threadId}-run-c-completed`), - type: "run.updated", - threadId, - runId: runC.id, - occurredAt: runC.requestedAt, - payload: { ...runC, status: "completed", completedAt: runC.requestedAt }, - }, - ], + const runC = yield* latestRun(); + yield* updateRun(runC, "run-c-completed", { + status: "completed", + completedAt: runC.requestedAt, }); yield* send("run-d-wake"); - const runD = (yield* orchestrator.getThreadProjection(threadId)).runs.find( - (run) => run.id !== runA.id && run.id !== runC.id, - )!; - const staleAOnWake = yield* threadManagement - .submitRunOutput({ - threadId, - commandId: CommandId.make("runtime-layer-late-run-output-from-a-during-wake"), - json: '{"from":"stale-run-a"}', - callerRunId: runA.id, - }) - .pipe(Effect.flip); + const runD = yield* latestRun(); + const staleAOnWake = yield* submit( + "late-run-output-from-a-during-wake", + '{"from":"stale-run-a"}', + { callerRunId: runA.id }, + ).pipe(Effect.flip); assert.equal(staleAOnWake._tag, "ThreadManagementRunOutputRejectedError"); - const acceptedFromC = yield* threadManagement.submitRunOutput({ - threadId, - commandId: CommandId.make("runtime-layer-late-run-output-from-c"), - json: '{"from":"run-c"}', + const acceptedFromC = yield* submit("late-run-output-from-c", '{"from":"run-c"}', { callerRunId: runC.id, }); assert.equal(acceptedFromC.runId, runC.id); @@ -12424,42 +12397,19 @@ it.layer(layerSharedApplicationDataPlaneTest)("run output after a stop", (it) => from: "run-c", }); - yield* eventSink.write({ - events: [ - { - id: EventId.make(`${threadId}-run-d-completed`), - type: "run.updated", - threadId, - runId: runD.id, - occurredAt: runD.requestedAt, - payload: { ...runD, status: "completed", completedAt: runD.requestedAt }, - }, - ], + yield* updateRun(runD, "run-d-completed", { + status: "completed", + completedAt: runD.requestedAt, }); yield* send("run-e", { type: "object" }); - const runE = (yield* orchestrator.getThreadProjection(threadId)).runs.find( - (run) => ![runA.id, runC.id, runD.id].includes(run.id), - )!; - yield* eventSink.write({ - events: [ - { - id: EventId.make(`${threadId}-run-e-completed`), - type: "run.updated", - threadId, - runId: runE.id, - occurredAt: runE.requestedAt, - payload: { ...runE, status: "completed", completedAt: runE.requestedAt }, - }, - ], + const runE = yield* latestRun(); + yield* updateRun(runE, "run-e-completed", { + status: "completed", + completedAt: runE.requestedAt, }); yield* send("run-f-wake"); - const runF = (yield* orchestrator.getThreadProjection(threadId)).runs.find( - (run) => ![runA.id, runC.id, runD.id, runE.id].includes(run.id), - )!; - const acceptedFromF = yield* threadManagement.submitRunOutput({ - threadId, - commandId: CommandId.make("runtime-layer-late-run-output-from-f"), - json: '{"from":"run-f"}', + const runF = yield* latestRun(); + const acceptedFromF = yield* submit("late-run-output-from-f", '{"from":"run-f"}', { callerRunId: runF.id, }); assert.equal(acceptedFromF.runId, runE.id); @@ -12470,28 +12420,16 @@ it.layer(layerSharedApplicationDataPlaneTest)("run output after a stop", (it) => return; } - const { orchestrator, eventSink, threadId, send } = yield* setupOutputThread( + const { orchestrator, threadId, send, latestRun, updateRun } = yield* setupOutputThread( "completed-before-dispatch", ); yield* send("run-own", { type: "object" }); - const run = (yield* orchestrator.getThreadProjection(threadId)).runs[0]!; + const run = yield* latestRun(); const attempt = RunAttemptId.make(`${run.id}:attempt:1`); - yield* eventSink.write({ - events: [ - { - id: EventId.make(`${threadId}-run-own-completed`), - type: "run.updated", - threadId, - runId: run.id, - occurredAt: run.requestedAt, - payload: { - ...run, - activeAttemptId: attempt, - status: "completed", - completedAt: run.requestedAt, - }, - }, - ], + yield* updateRun(run, "run-own-completed", { + activeAttemptId: attempt, + status: "completed", + completedAt: run.requestedAt, }); // Simulate the race where the run completes after service validation, with no active run. diff --git a/apps/server/src/preview/ServerBrowser.test.ts b/apps/server/src/preview/ServerBrowser.test.ts index 46ce03d64c169..4dbfd1d79d3b3 100644 --- a/apps/server/src/preview/ServerBrowser.test.ts +++ b/apps/server/src/preview/ServerBrowser.test.ts @@ -1561,39 +1561,37 @@ it.effect( ); yield* Effect.yieldNow; - const runA = yield* registry.issue({ - threadId: scope.thread.threadId, - providerInstanceId: scope.thread.providerInstanceId, - capabilities: new Set(["preview"]), - runId: RunId.make("run-a"), - }); - const scopeA = yield* registry.resolve( - runA.config.authorizationHeader.replace(/^Bearer\s+/, ""), - ); - expect(scopeA).toBeDefined(); + const issueScope = (runId: string, providerSessionId?: string) => + Effect.gen(function* () { + const issued = yield* registry.issue({ + threadId: scope.thread.threadId, + providerInstanceId: scope.thread.providerInstanceId, + capabilities: new Set(["preview"]), + ...(providerSessionId === undefined ? {} : { providerSessionId }), + runId: RunId.make(runId), + }); + const resolved = yield* registry.resolve( + issued.config.authorizationHeader.replace(/^Bearer\s+/, ""), + ); + return { config: issued.config, scope: resolved }; + }); + + const runA = yield* issueScope("run-a"); + expect(runA.scope).toBeDefined(); const opened = yield* broker.invoke({ - scope: scopeA!, + scope: runA.scope!, operation: "open", input: { reuseExistingTab: false, show: false }, }); const tabId = PreviewTabId.make(opened.tabId!); - const runB = yield* registry.issue({ - threadId: scope.thread.threadId, - providerInstanceId: scope.thread.providerInstanceId, - capabilities: new Set(["preview"]), - providerSessionId: runA.config.providerSessionId, - runId: RunId.make("run-b"), - }); + const runB = yield* issueScope("run-b", runA.config.providerSessionId); expect(runB.config.providerSessionId).toBe(runA.config.providerSessionId); expect(runB.config.credentialId).not.toBe(runA.config.credentialId); - const scopeB = yield* registry.resolve( - runB.config.authorizationHeader.replace(/^Bearer\s+/, ""), - ); - expect(scopeB?.thread.runId).toBe("run-b"); + expect(runB.scope?.thread.runId).toBe("run-b"); yield* broker.invoke({ - scope: scopeB!, + scope: runB.scope!, tabId, operation: "navigate", input: { url: "http://localhost:5173/after-rotation" }, @@ -1603,26 +1601,18 @@ it.effect( expect.anything(), ); const evaluated = yield* broker.invoke({ - scope: scopeB!, + scope: runB.scope!, tabId, operation: "evaluate", input: { expression: "ownedAfterRotation()" }, }); expect(evaluated).toBe("evaluated"); - const separateSession = yield* registry.issue({ - threadId: scope.thread.threadId, - providerInstanceId: scope.thread.providerInstanceId, - capabilities: new Set(["preview"]), - runId: RunId.make("run-c"), - }); + const separateSession = yield* issueScope("run-c"); expect(separateSession.config.providerSessionId).not.toBe(runA.config.providerSessionId); - const scopeOther = yield* registry.resolve( - separateSession.config.authorizationHeader.replace(/^Bearer\s+/, ""), - ); const foreign = yield* broker .invoke({ - scope: scopeOther!, + scope: separateSession.scope!, tabId, operation: "navigate", input: { url: "http://localhost:5173/separate-session" }, diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts index 829c8d9891090..4f66ca95c4230 100644 --- a/packages/provider-acp/src/server/adapter.ts +++ b/packages/provider-acp/src/server/adapter.ts @@ -9421,17 +9421,16 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( const isContinuationTurn = (postSettleContinuationEnabled || followsAgentWorkState) && acpIsProviderContinuationMessage(turnInput.message); + const currentSessionId = yield* Ref.get(activeSessionId); const mcpReloadRequired = !restartAfterInterrupt && - (yield* Ref.get(activeSessionId)) === requestedSessionId && + currentSessionId === requestedSessionId && (yield* syncMcpCredentialForSession(requestedSessionId, turnInput.threadId, { allowReload: !isContinuationTurn, providerThreadId: turnInput.providerThread.id, })); const needsSessionActivation = - (yield* Ref.get(activeSessionId)) !== requestedSessionId || - restartAfterInterrupt || - mcpReloadRequired; + currentSessionId !== requestedSessionId || restartAfterInterrupt || mcpReloadRequired; if (needsSessionActivation) { const activated = yield* activateSession(requestedSessionId, turnInput.threadId); yield* Ref.set(activeSessionId, activated.sessionId); @@ -10132,16 +10131,17 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( const restartAfterInterrupt = yield* restartRuntimeAfterTeardownIfRequired( threadInput.providerThread.appThreadId, ).pipe(Effect.tapError(() => restorePreviousItemIdentity)); + const currentSessionId = yield* Ref.get(activeSessionId); const mcpReloadRequired = !restartAfterInterrupt && - (yield* Ref.get(activeSessionId)) === sessionId && + currentSessionId === sessionId && (yield* syncMcpCredentialForSession( sessionId, threadInput.providerThread.appThreadId, { providerThreadId: threadInput.providerThread.id }, ).pipe(Effect.tapError(() => restorePreviousItemIdentity))); if ( - (yield* Ref.get(activeSessionId)) !== sessionId || + currentSessionId !== sessionId || restartAfterInterrupt || mcpReloadRequired ) { diff --git a/packages/provider-acp/src/server/mcpOverAcpBridge.test.ts b/packages/provider-acp/src/server/mcpOverAcpBridge.test.ts index 53fcdfa6a904a..8f8d6a73bc7ce 100644 --- a/packages/provider-acp/src/server/mcpOverAcpBridge.test.ts +++ b/packages/provider-acp/src/server/mcpOverAcpBridge.test.ts @@ -273,69 +273,97 @@ describe("AcpMcpOverAcpBridge", () => { }, ])("$description", ({ scenario }) => Effect.gen(function* () { + const INIT_PARAMS = { + protocolVersion: "2025-06-18", + capabilities: {}, + clientInfo: { name: "acp" }, + }; + const jsonResponse = (body: unknown, headers?: Record) => + new Response(JSON.stringify(body), { + headers: { "content-type": "application/json", ...headers }, + }); + const makeStatefulBridge = (opts?: { + readonly onRequest?: ( + auth: string | null, + body: { + readonly id?: unknown; + readonly method: string; + readonly params?: { readonly name?: string }; + }, + ) => Promise; + }) => + Effect.gen(function* () { + const seen: Array<{ + readonly authorization: string | null; + readonly sessionId: string | null; + readonly method: string; + }> = []; + let sessionCounter = 0; + const sessionAuth = new Map(); + const bridge = yield* makeAcpMcpOverAcpBridge({ + endpoint: "http://127.0.0.1:1/mcp", + authorization: "Bearer run-1-token", + allocateConnectionId: Effect.succeed(`conn-${scenario}`), + fetchImplementation: async (_url, init) => { + const headers = new Headers(init?.headers); + const auth = headers.get("authorization"); + const incomingSid = headers.get("mcp-session-id"); + const body = JSON.parse(String(init?.body)) as { + readonly id?: unknown; + readonly method: string; + readonly params?: { readonly name?: string }; + }; + seen.push({ authorization: auth, sessionId: incomingSid, method: body.method }); + const override = await opts?.onRequest?.(auth, body); + if (override !== undefined) return override; + if (body.method === "initialize") { + const sid = `session-${++sessionCounter}`; + sessionAuth.set(sid, auth ?? ""); + return jsonResponse( + { + jsonrpc: "2.0", + id: body.id, + result: { protocolVersion: "2025-06-18", capabilities: {}, serverInfo: {} }, + }, + { "mcp-session-id": sid }, + ); + } + // Stateful MCP 2025-06-18 rejects non-initialize requests without a valid session id. + if (incomingSid === null || sessionAuth.get(incomingSid) !== auth) { + return new Response("Mcp-Session-Id does not exist", { status: 400 }); + } + if (body.method === "notifications/initialized") { + return new Response(null, { status: 202 }); + } + return jsonResponse( + { jsonrpc: "2.0", id: body.id, result: { content: [] } }, + { "mcp-session-id": incomingSid }, + ); + }, + }); + const { connectionId } = yield* bridge.connect({ serverId: "t3-code" }); + const init = () => + bridge.message({ connectionId, method: "initialize", params: INIT_PARAMS }); + const callTool = (name = "t3_submit_output") => + bridge.message({ connectionId, method: "tools/call", params: { name } }); + return { bridge, seen, init, callTool }; + }); + if (scenario === "reinitialize-and-stale-headers") { - const seen: Array<{ - readonly authorization: string | null; - readonly sessionId: string | null; - readonly method: unknown; - }> = []; const slowCallStarted = Promise.withResolvers(); const releaseSlowCall = Promise.withResolvers(); - let sessionCounter = 0; - const sessionAuth = new Map(); - const bridge = yield* makeAcpMcpOverAcpBridge({ - endpoint: "http://127.0.0.1:1/mcp", - authorization: "Bearer run-1-token", - allocateConnectionId: Effect.succeed("connection-1"), - fetchImplementation: async (_url, init) => { - const headers = new Headers(init?.headers); - const auth = headers.get("authorization"); - const incomingSid = headers.get("mcp-session-id"); - const body = JSON.parse(String(init?.body)) as { - readonly id?: unknown; - readonly method?: unknown; - readonly params?: { readonly name?: string }; - }; - seen.push({ authorization: auth, sessionId: incomingSid, method: body.method }); - if (body.method === "initialize") { - const sid = `session-${++sessionCounter}`; - sessionAuth.set(sid, auth ?? ""); - return new Response( - JSON.stringify({ - jsonrpc: "2.0", - id: body.id, - result: { protocolVersion: "2025-06-18", capabilities: {}, serverInfo: {} }, - }), - { headers: { "content-type": "application/json", "mcp-session-id": sid } }, - ); - } - // Stateful MCP 2025-06-18 rejects non-initialize requests without a valid session id. - if (incomingSid === null || sessionAuth.get(incomingSid) !== auth) { - return new Response("Mcp-Session-Id does not exist", { status: 400 }); - } - if (body.method === "notifications/initialized") { - return new Response(null, { status: 202 }); - } + const { bridge, seen, init, callTool } = yield* makeStatefulBridge({ + onRequest: async (_auth, body) => { if (body.params?.name === "slow_call") { slowCallStarted.resolve(); await releaseSlowCall.promise; } - return new Response( - JSON.stringify({ jsonrpc: "2.0", id: body.id, result: { content: [] } }), - { headers: { "content-type": "application/json", "mcp-session-id": incomingSid } }, - ); + return undefined; }, }); - const { connectionId } = yield* bridge.connect({ serverId: "t3-code" }); - yield* bridge.message({ - connectionId, - method: "initialize", - params: { protocolVersion: "2025-06-18", capabilities: {}, clientInfo: { name: "acp" } }, - }); - const inFlight = yield* bridge - .message({ connectionId, method: "tools/call", params: { name: "slow_call" } }) - .pipe(Effect.forkChild); + yield* init(); + const inFlight = yield* callTool("slow_call").pipe(Effect.forkChild); yield* Effect.promise(() => slowCallStarted.promise); // Rotate auth while generation-1 call is in flight, then let generation-1 finish. @@ -344,14 +372,7 @@ describe("AcpMcpOverAcpBridge", () => { yield* Fiber.join(inFlight); // Generation-2 call must transparently re-initialize with run-2-token, not reuse session-1. - expect( - yield* bridge.message({ - connectionId, - method: "tools/call", - params: { name: "t3_submit_output" }, - }), - ).toEqual({ content: [] }); - + expect(yield* callTool()).toEqual({ content: [] }); expect(seen).toEqual([ { authorization: "Bearer run-1-token", sessionId: null, method: "initialize" }, { authorization: "Bearer run-1-token", sessionId: "session-1", method: "tools/call" }, @@ -367,96 +388,36 @@ describe("AcpMcpOverAcpBridge", () => { } if (scenario === "init-race-and-waiting-rejection") { - const seen: Array<{ - readonly authorization: string | null; - readonly sessionId: string | null; - readonly method: string; - }> = []; const initStarted = Promise.withResolvers(); const releaseInit = Promise.withResolvers(); const reconnect3Started = Promise.withResolvers(); const releaseReconnect3 = Promise.withResolvers(); - let nextSessionOrdinal = 0; - const activeSessionByAuth = new Map(); - const bridge = yield* makeAcpMcpOverAcpBridge({ - endpoint: "http://127.0.0.1:43123/mcp", - authorization: "Bearer run-1-token", - allocateConnectionId: Effect.succeed("conn-init-race"), - fetchImplementation: async (_input, init) => { - const headers = new Headers(init?.headers); - const auth = headers.get("authorization") ?? ""; - const incomingSid = headers.get("mcp-session-id"); - const body = JSON.parse(String(init?.body)) as { - id?: number; - method: string; - params?: { name?: string }; - }; - seen.push({ authorization: auth, sessionId: incomingSid, method: body.method }); - if (body.method === "initialize") { - if (auth === "Bearer run-1-token") { - initStarted.resolve(); - await releaseInit.promise; - } - if (auth === "Bearer run-3-token") { - reconnect3Started.resolve(); - await releaseReconnect3.promise; - } - const sid = `session-${++nextSessionOrdinal}`; - activeSessionByAuth.set(auth, sid); - return new Response( - JSON.stringify({ - jsonrpc: "2.0", - id: body.id, - result: { protocolVersion: "2025-06-18", capabilities: {} }, - }), - { headers: { "content-type": "application/json", "mcp-session-id": sid } }, - ); - } - const expectedSid = activeSessionByAuth.get(auth); - if (!incomingSid || incomingSid !== expectedSid) { - return new Response("Mcp-Session-Id does not exist", { status: 400 }); + const { bridge, seen, init, callTool } = yield* makeStatefulBridge({ + onRequest: async (auth, body) => { + if (body.method === "initialize" && auth === "Bearer run-1-token") { + initStarted.resolve(); + await releaseInit.promise; } - if (body.method === "notifications/initialized") { - return new Response(null, { status: 202 }); + if (body.method === "initialize" && auth === "Bearer run-3-token") { + reconnect3Started.resolve(); + await releaseReconnect3.promise; } - return new Response( - JSON.stringify({ jsonrpc: "2.0", id: body.id, result: { content: [] } }), - { headers: { "content-type": "application/json", "mcp-session-id": incomingSid } }, - ); + return undefined; }, }); // 1. Auth rotates while initial initialize is still in flight; subsequent call must reconnect. - const { connectionId } = yield* bridge.connect({ serverId: "t3-code" }); - const initFiber = yield* bridge - .message({ - connectionId, - method: "initialize", - params: { - protocolVersion: "2025-06-18", - capabilities: {}, - clientInfo: { name: "acp" }, - }, - }) - .pipe(Effect.forkChild); + const initFiber = yield* init().pipe(Effect.forkChild); yield* Effect.promise(() => initStarted.promise); bridge.setAuthorization("Bearer run-2-token"); releaseInit.resolve(); yield* Fiber.join(initFiber); - expect( - yield* bridge.message({ - connectionId, - method: "tools/call", - params: { name: "after_init_race" }, - }), - ).toEqual({ content: [] }); + expect(yield* callTool("after_init_race")).toEqual({ content: [] }); // 2. A gen-3 call waiting on reconnect while auth rotates to gen-4 is rejected before posting. bridge.setAuthorization("Bearer run-3-token"); - const waitingGen3 = yield* bridge - .message({ connectionId, method: "tools/call", params: { name: "t3_submit_output" } }) - .pipe(Effect.flip, Effect.forkChild); + const waitingGen3 = yield* callTool().pipe(Effect.flip, Effect.forkChild); yield* Effect.promise(() => reconnect3Started.promise); bridge.setAuthorization("Bearer run-4-token"); releaseReconnect3.resolve(); @@ -467,78 +428,35 @@ describe("AcpMcpOverAcpBridge", () => { return; } - const methods: Array = []; let nextInitMode: "ok" | "error" | "malformed" = "ok"; - const bridge = yield* makeAcpMcpOverAcpBridge({ - endpoint: "http://127.0.0.1:43123/mcp", - authorization: "Bearer run-1-token", - allocateConnectionId: Effect.succeed("conn-init-err"), - fetchImplementation: async (_input, init) => { - const body = JSON.parse(String(init?.body)) as { id?: number; method: string }; - methods.push(body.method); - if (body.method === "initialize") { - const mode = nextInitMode; - nextInitMode = "ok"; - if (mode === "error") { - return new Response( - JSON.stringify({ - jsonrpc: "2.0", - id: body.id, - error: { code: -32000, message: "initialize rejected" }, - }), - { headers: { "content-type": "application/json" } }, - ); - } - if (mode === "malformed") { - return new Response(JSON.stringify({ jsonrpc: "2.0", id: body.id }), { - headers: { "content-type": "application/json" }, - }); - } - return new Response( - JSON.stringify({ - jsonrpc: "2.0", - id: body.id, - result: { protocolVersion: "2025-06-18", capabilities: {} }, - }), - { headers: { "content-type": "application/json", "mcp-session-id": "sid-ok" } }, - ); + const { bridge, seen, init, callTool } = yield* makeStatefulBridge({ + onRequest: async (_auth, body) => { + if (body.method !== "initialize") return undefined; + const mode = nextInitMode; + nextInitMode = "ok"; + if (mode === "error") { + return jsonResponse({ + jsonrpc: "2.0", + id: body.id, + error: { code: -32000, message: "initialize rejected" }, + }); } - if (body.method === "notifications/initialized") { - return new Response(null, { status: 202 }); + if (mode === "malformed") { + return jsonResponse({ jsonrpc: "2.0", id: body.id }); } - return new Response( - JSON.stringify({ jsonrpc: "2.0", id: body.id, result: { content: [] } }), - { headers: { "content-type": "application/json", "mcp-session-id": "sid-ok" } }, - ); + return undefined; }, }); - const { connectionId } = yield* bridge.connect({ serverId: "t3-code" }); - yield* bridge.message({ - connectionId, - method: "initialize", - params: { protocolVersion: "2025-06-18", capabilities: {}, clientInfo: { name: "acp" } }, - }); + yield* init(); bridge.setAuthorization("Bearer run-2-token"); nextInitMode = "error"; - const failedError = yield* bridge - .message({ connectionId, method: "tools/call", params: { name: "t3_submit_output" } }) - .pipe(Effect.flip); - expect(failedError.message).toContain("initialize rejected"); + expect((yield* callTool().pipe(Effect.flip)).message).toContain("initialize rejected"); nextInitMode = "malformed"; - const failedMalformed = yield* bridge - .message({ connectionId, method: "tools/call", params: { name: "t3_submit_output" } }) - .pipe(Effect.flip); - expect(failedMalformed.message).toContain("valid initialize response"); - expect(methods).toEqual(["initialize", "initialize", "initialize"]); + expect((yield* callTool().pipe(Effect.flip)).message).toContain("valid initialize response"); + expect(seen.map((entry) => entry.method)).toEqual(["initialize", "initialize", "initialize"]); // Next call still retries reconnect because needsReconnect stayed true. - expect( - yield* bridge.message({ - connectionId, - method: "tools/call", - params: { name: "t3_submit_output" }, - }), - ).toEqual({ content: [] }); - expect(methods).toEqual([ + expect(yield* callTool()).toEqual({ content: [] }); + expect(seen.map((entry) => entry.method)).toEqual([ "initialize", "initialize", "initialize", @@ -550,41 +468,14 @@ describe("AcpMcpOverAcpBridge", () => { // An agent-issued initialize with an error or malformed response does not clear needsReconnect. bridge.setAuthorization("Bearer run-3-token"); nextInitMode = "error"; - const explicitError = yield* bridge - .message({ - connectionId, - method: "initialize", - params: { - protocolVersion: "2025-06-18", - capabilities: {}, - clientInfo: { name: "acp" }, - }, - }) - .pipe(Effect.flip); - expect(explicitError.message).toContain("initialize rejected"); + expect((yield* init().pipe(Effect.flip)).message).toContain("initialize rejected"); nextInitMode = "malformed"; - const explicitMalformed = yield* bridge - .message({ - connectionId, - method: "initialize", - params: { - protocolVersion: "2025-06-18", - capabilities: {}, - clientInfo: { name: "acp" }, - }, - }) - .pipe(Effect.flip); + const explicitMalformed = yield* init().pipe(Effect.flip); expect(explicitMalformed._tag).toBe("AcpMcpOverAcpError"); expect(explicitMalformed.message).toContain("valid initialize response"); - const methodsBeforeRecovery = methods.length; - expect( - yield* bridge.message({ - connectionId, - method: "tools/call", - params: { name: "t3_submit_output" }, - }), - ).toEqual({ content: [] }); - expect(methods.slice(methodsBeforeRecovery)).toEqual([ + const methodsBeforeRecovery = seen.length; + expect(yield* callTool()).toEqual({ content: [] }); + expect(seen.slice(methodsBeforeRecovery).map((entry) => entry.method)).toEqual([ "initialize", "notifications/initialized", "tools/call", diff --git a/packages/provider-acp/src/server/mcpOverAcpBridge.ts b/packages/provider-acp/src/server/mcpOverAcpBridge.ts index 3b516941c0e87..a40efd06ab65a 100644 --- a/packages/provider-acp/src/server/mcpOverAcpBridge.ts +++ b/packages/provider-acp/src/server/mcpOverAcpBridge.ts @@ -175,10 +175,7 @@ export const makeAcpMcpOverAcpBridge = Effect.fn("AcpMcpOverAcpBridge.make")(fun const reconnectIfNeeded = Effect.fn("AcpMcpOverAcpBridge.reconnectIfNeeded")(function* ( connection: Connection, - message: unknown, ) { - const method = asEnvelope(message)?.method; - if (!connection.needsReconnect || method === "initialize") return; const reconnectGeneration = authorizationGeneration; const reconnectAuth = authorization; const initId = ++connection.nextRequestId; @@ -234,18 +231,14 @@ export const makeAcpMcpOverAcpBridge = Effect.fn("AcpMcpOverAcpBridge.make")(fun connection, Effect.gen(function* () { if (method !== "initialize") { - while (connection.needsReconnect) { + while (true) { if (authorizationGeneration !== pinnedGeneration) { return yield* new AcpMcpOverAcpError({ message: "MCP credentials rotated while the request was waiting to send.", }); } - yield* reconnectIfNeeded(connection, message); - } - if (authorizationGeneration !== pinnedGeneration) { - return yield* new AcpMcpOverAcpError({ - message: "MCP credentials rotated while the request was waiting to send.", - }); + if (!connection.needsReconnect) break; + yield* reconnectIfNeeded(connection); } } const requestGeneration = authorizationGeneration; diff --git a/packages/provider-muse/src/server/adapter.ts b/packages/provider-muse/src/server/adapter.ts index b132884c1bbe6..4d107606f026a 100644 --- a/packages/provider-muse/src/server/adapter.ts +++ b/packages/provider-muse/src/server/adapter.ts @@ -1928,16 +1928,15 @@ export const makeMuseAdapterV2 = Effect.fn("makeMuseAdapterV2")(function* ( thread !== undefined && (!requestedId || requestedId === nativeSessionId) && thread.appThreadId === args.threadId; + if (thread && !sameThread) { + return yield* protocolError("Open a new host to attach another Muse session"); + } if ( thread !== undefined && - sameThread && registeredMcpAuthorization === mcpSession?.authorizationHeader ) { return thread; } - if (thread && !sameThread) { - return yield* protocolError("Open a new host to attach another Muse session"); - } let missingNativeSession = false; return yield* Effect.gen(function* () { const resumeExistingId = sameThread ? nativeSessionId : requestedId; diff --git a/packages/provider-pi/src/server/mcpBridge.testkit.ts b/packages/provider-pi/src/server/mcpBridge.testkit.ts index 8749805110625..35e2846f51d7c 100644 --- a/packages/provider-pi/src/server/mcpBridge.testkit.ts +++ b/packages/provider-pi/src/server/mcpBridge.testkit.ts @@ -73,7 +73,6 @@ export async function loadMcpBridge( } = {}, ) { const handlers = new Map(); - const commands = new Map Promise | void>(); const tools: RegisteredTool[] = []; const requests: Array<{ readonly method: string; readonly params?: unknown }> = []; let activeTools = ["read"]; @@ -167,10 +166,7 @@ export async function loadMcpBridge( }, pi: { on: (name: string, handler: AgentStartHook) => handlers.set(name, handler), - registerCommand: ( - name: string, - command: { readonly handler: (args: string) => Promise | void }, - ) => commands.set(name, command.handler), + registerCommand: () => {}, registerTool: (tool: RegisteredTool) => { if (options.allowsTool && !options.allowsTool(tool.name)) return; const index = tools.findIndex((current) => current.name === tool.name); @@ -234,7 +230,6 @@ export async function loadMcpBridge( }; return { handlers, - commands, tools, declaredTools, callableTools: () => callableTools().map((tool) => tool.name), diff --git a/packages/provider-pi/src/server/mcpExtensionSource.test.ts b/packages/provider-pi/src/server/mcpExtensionSource.test.ts index e0cfaa0618d7d..21f985f4490c8 100644 --- a/packages/provider-pi/src/server/mcpExtensionSource.test.ts +++ b/packages/provider-pi/src/server/mcpExtensionSource.test.ts @@ -191,19 +191,20 @@ describe("Pi MCP tool results", () => { "rejects a waiting tool call if the MCP bearer token rotates during its first read or connect", }, ])("$description", async ({ scenario }) => { + const startTurn = (bridge: Awaited>) => + bridge.handlers.get("before_agent_start")!( + { systemPrompt: "" }, + { ui: { notify: assert.fail } }, + ); + if (scenario === "rotate-and-coalesce") { const bridge = await loadMcpBridge(); - const startTurn = () => - bridge.handlers.get("before_agent_start")!( - { systemPrompt: "" }, - { ui: { notify: assert.fail } }, - ); const tool = bridge.tools[0]!; await tool.execute("call-1", {}); assert.equal(bridge.transports.at(-1)?.authorization, "Bearer fixture-token"); bridge.setBearerTokenFile("rotated-run-2-token"); - await startTurn(); + await startTurn(bridge); const requestCountBefore = bridge.requests.length; await tool.execute("call-2", {}); @@ -216,7 +217,7 @@ describe("Pi MCP tool results", () => { // Concurrent calls after a rotation coalesce into a single initialize handshake. bridge.setBearerTokenFile("rotated-run-3-token"); - await startTurn(); + await startTurn(bridge); const concurrentStart = bridge.requests.length; await Promise.all([tool.execute("call-3a", {}), tool.execute("call-3b", {})]); const concurrentMethods = bridge.requests.slice(concurrentStart).map((req) => req.method); @@ -271,10 +272,7 @@ describe("Pi MCP tool results", () => { bridge.setBearerTokenFile("run-2-token"); releaseSlow.resolve(); await inFlight; - await bridge.handlers.get("before_agent_start")!( - { systemPrompt: "" }, - { ui: { notify: assert.fail } }, - ); + await startTurn(bridge); const beforeGen2 = seen.length; await tool.execute("fresh-2", {}); @@ -316,11 +314,14 @@ describe("Pi MCP tool results", () => { }, }); const tool = bridge.tools[0]!; - const startTurn = () => - bridge.handlers.get("before_agent_start")!( - { systemPrompt: "" }, - { ui: { notify: assert.fail } }, + const expectRotatedRejection = async (pending: Promise) => { + const error = await pending.then( + () => undefined, + (caught: unknown) => caught, ); + assert.include(String(error), "rotated"); + assert.deepEqual(postedCalls, []); + }; // 1. Run A's call starts before Run B's turn; Run B renames the token file while Run A reads it. interceptFirstRead = true; @@ -328,29 +329,15 @@ describe("Pi MCP tool results", () => { await firstReadStarted.promise; bridge.setBearerTokenFile("run-2-token"); releaseFirstRead.resolve(); - let firstReadError: unknown; - try { - await waitingFirstRead; - } catch (caught) { - firstReadError = caught; - } - assert.include(String(firstReadError), "rotated"); - assert.deepEqual(postedCalls, []); + await expectRotatedRejection(waitingFirstRead); // 2. Run B's turn starts and syncs run-2-token, then token rotates to run-3-token during connect. - await startTurn(); + await startTurn(bridge); const waitingGen2 = tool.execute("waiting-gen2", { stale: true }); await initStarted.promise; bridge.setBearerTokenFile("run-3-token"); releaseInit.resolve(); - let error: unknown; - try { - await waitingGen2; - } catch (caught) { - error = caught; - } - assert.include(String(error), "rotated"); - assert.deepEqual(postedCalls, []); + await expectRotatedRejection(waitingGen2); }); }); diff --git a/packages/provider-pi/src/server/mcpExtensionSource.ts b/packages/provider-pi/src/server/mcpExtensionSource.ts index 25ac78eacb2d2..413ed892f8203 100644 --- a/packages/provider-pi/src/server/mcpExtensionSource.ts +++ b/packages/provider-pi/src/server/mcpExtensionSource.ts @@ -180,21 +180,17 @@ function createMcpClient(endpoint: string, initialToken: string, tokenFile: stri let needsReconnect = false; let connectInFlight: { readonly generation: number; readonly promise: Promise } | undefined; - const setToken = (nextToken: string) => { - if (nextToken === currentToken) return; - currentToken = nextToken; - process.env[TOKEN_ENV] = nextToken; - authGeneration += 1; - sessionId = undefined; - connectInFlight = undefined; - needsReconnect = true; - }; - const syncToken = async () => { if (tokenFile === undefined) return; try { const next = (await NodeFSP.readFile(tokenFile, "utf8")).trim(); - if (next.length > 0 && next !== currentToken) setToken(next); + if (next.length === 0 || next === currentToken) return; + currentToken = next; + process.env[TOKEN_ENV] = next; + authGeneration += 1; + sessionId = undefined; + connectInFlight = undefined; + needsReconnect = true; } catch { // Missing or transient file read keeps the current in-memory bearer. } @@ -299,19 +295,13 @@ function createMcpClient(endpoint: string, initialToken: string, tokenFile: stri }, async callTool(name: string, args: Record, signal?: AbortSignal) { const pinnedGeneration = authGeneration; - await syncToken(); - if (authGeneration !== pinnedGeneration) { - throw new Error("MCP credentials rotated while the tool call was waiting to send."); - } - while (needsReconnect) { + while (true) { + await syncToken(); if (authGeneration !== pinnedGeneration) { throw new Error("MCP credentials rotated while the tool call was waiting to send."); } + if (!needsReconnect) break; await connect(signal); - await syncToken(); - } - if (authGeneration !== pinnedGeneration) { - throw new Error("MCP credentials rotated while the tool call was waiting to send."); } return request("tools/call", { name, arguments: args }, signal); }, From d97fc163d376fd82e7cb6fe8ad3d2ab72d631299 Mon Sep 17 00:00:00 2001 From: Victor Vogel Date: Mon, 23 Nov 2026 01:28:51 +0000 Subject: [PATCH 14/34] fix(server): harden MCP credential unload records, error reasons, and output rejection causes Replace free-text detail on ProviderAdapterMcpRotationBlockedError with a structured reason union whose fixed public messages live in the error class, preserve OrchestratorDispatchError as cause on ThreadManagementRunOutputRejectedError while restricting MCP output rendering to SchemaError details, retain native-thread-scoped loadedMcpCredentialByThread records until unloads succeed across linked-environment, idle, detach, and MCP rotation paths, and tighten the stale-session and failed-unload retry tests. --- apps/server/src/mcp/toolkits/core.test.ts | 36 +- .../src/mcp/toolkits/thread/handlers.ts | 8 +- .../Adapters/ClaudeAdapterV2.ts | 2 +- .../ProviderSessionManager.test.ts | 130 ++++++- .../ProviderSessionManager.ts | 354 +++++++++++++----- .../ProviderTurnStartService.test.ts | 21 +- .../ThreadManagementService.ts | 1 + .../src/orchestration-v2/runtimeLayer.test.ts | 3 + packages/provider-acp/src/server/adapter.ts | 3 +- .../src/server/mcpOverAcpBridge.test.ts | 6 +- .../src/server/ProviderAdapter.ts | 15 +- .../src/server/mcpExtensionSource.test.ts | 6 +- 12 files changed, 468 insertions(+), 117 deletions(-) diff --git a/apps/server/src/mcp/toolkits/core.test.ts b/apps/server/src/mcp/toolkits/core.test.ts index 55126a99b4e0c..f7f654fd22948 100644 --- a/apps/server/src/mcp/toolkits/core.test.ts +++ b/apps/server/src/mcp/toolkits/core.test.ts @@ -1656,6 +1656,8 @@ it.effect( }, ); +const decodeSubmitOutputFixture = Schema.decodeUnknownEffect(Schema.Struct({ ok: Schema.Boolean })); + it.effect("t3_submit_output forwards caller run and attempt identity and surfaces rejection", () => Effect.gen(function* () { const calls: Array<{ @@ -1669,7 +1671,7 @@ it.effect("t3_submit_output forwards caller run and attempt identity and surface const runB = RunId.make("run-b"); const attemptB = RunAttemptId.make("attempt-b"); - let rejectNext: string | undefined; + let rejectNext: { readonly problem: string; readonly cause?: unknown } | undefined; const serverLayer = layerThreadToolkit.pipe( Layer.provideMerge(McpHttpServer.layerInProcessMcpServer), Layer.provide(NodeCrypto.layer), @@ -1684,12 +1686,13 @@ it.effect("t3_submit_output forwards caller run and attempt identity and surface callerAttemptId: input.callerAttemptId, }); if (rejectNext !== undefined) { - const problem = rejectNext; + const rejection = rejectNext; rejectNext = undefined; return Effect.fail( new ThreadManagement.ThreadManagementRunOutputRejectedError({ threadId: input.threadId, - problem, + problem: rejection.problem, + ...(rejection.cause === undefined ? {} : { cause: rejection.cause }), }), ); } @@ -1723,7 +1726,7 @@ it.effect("t3_submit_output forwards caller run and attempt identity and surface }); // An unbound credential names its run in the call; service rejections surface as invalid_request. - rejectNext = "This output was submitted for a turn that is no longer active."; + rejectNext = { problem: "This output was submitted for a turn that is no longer active." }; const unbound = yield* callWith(undefined, undefined, '{"ok":false}', runA).pipe( Effect.provide(serverLayer), ); @@ -1734,7 +1737,14 @@ it.effect("t3_submit_output forwards caller run and attempt identity and surface message: "This output was submitted for a turn that is no longer active.", }); - rejectNext = "This output was submitted for a turn that is no longer active."; + // Preserved dispatch causes stay out of MCP output; only SchemaError validation details append. + rejectNext = { + problem: "This output was submitted for a turn that is no longer active.", + cause: new OrchestratorDispatchError({ + commandId: CommandId.make("cmd-submit-stale"), + commandType: "run.output.submit", + }), + }; const stale = yield* callWith(runA, attemptA, '{"ok":false}').pipe(Effect.provide(serverLayer)); expect(stale.isError).toBe(true); expect(declaredFailure(stale)).toEqual({ @@ -1743,6 +1753,16 @@ it.effect("t3_submit_output forwards caller run and attempt identity and surface message: "This output was submitted for a turn that is no longer active.", }); + const schemaCause = yield* decodeSubmitOutputFixture({}).pipe(Effect.flip); + rejectNext = { problem: "The result does not match the schema.", cause: schemaCause }; + const invalidSchema = yield* callWith(runB, attemptB, "{}").pipe(Effect.provide(serverLayer)); + expect(invalidSchema.isError).toBe(true); + expect(declaredFailure(invalidSchema)).toEqual({ + _tag: "OrchestratorMcpFailure", + code: "invalid_request", + message: `The result does not match the schema.\n${schemaCause.message.slice(0, 2000)}`, + }); + // A bound credential outranks the argument. const active = yield* callWith(runB, attemptB, '{"ok":true}', runA).pipe( Effect.provide(serverLayer), @@ -1762,6 +1782,12 @@ it.effect("t3_submit_output forwards caller run and attempt identity and surface callerRunId: runA, callerAttemptId: attemptA, }, + { + threadId, + json: "{}", + callerRunId: runB, + callerAttemptId: attemptB, + }, { threadId, json: '{"ok":true}', diff --git a/apps/server/src/mcp/toolkits/thread/handlers.ts b/apps/server/src/mcp/toolkits/thread/handlers.ts index 52423efd4fab7..416a16b1493a8 100644 --- a/apps/server/src/mcp/toolkits/thread/handlers.ts +++ b/apps/server/src/mcp/toolkits/thread/handlers.ts @@ -8,6 +8,7 @@ import { type OrchestrationV2Command, } from "@t3tools/contracts"; import * as Effect from "effect/Effect"; +import * as Schema from "effect/Schema"; import { modelSelectionCommandType } from "@t3tools/shared/model"; import { topOfPinnedRunOrderKey } from "@t3tools/shared/pinOrderKey"; @@ -305,10 +306,9 @@ export const layer = McpToolAccess.toLayer(ThreadToolkit, { ? new OrchestratorMcpFailure({ code: "invalid_request", // The agent wrote the value, so it is told what in it did not fit. - message: - error.cause instanceof Error - ? `${error.message}\n${error.cause.message.slice(0, 2000)}` - : error.message, + message: Schema.isSchemaError(error.cause) + ? `${error.message}\n${error.cause.message.slice(0, 2000)}` + : error.message, }) : unavailable(), ), diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts index dd9490d2619a1..8d2d224132a0f 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts @@ -13288,7 +13288,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( driver: CLAUDE_PROVIDER, providerSessionId: input.providerSessionId, providerThreadId: turnInput.providerThread.id, - detail: "Cannot refresh MCP credentials on a retained Claude continuation query.", + reason: "continuation_query", }); if ( mcpOverrides.mcpServers === undefined || diff --git a/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts b/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts index 6d1e121a7ef34..2df7bf451e625 100644 --- a/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts +++ b/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts @@ -3862,13 +3862,15 @@ it.effect.each([ modelSelection, runtimePolicy, }); + const unloadFailedRunId = RunId.make("run-unload-failed-typed"); + const unloadFailedAttemptId = RunAttemptId.make("attempt-unload-failed-typed"); yield* manager.open({ threadId: unloadFailedThreadId, providerSessionId, modelSelection, runtimePolicy, - runId: RunId.make("run-unload-failed-typed"), - attemptId: RunAttemptId.make("attempt-unload-failed-typed"), + runId: unloadFailedRunId, + attemptId: unloadFailedAttemptId, requireRunScopedMcp: true, }); const stagedToken = (yield* mcpSessions.read( @@ -3887,9 +3889,34 @@ it.effect.each([ beforeFailedUnload!.authorizationHeader, ); + // Once the unload fault clears, retrying the same run and attempt succeeds with a bound credential. + yield* Ref.set(failUnload, false); + yield* openFor(manager, providerSessionId, unloadFailedThreadId, { + runId: unloadFailedRunId, + attemptId: unloadFailedAttemptId, + requireRunScopedMcp: true, + }); + const retriedConfig = yield* mcpSessions.read(unloadFailedThreadId); + assert.isDefined(retriedConfig); + assert.notEqual( + retriedConfig!.authorizationHeader, + beforeFailedUnload!.authorizationHeader, + ); + yield* runtime.resumeThread({ + threadId: unloadFailedThreadId, + providerThread: unloadFailedProviderThread, + modelSelection, + runtimePolicy, + }); + assert.isTrue(Option.isSome(yield* Queue.poll(unloads))); + const resolvedRetried = yield* registry.resolve(rawBearer(retriedConfig)); + assert.isDefined(resolvedRetried); + assert.equal(resolvedRetried!.thread.runId, unloadFailedRunId); + assert.equal(resolvedRetried!.thread.attemptId, unloadFailedAttemptId); + assert.isUndefined(yield* registry.resolve(rawBearer(beforeFailedUnload))); + // Once background work finishes, reloading a thread whose loaded credential became unbound // during keepLoaded retires that old unbound credential. - yield* Ref.set(failUnload, false); yield* openFor(manager, providerSessionId, threadId, { runId: RunId.make("run-bg-3-retire"), attemptId: RunAttemptId.make("attempt-bg-3-retire"), @@ -3971,6 +3998,103 @@ it.effect.each([ ); } + // A failed linked-environment unload keeps the loaded MCP credential record so MCP refresh + // still rolls back a staged credential instead of bypassing rotation. + yield* Ref.set(sessionBackgroundWorkProbe, Effect.succeed(false)); + const { + threadId: linksFailThreadId, + providerThread: linksFailProviderThread, + loadedConfig: beforeLinksFail, + loadedToken: beforeLinksFailToken, + } = yield* attachLoadedThread("links-unload-fail"); + yield* settings.updateSettings({ linkedEnvironmentsEnabled: true }); + yield* openFor(manager, providerSessionId, linksFailThreadId, { + runId: RunId.make("run-links-fail-typed"), + attemptId: RunAttemptId.make("attempt-links-fail-typed"), + requireRunScopedMcp: true, + }); + const stagedLinksToken = rawBearer(yield* mcpSessions.read(linksFailThreadId)); + assert.notEqual(stagedLinksToken, beforeLinksFailToken); + yield* Ref.set(failUnload, true); + yield* runtime.resumeThread({ + threadId: linksFailThreadId, + providerThread: linksFailProviderThread, + modelSelection, + runtimePolicy, + }); + assert.isUndefined(yield* registry.resolve(stagedLinksToken)); + assert.equal( + (yield* mcpSessions.read(linksFailThreadId))?.authorizationHeader, + beforeLinksFail.authorizationHeader, + ); + + // A failed detach unload keeps the loaded MCP credential record so reattaching with a + // rotated credential still enforces reload/rollback and retries cleanly once unload recovers. + yield* Ref.set(failUnload, false); + const { + threadId: detachFailThreadId, + providerThread: detachFailProviderThread, + loadedConfig: beforeDetachFail, + loadedToken: beforeDetachFailToken, + } = yield* attachLoadedThread("detach-unload-fail"); + yield* eventSink.write({ + events: [ + { + id: yield* idAllocator.allocate.event({ threadId: detachFailThreadId }), + type: "provider-thread.updated", + threadId: detachFailThreadId, + occurredAt: now, + payload: detachFailProviderThread, + }, + ], + }); + yield* Ref.set(failUnload, true); + yield* manager.detach({ providerSessionId, threadId: detachFailThreadId }); + const detachRetryRunId = RunId.make("run-detach-fail-typed"); + const detachRetryAttemptId = RunAttemptId.make("attempt-detach-fail-typed"); + yield* openFor(manager, providerSessionId, detachFailThreadId, { + runId: detachRetryRunId, + attemptId: detachRetryAttemptId, + requireRunScopedMcp: true, + }); + const stagedDetachToken = rawBearer(yield* mcpSessions.read(detachFailThreadId)); + assert.notEqual(stagedDetachToken, beforeDetachFailToken); + yield* runtime.resumeThread({ + threadId: detachFailThreadId, + providerThread: detachFailProviderThread, + modelSelection, + runtimePolicy, + }); + assert.isUndefined(yield* registry.resolve(stagedDetachToken)); + assert.equal( + (yield* mcpSessions.read(detachFailThreadId))?.authorizationHeader, + beforeDetachFail.authorizationHeader, + ); + yield* Ref.set(failUnload, false); + yield* openFor(manager, providerSessionId, detachFailThreadId, { + runId: detachRetryRunId, + attemptId: detachRetryAttemptId, + requireRunScopedMcp: true, + }); + const retriedDetachConfig = yield* mcpSessions.read(detachFailThreadId); + assert.isDefined(retriedDetachConfig); + assert.notEqual( + retriedDetachConfig!.authorizationHeader, + beforeDetachFail.authorizationHeader, + ); + yield* runtime.resumeThread({ + threadId: detachFailThreadId, + providerThread: detachFailProviderThread, + modelSelection, + runtimePolicy, + }); + assert.isTrue(Option.isSome(yield* Queue.poll(unloads))); + const resolvedDetachRetry = yield* registry.resolve(rawBearer(retriedDetachConfig)); + assert.isDefined(resolvedDetachRetry); + assert.equal(resolvedDetachRetry!.thread.runId, detachRetryRunId); + assert.equal(resolvedDetachRetry!.thread.attemptId, detachRetryAttemptId); + assert.isUndefined(yield* registry.resolve(beforeDetachFailToken)); + yield* manager.close(providerSessionId); }); diff --git a/apps/server/src/orchestration-v2/ProviderSessionManager.ts b/apps/server/src/orchestration-v2/ProviderSessionManager.ts index acfcc4b3d8011..ed9462bced6a6 100644 --- a/apps/server/src/orchestration-v2/ProviderSessionManager.ts +++ b/apps/server/src/orchestration-v2/ProviderSessionManager.ts @@ -333,10 +333,13 @@ export class ProviderSessionManagerV2 extends Context.Service< interface LiveSessionEntry { readonly attachedThreadIds: ReadonlySet; readonly loadedProviderThreadKeyByThread: ReadonlyMap; - /** Credential that was active when this thread was last loaded natively. */ + /** Native thread and credential that were active when this thread was last loaded natively. */ readonly loadedMcpCredentialByThread: ReadonlyMap< ThreadId, - McpProviderSession.McpProviderSessionConfig + { + readonly providerThread: string; + readonly credential: McpProviderSession.McpProviderSessionConfig; + } >; /** Last (runId, attemptId) already evaluated for per-turn MCP rotation on this thread. */ readonly mcpTurnCheckedKeyByThread: ReadonlyMap; @@ -441,7 +444,7 @@ function isLoadKeyFor( providerThread: Parameters[0], ): boolean { return ( - loadKey === undefined || + loadKey !== undefined && (JSON.parse(loadKey) as { providerThread: string }).providerThread === providerThreadRuntimeKey(providerThread) ); @@ -665,26 +668,6 @@ export const layerWithOptions = ( updated.set(key, { ...entry, mcpCredentialIdsByThread, mcpOwnerSessionIdByThread }); return updated; }); - const removeSessionMcpCredential = ( - providerSessionId: ProviderSessionId, - threadId: ThreadId, - mcpCredentialId: string, - ) => - Ref.update(sessions, (current) => { - const key = sessionKey(providerSessionId); - const entry = current.get(key); - const existing = entry?.mcpCredentialIdsByThread.get(threadId); - if (entry === undefined || existing?.has(mcpCredentialId) !== true) return current; - const remaining = new Set(existing); - remaining.delete(mcpCredentialId); - const mcpCredentialIdsByThread = new Map(entry.mcpCredentialIdsByThread); - if (remaining.size === 0) { - mcpCredentialIdsByThread.delete(threadId); - } else { - mcpCredentialIdsByThread.set(threadId, remaining); - } - return new Map(current).set(key, { ...entry, mcpCredentialIdsByThread }); - }); const syncLoadedMcpCredential = ( threadId: ThreadId, credentialId: string, @@ -696,13 +679,13 @@ export const layerWithOptions = ( const loaded = entry.loadedMcpCredentialByThread.get(threadId); if ( loaded === undefined || - McpProviderSession.mcpCredentialIdOf(loaded) !== credentialId + McpProviderSession.mcpCredentialIdOf(loaded.credential) !== credentialId ) { continue; } next ??= new Map(current); const loadedMcpCredentialByThread = new Map(entry.loadedMcpCredentialByThread); - loadedMcpCredentialByThread.set(threadId, updatedCredential); + loadedMcpCredentialByThread.set(threadId, { ...loaded, credential: updatedCredential }); next.set(key, { ...entry, loadedMcpCredentialByThread }); } return next ?? current; @@ -2029,8 +2012,6 @@ export const layerWithOptions = ( attachedThreadIds.delete(input.threadId); const loadedProviderThreadKeyByThread = new Map(entry.loadedProviderThreadKeyByThread); loadedProviderThreadKeyByThread.delete(input.threadId); - const loadedMcpCredentialByThread = new Map(entry.loadedMcpCredentialByThread); - loadedMcpCredentialByThread.delete(input.threadId); const mcpTurnCheckedKeyByThread = new Map(entry.mcpTurnCheckedKeyByThread); mcpTurnCheckedKeyByThread.delete(input.threadId); const mcpOwnerSessionIdByThread = new Map(entry.mcpOwnerSessionIdByThread); @@ -2042,7 +2023,6 @@ export const layerWithOptions = ( ...entry, attachedThreadIds, loadedProviderThreadKeyByThread, - loadedMcpCredentialByThread, mcpTurnCheckedKeyByThread, mcpOwnerSessionIdByThread, linkedEnvironmentsByThread, @@ -2080,12 +2060,9 @@ export const layerWithOptions = ( } const loadedProviderThreadKeyByThread = new Map(entry.loadedProviderThreadKeyByThread); loadedProviderThreadKeyByThread.delete(input.threadId); - const loadedMcpCredentialByThread = new Map(entry.loadedMcpCredentialByThread); - loadedMcpCredentialByThread.delete(input.threadId); return new Map(current).set(key, { ...entry, loadedProviderThreadKeyByThread, - loadedMcpCredentialByThread, }); }); @@ -2093,6 +2070,7 @@ export const layerWithOptions = ( const markProviderThreadLoaded = (input: { readonly providerSessionId: ProviderSessionId; readonly threadId: ThreadId; + readonly providerThread: Parameters[0]; readonly providerThreadKey: string; readonly linkedEnvironments: boolean | null | undefined; readonly mcpCredential?: McpProviderSession.McpProviderSessionConfig | undefined; @@ -2108,7 +2086,10 @@ export const layerWithOptions = ( const loadedMcpCredentialByThread = input.mcpCredential === undefined ? entry.loadedMcpCredentialByThread - : new Map(entry.loadedMcpCredentialByThread).set(input.threadId, input.mcpCredential); + : new Map(entry.loadedMcpCredentialByThread).set(input.threadId, { + providerThread: providerThreadRuntimeKey(input.providerThread), + credential: input.mcpCredential, + }); const linkedEnvironmentsByThread = new Map(entry.linkedEnvironmentsByThread); if ( input.linkedEnvironments !== undefined && @@ -2587,6 +2568,29 @@ export const layerWithOptions = ( (effect) => effect.pipe(Effect.orElseSucceed(() => undefined)), ); + const withoutLoadedMcpCredential = ( + latest: LiveSessionEntry, + threadId: ThreadId, + match: { + readonly providerThread?: string; + readonly credentialId?: string; + }, + ) => { + const loaded = latest.loadedMcpCredentialByThread.get(threadId); + if ( + loaded === undefined || + latest.loadedProviderThreadKeyByThread.has(threadId) || + (match.providerThread !== undefined && loaded.providerThread !== match.providerThread) || + (match.credentialId !== undefined && + McpProviderSession.mcpCredentialIdOf(loaded.credential) !== match.credentialId) + ) { + return latest.loadedMcpCredentialByThread; + } + const next = new Map(latest.loadedMcpCredentialByThread); + next.delete(threadId); + return next; + }; + const unloadIdleThread = Effect.fn("ProviderSessionManager.unloadIdleThread")( function* (input: { readonly providerSessionId: ProviderSessionId; @@ -2641,23 +2645,23 @@ export const layerWithOptions = ( const idleThreadUnloads = new Map(latest.idleThreadUnloads); idleThreadUnloads.delete(input.providerThreadId); // A native thread a fresh session replaced is not what the app thread has loaded. - const isCurrent = isLoadKeyFor( - latest.loadedProviderThreadKeyByThread.get(input.threadId), - pending.providerThread, - ); + const loadKey = latest.loadedProviderThreadKeyByThread.get(input.threadId); + const loadedMcp = latest.loadedMcpCredentialByThread.get(input.threadId); + const unloadingRuntimeKey = providerThreadRuntimeKey(pending.providerThread); + const isCurrent = + loadKey === undefined + ? loadedMcp === undefined || loadedMcp.providerThread === unloadingRuntimeKey + : isLoadKeyFor(loadKey, pending.providerThread); const loadedProviderThreadKeyByThread = new Map( latest.loadedProviderThreadKeyByThread, ); - const loadedMcpCredentialByThread = new Map(latest.loadedMcpCredentialByThread); if (isCurrent) { loadedProviderThreadKeyByThread.delete(input.threadId); - loadedMcpCredentialByThread.delete(input.threadId); } const updated = new Map(current); updated.set(key, { ...latest, loadedProviderThreadKeyByThread, - loadedMcpCredentialByThread, idleThreadUnloads, }); return [isCurrent, updated]; @@ -2684,10 +2688,28 @@ export const layerWithOptions = ( Effect.tap(() => Ref.update(sessions, (current) => { const latest = current.get(key); - if (latest?.runtime !== entry.runtime || !unloadsLoadedThread) return current; + if ( + latest?.runtime !== entry.runtime || + latest.loadedProviderThreadKeyByThread.has(input.threadId) + ) { + return current; + } + const unloadingRuntimeKey = providerThreadRuntimeKey(pending.providerThread); + const loadedMcpCredentialByThread = withoutLoadedMcpCredential( + latest, + input.threadId, + { providerThread: unloadingRuntimeKey }, + ); + const clearedLoadedMcp = + loadedMcpCredentialByThread !== latest.loadedMcpCredentialByThread; + if (!unloadsLoadedThread && !clearedLoadedMcp) return current; const linkedEnvironmentsByThread = new Map(latest.linkedEnvironmentsByThread); linkedEnvironmentsByThread.delete(input.threadId); - return new Map(current).set(key, { ...latest, linkedEnvironmentsByThread }); + return new Map(current).set(key, { + ...latest, + linkedEnvironmentsByThread, + loadedMcpCredentialByThread, + }); }), ), Effect.catchCause((cause) => @@ -2761,14 +2783,11 @@ export const layerWithOptions = ( latest.loadedProviderThreadKeyByThread, ); loadedProviderThreadKeyByThread.delete(input.threadId); - const loadedMcpCredentialByThread = new Map(latest.loadedMcpCredentialByThread); - loadedMcpCredentialByThread.delete(input.threadId); return [ true, new Map(current).set(key, { ...latest, loadedProviderThreadKeyByThread, - loadedMcpCredentialByThread, }), ] as const; }); @@ -2781,7 +2800,15 @@ export const layerWithOptions = ( if (latest?.runtime !== entry.runtime) return current; const linkedEnvironmentsByThread = new Map(latest.linkedEnvironmentsByThread); linkedEnvironmentsByThread.delete(input.threadId); - return new Map(current).set(key, { ...latest, linkedEnvironmentsByThread }); + return new Map(current).set(key, { + ...latest, + linkedEnvironmentsByThread, + loadedMcpCredentialByThread: withoutLoadedMcpCredential( + latest, + input.threadId, + { providerThread: providerThreadRuntimeKey(input.providerThread) }, + ), + }); }), ), Effect.catchCause((cause) => @@ -2805,7 +2832,12 @@ export const layerWithOptions = ( }) { const key = sessionKey(input.providerSessionId); const entry = (yield* Ref.get(sessions)).get(key); - const loadedCredential = entry?.loadedMcpCredentialByThread.get(input.threadId); + const providerThreadKey = providerThreadRuntimeKey(input.providerThread); + const loadedEntry = entry?.loadedMcpCredentialByThread.get(input.threadId); + const loadedCredential = + loadedEntry !== undefined && loadedEntry.providerThread === providerThreadKey + ? loadedEntry.credential + : undefined; const unloadThread = entry?.runtime.unloadThread; if ( entry === undefined || @@ -2830,7 +2862,52 @@ export const layerWithOptions = ( yield* threadAttachment.withLock( threadAttachmentKey(input), Effect.gen(function* () { - if (hasBusyTurn(entry, input.providerThread.id)) return; + const isStillCurrentLoaded = ( + latest: LiveSessionEntry | undefined, + ): latest is LiveSessionEntry => { + if (latest?.runtime !== entry.runtime) return false; + const latestLoaded = latest.loadedMcpCredentialByThread.get(input.threadId); + return ( + latestLoaded !== undefined && + latestLoaded.providerThread === providerThreadKey && + McpProviderSession.mcpCredentialIdOf(latestLoaded.credential) === + loadedCredentialId + ); + }; + const pruneSessionCredential = ( + current: ReadonlyMap, + latest: LiveSessionEntry, + credentialId: string, + ) => { + const existingIds = latest.mcpCredentialIdsByThread.get(input.threadId); + let mcpCredentialIdsByThread = latest.mcpCredentialIdsByThread; + if (existingIds?.has(credentialId)) { + const nextIds = new Set(existingIds); + nextIds.delete(credentialId); + const nextMap = new Map(latest.mcpCredentialIdsByThread); + if (nextIds.size === 0) nextMap.delete(input.threadId); + else nextMap.set(input.threadId, nextIds); + mcpCredentialIdsByThread = nextMap; + } + const heldElsewhere = + isMcpCredentialReserved(input.threadId, credentialId) || + Array.from(current.values()).some((other) => { + if (other === latest) return false; + const otherLoaded = other.loadedMcpCredentialByThread.get(input.threadId); + return ( + other.mcpCredentialIdsByThread.get(input.threadId)?.has(credentialId) === + true || + (otherLoaded !== undefined && + McpProviderSession.mcpCredentialIdOf(otherLoaded.credential) === + credentialId) + ); + }); + return { mcpCredentialIdsByThread, heldElsewhere }; + }; + const locked = (yield* Ref.get(sessions)).get(key); + if (!isStillCurrentLoaded(locked) || hasBusyTurn(locked, input.providerThread.id)) { + return; + } // Unloading ends the thread's background work; a failed probe keeps it loaded too. const hasPendingWork = entry.runtime.hasPendingBackgroundWorkForThread === undefined @@ -2848,7 +2925,9 @@ export const layerWithOptions = ( // Keep the loaded thread on its credential and never mutate an issued bearer's run identity. // Without a reload the thread keeps its loaded credential, unbound so the turn's own // run can still submit through it; the agent then names its run in the call. - const keepLoaded = (detail: string) => + const keepLoaded = ( + reason: ProviderAdapter.ProviderAdapterMcpRotationBlockedError["reason"], + ) => mcpPrepareLock.withLock( input.threadId, Effect.gen(function* () { @@ -2860,12 +2939,25 @@ export const layerWithOptions = ( ) { return; } - yield* mcpSessionRegistry.revokeCredential(currentCredentialId); - yield* removeSessionMcpCredential( - input.providerSessionId, - input.threadId, - currentCredentialId, - ); + const rollback = yield* Ref.modify(sessions, (current) => { + const latest = current.get(key); + if (!isStillCurrentLoaded(latest)) return [undefined, current] as const; + const { mcpCredentialIdsByThread, heldElsewhere } = pruneSessionCredential( + current, + latest, + currentCredentialId, + ); + return [ + { revokeStaged: !heldElsewhere }, + new Map(current).set(key, { ...latest, mcpCredentialIdsByThread }), + ] as const; + }); + if (rollback === undefined) { + return; + } + if (rollback.revokeStaged) { + yield* mcpSessionRegistry.revokeCredential(currentCredentialId); + } const loadedRawToken = loadedCredential.authorizationHeader.replace( /^Bearer\s+/, "", @@ -2873,17 +2965,26 @@ export const layerWithOptions = ( const resolvedLoaded = yield* mcpSessionRegistry.resolve(loadedRawToken); // Capability removals revoke immediately; the thread then holds no working token. if (resolvedLoaded === undefined) { - yield* mcpSessions.clear(input.threadId); - yield* recordMcpTurnChecked( - input.providerSessionId, - input.threadId, - undefined, - ); + if (rollback.revokeStaged) { + yield* mcpSessions.clear(input.threadId); + } + yield* Ref.update(sessions, (current) => { + const latest = current.get(key); + if ( + latest?.runtime !== entry.runtime || + !latest.mcpTurnCheckedKeyByThread.has(input.threadId) + ) { + return current; + } + const mcpTurnCheckedKeyByThread = new Map(latest.mcpTurnCheckedKeyByThread); + mcpTurnCheckedKeyByThread.delete(input.threadId); + return new Map(current).set(key, { ...latest, mcpTurnCheckedKeyByThread }); + }); return yield* new ProviderAdapter.ProviderAdapterMcpRotationBlockedError({ driver: entry.runtime.driver, providerSessionId: input.providerSessionId, providerThreadId: input.providerThread.id, - detail, + reason, }); } yield* mcpSessionRegistry.releaseRunBinding(loadedCredentialId); @@ -2897,40 +2998,33 @@ export const layerWithOptions = ( browserToolsAvailable: resolvedLoaded.capabilities.has("preview"), capabilities: resolvedLoaded.capabilities, }; - yield* mcpSessions.set(unbound); + if (rollback.revokeStaged) { + yield* mcpSessions.set(unbound); + } yield* syncLoadedMcpCredential(input.threadId, loadedCredentialId, unbound); }), ); if (hasPendingWork) { - return yield* keepLoaded( - "Cannot refresh MCP credentials while background work is running on this thread.", - ); + return yield* keepLoaded("background_work"); } const unloadingCredential = yield* Ref.modify(sessions, (current) => { const latest = current.get(key); - const latestLoaded = latest?.loadedMcpCredentialByThread.get(input.threadId); - const latestThreadKey = latest?.loadedProviderThreadKeyByThread.get(input.threadId); - if ( - latest?.runtime !== entry.runtime || - latestLoaded === undefined || - latestThreadKey === undefined || - McpProviderSession.mcpCredentialIdOf(latestLoaded) !== loadedCredentialId || - hasBusyTurn(latest, input.providerThread.id) - ) { + if (!isStillCurrentLoaded(latest) || hasBusyTurn(latest, input.providerThread.id)) { return [undefined, current] as const; } + const latestLoaded = latest.loadedMcpCredentialByThread.get(input.threadId)!; + if (!latest.loadedProviderThreadKeyByThread.has(input.threadId)) { + return [latestLoaded.credential, current] as const; + } const loadedProviderThreadKeyByThread = new Map( latest.loadedProviderThreadKeyByThread, ); loadedProviderThreadKeyByThread.delete(input.threadId); - const loadedMcpCredentialByThread = new Map(latest.loadedMcpCredentialByThread); - loadedMcpCredentialByThread.delete(input.threadId); return [ - latestLoaded, + latestLoaded.credential, new Map(current).set(key, { ...latest, loadedProviderThreadKeyByThread, - loadedMcpCredentialByThread, }), ] as const; }); @@ -2949,15 +3043,49 @@ export const layerWithOptions = ( if (!unloaded) { // The thread may or may not have unloaded, so it stays marked unloaded and the next // step resumes it natively, on the old credential either way. - return yield* keepLoaded("Could not reload the thread to refresh MCP credentials."); + return yield* keepLoaded("reload_failed"); } - if (unloadingCredential.runId === undefined) { - yield* mcpSessionRegistry.revokeCredential(loadedCredentialId); - yield* removeSessionMcpCredential( - input.providerSessionId, + const threadCurrent = yield* mcpSessions.read(input.threadId); + const isThreadCurrent = + threadCurrent !== undefined && + McpProviderSession.mcpCredentialIdOf(threadCurrent) === loadedCredentialId; + const shouldRevoke = yield* Ref.modify(sessions, (current) => { + const latest = current.get(key); + if (latest?.runtime !== entry.runtime) return [false, current] as const; + const loadedMcpCredentialByThread = withoutLoadedMcpCredential( + latest, input.threadId, + { providerThread: providerThreadKey, credentialId: loadedCredentialId }, + ); + const kept = loadedMcpCredentialByThread.get(input.threadId); + const stillHeld = + kept !== undefined && + McpProviderSession.mcpCredentialIdOf(kept.credential) === loadedCredentialId; + if (stillHeld || unloadingCredential.runId !== undefined) { + if (loadedMcpCredentialByThread === latest.loadedMcpCredentialByThread) { + return [false, current] as const; + } + return [ + false, + new Map(current).set(key, { ...latest, loadedMcpCredentialByThread }), + ] as const; + } + const { mcpCredentialIdsByThread, heldElsewhere } = pruneSessionCredential( + current, + latest, loadedCredentialId, ); + return [ + !isThreadCurrent && !heldElsewhere, + new Map(current).set(key, { + ...latest, + loadedMcpCredentialByThread, + mcpCredentialIdsByThread, + }), + ] as const; + }); + if (shouldRevoke) { + yield* mcpSessionRegistry.revokeCredential(loadedCredentialId); } }), ); @@ -3152,6 +3280,7 @@ export const layerWithOptions = ( markProviderThreadLoaded({ providerSessionId, threadId: input.threadId, + providerThread, providerThreadKey: providerThreadLoadKey({ runtime, providerThread, @@ -3222,6 +3351,7 @@ export const layerWithOptions = ( markProviderThreadLoaded({ providerSessionId, threadId, + providerThread, providerThreadKey: providerThreadLoadKey({ runtime, providerThread, @@ -3253,6 +3383,7 @@ export const layerWithOptions = ( markProviderThreadLoaded({ providerSessionId, threadId: input.targetThreadId, + providerThread, providerThreadKey: providerThreadLoadKey({ runtime, providerThread, @@ -4304,18 +4435,32 @@ export const layerWithOptions = ( Option.none<{ readonly entry: LiveSessionEntry; readonly idleUnloadFibers: ReadonlyArray>; + readonly detachedCredentialId: string | undefined; }>(), current, ] as const; } + const detachedLoaded = entry.loadedMcpCredentialByThread.get(input.threadId); + const detachedCredentialId = + detachedLoaded === undefined + ? undefined + : McpProviderSession.mcpCredentialIdOf(detachedLoaded.credential); const attachedThreadIds = new Set(entry.attachedThreadIds); attachedThreadIds.delete(input.threadId); const loadedProviderThreadKeyByThread = new Map( entry.loadedProviderThreadKeyByThread, ); loadedProviderThreadKeyByThread.delete(input.threadId); - const loadedMcpCredentialByThread = new Map(entry.loadedMcpCredentialByThread); - loadedMcpCredentialByThread.delete(input.threadId); + // Keep loadedMcpCredentialByThread until the shared runtime's native unload succeeds. + const loadedMcpCredentialByThread = + entry.supportsMultipleProviderThreads && + entry.exposedRuntime.unloadThread !== undefined + ? entry.loadedMcpCredentialByThread + : (() => { + const next = new Map(entry.loadedMcpCredentialByThread); + next.delete(input.threadId); + return next; + })(); const mcpTurnCheckedKeyByThread = new Map(entry.mcpTurnCheckedKeyByThread); mcpTurnCheckedKeyByThread.delete(input.threadId); const mcpOwnerSessionIdByThread = new Map(entry.mcpOwnerSessionIdByThread); @@ -4354,6 +4499,7 @@ export const layerWithOptions = ( Option.some({ entry: updatedEntry, idleUnloadFibers, + detachedCredentialId, }), updated, ] as const; @@ -4364,6 +4510,9 @@ export const layerWithOptions = ( }); } const detached = Option.map(detachResult, (result) => result.entry); + const detachedCredentialId = Option.isSome(detachResult) + ? detachResult.value.detachedCredentialId + : undefined; // Plain detaches preserve credentials held by live shared providers across workspace handoffs. if (input.revokeMcpCredential === true) { yield* clearMcpSession(input.threadId); @@ -4405,6 +4554,41 @@ export const layerWithOptions = ( } yield* unloadThread({ providerThread }).pipe( Effect.timeout(UNLOAD_THREAD_TIMEOUT_MS), + Effect.tap(() => + Ref.update(sessions, (current) => { + const latest = current.get(key); + if ( + latest?.runtime !== detached.value.runtime || + latest.attachedThreadIds.has(ownerThreadId) + ) { + return current; + } + if ( + ownerThreadId === input.threadId && + detachedCredentialId === undefined + ) { + return current; + } + const loadedMcpCredentialByThread = withoutLoadedMcpCredential( + latest, + ownerThreadId, + { + providerThread: providerThreadRuntimeKey(providerThread), + ...(ownerThreadId === input.threadId && + detachedCredentialId !== undefined + ? { credentialId: detachedCredentialId } + : {}), + }, + ); + if (loadedMcpCredentialByThread === latest.loadedMcpCredentialByThread) { + return current; + } + return new Map(current).set(key, { + ...latest, + loadedMcpCredentialByThread, + }); + }), + ), Effect.catchCause((cause) => Effect.logWarning("orchestration-v2.driver-session.detach-unload-failed", { providerSessionId: input.providerSessionId, diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts index 7b932d5d955f9..8b6e20d8b664a 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts @@ -3404,16 +3404,15 @@ effectIt.effect( "fails the run instead of replacing a native thread when active background work blocks MCP rotation", () => Effect.gen(function* () { - const detail = - "Cannot refresh MCP credentials while background work is running on this thread."; + const blockedError = new ProviderAdapter.ProviderAdapterMcpRotationBlockedError({ + driver: ProviderDriverKind.make("codex"), + providerSessionId: ProviderSessionId.make("provider-session-mcp-blocked"), + providerThreadId: ProviderThreadId.make("new-provider-thread"), + reason: "background_work", + }); const harness = makeLocalCommandHarness({ text: "Continue", - resumeFailure: new ProviderAdapter.ProviderAdapterMcpRotationBlockedError({ - driver: ProviderDriverKind.make("codex"), - providerSessionId: ProviderSessionId.make("provider-session-mcp-blocked"), - providerThreadId: ProviderThreadId.make("new-provider-thread"), - detail, - }), + resumeFailure: blockedError, }); const exit = yield* Effect.exit(harness.start); @@ -3431,7 +3430,11 @@ effectIt.effect( { type: "error", title: "Provider turn failed to start", - failure: { class: "provider_error", message: detail }, + failure: { + class: "provider_error", + message: + "Cannot refresh MCP credentials while background work is running on this thread.", + }, }, ]); }), diff --git a/apps/server/src/orchestration-v2/ThreadManagementService.ts b/apps/server/src/orchestration-v2/ThreadManagementService.ts index c7b590f054f85..0a1b6a426ac9e 100644 --- a/apps/server/src/orchestration-v2/ThreadManagementService.ts +++ b/apps/server/src/orchestration-v2/ThreadManagementService.ts @@ -1098,6 +1098,7 @@ const make = Effect.gen(function* () { error.cause.reason === "stopped" ? "This turn was stopped and takes no result." : "This output was submitted for a turn that is no longer active.", + cause: error, }), ) : Effect.fail(error), diff --git a/apps/server/src/orchestration-v2/runtimeLayer.test.ts b/apps/server/src/orchestration-v2/runtimeLayer.test.ts index 9f052ea33c4d7..1aa4b853329d8 100644 --- a/apps/server/src/orchestration-v2/runtimeLayer.test.ts +++ b/apps/server/src/orchestration-v2/runtimeLayer.test.ts @@ -12173,6 +12173,9 @@ it.layer(layerSharedApplicationDataPlaneTest)("run output after a stop", (it) => .pipe(Effect.flip); assert.equal(rejected._tag, "ThreadManagementRunOutputRejectedError"); assert.include(rejected.message, "was stopped"); + assert.instanceOf(rejected.cause, Orchestrator.OrchestratorDispatchError); + assert.instanceOf(rejected.cause.cause, Orchestrator.RunOutputDispatchRejectionError); + assert.equal(rejected.cause.cause.reason, "stopped"); const after = yield* orchestrator.getThreadProjection(threadId); assert.isUndefined(after.runs[0]?.output); }), diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts index 6f4b7be9cd634..ddc7a0e4584b2 100644 --- a/packages/provider-acp/src/server/adapter.ts +++ b/packages/provider-acp/src/server/adapter.ts @@ -8147,8 +8147,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( driver, providerSessionId: input.providerSessionId, providerThreadId: options.providerThreadId, - detail: - "Cannot refresh MCP credentials while background work is running on this thread.", + reason: "background_work", }); } return true; diff --git a/packages/provider-acp/src/server/mcpOverAcpBridge.test.ts b/packages/provider-acp/src/server/mcpOverAcpBridge.test.ts index 8f8d6a73bc7ce..e856a7397feea 100644 --- a/packages/provider-acp/src/server/mcpOverAcpBridge.test.ts +++ b/packages/provider-acp/src/server/mcpOverAcpBridge.test.ts @@ -366,12 +366,13 @@ describe("AcpMcpOverAcpBridge", () => { const inFlight = yield* callTool("slow_call").pipe(Effect.forkChild); yield* Effect.promise(() => slowCallStarted.promise); - // Rotate auth while generation-1 call is in flight, then let generation-1 finish. + // Rotate auth while generation-1 is in flight, establish session-2 first, then let generation-1 finish. bridge.setAuthorization("Bearer run-2-token"); + expect(yield* callTool()).toEqual({ content: [] }); releaseSlowCall.resolve(); yield* Fiber.join(inFlight); - // Generation-2 call must transparently re-initialize with run-2-token, not reuse session-1. + // A call after the late generation-1 response must still use session-2, not stale session-1. expect(yield* callTool()).toEqual({ content: [] }); expect(seen).toEqual([ { authorization: "Bearer run-1-token", sessionId: null, method: "initialize" }, @@ -383,6 +384,7 @@ describe("AcpMcpOverAcpBridge", () => { method: "notifications/initialized", }, { authorization: "Bearer run-2-token", sessionId: "session-2", method: "tools/call" }, + { authorization: "Bearer run-2-token", sessionId: "session-2", method: "tools/call" }, ]); return; } diff --git a/packages/provider-core/src/server/ProviderAdapter.ts b/packages/provider-core/src/server/ProviderAdapter.ts index e415718aeb62d..ef0316ee108f5 100644 --- a/packages/provider-core/src/server/ProviderAdapter.ts +++ b/packages/provider-core/src/server/ProviderAdapter.ts @@ -320,8 +320,8 @@ export class ProviderAdapterThreadInUseError extends Schema.TaggedError()( "ProviderAdapterMcpRotationBlockedError", @@ -329,11 +329,18 @@ export class ProviderAdapterMcpRotationBlockedError extends Schema.TaggedError

{ const inFlight = tool.execute("late-1", {}); await slowStarted.promise; bridge.setBearerTokenFile("run-2-token"); - releaseSlow.resolve(); - await inFlight; await startTurn(bridge); const beforeGen2 = seen.length; await tool.execute("fresh-2", {}); + releaseSlow.resolve(); + await inFlight; + await tool.execute("fresh-3", {}); assert.deepEqual(seen.slice(beforeGen2), [ { method: "initialize", auth: "Bearer run-2-token" }, { method: "notifications/initialized", auth: "Bearer run-2-token", sid: "fresh-sid-2" }, { method: "tools/call", auth: "Bearer run-2-token", sid: "fresh-sid-2" }, + { method: "tools/call", auth: "Bearer run-2-token", sid: "fresh-sid-2" }, ]); return; } From e8c463963674cc4427a390b88c4a880cf41ac3e6 Mon Sep 17 00:00:00 2001 From: Victor Vogel Date: Mon, 23 Nov 2026 11:20:28 +0000 Subject: [PATCH 15/34] test(server): a warm Claude process with a rotated MCP credential is still replaced when it missed terminal messages --- .../Adapters/ClaudeAdapterV2.test.ts | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts index b91fbb3cc91f4..a0f2ac38e549a 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts @@ -11409,9 +11409,11 @@ describe("ClaudeAdapterV2 background wake turns", () => { readonly scheduledWakeup?: boolean; readonly wakeFiresDuringRead?: boolean; readonly pinnedHead?: string; + readonly rotateMcp?: boolean; }) { const fileSystem = yield* FileSystem.FileSystem; const path = yield* Path.Path; + const mcpSessions = yield* McpProviderSessions.McpProviderSessions; const configDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-claude-stale-" }); const projectDir = path.join(configDir, "projects", "-workspace"); yield* fileSystem.makeDirectory(projectDir, { recursive: true }); @@ -11457,6 +11459,21 @@ describe("ClaudeAdapterV2 background wake turns", () => { attachments: [], providerTurnOrdinal: ordinal, }); + const setMcp = (ordinal: number) => + input.rotateMcp === true + ? mcpSessions.set({ + environmentId: EnvironmentId.make("environment-claude-stale-process"), + threadId: harness.threadId, + providerSessionId: `mcp-session-claude-stale-process-${ordinal}`, + providerInstanceId: ProviderInstanceId.make("claudeAgent"), + runId: RunId.make(`claude-stale-process-run-${ordinal}`), + attemptId: RunAttemptId.make(`attempt-stale-process:${ordinal}`), + endpoint: "http://127.0.0.1:43123/mcp", + authorizationHeader: `Bearer claude-stale-process-run-${ordinal}`, + browserToolsAvailable: false, + }) + : Effect.void; + yield* setMcp(1); yield* harness.runtime.startTurn(turn(1)); if (input.backgroundShell === true) yield* harness.offerAndWait(wakeTaskStarted); if (input.scheduledWakeup === true || input.wakeFiresDuringRead === true) { @@ -11479,6 +11496,7 @@ describe("ClaudeAdapterV2 background wake turns", () => { input.transcript(harness.promptUuid(0)), ); } + yield* setMcp(2); if (input.wakeFiresDuringRead !== true) { yield* harness.runtime.startTurn(turn(2)); return harness; @@ -11513,10 +11531,16 @@ describe("ClaudeAdapterV2 background wake turns", () => { { type: "text", text: "y".repeat(1_200_000) }, ]), }, + { + name: "its MCP credential also rotated", + transcript: (promptUuid: string) => t3Turn(promptUuid) + terminalExchange, + rotateMcp: true, + }, ])("replaces a warm process when $name", (row) => Effect.gen(function* () { const harness = yield* nextTurnAfter(row); assert.lengthOf(harness.processQueues, 2, "the next turn must open a fresh process"); + assert.lengthOf(harness.setMcpServersCalls, 0); assert.equal(harness.getOpenedOptions()?.resume, WAKE_NATIVE_SESSION); assert.isUndefined(harness.getOpenedOptions()?.resumeSessionAt); }).pipe(Effect.provide(layer)), From 2200d7b93ca30dbe97d88afd751ad18b71e01f48 Mon Sep 17 00:00:00 2001 From: Victor Vogel Date: Mon, 23 Nov 2026 12:18:51 +0000 Subject: [PATCH 16/34] refactor(server): tighten typed-result submission paths and tests --- apps/server/src/mcp/McpSessionRegistry.ts | 5 +- apps/server/src/mcp/toolkits/core.test.ts | 81 ++- .../Adapters/AcpAdapterV2.test.ts | 43 +- .../Adapters/ClaudeAdapterV2.ts | 22 +- .../Adapters/OpenCode2AdapterV2.test.ts | 50 +- .../src/orchestration-v2/Orchestrator.ts | 51 +- .../ProviderSessionManager.test.ts | 547 +++++++----------- .../ProviderSessionManager.ts | 331 ++++------- .../src/orchestration-v2/runtimeLayer.test.ts | 312 ++++------ packages/provider-acp/src/server/adapter.ts | 12 +- .../provider-muse/src/server/adapter.test.ts | 30 +- .../src/server/adapter.test.ts | 30 +- .../provider-opencode/src/server/adapter.ts | 40 +- .../provider-pi/src/server/adapter.test.ts | 30 +- packages/provider-pi/src/server/adapter.ts | 7 +- .../provider-pi/src/server/mcpInjection.ts | 2 +- 16 files changed, 619 insertions(+), 974 deletions(-) diff --git a/apps/server/src/mcp/McpSessionRegistry.ts b/apps/server/src/mcp/McpSessionRegistry.ts index f2569bbe5ff99..d29f27c99ce92 100644 --- a/apps/server/src/mcp/McpSessionRegistry.ts +++ b/apps/server/src/mcp/McpSessionRegistry.ts @@ -256,13 +256,14 @@ const makeWithOptions = Effect.fn("McpSessionRegistry.make")(function* ( }), releaseRunBinding: Effect.fn("McpSessionRegistry.releaseRunBinding")(function* (credentialId) { yield* SynchronizedRef.update(state, ({ records }) => { - const next = new Map(records); + let next: Map | undefined; for (const [tokenHash, record] of records) { if (record.credentialId !== credentialId) continue; const { runId: _runId, attemptId: _attemptId, ...thread } = record.scope.thread; + next ??= new Map(records); next.set(tokenHash, { ...record, scope: { ...record.scope, thread } }); } - return { records: next }; + return next === undefined ? { records } : { records: next }; }); }), syncCapabilities: Effect.fn("McpSessionRegistry.syncCapabilities")( diff --git a/apps/server/src/mcp/toolkits/core.test.ts b/apps/server/src/mcp/toolkits/core.test.ts index f7f654fd22948..82f82e0d1f238 100644 --- a/apps/server/src/mcp/toolkits/core.test.ts +++ b/apps/server/src/mcp/toolkits/core.test.ts @@ -1725,50 +1725,49 @@ it.effect("t3_submit_output forwards caller run and attempt identity and surface ); }); - // An unbound credential names its run in the call; service rejections surface as invalid_request. - rejectNext = { problem: "This output was submitted for a turn that is no longer active." }; - const unbound = yield* callWith(undefined, undefined, '{"ok":false}', runA).pipe( - Effect.provide(serverLayer), - ); - expect(unbound.isError).toBe(true); - expect(declaredFailure(unbound)).toEqual({ - _tag: "OrchestratorMcpFailure", - code: "invalid_request", - message: "This output was submitted for a turn that is no longer active.", - }); - - // Preserved dispatch causes stay out of MCP output; only SchemaError validation details append. - rejectNext = { - problem: "This output was submitted for a turn that is no longer active.", - cause: new OrchestratorDispatchError({ - commandId: CommandId.make("cmd-submit-stale"), - commandType: "run.output.submit", - }), + const expectInvalidRequest = ( + result: Effect.Success>, + message: string, + ) => { + expect(result.isError).toBe(true); + expect(declaredFailure(result)).toEqual({ + _tag: "OrchestratorMcpFailure", + code: "invalid_request", + message, + }); }; - const stale = yield* callWith(runA, attemptA, '{"ok":false}').pipe(Effect.provide(serverLayer)); - expect(stale.isError).toBe(true); - expect(declaredFailure(stale)).toEqual({ - _tag: "OrchestratorMcpFailure", - code: "invalid_request", - message: "This output was submitted for a turn that is no longer active.", - }); - const schemaCause = yield* decodeSubmitOutputFixture({}).pipe(Effect.flip); - rejectNext = { problem: "The result does not match the schema.", cause: schemaCause }; - const invalidSchema = yield* callWith(runB, attemptB, "{}").pipe(Effect.provide(serverLayer)); - expect(invalidSchema.isError).toBe(true); - expect(declaredFailure(invalidSchema)).toEqual({ - _tag: "OrchestratorMcpFailure", - code: "invalid_request", - message: `The result does not match the schema.\n${schemaCause.message.slice(0, 2000)}`, - }); + const staleMessage = "This output was submitted for a turn that is no longer active."; + yield* Effect.gen(function* () { + // An unbound credential names its run in the call; service rejections surface as invalid_request. + rejectNext = { problem: staleMessage }; + expectInvalidRequest( + yield* callWith(undefined, undefined, '{"ok":false}', runA), + staleMessage, + ); - // A bound credential outranks the argument. - const active = yield* callWith(runB, attemptB, '{"ok":true}', runA).pipe( - Effect.provide(serverLayer), - ); - expect(active.isError).toBe(false); - expect(active.structuredContent).toEqual({ runId: runB }); + // Preserved dispatch causes stay out of MCP output; only SchemaError validation details append. + rejectNext = { + problem: staleMessage, + cause: new OrchestratorDispatchError({ + commandId: CommandId.make("cmd-submit-stale"), + commandType: "run.output.submit", + }), + }; + expectInvalidRequest(yield* callWith(runA, attemptA, '{"ok":false}'), staleMessage); + + const schemaCause = yield* decodeSubmitOutputFixture({}).pipe(Effect.flip); + rejectNext = { problem: "The result does not match the schema.", cause: schemaCause }; + expectInvalidRequest( + yield* callWith(runB, attemptB, "{}"), + `The result does not match the schema.\n${schemaCause.message.slice(0, 2000)}`, + ); + + // A bound credential outranks the argument. + const active = yield* callWith(runB, attemptB, '{"ok":true}', runA); + expect(active.isError).toBe(false); + expect(active.structuredContent).toEqual({ runId: runB }); + }).pipe(Effect.provide(serverLayer)); expect(calls).toEqual([ { threadId, diff --git a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts index 4e35b22265d97..7221c0b2ee7dc 100644 --- a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts @@ -6936,15 +6936,17 @@ describe("AcpAdapterV2", () => { const instanceId = ProviderInstanceId.make("acp-test-mcp-rotate"); const threadId = ThreadId.make("thread-acp-mcp-rotate"); const mcpSessions = yield* McpProviderSessions.McpProviderSessions; - yield* mcpSessions.set({ - environmentId: EnvironmentId.make("environment-acp-mcp-rotate"), - threadId, - providerSessionId: "mcp-session-acp-rotate-1", - providerInstanceId: instanceId, - endpoint: "http://127.0.0.1:43123/mcp", - authorizationHeader: "Bearer acp-run-1-token", - browserToolsAvailable: false, - }); + const setMcp = (ordinal: number) => + mcpSessions.set({ + environmentId: EnvironmentId.make("environment-acp-mcp-rotate"), + threadId, + providerSessionId: `mcp-session-acp-rotate-${ordinal}`, + providerInstanceId: instanceId, + endpoint: "http://127.0.0.1:43123/mcp", + authorizationHeader: `Bearer acp-run-${ordinal}-token`, + browserToolsAvailable: false, + }); + yield* setMcp(1); const adapter = yield* makeAcpAdapterV2({ instanceId, flavor: { @@ -6977,15 +6979,7 @@ describe("AcpAdapterV2", () => { runtimePolicy, }); - yield* mcpSessions.set({ - environmentId: EnvironmentId.make("environment-acp-mcp-rotate"), - threadId, - providerSessionId: "mcp-session-acp-rotate-2", - providerInstanceId: instanceId, - endpoint: "http://127.0.0.1:43123/mcp", - authorizationHeader: "Bearer acp-run-2-token", - browserToolsAvailable: false, - }); + yield* setMcp(2); yield* runtime.startTurn( makeTurnInput({ threadId, @@ -7007,17 +7001,12 @@ describe("AcpAdapterV2", () => { reloadRequestEvent, `expected session/load or session/resume in ${JSON.stringify(loggedEvents.map((e) => `${e.direction}:${rawProtocolMethod(e)}`))}`, ); - const loadRequest = Option.getOrThrow( - Option.fromNullishOr(rawProtocolRequest(reloadRequestEvent!)), - ); - const mcpServers = ( - loadRequest.params as { - mcpServers?: ReadonlyArray<{ + const mcpServers = rawProtocolRequestParam(reloadRequestEvent!, "mcpServers") as + | ReadonlyArray<{ name?: string; env?: ReadonlyArray<{ name: string; value: string }>; - }>; - } - ).mcpServers; + }> + | undefined; const t3Server = mcpServers?.find((server) => server.name === "t3-code"); assert.isDefined(t3Server); assert.equal( diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts index 4106e0d4c89e4..343b21a88a901 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts @@ -3929,23 +3929,19 @@ function claudeEffectiveQueryPolicyKeyWithoutMcpAuth( }, workspace?: ProviderAdapter.ProviderAdapterV2RuntimePolicy["workspace"], ): string { - const sanitizedServers = - mcpOverrides.mcpServers === undefined - ? undefined - : Object.fromEntries( - Object.entries(mcpOverrides.mcpServers).map(([name, server]) => { - if (name === "t3-code" && server.type === "http" && server.headers !== undefined) { - const { Authorization: _authorization, ...restHeaders } = server.headers; - return [name, { ...server, headers: restHeaders }]; - } - return [name, server]; - }), - ); + const t3Server = mcpOverrides.mcpServers?.["t3-code"]; + if (t3Server?.type !== "http" || t3Server.headers === undefined) { + return claudeEffectiveQueryPolicyKey(queryPolicy, mcpOverrides, workspace); + } + const { Authorization: _authorization, ...restHeaders } = t3Server.headers; return claudeEffectiveQueryPolicyKey( queryPolicy, { ...mcpOverrides, - ...(sanitizedServers === undefined ? {} : { mcpServers: sanitizedServers }), + mcpServers: { + ...mcpOverrides.mcpServers, + "t3-code": { ...t3Server, headers: restHeaders }, + }, }, workspace, ); diff --git a/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts index 72ecec1543e5b..c2394bebf70b2 100644 --- a/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts @@ -5568,15 +5568,17 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { it.effect("removes and re-registers T3 MCP when its bearer token rotates between turns", () => Effect.gen(function* () { const mcpSessions = yield* McpProviderSessions.McpProviderSessions; - yield* mcpSessions.set({ - environmentId: EnvironmentId.make("environment:opencode2-adapter"), - threadId, - providerSessionId: "mcp:opencode2-rotate-1", - providerInstanceId: instanceId, - endpoint: "http://127.0.0.1:3773/mcp", - authorizationHeader: "Bearer opencode2-run-1", - browserToolsAvailable: false, - }); + const setMcp = (ordinal: number) => + mcpSessions.set({ + environmentId: EnvironmentId.make("environment:opencode2-adapter"), + threadId, + providerSessionId: `mcp:opencode2-rotate-${ordinal}`, + providerInstanceId: instanceId, + endpoint: "http://127.0.0.1:3773/mcp", + authorizationHeader: `Bearer opencode2-run-${ordinal}`, + browserToolsAvailable: false, + }); + yield* setMcp(1); yield* Effect.addFinalizer(() => mcpSessions.clear(threadId)); const server = "t3-code-thread_opencode2-adapter"; const addFor = (authorization: string) => @@ -5608,27 +5610,17 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { reply("mcp.remove", null), ]); assert.equal(runtime.mcpCredentialRotation, "live"); - - const firstTerminal = yield* terminalOf(runtime).pipe(Effect.forkScoped); - const firstStarted = yield* runtime.startTurn(turnInput(thread)).pipe(Effect.forkScoped); - yield* TestClock.adjust("250 millis"); - yield* Fiber.join(firstStarted); - assert.equal((yield* Fiber.join(firstTerminal))?.status, "completed"); - - yield* mcpSessions.set({ - environmentId: EnvironmentId.make("environment:opencode2-adapter"), - threadId, - providerSessionId: "mcp:opencode2-rotate-2", - providerInstanceId: instanceId, - endpoint: "http://127.0.0.1:3773/mcp", - authorizationHeader: "Bearer opencode2-run-2", - browserToolsAvailable: false, + const runTurn = Effect.fnUntraced(function* () { + const terminal = yield* terminalOf(runtime).pipe(Effect.forkScoped); + const started = yield* runtime.startTurn(turnInput(thread)).pipe(Effect.forkScoped); + yield* TestClock.adjust("250 millis"); + yield* Fiber.join(started); + assert.equal((yield* Fiber.join(terminal))?.status, "completed"); }); - const secondTerminal = yield* terminalOf(runtime).pipe(Effect.forkScoped); - const secondStarted = yield* runtime.startTurn(turnInput(thread)).pipe(Effect.forkScoped); - yield* TestClock.adjust("250 millis"); - yield* Fiber.join(secondStarted); - assert.equal((yield* Fiber.join(secondTerminal))?.status, "completed"); + + yield* runTurn(); + yield* setMcp(2); + yield* runTurn(); }), ); diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index c7fdc29318672..a27d9d0a5be9e 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -12375,6 +12375,12 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio cause: `Run ${command.runId} was not asked for a result.`, }); } + const rejectOutput = (reason: RunOutputDispatchRejectionError["reason"], detail: string) => + new OrchestratorDispatchError({ + commandId: command.commandId, + commandType: command.type, + cause: new RunOutputDispatchRejectionError({ reason, detail }), + }); // The service picks the active run, but the run can end before this command is its turn. A // turn that completed without its result still owes it, and a later turn may give it. const owed = yield* resolveOwedOutputRun(projection.runs, () => @@ -12384,14 +12390,10 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ).pipe(mapDispatchError(command)); const owes = owed?.id === run.id; if (!isActiveRun(run) && !owes) { - return yield* new OrchestratorDispatchError({ - commandId: command.commandId, - commandType: command.type, - cause: new RunOutputDispatchRejectionError({ - reason: "inactive", - detail: `Run ${command.runId} is ${run.status} and takes no result.`, - }), - }); + return yield* rejectOutput( + "inactive", + `Run ${command.runId} is ${run.status} and takes no result.`, + ); } if (command.callerRunId !== undefined || command.callerAttemptId !== undefined) { let active: OrchestrationV2Run | undefined; @@ -12411,14 +12413,10 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio const callerAllowed = (active !== undefined && matchesRun(active)) || (owes && matchesRun(run)); if (!callerAllowed) { - return yield* new OrchestratorDispatchError({ - commandId: command.commandId, - commandType: command.type, - cause: new RunOutputDispatchRejectionError({ - reason: "stale_caller", - detail: `Caller run ${command.callerRunId ?? "unknown"} is no longer active on thread ${command.threadId}.`, - }), - }); + return yield* rejectOutput( + "stale_caller", + `Caller run ${command.callerRunId ?? "unknown"} is no longer active on thread ${command.threadId}.`, + ); } if ( active !== undefined && @@ -12426,26 +12424,15 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio matchesRun(active) && (yield* stopReachedRun(command, command.threadId, active.id)) ) { - return yield* new OrchestratorDispatchError({ - commandId: command.commandId, - commandType: command.type, - cause: new RunOutputDispatchRejectionError({ - reason: "stopped", - detail: `Run ${active.id} was stopped and takes no result.`, - }), - }); + return yield* rejectOutput("stopped", `Run ${active.id} was stopped and takes no result.`); } } // A stopped run stays active until its provider settles; what it submits then is not kept. if (yield* stopReachedRun(command, command.threadId, run.id)) { - return yield* new OrchestratorDispatchError({ - commandId: command.commandId, - commandType: command.type, - cause: new RunOutputDispatchRejectionError({ - reason: "stopped", - detail: `Run ${command.runId} was stopped and takes no result.`, - }), - }); + return yield* rejectOutput( + "stopped", + `Run ${command.runId} was stopped and takes no result.`, + ); } const now = yield* DateTime.now; yield* emit( diff --git a/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts b/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts index e50e3e5e5c73b..5f93a7c04ae41 100644 --- a/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts +++ b/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts @@ -3371,19 +3371,87 @@ it.effect.each([ runtimePolicy, ...turn, }); - if (scenario === "live") { - const effect = Effect.gen(function* () { + const setupSession = (slug: string) => + Effect.gen(function* () { const eventSink = yield* EventSink.EventSinkV2; const idAllocator = yield* IdAllocator.IdAllocatorV2; const manager = yield* ProviderSessionManager.ProviderSessionManagerV2; const registry = yield* McpSessionRegistry.McpSessionRegistry; const mcpSessions = yield* McpProviderSessions.McpProviderSessions; const now = yield* DateTime.now; - const threadId = ThreadId.make("thread-provider-session-manager-live-rotate"); + const threadId = ThreadId.make(`thread-provider-session-manager-${slug}`); const providerSessionId = yield* idAllocator.allocate.providerSession({ providerInstanceId: modelSelection.instanceId, threadId, }); + return { + eventSink, + idAllocator, + manager, + registry, + mcpSessions, + now, + threadId, + providerSessionId, + }; + }); + const makeCompletedRunEvent = (input: { + readonly idAllocator: IdAllocator.IdAllocatorV2["Service"]; + readonly threadId: ThreadId; + readonly runId: RunId; + readonly attemptId: RunAttemptId; + readonly nodeId: NodeId; + readonly userMessageId: MessageId; + readonly providerThreadId: OrchestrationV2ProviderThread["id"]; + readonly now: DateTime.Utc; + readonly outputSchema?: { readonly type: "object" }; + }) => + Effect.map(input.idAllocator.allocate.event({ threadId: input.threadId }), (id) => ({ + id, + type: "run.created" as const, + threadId: input.threadId, + runId: input.runId, + nodeId: input.nodeId, + driver: CODEX_DRIVER, + occurredAt: input.now, + payload: { + id: input.runId, + threadId: input.threadId, + ordinal: 1, + providerInstanceId: modelSelection.instanceId, + modelSelection, + providerThreadId: input.providerThreadId, + userMessageId: input.userMessageId, + rootNodeId: input.nodeId, + activeAttemptId: input.attemptId, + status: "completed" as const, + requestedAt: input.now, + startedAt: input.now, + completedAt: input.now, + checkpointId: null, + contextHandoffId: null, + ...(input.outputSchema === undefined ? {} : { outputSchema: input.outputSchema }), + }, + })); + const withServerSettings = ( + input: Omit[0], "serverSettingsLayer">, + ) => { + const serverSettingsLayer = ServerSettings.layerTest().pipe(Layer.orDie); + return Layer.merge(layerTest({ ...input, serverSettingsLayer }), serverSettingsLayer); + }; + + if (scenario === "live") { + const effect = Effect.gen(function* () { + const { + eventSink, + idAllocator, + manager, + registry, + mcpSessions, + now, + threadId, + providerSessionId, + } = yield* setupSession("live-rotate"); yield* eventSink.write({ events: [yield* makeThreadCreatedEvent({ idAllocator, threadId, now })], }); @@ -3438,36 +3506,28 @@ it.effect.each([ }); yield* effect.pipe( - Effect.provide( - layerTest({ - state, - idleTimeoutMs: 1_000, - mcpCredentialRotation: "live", - }), - ), + Effect.provide(layerTest({ state, idleTimeoutMs: 1_000, mcpCredentialRotation: "live" })), ); return; } if (scenario === "none") { const effect = Effect.gen(function* () { - const eventSink = yield* EventSink.EventSinkV2; - const idAllocator = yield* IdAllocator.IdAllocatorV2; - const manager = yield* ProviderSessionManager.ProviderSessionManagerV2; - const registry = yield* McpSessionRegistry.McpSessionRegistry; - const mcpSessions = yield* McpProviderSessions.McpProviderSessions; - const settings = yield* ServerSettings.ServerSettingsService; - const now = yield* DateTime.now; - const threadId = ThreadId.make("thread-provider-session-manager-no-rotation"); - const providerSessionId = yield* idAllocator.allocate.providerSession({ - providerInstanceId: modelSelection.instanceId, + const { + eventSink, + idAllocator, + manager, + registry, + mcpSessions, + now, threadId, - }); + providerSessionId, + } = yield* setupSession("no-rotation"); + const settings = yield* ServerSettings.ServerSettingsService; const run1 = RunId.make("run-none-1"); const run2 = RunId.make("run-none-2"); const run3 = RunId.make("run-none-3"); const run4 = RunId.make("run-none-4"); - const rootNode1 = NodeId.make("node-none-1"); const providerThread = makeProviderThread({ idAllocator, threadId, @@ -3477,33 +3537,17 @@ it.effect.each([ yield* eventSink.write({ events: [ yield* makeThreadCreatedEvent({ idAllocator, threadId, now }), - { - id: yield* idAllocator.allocate.event({ threadId }), - type: "run.created", + yield* makeCompletedRunEvent({ + idAllocator, threadId, runId: run1, - nodeId: rootNode1, - driver: CODEX_DRIVER, - occurredAt: now, - payload: { - id: run1, - threadId, - ordinal: 1, - providerInstanceId: modelSelection.instanceId, - modelSelection, - providerThreadId: providerThread.id, - userMessageId: MessageId.make("msg-none-1"), - rootNodeId: rootNode1, - activeAttemptId: RunAttemptId.make("attempt-none-1"), - status: "completed", - requestedAt: now, - startedAt: now, - completedAt: now, - checkpointId: null, - contextHandoffId: null, - outputSchema: { type: "object" }, - }, - }, + attemptId: RunAttemptId.make("attempt-none-1"), + nodeId: NodeId.make("node-none-1"), + userMessageId: MessageId.make("msg-none-1"), + providerThreadId: providerThread.id, + now, + outputSchema: { type: "object" }, + }), ], }); @@ -3558,11 +3602,7 @@ it.effect.each([ // A non-rotatable runtime cannot take a token for a second typed run: the turn still runs, // and its token stops answering for run1 so the new run can submit. - yield* manager.open({ - threadId, - providerSessionId, - modelSelection, - runtimePolicy, + yield* openFor(manager, providerSessionId, threadId, { runId: run3, attemptId: RunAttemptId.make("attempt-none-3"), requireRunScopedMcp: true, @@ -3597,18 +3637,9 @@ it.effect.each([ yield* manager.close(providerSessionId); }); - const serverSettingsLayer = ServerSettings.layerTest().pipe(Layer.orDie); yield* effect.pipe( Effect.provide( - Layer.merge( - layerTest({ - state, - idleTimeoutMs: 1_000, - mcpCredentialRotation: "none", - serverSettingsLayer, - }), - serverSettingsLayer, - ), + withServerSettings({ state, idleTimeoutMs: 1_000, mcpCredentialRotation: "none" }), ), ); return; @@ -3622,22 +3653,20 @@ it.effect.each([ ); const failUnload = yield* Ref.make(false); const effect = Effect.gen(function* () { - const eventSink = yield* EventSink.EventSinkV2; - const idAllocator = yield* IdAllocator.IdAllocatorV2; - const manager = yield* ProviderSessionManager.ProviderSessionManagerV2; - const registry = yield* McpSessionRegistry.McpSessionRegistry; - const mcpSessions = yield* McpProviderSessions.McpProviderSessions; - const now = yield* DateTime.now; - const threadId = ThreadId.make("thread-provider-session-manager-bg-no-unload"); - const providerSessionId = yield* idAllocator.allocate.providerSession({ - providerInstanceId: modelSelection.instanceId, + const { + eventSink, + idAllocator, + manager, + registry, + mcpSessions, + now, threadId, - }); + providerSessionId, + } = yield* setupSession("bg-no-unload"); const run1 = RunId.make("run-bg-1"); const run2 = RunId.make("run-bg-2"); const attempt1 = RunAttemptId.make("attempt-bg-1"); const attempt2 = RunAttemptId.make("attempt-bg-2"); - const rootNode1 = NodeId.make("node-bg-1"); const providerThread = makeProviderThread({ idAllocator, threadId, @@ -3647,32 +3676,16 @@ it.effect.each([ yield* eventSink.write({ events: [ yield* makeThreadCreatedEvent({ idAllocator, threadId, now }), - { - id: yield* idAllocator.allocate.event({ threadId }), - type: "run.created", + yield* makeCompletedRunEvent({ + idAllocator, threadId, runId: run1, - nodeId: rootNode1, - driver: CODEX_DRIVER, - occurredAt: now, - payload: { - id: run1, - threadId, - ordinal: 1, - providerInstanceId: modelSelection.instanceId, - modelSelection, - providerThreadId: providerThread.id, - userMessageId: MessageId.make("msg-bg-1"), - rootNodeId: rootNode1, - activeAttemptId: attempt1, - status: "completed", - requestedAt: now, - startedAt: now, - completedAt: now, - checkpointId: null, - contextHandoffId: null, - }, - }, + attemptId: attempt1, + nodeId: NodeId.make("node-bg-1"), + userMessageId: MessageId.make("msg-bg-1"), + providerThreadId: providerThread.id, + now, + }), ], }); const runtime = yield* openFor(manager, providerSessionId, threadId, { @@ -3680,6 +3693,16 @@ it.effect.each([ attemptId: attempt1, requireRunScopedMcp: true, }); + const resume = ( + targetThreadId: ThreadId, + targetProviderThread: OrchestrationV2ProviderThread, + ) => + runtime.resumeThread({ + threadId: targetThreadId, + providerThread: targetProviderThread, + modelSelection, + runtimePolicy, + }); const attachLoadedThread = (name: string) => Effect.gen(function* () { const nextThreadId = ThreadId.make(`thread-provider-session-manager-${name}`); @@ -3695,12 +3718,7 @@ it.effect.each([ yield* openFor(manager, providerSessionId, nextThreadId); const loadedConfig = yield* mcpSessions.read(nextThreadId); const loadedToken = rawBearer(loadedConfig); - yield* runtime.resumeThread({ - threadId: nextThreadId, - providerThread: nextProviderThread, - modelSelection, - runtimePolicy, - }); + yield* resume(nextThreadId, nextProviderThread); return { threadId: nextThreadId, providerThread: nextProviderThread, @@ -3708,14 +3726,54 @@ it.effect.each([ loadedToken, }; }); + const assertFailedUnloadRollback = (input: { + readonly targetThreadId: ThreadId; + readonly targetProviderThread: OrchestrationV2ProviderThread; + readonly beforeConfig: McpProviderSession.McpProviderSessionConfig; + readonly beforeToken: string; + readonly runId: RunId; + readonly attemptId: RunAttemptId; + readonly retryAfterRecovery?: boolean; + }) => + Effect.gen(function* () { + yield* openFor(manager, providerSessionId, input.targetThreadId, { + runId: input.runId, + attemptId: input.attemptId, + requireRunScopedMcp: true, + }); + const stagedToken = rawBearer(yield* mcpSessions.read(input.targetThreadId)); + assert.notEqual(stagedToken, input.beforeToken); + yield* Ref.set(failUnload, true); + yield* resume(input.targetThreadId, input.targetProviderThread); + assert.isUndefined(yield* registry.resolve(stagedToken)); + assert.equal( + (yield* mcpSessions.read(input.targetThreadId))?.authorizationHeader, + input.beforeConfig.authorizationHeader, + ); + if (input.retryAfterRecovery !== true) return; + yield* Ref.set(failUnload, false); + yield* openFor(manager, providerSessionId, input.targetThreadId, { + runId: input.runId, + attemptId: input.attemptId, + requireRunScopedMcp: true, + }); + const retriedConfig = yield* mcpSessions.read(input.targetThreadId); + assert.isDefined(retriedConfig); + assert.notEqual( + retriedConfig!.authorizationHeader, + input.beforeConfig.authorizationHeader, + ); + yield* resume(input.targetThreadId, input.targetProviderThread); + assert.isTrue(Option.isSome(yield* Queue.poll(unloads))); + const resolvedRetried = yield* registry.resolve(rawBearer(retriedConfig)); + assert.isDefined(resolvedRetried); + assert.equal(resolvedRetried!.thread.runId, input.runId); + assert.equal(resolvedRetried!.thread.attemptId, input.attemptId); + assert.isUndefined(yield* registry.resolve(input.beforeToken)); + }); const loadedConfig = yield* mcpSessions.read(threadId); const loadedToken = rawBearer(loadedConfig); - yield* runtime.resumeThread({ - threadId, - providerThread, - modelSelection, - runtimePolicy, - }); + yield* resume(threadId, providerThread); yield* openFor(manager, providerSessionId, threadId, { runId: run2, attemptId: attempt2, @@ -3724,12 +3782,7 @@ it.effect.each([ const rotatedToken = rawBearer(yield* mcpSessions.read(threadId)); assert.notEqual(rotatedToken, loadedToken); - yield* runtime.resumeThread({ - threadId, - providerThread, - modelSelection, - runtimePolicy, - }); + yield* resume(threadId, providerThread); // Background work stayed alive (no unload): the turn runs on the loaded token, now unbound so // its run can submit, and the unused token was revoked. assert.isTrue(Option.isNone(yield* Queue.poll(unloads))); @@ -3760,12 +3813,7 @@ it.effect.each([ const unboundRotatedToken = rawBearer(yield* mcpSessions.read(unboundThreadId)); assert.notEqual(unboundRotatedToken, unboundLoadedToken); - yield* runtime.resumeThread({ - threadId: unboundThreadId, - providerThread: unboundProviderThread, - modelSelection, - runtimePolicy, - }); + yield* resume(unboundThreadId, unboundProviderThread); assert.isTrue(Option.isNone(yield* Queue.poll(unloads))); const resolvedUnboundLoaded = yield* registry.resolve(unboundLoadedToken); assert.isDefined(resolvedUnboundLoaded); @@ -3796,12 +3844,7 @@ it.effect.each([ const widerRotatedConfig = yield* mcpSessions.read(widenedThreadId); assert.isTrue(widerRotatedConfig?.browserToolsAvailable); const widerRotatedToken = rawBearer(widerRotatedConfig); - yield* runtime.resumeThread({ - threadId: widenedThreadId, - providerThread: widenedProviderThread, - modelSelection, - runtimePolicy, - }); + yield* resume(widenedThreadId, widenedProviderThread); const resolvedNarrow = yield* registry.resolve(narrowLoadedToken); assert.isDefined(resolvedNarrow); assert.isFalse(resolvedNarrow!.capabilities.has("preview")); @@ -3826,14 +3869,9 @@ it.effect.each([ requireRunScopedMcp: true, }); const narrowedRotatedToken = rawBearer(yield* mcpSessions.read(narrowedThreadId)); - const narrowedFailed = yield* runtime - .resumeThread({ - threadId: narrowedThreadId, - providerThread: narrowedProviderThread, - modelSelection, - runtimePolicy, - }) - .pipe(Effect.flip); + const narrowedFailed = yield* resume(narrowedThreadId, narrowedProviderThread).pipe( + Effect.flip, + ); assert.equal(narrowedFailed._tag, "ProviderAdapterMcpRotationBlockedError"); assert.isUndefined(yield* registry.resolve(broadLoadedToken)); assert.isUndefined(yield* registry.resolve(narrowedRotatedToken)); @@ -3848,12 +3886,7 @@ it.effect.each([ attemptId: RunAttemptId.make("attempt-bg-narrowed-next-plain"), requireRunScopedMcp: false, }); - yield* runtime.resumeThread({ - threadId: narrowedThreadId, - providerThread: narrowedProviderThread, - modelSelection, - runtimePolicy, - }); + yield* resume(narrowedThreadId, narrowedProviderThread); assert.isTrue(Option.isSome(yield* Queue.poll(unloads))); const recoveredConfig = yield* mcpSessions.read(narrowedThreadId); assert.isFalse(recoveredConfig?.browserToolsAvailable); @@ -3873,83 +3906,17 @@ it.effect.each([ assert.isFalse(runlessRecovered!.browserToolsAvailable); // A failed unload may leave the thread loaded, where a resume ignores new config: keep the old credential. - const unloadFailedThreadId = ThreadId.make("thread-provider-session-manager-unload-failed"); - const unloadFailedProviderThread = makeProviderThread({ - idAllocator, - threadId: unloadFailedThreadId, - providerSessionId, - now, - }); - yield* eventSink.write({ - events: [ - yield* makeThreadCreatedEvent({ idAllocator, threadId: unloadFailedThreadId, now }), - ], - }); - yield* manager.open({ - threadId: unloadFailedThreadId, - providerSessionId, - modelSelection, - runtimePolicy, - }); - const beforeFailedUnload = yield* mcpSessions.read(unloadFailedThreadId); - yield* runtime.resumeThread({ - threadId: unloadFailedThreadId, - providerThread: unloadFailedProviderThread, - modelSelection, - runtimePolicy, - }); - const unloadFailedRunId = RunId.make("run-unload-failed-typed"); - const unloadFailedAttemptId = RunAttemptId.make("attempt-unload-failed-typed"); - yield* manager.open({ - threadId: unloadFailedThreadId, - providerSessionId, - modelSelection, - runtimePolicy, - runId: unloadFailedRunId, - attemptId: unloadFailedAttemptId, - requireRunScopedMcp: true, - }); - const stagedToken = (yield* mcpSessions.read( - unloadFailedThreadId, - ))!.authorizationHeader.replace(/^Bearer\s+/, ""); - yield* Ref.set(failUnload, true); - yield* runtime.resumeThread({ - threadId: unloadFailedThreadId, - providerThread: unloadFailedProviderThread, - modelSelection, - runtimePolicy, - }); - assert.isUndefined(yield* registry.resolve(stagedToken)); - assert.equal( - (yield* mcpSessions.read(unloadFailedThreadId))?.authorizationHeader, - beforeFailedUnload!.authorizationHeader, - ); - // Once the unload fault clears, retrying the same run and attempt succeeds with a bound credential. - yield* Ref.set(failUnload, false); - yield* openFor(manager, providerSessionId, unloadFailedThreadId, { - runId: unloadFailedRunId, - attemptId: unloadFailedAttemptId, - requireRunScopedMcp: true, - }); - const retriedConfig = yield* mcpSessions.read(unloadFailedThreadId); - assert.isDefined(retriedConfig); - assert.notEqual( - retriedConfig!.authorizationHeader, - beforeFailedUnload!.authorizationHeader, - ); - yield* runtime.resumeThread({ - threadId: unloadFailedThreadId, - providerThread: unloadFailedProviderThread, - modelSelection, - runtimePolicy, + const unloadFailed = yield* attachLoadedThread("unload-failed"); + yield* assertFailedUnloadRollback({ + targetThreadId: unloadFailed.threadId, + targetProviderThread: unloadFailed.providerThread, + beforeConfig: unloadFailed.loadedConfig, + beforeToken: unloadFailed.loadedToken, + runId: RunId.make("run-unload-failed-typed"), + attemptId: RunAttemptId.make("attempt-unload-failed-typed"), + retryAfterRecovery: true, }); - assert.isTrue(Option.isSome(yield* Queue.poll(unloads))); - const resolvedRetried = yield* registry.resolve(rawBearer(retriedConfig)); - assert.isDefined(resolvedRetried); - assert.equal(resolvedRetried!.thread.runId, unloadFailedRunId); - assert.equal(resolvedRetried!.thread.attemptId, unloadFailedAttemptId); - assert.isUndefined(yield* registry.resolve(rawBearer(beforeFailedUnload))); // Once background work finishes, reloading a thread whose loaded credential became unbound // during keepLoaded retires that old unbound credential. @@ -3958,12 +3925,7 @@ it.effect.each([ attemptId: RunAttemptId.make("attempt-bg-3-retire"), requireRunScopedMcp: true, }); - yield* runtime.resumeThread({ - threadId, - providerThread, - modelSelection, - runtimePolicy, - }); + yield* resume(threadId, providerThread); assert.isTrue(Option.isSome(yield* Queue.poll(unloads))); assert.isUndefined(yield* registry.resolve(loadedToken)); @@ -4037,120 +3999,59 @@ it.effect.each([ // A failed linked-environment unload keeps the loaded MCP credential record so MCP refresh // still rolls back a staged credential instead of bypassing rotation. yield* Ref.set(sessionBackgroundWorkProbe, Effect.succeed(false)); - const { - threadId: linksFailThreadId, - providerThread: linksFailProviderThread, - loadedConfig: beforeLinksFail, - loadedToken: beforeLinksFailToken, - } = yield* attachLoadedThread("links-unload-fail"); + const linksFail = yield* attachLoadedThread("links-unload-fail"); yield* settings.updateSettings({ linkedEnvironmentsEnabled: true }); - yield* openFor(manager, providerSessionId, linksFailThreadId, { + yield* assertFailedUnloadRollback({ + targetThreadId: linksFail.threadId, + targetProviderThread: linksFail.providerThread, + beforeConfig: linksFail.loadedConfig, + beforeToken: linksFail.loadedToken, runId: RunId.make("run-links-fail-typed"), attemptId: RunAttemptId.make("attempt-links-fail-typed"), - requireRunScopedMcp: true, }); - const stagedLinksToken = rawBearer(yield* mcpSessions.read(linksFailThreadId)); - assert.notEqual(stagedLinksToken, beforeLinksFailToken); - yield* Ref.set(failUnload, true); - yield* runtime.resumeThread({ - threadId: linksFailThreadId, - providerThread: linksFailProviderThread, - modelSelection, - runtimePolicy, - }); - assert.isUndefined(yield* registry.resolve(stagedLinksToken)); - assert.equal( - (yield* mcpSessions.read(linksFailThreadId))?.authorizationHeader, - beforeLinksFail.authorizationHeader, - ); // A failed detach unload keeps the loaded MCP credential record so reattaching with a // rotated credential still enforces reload/rollback and retries cleanly once unload recovers. yield* Ref.set(failUnload, false); - const { - threadId: detachFailThreadId, - providerThread: detachFailProviderThread, - loadedConfig: beforeDetachFail, - loadedToken: beforeDetachFailToken, - } = yield* attachLoadedThread("detach-unload-fail"); + const detachFail = yield* attachLoadedThread("detach-unload-fail"); yield* eventSink.write({ events: [ { - id: yield* idAllocator.allocate.event({ threadId: detachFailThreadId }), + id: yield* idAllocator.allocate.event({ threadId: detachFail.threadId }), type: "provider-thread.updated", - threadId: detachFailThreadId, + threadId: detachFail.threadId, occurredAt: now, - payload: detachFailProviderThread, + payload: detachFail.providerThread, }, ], }); yield* Ref.set(failUnload, true); - yield* manager.detach({ providerSessionId, threadId: detachFailThreadId }); - const detachRetryRunId = RunId.make("run-detach-fail-typed"); - const detachRetryAttemptId = RunAttemptId.make("attempt-detach-fail-typed"); - yield* openFor(manager, providerSessionId, detachFailThreadId, { - runId: detachRetryRunId, - attemptId: detachRetryAttemptId, - requireRunScopedMcp: true, - }); - const stagedDetachToken = rawBearer(yield* mcpSessions.read(detachFailThreadId)); - assert.notEqual(stagedDetachToken, beforeDetachFailToken); - yield* runtime.resumeThread({ - threadId: detachFailThreadId, - providerThread: detachFailProviderThread, - modelSelection, - runtimePolicy, - }); - assert.isUndefined(yield* registry.resolve(stagedDetachToken)); - assert.equal( - (yield* mcpSessions.read(detachFailThreadId))?.authorizationHeader, - beforeDetachFail.authorizationHeader, - ); - yield* Ref.set(failUnload, false); - yield* openFor(manager, providerSessionId, detachFailThreadId, { - runId: detachRetryRunId, - attemptId: detachRetryAttemptId, - requireRunScopedMcp: true, + yield* manager.detach({ providerSessionId, threadId: detachFail.threadId }); + yield* assertFailedUnloadRollback({ + targetThreadId: detachFail.threadId, + targetProviderThread: detachFail.providerThread, + beforeConfig: detachFail.loadedConfig, + beforeToken: detachFail.loadedToken, + runId: RunId.make("run-detach-fail-typed"), + attemptId: RunAttemptId.make("attempt-detach-fail-typed"), + retryAfterRecovery: true, }); - const retriedDetachConfig = yield* mcpSessions.read(detachFailThreadId); - assert.isDefined(retriedDetachConfig); - assert.notEqual( - retriedDetachConfig!.authorizationHeader, - beforeDetachFail.authorizationHeader, - ); - yield* runtime.resumeThread({ - threadId: detachFailThreadId, - providerThread: detachFailProviderThread, - modelSelection, - runtimePolicy, - }); - assert.isTrue(Option.isSome(yield* Queue.poll(unloads))); - const resolvedDetachRetry = yield* registry.resolve(rawBearer(retriedDetachConfig)); - assert.isDefined(resolvedDetachRetry); - assert.equal(resolvedDetachRetry!.thread.runId, detachRetryRunId); - assert.equal(resolvedDetachRetry!.thread.attemptId, detachRetryAttemptId); - assert.isUndefined(yield* registry.resolve(beforeDetachFailToken)); yield* manager.close(providerSessionId); }); - const serverSettingsLayer = ServerSettings.layerTest().pipe(Layer.orDie); yield* effect.pipe( Effect.provide( - Layer.merge( - layerTest({ - state, - idleTimeoutMs: 1_000, - unloads, - hasPendingBackgroundWork: Ref.get(sessionBackgroundWorkProbe).pipe(Effect.flatten), - hasPendingBackgroundWorkForThread: Ref.get(pendingBackgroundWork), - beforeUnload: Ref.get(failUnload).pipe( - Effect.flatMap((fail) => (fail ? Effect.die("unload failed") : Effect.void)), - ), - serverSettingsLayer, - }), - serverSettingsLayer, - ), + withServerSettings({ + state, + idleTimeoutMs: 1_000, + unloads, + hasPendingBackgroundWork: Ref.get(sessionBackgroundWorkProbe).pipe(Effect.flatten), + hasPendingBackgroundWorkForThread: Ref.get(pendingBackgroundWork), + beforeUnload: Ref.get(failUnload).pipe( + Effect.flatMap((fail) => (fail ? Effect.die("unload failed") : Effect.void)), + ), + }), ), ); return; @@ -4158,16 +4059,8 @@ it.effect.each([ const unloads = yield* Queue.unbounded(); const effect = Effect.gen(function* () { - const eventSink = yield* EventSink.EventSinkV2; - const idAllocator = yield* IdAllocator.IdAllocatorV2; - const manager = yield* ProviderSessionManager.ProviderSessionManagerV2; - const mcpSessions = yield* McpProviderSessions.McpProviderSessions; - const now = yield* DateTime.now; - const threadId = ThreadId.make("thread-provider-session-manager-shared-rotate"); - const providerSessionId = yield* idAllocator.allocate.providerSession({ - providerInstanceId: modelSelection.instanceId, - threadId, - }); + const { eventSink, idAllocator, manager, mcpSessions, now, threadId, providerSessionId } = + yield* setupSession("shared-rotate"); yield* eventSink.write({ events: [yield* makeThreadCreatedEvent({ idAllocator, threadId, now })], }); @@ -4223,15 +4116,7 @@ it.effect.each([ yield* manager.close(providerSessionId); }); - yield* effect.pipe( - Effect.provide( - layerTest({ - state, - idleTimeoutMs: 1_000, - unloads, - }), - ), - ); + yield* effect.pipe(Effect.provide(layerTest({ state, idleTimeoutMs: 1_000, unloads }))); }), ); diff --git a/apps/server/src/orchestration-v2/ProviderSessionManager.ts b/apps/server/src/orchestration-v2/ProviderSessionManager.ts index dd384510c01c4..d33485009dfbe 100644 --- a/apps/server/src/orchestration-v2/ProviderSessionManager.ts +++ b/apps/server/src/orchestration-v2/ProviderSessionManager.ts @@ -699,24 +699,29 @@ export const layerWithOptions = ( } return next ?? current; }); + const rawBearerToken = ( + config: Pick, + ) => config.authorizationHeader.replace(/^Bearer\s+/, ""); const mcpTurnKey = (runId: RunId, attemptId?: RunAttemptId) => `${runId}:${attemptId ?? ""}`; const recordMcpTurnChecked = ( providerSessionId: ProviderSessionId, threadId: ThreadId, turnKey: string | undefined, + expectedRuntime?: ProviderAdapter.ProviderAdapterV2SessionRuntime, ) => Ref.update(sessions, (current) => { const key = sessionKey(providerSessionId); const entry = current.get(key); - if (entry === undefined || entry.mcpTurnCheckedKeyByThread.get(threadId) === turnKey) { + if ( + entry === undefined || + (expectedRuntime !== undefined && entry.runtime !== expectedRuntime) || + entry.mcpTurnCheckedKeyByThread.get(threadId) === turnKey + ) { return current; } const mcpTurnCheckedKeyByThread = new Map(entry.mcpTurnCheckedKeyByThread); - if (turnKey === undefined) { - mcpTurnCheckedKeyByThread.delete(threadId); - } else { - mcpTurnCheckedKeyByThread.set(threadId, turnKey); - } + if (turnKey === undefined) mcpTurnCheckedKeyByThread.delete(threadId); + else mcpTurnCheckedKeyByThread.set(threadId, turnKey); return new Map(current).set(key, { ...entry, mcpTurnCheckedKeyByThread }); }); const threadRequiresRunScopedMcp = ( @@ -738,10 +743,10 @@ export const layerWithOptions = ( threadId: ThreadId, providerInstanceId: ProviderInstanceId, turn?: { - readonly runId?: RunId; - readonly attemptId?: RunAttemptId; - readonly rotateOnRunChange?: boolean; - readonly ownerSessionId?: string; + readonly runId?: RunId | undefined; + readonly attemptId?: RunAttemptId | undefined; + readonly rotateOnRunChange?: boolean | undefined; + readonly ownerSessionId?: string | undefined; }, ): Effect.Effect => options.configureMcp === false @@ -785,7 +790,7 @@ export const layerWithOptions = ( const existingCredentialId = McpProviderSession.mcpCredentialIdOf(existing); // Reserve before async validation so release cannot revoke between validation and reservation. reserveMcpCredential(threadId, existingCredentialId); - const rawToken = existing.authorizationHeader.replace(/^Bearer\s+/, ""); + const rawToken = rawBearerToken(existing); // Interrupted resolution must release the reservation before the caller learns of it. const resolved = yield* mcpSessionRegistry .resolve(rawToken) @@ -2073,10 +2078,7 @@ export const layerWithOptions = ( } const loadedProviderThreadKeyByThread = new Map(entry.loadedProviderThreadKeyByThread); loadedProviderThreadKeyByThread.delete(input.threadId); - return new Map(current).set(key, { - ...entry, - loadedProviderThreadKeyByThread, - }); + return new Map(current).set(key, { ...entry, loadedProviderThreadKeyByThread }); }); /** Pass the setting read before a native load; cache hits keep the earlier record. */ @@ -2226,9 +2228,9 @@ export const layerWithOptions = ( readonly providerInstanceId: ProviderInstanceId; readonly runtime: ProviderAdapter.ProviderAdapterV2SessionRuntime; readonly runId: RunId; - readonly attemptId?: RunAttemptId; - readonly requireRunScopedMcp?: boolean; - readonly owedOutputRunId?: RunId; + readonly attemptId?: RunAttemptId | undefined; + readonly requireRunScopedMcp?: boolean | undefined; + readonly owedOutputRunId?: RunId | undefined; }) { if (options.configureMcp === false) return; let reservedCredentialId: string | undefined; @@ -2265,8 +2267,7 @@ export const layerWithOptions = ( } const { browser: browserToolsAvailable, device: deviceToolsAvailable } = yield* agentAccessSettings(input.threadId); - const rawToken = latest.authorizationHeader.replace(/^Bearer\s+/, ""); - const resolved = yield* mcpSessionRegistry.resolve(rawToken); + const resolved = yield* mcpSessionRegistry.resolve(rawBearerToken(latest)); const hasPreview = resolved !== undefined ? resolved.capabilities.has("preview") @@ -2378,8 +2379,8 @@ export const layerWithOptions = ( ?.mcpOwnerSessionIdByThread.get(input.threadId); const prepared = yield* prepareMcpSession(input.threadId, input.providerInstanceId, { runId: input.runId, - ...(input.attemptId === undefined ? {} : { attemptId: input.attemptId }), - ...(ownerSessionId === undefined ? {} : { ownerSessionId }), + attemptId: input.attemptId, + ownerSessionId, rotateOnRunChange, }); reservedCredentialId = prepared.mcpCredentialId; @@ -2670,9 +2671,7 @@ export const layerWithOptions = ( const loadedProviderThreadKeyByThread = new Map( latest.loadedProviderThreadKeyByThread, ); - if (isCurrent) { - loadedProviderThreadKeyByThread.delete(input.threadId); - } + if (isCurrent) loadedProviderThreadKeyByThread.delete(input.threadId); const updated = new Map(current); updated.set(key, { ...latest, @@ -2800,10 +2799,7 @@ export const layerWithOptions = ( loadedProviderThreadKeyByThread.delete(input.threadId); return [ true, - new Map(current).set(key, { - ...latest, - loadedProviderThreadKeyByThread, - }), + new Map(current).set(key, { ...latest, loadedProviderThreadKeyByThread }), ] as const; }); if (!unloading) return; @@ -2973,28 +2969,20 @@ export const layerWithOptions = ( if (rollback.revokeStaged) { yield* mcpSessionRegistry.revokeCredential(currentCredentialId); } - const loadedRawToken = loadedCredential.authorizationHeader.replace( - /^Bearer\s+/, - "", + const resolvedLoaded = yield* mcpSessionRegistry.resolve( + rawBearerToken(loadedCredential), ); - const resolvedLoaded = yield* mcpSessionRegistry.resolve(loadedRawToken); // Capability removals revoke immediately; the thread then holds no working token. if (resolvedLoaded === undefined) { if (rollback.revokeStaged) { yield* mcpSessions.clear(input.threadId); } - yield* Ref.update(sessions, (current) => { - const latest = current.get(key); - if ( - latest?.runtime !== entry.runtime || - !latest.mcpTurnCheckedKeyByThread.has(input.threadId) - ) { - return current; - } - const mcpTurnCheckedKeyByThread = new Map(latest.mcpTurnCheckedKeyByThread); - mcpTurnCheckedKeyByThread.delete(input.threadId); - return new Map(current).set(key, { ...latest, mcpTurnCheckedKeyByThread }); - }); + yield* recordMcpTurnChecked( + input.providerSessionId, + input.threadId, + undefined, + entry.runtime, + ); return yield* new ProviderAdapter.ProviderAdapterMcpRotationBlockedError({ driver: entry.runtime.driver, providerSessionId: input.providerSessionId, @@ -3271,6 +3259,81 @@ export const layerWithOptions = ( }), ), ); + const runTrackedTurn = ( + input: Pick< + ProviderAdapter.ProviderAdapterV2TurnInput, + "threadId" | "providerThread" | "runId" | "attemptId" | "runOrdinal" | "modelSelection" + >, + releasedCause: string, + run: () => Effect.Effect, + ) => + observeActivity( + providerSessionId, + ensureThreadAttached({ + providerSessionId, + threadId: input.threadId, + providerInstanceId: runtime.instanceId, + }), + ).pipe( + Effect.andThen(ensureTurnMcp(input)), + // Failed or stopped starts may omit turn.terminal; clear their turns so sessions can idle. + Effect.andThen( + holdThreadLoaded({ + providerSessionId, + threadId: input.threadId, + providerThread: input.providerThread, + }), + ), + Effect.andThen( + Effect.acquireUseRelease( + markBusy( + providerSessionId, + busyTurnKey(input.providerThread.id, input.runOrdinal), + runtime, + ).pipe( + Effect.catchCause((cause) => + Effect.logWarning("orchestration-v2.driver-session.activity-failed", { + providerSessionId, + cause, + }).pipe(Effect.as(true)), + ), + // A release between attach and markBusy leaves nothing to mark: fail the + // start instead of running it on a runtime being torn down. + Effect.flatMap((marked) => + marked + ? Effect.void + : Effect.fail( + new ProviderAdapter.ProviderAdapterTurnStartError({ + driver: runtime.driver, + threadId: input.threadId, + providerThreadId: input.providerThread.id, + runId: input.runId, + cause: releasedCause, + }), + ), + ), + ), + () => run().pipe(turnMetrics("send", input.modelSelection.model)), + (_, exit) => + Exit.isFailure(exit) + ? observeActivity( + providerSessionId, + markIdle(providerSessionId, input.providerThread.id, input.runOrdinal), + ).pipe( + // A failed start can leave its native thread gone (Claude rejecting a + // resume), so the next start must ask the adapter to resume it again. + Effect.andThen( + forgetProviderThreadLoaded({ + providerSessionId, + threadId: input.threadId, + runtime, + }), + ), + ) + : Effect.void, + ), + ), + ); return { ...runtime, // Pi replaces its session snapshot as metadata changes. @@ -3416,152 +3479,19 @@ export const layerWithOptions = ( Effect.map(({ loaded }) => loaded), ), startTurn: (input) => - observeActivity( - providerSessionId, - ensureThreadAttached({ - providerSessionId, - threadId: input.threadId, - providerInstanceId: runtime.instanceId, - }), - ).pipe( - Effect.andThen(ensureTurnMcp(input)), - // Failed or stopped starts may omit turn.terminal; clear their turns so sessions can idle. - Effect.andThen( - holdThreadLoaded({ - providerSessionId, - threadId: input.threadId, - providerThread: input.providerThread, - }), - ), - Effect.andThen( - Effect.acquireUseRelease( - markBusy( - providerSessionId, - busyTurnKey(input.providerThread.id, input.runOrdinal), - runtime, - ).pipe( - Effect.catchCause((cause) => - Effect.logWarning("orchestration-v2.driver-session.activity-failed", { - providerSessionId, - cause, - }).pipe(Effect.as(true)), - ), - // A release between attach and markBusy leaves nothing to mark: fail the - // start instead of running it on a runtime being torn down. - Effect.flatMap((marked) => - marked - ? Effect.void - : Effect.fail( - new ProviderAdapter.ProviderAdapterTurnStartError({ - driver: runtime.driver, - threadId: input.threadId, - providerThreadId: input.providerThread.id, - runId: input.runId, - cause: "The provider session was released while the turn started.", - }), - ), - ), - ), - () => - agentFeedbackMode.pipe( - Effect.flatMap((agentFeedback) => - runtime.startTurn({ ...input, agentFeedback }), - ), - turnMetrics("send", input.modelSelection.model), - ), - (_, exit) => - Exit.isFailure(exit) - ? observeActivity( - providerSessionId, - markIdle(providerSessionId, input.providerThread.id, input.runOrdinal), - ).pipe( - // A failed start can leave its native thread gone (Claude rejecting a - // resume), so the next start must ask the adapter to resume it again. - Effect.andThen( - forgetProviderThreadLoaded({ - providerSessionId, - threadId: input.threadId, - runtime, - }), - ), - ) - : Effect.void, - ), + runTrackedTurn(input, "The provider session was released while the turn started.", () => + agentFeedbackMode.pipe( + Effect.flatMap((agentFeedback) => runtime.startTurn({ ...input, agentFeedback })), ), ), ...(runtime.resumeTurn === undefined ? {} : { resumeTurn: (input) => - observeActivity( - providerSessionId, - ensureThreadAttached({ - providerSessionId, - threadId: input.threadId, - providerInstanceId: runtime.instanceId, - }), - ).pipe( - Effect.andThen(ensureTurnMcp(input)), - Effect.andThen( - holdThreadLoaded({ - providerSessionId, - threadId: input.threadId, - providerThread: input.providerThread, - }), - ), - Effect.andThen( - Effect.acquireUseRelease( - markBusy( - providerSessionId, - busyTurnKey(input.providerThread.id, input.runOrdinal), - runtime, - ).pipe( - Effect.catchCause((cause) => - Effect.logWarning("orchestration-v2.driver-session.activity-failed", { - providerSessionId, - cause, - }).pipe(Effect.as(true)), - ), - Effect.flatMap((marked) => - marked - ? Effect.void - : Effect.fail( - new ProviderAdapter.ProviderAdapterTurnStartError({ - driver: runtime.driver, - threadId: input.threadId, - providerThreadId: input.providerThread.id, - runId: input.runId, - cause: - "The provider session was released while the turn resumed.", - }), - ), - ), - ), - () => - runtime.resumeTurn!(input).pipe( - turnMetrics("send", input.modelSelection.model), - ), - (_, exit) => - Exit.isFailure(exit) - ? observeActivity( - providerSessionId, - markIdle( - providerSessionId, - input.providerThread.id, - input.runOrdinal, - ), - ).pipe( - Effect.andThen( - forgetProviderThreadLoaded({ - providerSessionId, - threadId: input.threadId, - runtime, - }), - ), - ) - : Effect.void, - ), - ), + runTrackedTurn( + input, + "The provider session was released while the turn resumed.", + () => runtime.resumeTurn!(input), ), }), steerTurn: (input) => @@ -4081,13 +4011,9 @@ export const layerWithOptions = ( providerInstanceId: existing.runtime.instanceId, runtime: existing.runtime, runId: input.runId, - ...(input.attemptId === undefined ? {} : { attemptId: input.attemptId }), - ...(input.requireRunScopedMcp === undefined - ? {} - : { requireRunScopedMcp: input.requireRunScopedMcp }), - ...(input.owedOutputRunId === undefined - ? {} - : { owedOutputRunId: input.owedOutputRunId }), + attemptId: input.attemptId, + requireRunScopedMcp: input.requireRunScopedMcp, + owedOutputRunId: input.owedOutputRunId, }); } else if ( options.configureMcp !== false && @@ -4140,7 +4066,7 @@ export const layerWithOptions = ( input.runId !== undefined ? { runId: input.runId, - ...(input.attemptId === undefined ? {} : { attemptId: input.attemptId }), + attemptId: input.attemptId, rotateOnRunChange: input.requireRunScopedMcp === true || input.owedOutputRunId !== undefined, } @@ -4525,20 +4451,17 @@ export const layerWithOptions = ( discard: true, }); } - const detached = Option.map(detachResult, (result) => result.entry); - const detachedCredentialId = Option.isSome(detachResult) - ? detachResult.value.detachedCredentialId - : undefined; // Plain detaches preserve credentials held by live shared providers across workspace handoffs. if (input.revokeMcpCredential === true) { yield* clearMcpSession(input.threadId); } - if (Option.isNone(detached)) { + if (Option.isNone(detachResult)) { return; } + const { entry: detachedEntry, detachedCredentialId } = detachResult.value; if ( - detached.value.attachedThreadIds.size === 0 && - !detached.value.supportsMultipleProviderThreads + detachedEntry.attachedThreadIds.size === 0 && + !detachedEntry.supportsMultipleProviderThreads ) { yield* releaseEntry({ providerSessionId: input.providerSessionId, @@ -4548,8 +4471,8 @@ export const layerWithOptions = ( }); return; } - const unloadThread = detached.value.exposedRuntime.unloadThread; - if (detached.value.supportsMultipleProviderThreads && unloadThread !== undefined) { + const unloadThread = detachedEntry.exposedRuntime.unloadThread; + if (detachedEntry.supportsMultipleProviderThreads && unloadThread !== undefined) { // The projection includes native children owned by other app threads; // lock each owner so an attached child stays loaded and later attaches wait. for (const providerThread of detachedProviderThreads) { @@ -4563,7 +4486,7 @@ export const layerWithOptions = ( Effect.gen(function* () { const entry = (yield* Ref.get(sessions)).get(key); if ( - entry?.runtime !== detached.value.runtime || + entry?.runtime !== detachedEntry.runtime || entry.attachedThreadIds.has(ownerThreadId) ) { return; @@ -4574,7 +4497,7 @@ export const layerWithOptions = ( Ref.update(sessions, (current) => { const latest = current.get(key); if ( - latest?.runtime !== detached.value.runtime || + latest?.runtime !== detachedEntry.runtime || latest.attachedThreadIds.has(ownerThreadId) ) { return current; diff --git a/apps/server/src/orchestration-v2/runtimeLayer.test.ts b/apps/server/src/orchestration-v2/runtimeLayer.test.ts index 5a782bcf542e6..0d86132c98010 100644 --- a/apps/server/src/orchestration-v2/runtimeLayer.test.ts +++ b/apps/server/src/orchestration-v2/runtimeLayer.test.ts @@ -12518,6 +12518,12 @@ it.layer(layerSharedApplicationDataPlaneTest)("run output after a stop", (it) => }, ], }); + const finishRun = ( + run: Effect.Success>, + suffix: string, + status: "completed" | "interrupted", + extra?: Partial>>, + ) => updateRun(run, suffix, { status, completedAt: run.requestedAt, ...extra }); const submit = ( command: string, json: string, @@ -12531,12 +12537,11 @@ it.layer(layerSharedApplicationDataPlaneTest)("run output after a stop", (it) => }); return { orchestrator, - eventSink, - threadManagement, threadId, send, latestRun, updateRun, + finishRun, submit, }; }); @@ -12560,24 +12565,13 @@ it.layer(layerSharedApplicationDataPlaneTest)("run output after a stop", (it) => ])("$description", ({ scenario }) => Effect.gen(function* () { if (scenario === "stopped-run-or-stale-attempt") { - const { - orchestrator, - eventSink, - threadManagement, - threadId, - send, - latestRun, - updateRun, - submit, - } = yield* setupOutputThread("late-stopped-run"); + const { orchestrator, threadId, send, latestRun, updateRun, finishRun, submit } = + yield* setupOutputThread("late-stopped-run"); // Run A starts with a schema, then is stopped while its submission is in flight. yield* send("run-a", { type: "object" }); const runA = yield* latestRun(); - yield* updateRun(runA, "run-a-interrupted", { - status: "interrupted", - completedAt: runA.requestedAt, - }); + yield* finishRun(runA, "run-a-interrupted", "interrupted"); // Run B starts with a compatible schema and attempt 2 active. yield* send("run-b", { type: "object" }); @@ -12587,13 +12581,9 @@ it.layer(layerSharedApplicationDataPlaneTest)("run output after a stop", (it) => yield* updateRun(runB, "run-b-attempt-2", { activeAttemptId: attempt2 }); // A caller that names no run cannot be told from a stopped run's late call. - const anonymous = yield* threadManagement - .submitRunOutput({ - threadId, - commandId: CommandId.make("runtime-layer-anonymous-run-output"), - json: '{"from":"anonymous"}', - }) - .pipe(Effect.flip); + const anonymous = yield* submit("anonymous-run-output", '{"from":"anonymous"}').pipe( + Effect.flip, + ); assert.equal(anonymous._tag, "ThreadManagementRunOutputRejectedError"); assert.include(anonymous.message, "runId"); @@ -12606,10 +12596,7 @@ it.layer(layerSharedApplicationDataPlaneTest)("run output after a stop", (it) => const lateFromAttempt1 = yield* submit( "late-run-output-from-attempt-1", '{"from":"attempt-1"}', - { - callerRunId: runB.id, - callerAttemptId: attempt1, - }, + { callerRunId: runB.id, callerAttemptId: attempt1 }, ).pipe(Effect.flip); assert.equal(lateFromAttempt1._tag, "ThreadManagementRunOutputRejectedError"); assert.include(lateFromAttempt1.message, "no longer active"); @@ -12621,82 +12608,37 @@ it.layer(layerSharedApplicationDataPlaneTest)("run output after a stop", (it) => callerAttemptId: attempt2, }); assert.equal(acceptedB.runId, runB.id); - const afterB = yield* orchestrator.getThreadProjection(threadId); - assert.deepEqual(afterB.runs.find((run) => run.id === runB.id)?.output?.value, { - from: "run-b", - }); + const afterB = (yield* orchestrator.getThreadProjection(threadId)).runs.find( + (run) => run.id === runB.id, + )!; + assert.deepEqual(afterB.output?.value, { from: "run-b" }); // A continuation of stopped run A rejects A's delayed unbound submission and accepts C's own runId. - yield* eventSink.write({ - events: [ - { - id: EventId.make(`${threadId}-run-b-completed`), - type: "run.updated", - threadId, - runId: runB.id, - occurredAt: runB.requestedAt, - payload: { - ...afterB.runs.find((run) => run.id === runB.id)!, - status: "completed", - completedAt: runB.requestedAt, - }, - }, - ], - }); + yield* finishRun(afterB, "run-b-completed", "completed"); yield* send("run-c", { type: "object" }); - const runC = (yield* orchestrator.getThreadProjection(threadId)).runs.find( - (run) => run.id !== runA.id && run.id !== runB.id, - )!; - yield* eventSink.write({ - events: [ - { - id: EventId.make(`${threadId}-run-c-continues-a`), - type: "run.updated", - threadId, - runId: runC.id, - occurredAt: runC.requestedAt, - payload: { - ...runC, - manualContinuationOfRunId: runA.id, - }, - }, - ], - }); - const lateFromStoppedAncestor = yield* threadManagement - .submitRunOutput({ - threadId, - commandId: CommandId.make("runtime-layer-run-output-from-stopped-ancestor"), - json: '{"from":"late-ancestor"}', - callerRunId: runA.id, - }) - .pipe(Effect.flip); + const runC = yield* latestRun(); + yield* updateRun(runC, "run-c-continues-a", { manualContinuationOfRunId: runA.id }); + const lateFromStoppedAncestor = yield* submit( + "run-output-from-stopped-ancestor", + '{"from":"late-ancestor"}', + { callerRunId: runA.id }, + ).pipe(Effect.flip); assert.equal(lateFromStoppedAncestor._tag, "ThreadManagementRunOutputRejectedError"); assert.include(lateFromStoppedAncestor.message, "no longer active"); - assert.isUndefined( - (yield* orchestrator.getThreadProjection(threadId)).runs.find((run) => run.id === runC.id) - ?.output, + assert.isUndefined((yield* latestRun()).output); + const acceptedViaContinuation = yield* submit( + "run-output-via-continuation", + '{"from":"continued"}', + { callerRunId: runC.id }, ); - const acceptedViaContinuation = yield* threadManagement.submitRunOutput({ - threadId, - commandId: CommandId.make("runtime-layer-run-output-via-continuation"), - json: '{"from":"continued"}', - callerRunId: runC.id, - }); assert.equal(acceptedViaContinuation.runId, runC.id); - const afterC = yield* orchestrator.getThreadProjection(threadId); - assert.deepEqual(afterC.runs.find((run) => run.id === runC.id)?.output?.value, { - from: "continued", - }); + const afterC = (yield* orchestrator.getThreadProjection(threadId)).runs.find( + (run) => run.id === runC.id, + )!; + assert.deepEqual(afterC.output?.value, { from: "continued" }); // A plain turn with no schema preserves the plain-turn guidance even for stale/unbound MCP callers. - yield* updateRun( - afterC.runs.find((run) => run.id === runC.id)!, - "run-c-completed", - { - status: "completed", - completedAt: runC.requestedAt, - }, - ); + yield* finishRun(afterC, "run-c-completed", "completed"); yield* send("run-plain"); const plainFromStale = yield* submit("plain-run-output-stale", "{}", { callerRunId: runA.id, @@ -12710,22 +12652,16 @@ it.layer(layerSharedApplicationDataPlaneTest)("run output after a stop", (it) => } if (scenario === "owed-run-and-wake") { - const { orchestrator, threadId, send, latestRun, updateRun, submit } = + const { orchestrator, threadId, send, latestRun, finishRun, submit } = yield* setupOutputThread("owed-wake-output"); yield* send("run-a", { type: "object" }); const runA = yield* latestRun(); - yield* updateRun(runA, "run-a-interrupted", { - status: "interrupted", - completedAt: runA.requestedAt, - }); + yield* finishRun(runA, "run-a-interrupted", "interrupted"); yield* send("run-c", { type: "object" }); const runC = yield* latestRun(); - yield* updateRun(runC, "run-c-completed", { - status: "completed", - completedAt: runC.requestedAt, - }); + yield* finishRun(runC, "run-c-completed", "completed"); yield* send("run-d-wake"); const runD = yield* latestRun(); const staleAOnWake = yield* submit( @@ -12739,146 +12675,112 @@ it.layer(layerSharedApplicationDataPlaneTest)("run output after a stop", (it) => callerRunId: runC.id, }); assert.equal(acceptedFromC.runId, runC.id); - const afterC = yield* orchestrator.getThreadProjection(threadId); - assert.deepEqual(afterC.runs.find((run) => run.id === runC.id)?.output?.value, { - from: "run-c", - }); + assert.deepEqual( + (yield* orchestrator.getThreadProjection(threadId)).runs.find((run) => run.id === runC.id) + ?.output?.value, + { from: "run-c" }, + ); - yield* updateRun(runD, "run-d-completed", { - status: "completed", - completedAt: runD.requestedAt, - }); + yield* finishRun(runD, "run-d-completed", "completed"); yield* send("run-e", { type: "object" }); const runE = yield* latestRun(); - yield* updateRun(runE, "run-e-completed", { - status: "completed", - completedAt: runE.requestedAt, - }); + yield* finishRun(runE, "run-e-completed", "completed"); yield* send("run-f-wake"); const runF = yield* latestRun(); const acceptedFromF = yield* submit("late-run-output-from-f", '{"from":"run-f"}', { callerRunId: runF.id, }); assert.equal(acceptedFromF.runId, runE.id); - const afterF = yield* orchestrator.getThreadProjection(threadId); - assert.deepEqual(afterF.runs.find((run) => run.id === runE.id)?.output?.value, { - from: "run-f", - }); + assert.deepEqual( + (yield* orchestrator.getThreadProjection(threadId)).runs.find((run) => run.id === runE.id) + ?.output?.value, + { from: "run-f" }, + ); return; } - const { orchestrator, threadId, send, latestRun, updateRun } = yield* setupOutputThread( + const { orchestrator, threadId, send, latestRun, finishRun } = yield* setupOutputThread( "completed-before-dispatch", ); - yield* send("run-own", { type: "object" }); - const run = yield* latestRun(); - const attempt = RunAttemptId.make(`${run.id}:attempt:1`); - yield* updateRun(run, "run-own-completed", { - activeAttemptId: attempt, - status: "completed", - completedAt: run.requestedAt, - }); + const dispatchOutput = ( + command: string, + targetRunId: RunId, + callerAttemptId: RunAttemptId, + answer: string, + ) => + orchestrator.dispatch({ + type: "run.output.submit", + commandId: CommandId.make(`runtime-layer-${command}`), + threadId, + runId: targetRunId, + callerRunId: targetRunId, + callerAttemptId, + value: { answer }, + }); + const completeWithAttempt = (name: string) => + Effect.gen(function* () { + yield* send(name, { type: "object" }); + const run = yield* latestRun(); + const attempt = RunAttemptId.make(`${run.id}:attempt:1`); + yield* finishRun(run, `${name}-completed`, "completed", { activeAttemptId: attempt }); + return { run, attempt }; + }); + const own = yield* completeWithAttempt("run-own"); // Simulate the race where the run completes after service validation, with no active run. - yield* orchestrator.dispatch({ - type: "run.output.submit", - commandId: CommandId.make("runtime-layer-completed-before-dispatch-submit"), - threadId, - runId: run.id, - callerRunId: run.id, - callerAttemptId: attempt, - value: { answer: "landed-on-completion-race" }, - }); - const after = yield* orchestrator.getThreadProjection(threadId); - assert.deepEqual(after.runs[0]?.output?.value, { + yield* dispatchOutput( + "completed-before-dispatch-submit", + own.run.id, + own.attempt, + "landed-on-completion-race", + ); + assert.deepEqual((yield* orchestrator.getThreadProjection(threadId)).runs[0]?.output?.value, { answer: "landed-on-completion-race", }); // A scheduled fresh-context run is a side conversation and still allows the owed submission. - yield* send("run-before-sched", { type: "object" }); - const beforeSched = yield* latestRun(); - const beforeSchedAttempt = RunAttemptId.make(`${beforeSched.id}:attempt:1`); - yield* updateRun(beforeSched, "run-before-sched-completed", { - activeAttemptId: beforeSchedAttempt, - status: "completed", - completedAt: beforeSched.requestedAt, - }); + const beforeSched = yield* completeWithAttempt("run-before-sched"); yield* send("run-sched-fresh", undefined, { freshContext: true, scheduledTaskId: ScheduledTaskId.make("runtime-layer-sched-fresh-task"), }); - yield* orchestrator.dispatch({ - type: "run.output.submit", - commandId: CommandId.make("runtime-layer-sched-fresh-owed-dispatch-submit"), - threadId, - runId: beforeSched.id, - callerRunId: beforeSched.id, - callerAttemptId: beforeSchedAttempt, - value: { answer: "landed-across-scheduled-fresh" }, - }); - const schedFresh = yield* latestRun(); - yield* updateRun(schedFresh, "run-sched-fresh-completed", { - status: "completed", - completedAt: schedFresh.requestedAt, - }); + yield* dispatchOutput( + "sched-fresh-owed-dispatch-submit", + beforeSched.run.id, + beforeSched.attempt, + "landed-across-scheduled-fresh", + ); + yield* finishRun(yield* latestRun(), "run-sched-fresh-completed", "completed"); assert.deepEqual( (yield* orchestrator.getThreadProjection(threadId)).runs.find( - (candidate) => candidate.id === beforeSched.id, + (candidate) => candidate.id === beforeSched.run.id, )?.output?.value, { answer: "landed-across-scheduled-fresh" }, ); // An unscheduled fresh-context run moves the context boundary past the owed run under the lock. - yield* send("run-before-fresh", { type: "object" }); - const beforeFresh = yield* latestRun(); - const beforeFreshAttempt = RunAttemptId.make(`${beforeFresh.id}:attempt:1`); - yield* updateRun(beforeFresh, "run-before-fresh-completed", { - activeAttemptId: beforeFreshAttempt, - status: "completed", - completedAt: beforeFresh.requestedAt, - }); + const beforeFresh = yield* completeWithAttempt("run-before-fresh"); yield* send("run-unscheduled-fresh", undefined, { freshContext: true }); - const acrossFresh = yield* orchestrator - .dispatch({ - type: "run.output.submit", - commandId: CommandId.make("runtime-layer-fresh-owed-dispatch-submit"), - threadId, - runId: beforeFresh.id, - callerRunId: beforeFresh.id, - callerAttemptId: beforeFreshAttempt, - value: { answer: "stale-after-fresh-context" }, - }) - .pipe(Effect.flip); + const acrossFresh = yield* dispatchOutput( + "fresh-owed-dispatch-submit", + beforeFresh.run.id, + beforeFresh.attempt, + "stale-after-fresh-context", + ).pipe(Effect.flip); assert.instanceOf(acrossFresh, Orchestrator.OrchestratorDispatchError); assert.instanceOf(acrossFresh.cause, Orchestrator.RunOutputDispatchRejectionError); assert.equal(acrossFresh.cause.reason, "inactive"); - const unscheduledFresh = yield* latestRun(); - yield* updateRun(unscheduledFresh, "run-unscheduled-fresh-completed", { - status: "completed", - completedAt: unscheduledFresh.requestedAt, - }); + yield* finishRun(yield* latestRun(), "run-unscheduled-fresh-completed", "completed"); // Once a newer started turn asks for a result, an earlier unanswered turn no longer owes one. - yield* send("run-first", { type: "object" }); - const first = yield* latestRun(); - const firstAttempt = RunAttemptId.make(`${first.id}:attempt:1`); - yield* updateRun(first, "run-first-completed", { - activeAttemptId: firstAttempt, - status: "completed", - completedAt: first.requestedAt, - }); + const first = yield* completeWithAttempt("run-first"); yield* send("run-superseded", { type: "object" }); - const superseded = yield* orchestrator - .dispatch({ - type: "run.output.submit", - commandId: CommandId.make("runtime-layer-superseded-owed-dispatch-submit"), - threadId, - runId: first.id, - callerRunId: first.id, - callerAttemptId: firstAttempt, - value: { answer: "stale-after-superseded" }, - }) - .pipe(Effect.flip); + const superseded = yield* dispatchOutput( + "superseded-owed-dispatch-submit", + first.run.id, + first.attempt, + "stale-after-superseded", + ).pipe(Effect.flip); assert.instanceOf(superseded, Orchestrator.OrchestratorDispatchError); assert.instanceOf(superseded.cause, Orchestrator.RunOutputDispatchRejectionError); assert.equal(superseded.cause.reason, "inactive"); diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts index c3f426920c7bf..03112b09a00cc 100644 --- a/packages/provider-acp/src/server/adapter.ts +++ b/packages/provider-acp/src/server/adapter.ts @@ -8127,6 +8127,10 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( Ref.getUnsafe(installedInitializeResult) ?? started.initializeResult; const installedAgentCapabilities = () => installedInitialize().agentCapabilities; + const canLoadOrResume = () => { + const agent = installedAgentCapabilities(); + return agent?.loadSession === true || agent?.sessionCapabilities?.resume != null; + }; const usesMcpOverAcp = () => installedAgentCapabilities()?.mcpCapabilities?.acp === true && runtimeMcpBridge !== undefined; @@ -10236,15 +10240,11 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( return providerSession; }, get canResumeAfterRestart() { - const agent = installedAgentCapabilities(); - return agent?.loadSession === true || agent?.sessionCapabilities?.resume != null; + return canLoadOrResume(); }, get mcpCredentialRotation() { - const agent = installedAgentCapabilities(); if (usesMcpOverAcp()) return "live" as const; - return agent?.loadSession === true || agent?.sessionCapabilities?.resume != null - ? ("reload" as const) - : ("none" as const); + return canLoadOrResume() ? ("reload" as const) : ("none" as const); }, events: Stream.fromEffectRepeat(Queue.take(events)), ...(flavor.getModelContextWindow === undefined diff --git a/packages/provider-muse/src/server/adapter.test.ts b/packages/provider-muse/src/server/adapter.test.ts index 5fe501bf5295a..c2351c162ed7a 100644 --- a/packages/provider-muse/src/server/adapter.test.ts +++ b/packages/provider-muse/src/server/adapter.test.ts @@ -428,15 +428,17 @@ describe("MuseAdapterV2", () => { it.effect("re-resumes with rotated MCP credentials on the next turn", () => Effect.gen(function* () { const mcpSessions = yield* McpProviderSessions.McpProviderSessions; - yield* mcpSessions.set({ - environmentId: EnvironmentId.make("test-environment"), - threadId: THREAD_ID, - providerSessionId: "test-session-1", - providerInstanceId: INSTANCE_ID, - endpoint: "http://127.0.0.1:43210/mcp", - authorizationHeader: "Bearer muse-run-1-token", - browserToolsAvailable: false, - }); + const setMcp = (ordinal: number) => + mcpSessions.set({ + environmentId: EnvironmentId.make("test-environment"), + threadId: THREAD_ID, + providerSessionId: `test-session-${ordinal}`, + providerInstanceId: INSTANCE_ID, + endpoint: "http://127.0.0.1:43210/mcp", + authorizationHeader: `Bearer muse-run-${ordinal}-token`, + browserToolsAvailable: false, + }); + yield* setMcp(1); const fake = yield* makeFakeMuse(); fake.host.initializeResult.grantedCapabilities.push("sessionMcp"); const harness = yield* makeHarness(fake, INSTANCE_ID); @@ -450,15 +452,7 @@ describe("MuseAdapterV2", () => { "Bearer muse-run-1-token", ); - yield* mcpSessions.set({ - environmentId: EnvironmentId.make("test-environment"), - threadId: THREAD_ID, - providerSessionId: "test-session-2", - providerInstanceId: INSTANCE_ID, - endpoint: "http://127.0.0.1:43210/mcp", - authorizationHeader: "Bearer muse-run-2-token", - browserToolsAvailable: false, - }); + yield* setMcp(2); yield* harness.runtime.startTurn(yield* turnInput(harness.providerThread, 2)); const resumed = yield* fake.takeCall("session/resume"); assert.deepStrictEqual(resumed.params.config, { diff --git a/packages/provider-opencode/src/server/adapter.test.ts b/packages/provider-opencode/src/server/adapter.test.ts index 407888c6dd6e5..331da779816f1 100644 --- a/packages/provider-opencode/src/server/adapter.test.ts +++ b/packages/provider-opencode/src/server/adapter.test.ts @@ -360,15 +360,17 @@ describe("OpenCodeAdapterV2", () => { const mcpSessions = yield* McpProviderSessions.McpProviderSessions; const threadId = ThreadId.make("thread-opencode-mcp-rotate"); const instanceId = ProviderInstanceId.make("opencode-mcp-rotate"); - yield* mcpSessions.set({ - environmentId: EnvironmentId.make("env-opencode-mcp-rotate"), - threadId, - providerSessionId: "mcp-session-opencode-1", - providerInstanceId: instanceId, - endpoint: "http://127.0.0.1:43123/mcp", - authorizationHeader: "Bearer opencode-run-1-token", - browserToolsAvailable: false, - }); + const setMcp = (ordinal: number) => + mcpSessions.set({ + environmentId: EnvironmentId.make("env-opencode-mcp-rotate"), + threadId, + providerSessionId: `mcp-session-opencode-${ordinal}`, + providerInstanceId: instanceId, + endpoint: "http://127.0.0.1:43123/mcp", + authorizationHeader: `Bearer opencode-run-${ordinal}-token`, + browserToolsAvailable: false, + }); + yield* setMcp(1); const harness = yield* makeOpenCodeRuntimeHarness( "mcp-rotate", "ses_mcp_rotate", @@ -392,15 +394,7 @@ describe("OpenCodeAdapterV2", () => { ); assert.equal(mcpAdds.length, 1); - yield* mcpSessions.set({ - environmentId: EnvironmentId.make("env-opencode-mcp-rotate"), - threadId, - providerSessionId: "mcp-session-opencode-2", - providerInstanceId: instanceId, - endpoint: "http://127.0.0.1:43123/mcp", - authorizationHeader: "Bearer opencode-run-2-token", - browserToolsAvailable: false, - }); + yield* setMcp(2); yield* harness.startTurn("Second turn", harness.providerThread, harness.policy, false, "2"); assert.deepEqual( mcpAdds.map( diff --git a/packages/provider-opencode/src/server/adapter.ts b/packages/provider-opencode/src/server/adapter.ts index 102df49ce3f48..ef7ac209cf0f3 100644 --- a/packages/provider-opencode/src/server/adapter.ts +++ b/packages/provider-opencode/src/server/adapter.ts @@ -1098,21 +1098,29 @@ export const makeOpenCodeAdapterV2 = Effect.fn("makeOpenCodeAdapterV2")(function hasT3Mcp, mcpSession?.capabilities?.has("device") === true, ); - let appliedMcpAuthorization: string | undefined = undefined; - if (hasT3Mcp) { + let appliedMcpAuthorization: string | undefined; + const syncT3Mcp = Effect.fnUntraced(function* (mcp: typeof mcpSession) { + if ( + mcp === undefined || + connection.external || + mcp.authorizationHeader === appliedMcpAuthorization + ) { + return; + } yield* OpenCodeRuntime.runOpenCodeSdk("mcp.add", () => client.mcp.add({ name: "t3-code", config: { type: "remote", - url: mcpSession.endpoint, - headers: { Authorization: mcpSession.authorizationHeader }, + url: mcp.endpoint, + headers: { Authorization: mcp.authorizationHeader }, oauth: false, }, }), ); - appliedMcpAuthorization = mcpSession.authorizationHeader; - } + appliedMcpAuthorization = mcp.authorizationHeader; + }); + yield* syncT3Mcp(mcpSession); const now = yield* DateTime.now; let sessionEntity: OrchestrationV2ProviderSession = { @@ -3759,25 +3767,7 @@ export const makeOpenCodeAdapterV2 = Effect.fn("makeOpenCodeAdapterV2")(function ); } yield* applyPermissionRules(state, turnInput.runtimePolicy); - const currentMcp = yield* mcpSessions.read(turnInput.threadId); - if ( - currentMcp !== undefined && - !connection.external && - currentMcp.authorizationHeader !== appliedMcpAuthorization - ) { - yield* OpenCodeRuntime.runOpenCodeSdk("mcp.add", () => - client.mcp.add({ - name: "t3-code", - config: { - type: "remote", - url: currentMcp.endpoint, - headers: { Authorization: currentMcp.authorizationHeader }, - oauth: false, - }, - }), - ); - appliedMcpAuthorization = currentMcp.authorizationHeader; - } + yield* syncT3Mcp(yield* mcpSessions.read(turnInput.threadId)); // A continuation admits a wake OpenCode is already running, so it sends no prompt. const isCompaction = !continuation && diff --git a/packages/provider-pi/src/server/adapter.test.ts b/packages/provider-pi/src/server/adapter.test.ts index e131f8f0cce69..9e6f33f6d5170 100644 --- a/packages/provider-pi/src/server/adapter.test.ts +++ b/packages/provider-pi/src/server/adapter.test.ts @@ -2190,15 +2190,17 @@ describe("PiAdapterV2", () => { Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; const mcpSessions = yield* McpProviderSessions.McpProviderSessions; - yield* mcpSessions.set({ - environmentId: EnvironmentId.make("environment-pi-mcp-rotate"), - threadId: THREAD_ID, - providerSessionId: "mcp-session-pi-1", - providerInstanceId: PI_INSTANCE_ID, - endpoint: "http://127.0.0.1:43123/mcp", - authorizationHeader: "Bearer secret-pi-token-1", - browserToolsAvailable: false, - }); + const setMcp = (ordinal: number) => + mcpSessions.set({ + environmentId: EnvironmentId.make("environment-pi-mcp-rotate"), + threadId: THREAD_ID, + providerSessionId: `mcp-session-pi-${ordinal}`, + providerInstanceId: PI_INSTANCE_ID, + endpoint: "http://127.0.0.1:43123/mcp", + authorizationHeader: `Bearer secret-pi-token-${ordinal}`, + browserToolsAvailable: false, + }); + yield* setMcp(1); const fake = yield* makeFakePi; const { runtime, takeEvent } = yield* openRuntime(fake); const rawTokenFile = fake.lastSpawn().env.T3_MCP_BEARER_TOKEN_FILE; @@ -2222,15 +2224,7 @@ describe("PiAdapterV2", () => { }); yield* runTurn("First turn", 1); - yield* mcpSessions.set({ - environmentId: EnvironmentId.make("environment-pi-mcp-rotate"), - threadId: THREAD_ID, - providerSessionId: "mcp-session-pi-2", - providerInstanceId: PI_INSTANCE_ID, - endpoint: "http://127.0.0.1:43123/mcp", - authorizationHeader: "Bearer secret-pi-token-2", - browserToolsAvailable: false, - }); + yield* setMcp(2); yield* runTurn("Second turn", 2); assert.equal(yield* fs.readFileString(tokenFile), "secret-pi-token-2"); diff --git a/packages/provider-pi/src/server/adapter.ts b/packages/provider-pi/src/server/adapter.ts index cf6c67352ae1e..4743bdbed0c2c 100644 --- a/packages/provider-pi/src/server/adapter.ts +++ b/packages/provider-pi/src/server/adapter.ts @@ -75,6 +75,7 @@ import { type PiRpcRecord, } from "./rpc.ts"; import { + bearerTokenFromAuthorizationHeader, buildPiRpcLaunch, materializePiT3McpExtension, resolvePiLaunchArgs, @@ -497,7 +498,7 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( ) { const scope = yield* Effect.scope; const cwd = input.runtimePolicy.cwd ?? host.paths.cwd; - let appliedMcpAuthorization: string | undefined = undefined; + let appliedMcpAuthorization: string | undefined; const mcpAuthDir = yield* fileSystem .makeTempDirectoryScoped({ prefix: "t3-pi-mcp-auth-" }) .pipe( @@ -516,9 +517,7 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( const writeMcpTokenFile = Effect.fn("PiAdapterV2.writeMcpTokenFile")(function* ( authorizationHeader: string, ) { - const bearerToken = authorizationHeader.startsWith("Bearer ") - ? authorizationHeader.slice("Bearer ".length) - : authorizationHeader; + const bearerToken = bearerTokenFromAuthorizationHeader(authorizationHeader); const stagingPath = path.join(mcpAuthDir, `token.${++mcpTokenWriteOrdinal}.tmp`); yield* fileSystem.writeFileString(stagingPath, bearerToken, { mode: 0o600 }); yield* fileSystem.rename(stagingPath, mcpTokenFilePath); diff --git a/packages/provider-pi/src/server/mcpInjection.ts b/packages/provider-pi/src/server/mcpInjection.ts index 738558e5d91c9..5c8c3c576dc92 100644 --- a/packages/provider-pi/src/server/mcpInjection.ts +++ b/packages/provider-pi/src/server/mcpInjection.ts @@ -160,7 +160,7 @@ export function resolvePiLaunchArgs(launchArgs: string): PiLaunchArgsResolution return { ok: true, args }; } -function bearerTokenFromAuthorizationHeader(header: string): string { +export function bearerTokenFromAuthorizationHeader(header: string): string { return header.startsWith("Bearer ") ? header.slice("Bearer ".length) : header; } From bbe733cc5ec08881dd3f37599a55fd761c1740c6 Mon Sep 17 00:00:00 2001 From: Victor Vogel Date: Mon, 23 Nov 2026 15:29:36 +0000 Subject: [PATCH 17/34] refactor(server): fold the turn MCP check into the tracked-turn wrapper and reuse run event helpers --- .../ProviderSessionManager.test.ts | 159 ++++++++---------- .../ProviderSessionManager.ts | 51 +++--- 2 files changed, 97 insertions(+), 113 deletions(-) diff --git a/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts b/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts index cb2381b7f13c6..17c5cdc0960af 100644 --- a/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts +++ b/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts @@ -366,6 +366,52 @@ function makeProviderThread(input: { }; } +const rawBearer = (config: { readonly authorizationHeader: string } | undefined) => { + assert.isDefined(config); + return config!.authorizationHeader.replace(/^Bearer\s+/, ""); +}; + +const makeRunCreatedEvent = (input: { + readonly idAllocator: IdAllocator.IdAllocatorV2["Service"]; + readonly threadId: ThreadId; + readonly runId: RunId; + readonly attemptId: RunAttemptId; + readonly nodeId: NodeId; + readonly userMessageId: MessageId; + readonly providerThreadId: OrchestrationV2ProviderThread["id"]; + readonly now: DateTime.Utc; + readonly ordinal?: number; + readonly status?: "interrupted" | "completed"; + readonly outputSchema?: { readonly type: "object" }; +}) => + Effect.map(input.idAllocator.allocate.event({ threadId: input.threadId }), (id) => ({ + id, + type: "run.created" as const, + threadId: input.threadId, + runId: input.runId, + nodeId: input.nodeId, + driver: CODEX_DRIVER, + occurredAt: input.now, + payload: { + id: input.runId, + threadId: input.threadId, + ordinal: input.ordinal ?? 1, + providerInstanceId: modelSelection.instanceId, + modelSelection, + providerThreadId: input.providerThreadId, + userMessageId: input.userMessageId, + rootNodeId: input.nodeId, + activeAttemptId: input.attemptId, + status: input.status ?? ("completed" as const), + requestedAt: input.now, + startedAt: input.now, + completedAt: input.now, + checkpointId: null, + contextHandoffId: null, + ...(input.outputSchema === undefined ? {} : { outputSchema: input.outputSchema }), + }, + })); + // A Codex native subagent's provider thread is owned by its child app thread // but reachable from the parent's projection through the subagent record. const makeNativeChildFixture = Effect.fnUntraced(function* () { @@ -2277,44 +2323,33 @@ it.effect( const attempt2 = idAllocator.derive.runAttempt({ runId: run2, attemptOrdinal: 1 }); const run3 = idAllocator.derive.run({ threadId, ordinal: 3 }); const attempt3 = idAllocator.derive.runAttempt({ runId: run3, attemptOrdinal: 1 }); - const makeTypedRunEvent = ( - runId: RunId, - attemptId: RunAttemptId, - ordinal: number, - status: "interrupted" | "completed", - ) => - Effect.map(idAllocator.allocate.event({ threadId }), (id) => ({ - id, - type: "run.created" as const, - threadId, - runId, - nodeId: idAllocator.derive.rootNode({ runId }), - driver: CODEX_DRIVER, - occurredAt: now, - payload: { - id: runId, - threadId, - ordinal, - providerInstanceId: modelSelection.instanceId, - modelSelection, - providerThreadId: providerThread.id, - userMessageId: MessageId.make(`msg-compact-mcp-${ordinal}`), - rootNodeId: idAllocator.derive.rootNode({ runId }), - activeAttemptId: attemptId, - status, - requestedAt: now, - startedAt: now, - completedAt: now, - checkpointId: null, - contextHandoffId: null, - outputSchema: { type: "object" as const }, - }, - })); yield* eventSink.write({ events: [ yield* makeThreadCreatedEvent({ idAllocator, threadId, now }), - yield* makeTypedRunEvent(run1, attempt1, 1, "interrupted"), - yield* makeTypedRunEvent(run2, attempt2, 2, "completed"), + yield* makeRunCreatedEvent({ + idAllocator, + threadId, + runId: run1, + attemptId: attempt1, + nodeId: idAllocator.derive.rootNode({ runId: run1 }), + userMessageId: MessageId.make("msg-compact-mcp-1"), + providerThreadId: providerThread.id, + now, + status: "interrupted", + outputSchema: { type: "object" }, + }), + yield* makeRunCreatedEvent({ + idAllocator, + threadId, + runId: run2, + attemptId: attempt2, + nodeId: idAllocator.derive.rootNode({ runId: run2 }), + userMessageId: MessageId.make("msg-compact-mcp-2"), + providerThreadId: providerThread.id, + now, + ordinal: 2, + outputSchema: { type: "object" }, + }), ], }); @@ -2327,9 +2362,7 @@ it.effect( attemptId: attempt1, requireRunScopedMcp: true, }); - const config1 = yield* mcpSessions.read(threadId); - assert.isDefined(config1); - const token1 = config1!.authorizationHeader.replace(/^Bearer\s+/, ""); + const token1 = rawBearer(yield* mcpSessions.read(threadId)); assert.equal((yield* registry.resolve(token1))?.thread.runId, run1); const subscriber = yield* runtime.subscribeEvents!; @@ -2359,9 +2392,7 @@ it.effect( }, }); - const config3 = yield* mcpSessions.read(threadId); - assert.isDefined(config3); - const token3 = config3!.authorizationHeader.replace(/^Bearer\s+/, ""); + const token3 = rawBearer(yield* mcpSessions.read(threadId)); assert.notEqual(token3, token1); assert.equal((yield* registry.resolve(token1))?.thread.runId, run1); assert.equal((yield* registry.resolve(token3))?.thread.runId, run3); @@ -3599,10 +3630,6 @@ it.effect.each([ ])("$description", ({ scenario }) => Effect.gen(function* () { const state = yield* Ref.make(emptyState); - const rawBearer = (config: { readonly authorizationHeader: string } | undefined) => { - assert.isDefined(config); - return config!.authorizationHeader.replace(/^Bearer\s+/, ""); - }; const openFor = ( manager: ProviderSessionManager.ProviderSessionManagerV2Shape, providerSessionId: ProviderSessionId, @@ -3644,44 +3671,6 @@ it.effect.each([ providerSessionId, }; }); - const makeCompletedRunEvent = (input: { - readonly idAllocator: IdAllocator.IdAllocatorV2["Service"]; - readonly threadId: ThreadId; - readonly runId: RunId; - readonly attemptId: RunAttemptId; - readonly nodeId: NodeId; - readonly userMessageId: MessageId; - readonly providerThreadId: OrchestrationV2ProviderThread["id"]; - readonly now: DateTime.Utc; - readonly outputSchema?: { readonly type: "object" }; - }) => - Effect.map(input.idAllocator.allocate.event({ threadId: input.threadId }), (id) => ({ - id, - type: "run.created" as const, - threadId: input.threadId, - runId: input.runId, - nodeId: input.nodeId, - driver: CODEX_DRIVER, - occurredAt: input.now, - payload: { - id: input.runId, - threadId: input.threadId, - ordinal: 1, - providerInstanceId: modelSelection.instanceId, - modelSelection, - providerThreadId: input.providerThreadId, - userMessageId: input.userMessageId, - rootNodeId: input.nodeId, - activeAttemptId: input.attemptId, - status: "completed" as const, - requestedAt: input.now, - startedAt: input.now, - completedAt: input.now, - checkpointId: null, - contextHandoffId: null, - ...(input.outputSchema === undefined ? {} : { outputSchema: input.outputSchema }), - }, - })); const withServerSettings = ( input: Omit[0], "serverSettingsLayer">, ) => { @@ -3786,7 +3775,7 @@ it.effect.each([ yield* eventSink.write({ events: [ yield* makeThreadCreatedEvent({ idAllocator, threadId, now }), - yield* makeCompletedRunEvent({ + yield* makeRunCreatedEvent({ idAllocator, threadId, runId: run1, @@ -3925,7 +3914,7 @@ it.effect.each([ yield* eventSink.write({ events: [ yield* makeThreadCreatedEvent({ idAllocator, threadId, now }), - yield* makeCompletedRunEvent({ + yield* makeRunCreatedEvent({ idAllocator, threadId, runId: run1, diff --git a/apps/server/src/orchestration-v2/ProviderSessionManager.ts b/apps/server/src/orchestration-v2/ProviderSessionManager.ts index e4aa782b128cf..8b7ccde92610f 100644 --- a/apps/server/src/orchestration-v2/ProviderSessionManager.ts +++ b/apps/server/src/orchestration-v2/ProviderSessionManager.ts @@ -3234,39 +3234,14 @@ export const layerWithOptions = ( modelFamily: normalizeModelMetricLabel(model), }, }); - const ensureTurnMcp = ( - input: Pick< - ProviderAdapter.ProviderAdapterV2TurnInput, - "threadId" | "providerThread" | "runId" | "attemptId" - >, - ) => - ensureTurnMcpSession({ - providerSessionId, - threadId: input.threadId, - providerInstanceId: runtime.instanceId, - runtime, - runId: input.runId, - attemptId: input.attemptId, - }).pipe( - Effect.mapError( - (cause) => - new ProviderAdapter.ProviderAdapterTurnStartError({ - driver: runtime.driver, - threadId: input.threadId, - providerThreadId: input.providerThread.id, - runId: input.runId, - cause, - }), - ), - ); // A start, continuation or compaction keeps the session busy until its turn.terminal. - const runTrackedTurn = ( + const runTrackedTurn = ( input: Pick< ProviderAdapter.ProviderAdapterV2TurnInput, "threadId" | "providerThread" | "runId" | "attemptId" | "runOrdinal" >, releasedCause: string, - run: () => Effect.Effect, + run: () => Effect.Effect, ) => observeActivity( providerSessionId, @@ -3276,7 +3251,27 @@ export const layerWithOptions = ( providerInstanceId: runtime.instanceId, }), ).pipe( - Effect.andThen(ensureTurnMcp(input)), + Effect.andThen( + ensureTurnMcpSession({ + providerSessionId, + threadId: input.threadId, + providerInstanceId: runtime.instanceId, + runtime, + runId: input.runId, + attemptId: input.attemptId, + }).pipe( + Effect.mapError( + (cause) => + new ProviderAdapter.ProviderAdapterTurnStartError({ + driver: runtime.driver, + threadId: input.threadId, + providerThreadId: input.providerThread.id, + runId: input.runId, + cause, + }), + ), + ), + ), // Failed or stopped starts may omit turn.terminal; clear their turns so sessions can idle. Effect.andThen( holdThreadLoaded({ From 29a8c41e688fd143b18a6348e99eb73c9f6a2f0e Mon Sep 17 00:00:00 2001 From: Victor Vogel Date: Mon, 23 Nov 2026 15:54:51 +0000 Subject: [PATCH 18/34] fix(server): check a turn's MCP credential only once its session is busy --- .../ProviderSessionManager.test.ts | 81 ++++++++++--------- .../ProviderSessionManager.ts | 74 ++++++++--------- 2 files changed, 75 insertions(+), 80 deletions(-) diff --git a/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts b/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts index 17c5cdc0960af..64b75b5ac77d7 100644 --- a/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts +++ b/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts @@ -536,7 +536,11 @@ const makeProviderAdapter = Effect.fnUntraced(function* ( readonly hasPendingBackgroundWorkForThread?: Effect.Effect; readonly backgroundTasksEndWithProcess?: boolean; readonly hangSessionScopeClose?: boolean; - readonly startTurn?: Effect.Effect; + readonly startTurn?: Effect.Effect< + void, + ProviderAdapter.ProviderAdapterProtocolError, + McpProviderSessions.McpProviderSessions + >; readonly interruptTurn?: Effect.Effect; readonly beforeUnload?: Effect.Effect; readonly unloads?: Queue.Queue; @@ -612,6 +616,15 @@ const makeProviderAdapter = Effect.fnUntraced(function* ( if (options.hangSessionScopeClose === true) yield* hangClose; } + const runStartTurn = () => + options.startTurn === undefined + ? Effect.void + : Effect.provideService( + options.startTurn, + McpProviderSessions.McpProviderSessions, + mcpSessions, + ); + return { instanceId: ProviderInstanceId.make("codex"), driver: CODEX_DRIVER, @@ -662,9 +675,9 @@ const makeProviderAdapter = Effect.fnUntraced(function* ( ...current, resumeCount: current.resumeCount + 1, })).pipe(Effect.as(threadInput.providerThread)), - startTurn: () => options.startTurn ?? Effect.void, - resumeTurn: () => options.startTurn ?? Effect.void, - compactThread: () => options.startTurn ?? Effect.void, + startTurn: runStartTurn, + resumeTurn: runStartTurn, + compactThread: runStartTurn, steerTurn: () => Effect.void, interruptTurn: () => Ref.update(state, (current) => ({ @@ -730,7 +743,11 @@ function layerTest(input: { readonly hasPendingBackgroundWorkForThread?: Effect.Effect; readonly backgroundTasksEndWithProcess?: boolean; readonly hangSessionScopeClose?: boolean; - readonly startTurn?: Effect.Effect; + readonly startTurn?: Effect.Effect< + void, + ProviderAdapter.ProviderAdapterProtocolError, + McpProviderSessions.McpProviderSessions + >; readonly interruptTurn?: Effect.Effect; readonly beforeUnload?: Effect.Effect; readonly unloads?: Queue.Queue; @@ -2293,10 +2310,14 @@ it.effect.each([ ); it.effect( - "ProviderSessionManagerV2 rotates a stale run-scoped MCP credential and keeps the session busy during compaction", + "ProviderSessionManagerV2 rotates a stale run-scoped MCP credential before a compaction", () => Effect.gen(function* () { const state = yield* Ref.make(emptyState); + const compactMcpConfigs = yield* Ref.make< + ReadonlyArray + >([]); + const threadId = ThreadId.make("thread-compact-rotates-stale-mcp"); yield* Effect.gen(function* () { const eventSink = yield* EventSink.EventSinkV2; const idAllocator = yield* IdAllocator.IdAllocatorV2; @@ -2305,7 +2326,6 @@ it.effect( const mcpSessions = yield* McpProviderSessions.McpProviderSessions; const projectionStore = yield* ProjectionStore.ProjectionStoreV2; const now = yield* DateTime.now; - const threadId = ThreadId.make("thread-compact-rotates-stale-mcp-and-stays-busy"); const providerSessionId = yield* idAllocator.allocate.providerSession({ providerInstanceId: modelSelection.instanceId, threadId, @@ -2365,12 +2385,6 @@ it.effect( const token1 = rawBearer(yield* mcpSessions.read(threadId)); assert.equal((yield* registry.resolve(token1))?.thread.runId, run1); - const subscriber = yield* runtime.subscribeEvents!; - const terminal = yield* subscriber.events.pipe( - Stream.filter((event) => event.type === "turn.terminal"), - Stream.runHead, - Effect.forkScoped, - ); const messageId = yield* idAllocator.allocate.message({ threadId, ordinal: 3 }); yield* runtime.compactThread!({ appThread: (yield* projectionStore.getThreadProjection(threadId)).thread, @@ -2392,37 +2406,26 @@ it.effect( }, }); - const token3 = rawBearer(yield* mcpSessions.read(threadId)); + const dispatched = yield* Ref.get(compactMcpConfigs); + assert.equal(dispatched.length, 1); + const token3 = rawBearer(dispatched[0]); assert.notEqual(token3, token1); + assert.equal(rawBearer(yield* mcpSessions.read(threadId)), token3); assert.equal((yield* registry.resolve(token1))?.thread.runId, run1); assert.equal((yield* registry.resolve(token3))?.thread.runId, run3); assert.equal((yield* registry.resolve(token3))?.thread.attemptId, attempt3); - - yield* TestClock.adjust("2 seconds"); - assert.isTrue(yield* manager.isLive(providerSessionId)); - - const queue = (yield* Ref.get(state)).eventQueues.get(String(providerSessionId)); - assert.isDefined(queue); - yield* Queue.offer(queue!, { - type: "turn.terminal", - driver: CODEX_DRIVER, - providerThreadId: providerThread.id, - providerTurnId: idAllocator.derive.providerTurn({ - driver: CODEX_DRIVER, - nativeTurnId: "native-turn-compact-mcp", - }), - runOrdinal: 3, - status: "completed", - failure: null, - threadDisposition: "reusable", - }); - yield* Fiber.join(terminal); - yield* TestClock.adjust("2 seconds"); - assert.isFalse(yield* manager.isLive(providerSessionId)); - assert.isUndefined(yield* registry.resolve(token1)); - assert.isUndefined(yield* registry.resolve(token3)); }).pipe( - Effect.provide(layerTest({ state, idleTimeoutMs: 1_000, mcpCredentialRotation: "live" })), + Effect.provide( + layerTest({ + state, + mcpCredentialRotation: "live", + startTurn: Effect.gen(function* () { + const mcpSessions = yield* McpProviderSessions.McpProviderSessions; + const config = yield* mcpSessions.read(threadId); + yield* Ref.update(compactMcpConfigs, (configs) => [...configs, config]); + }), + }), + ), ); }), ); diff --git a/apps/server/src/orchestration-v2/ProviderSessionManager.ts b/apps/server/src/orchestration-v2/ProviderSessionManager.ts index 8b7ccde92610f..463f67b238379 100644 --- a/apps/server/src/orchestration-v2/ProviderSessionManager.ts +++ b/apps/server/src/orchestration-v2/ProviderSessionManager.ts @@ -3235,12 +3235,11 @@ export const layerWithOptions = ( }, }); // A start, continuation or compaction keeps the session busy until its turn.terminal. - const runTrackedTurn = ( + const busyTurn = ( input: Pick< ProviderAdapter.ProviderAdapterV2TurnInput, - "threadId" | "providerThread" | "runId" | "attemptId" | "runOrdinal" + "threadId" | "providerThread" | "runOrdinal" | "runId" | "attemptId" >, - releasedCause: string, run: () => Effect.Effect, ) => observeActivity( @@ -3251,27 +3250,6 @@ export const layerWithOptions = ( providerInstanceId: runtime.instanceId, }), ).pipe( - Effect.andThen( - ensureTurnMcpSession({ - providerSessionId, - threadId: input.threadId, - providerInstanceId: runtime.instanceId, - runtime, - runId: input.runId, - attemptId: input.attemptId, - }).pipe( - Effect.mapError( - (cause) => - new ProviderAdapter.ProviderAdapterTurnStartError({ - driver: runtime.driver, - threadId: input.threadId, - providerThreadId: input.providerThread.id, - runId: input.runId, - cause, - }), - ), - ), - ), // Failed or stopped starts may omit turn.terminal; clear their turns so sessions can idle. Effect.andThen( holdThreadLoaded({ @@ -3304,12 +3282,32 @@ export const layerWithOptions = ( threadId: input.threadId, providerThreadId: input.providerThread.id, runId: input.runId, - cause: releasedCause, + cause: "The provider session was released while the turn started.", }), ), ), ), - run, + () => + ensureTurnMcpSession({ + providerSessionId, + threadId: input.threadId, + providerInstanceId: runtime.instanceId, + runtime, + runId: input.runId, + attemptId: input.attemptId, + }).pipe( + Effect.mapError( + (cause) => + new ProviderAdapter.ProviderAdapterTurnStartError({ + driver: runtime.driver, + threadId: input.threadId, + providerThreadId: input.providerThread.id, + runId: input.runId, + cause, + }), + ), + Effect.andThen(run), + ), (_, exit) => Exit.isFailure(exit) ? observeActivity( @@ -3475,7 +3473,7 @@ export const layerWithOptions = ( Effect.map(({ loaded }) => loaded), ), startTurn: (input) => - runTrackedTurn(input, "The provider session was released while the turn started.", () => + busyTurn(input, () => agentFeedbackMode.pipe( Effect.flatMap((agentFeedback) => runtime.startTurn({ ...input, agentFeedback })), turnMetrics("send", input.modelSelection.model), @@ -3485,26 +3483,20 @@ export const layerWithOptions = ( ? {} : { resumeTurn: (input: ProviderAdapter.ProviderAdapterV2ResumeTurnInput) => - runTrackedTurn( - input, - "The provider session was released while the turn resumed.", - () => - runtime.resumeTurn!(input).pipe( - turnMetrics("resume", input.modelSelection.model), - ), + busyTurn(input, () => + runtime.resumeTurn!(input).pipe( + turnMetrics("resume", input.modelSelection.model), + ), ), }), ...(runtime.compactThread === undefined ? {} : { compactThread: (input: ProviderAdapter.ProviderAdapterV2TurnInput) => - runTrackedTurn( - input, - "The provider session was released while the thread compacted.", - () => - runtime.compactThread!(input).pipe( - turnMetrics("compact", input.modelSelection.model), - ), + busyTurn(input, () => + runtime.compactThread!(input).pipe( + turnMetrics("compact", input.modelSelection.model), + ), ), }), steerTurn: (input) => From 029a970b3143aaf883495b32c9a05763d81ab613 Mon Sep 17 00:00:00 2001 From: Victor Vogel Date: Tue, 24 Nov 2026 01:22:32 +0000 Subject: [PATCH 19/34] fix(server): a typed result naming another run, or sent while its wake is stopped, is not kept The submission's own runId must name the run it is written to, or a run that run continues, even when a bound credential names a different caller. A result owed by a completed run is also rejected once Stop reaches the wake turn answering it. --- apps/server/src/mcp/toolkits/core.test.ts | 8 +- .../src/mcp/toolkits/thread/handlers.ts | 1 + .../src/orchestration-v2/Orchestrator.ts | 2 +- .../ThreadManagementService.ts | 20 ++++- .../src/orchestration-v2/runtimeLayer.test.ts | 82 ++++++++++++++++++- 5 files changed, 108 insertions(+), 5 deletions(-) diff --git a/apps/server/src/mcp/toolkits/core.test.ts b/apps/server/src/mcp/toolkits/core.test.ts index e5cc48b74b2fe..e81f2de5b47b6 100644 --- a/apps/server/src/mcp/toolkits/core.test.ts +++ b/apps/server/src/mcp/toolkits/core.test.ts @@ -1706,6 +1706,7 @@ it.effect("t3_submit_output forwards caller run and attempt identity and surface readonly json: string; readonly callerRunId?: RunId | undefined; readonly callerAttemptId?: RunAttemptId | undefined; + readonly requestedRunId?: RunId | undefined; }> = []; const runA = RunId.make("run-a"); const attemptA = RunAttemptId.make("attempt-a"); @@ -1725,6 +1726,7 @@ it.effect("t3_submit_output forwards caller run and attempt identity and surface json: input.json, callerRunId: input.callerRunId, callerAttemptId: input.callerAttemptId, + requestedRunId: input.requestedRunId, }); if (rejectNext !== undefined) { const rejection = rejectNext; @@ -1804,7 +1806,7 @@ it.effect("t3_submit_output forwards caller run and attempt identity and surface `The result does not match the schema.\n${schemaCause.message.slice(0, 2000)}`, ); - // A bound credential outranks the argument. + // A bound credential is the caller; the argument still goes along as the run it names. const active = yield* callWith(runB, attemptB, '{"ok":true}', runA); expect(active.isError).toBe(false); expect(active.structuredContent).toEqual({ runId: runB }); @@ -1815,24 +1817,28 @@ it.effect("t3_submit_output forwards caller run and attempt identity and surface json: '{"ok":false}', callerRunId: runA, callerAttemptId: undefined, + requestedRunId: runA, }, { threadId, json: '{"ok":false}', callerRunId: runA, callerAttemptId: attemptA, + requestedRunId: undefined, }, { threadId, json: "{}", callerRunId: runB, callerAttemptId: attemptB, + requestedRunId: undefined, }, { threadId, json: '{"ok":true}', callerRunId: runB, callerAttemptId: attemptB, + requestedRunId: runA, }, ]); }), diff --git a/apps/server/src/mcp/toolkits/thread/handlers.ts b/apps/server/src/mcp/toolkits/thread/handlers.ts index 416a16b1493a8..39ff22316ee03 100644 --- a/apps/server/src/mcp/toolkits/thread/handlers.ts +++ b/apps/server/src/mcp/toolkits/thread/handlers.ts @@ -296,6 +296,7 @@ export const layer = McpToolAccess.toLayer(ThreadToolkit, { commandId: yield* newCommandId(), json: input.json, ...(callerRunId === undefined ? {} : { callerRunId }), + ...(input.runId === undefined ? {} : { requestedRunId: input.runId }), ...(scope.thread.attemptId === undefined ? {} : { callerAttemptId: scope.thread.attemptId }), diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 649026355ecd8..6a3413ea286bd 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -12540,10 +12540,10 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio `Caller run ${command.callerRunId ?? "unknown"} is no longer active on thread ${command.threadId}.`, ); } + // A wake turn may reuse the owed run's credential, so its calls cannot be told apart. if ( active !== undefined && active.id !== run.id && - matchesRun(active) && (yield* stopReachedRun(command, command.threadId, active.id)) ) { return yield* rejectOutput("stopped", `Run ${active.id} was stopped and takes no result.`); diff --git a/apps/server/src/orchestration-v2/ThreadManagementService.ts b/apps/server/src/orchestration-v2/ThreadManagementService.ts index 9aa1134f708df..9f419cf155426 100644 --- a/apps/server/src/orchestration-v2/ThreadManagementService.ts +++ b/apps/server/src/orchestration-v2/ThreadManagementService.ts @@ -498,6 +498,7 @@ export interface ThreadManagementServiceShape { readonly json: string; readonly callerRunId?: RunId; readonly callerAttemptId?: RunAttemptId; + readonly requestedRunId?: RunId; }) => Effect.Effect<{ readonly runId: RunId }, ThreadManagementFailure>; readonly assertProviderInstanceEnabled: (input: { readonly projectId: ProjectId; @@ -1087,8 +1088,25 @@ const make = Effect.gen(function* () { const matchesRun = (candidate: OrchestrationV2Run) => candidate.id === callerRunId && (input.callerAttemptId === undefined || candidate.activeAttemptId === input.callerAttemptId); + // A continuation that resumes natively on a bound credential still has only the earlier + // run's prompt, so the run named in the call may be one the target continues. + const continuesNamedRun = (named: RunId) => { + let current: OrchestrationV2Run | undefined = run; + for (let hops = 0; current !== undefined && hops <= records.runs.length; hops++) { + if (current.id === named) return true; + const continued: RunId | undefined = + current.restartContinuationOfRunId ?? + current.usageLimitContinuationOfRunId ?? + current.manualContinuationOfRunId; + current = records.runs.find((candidate) => candidate.id === continued); + } + return false; + }; // Accept the active run, or the un-stopped completed run whose own owed output is targeted. - if (!matchesRun(active) && !(run.id !== active.id && matchesRun(run))) { + if ( + (input.requestedRunId !== undefined && !continuesNamedRun(input.requestedRunId)) || + (!matchesRun(active) && !(run.id !== active.id && matchesRun(run))) + ) { return yield* new ThreadManagementRunOutputRejectedError({ threadId: input.threadId, problem: "This output was submitted for a turn that is no longer active.", diff --git a/apps/server/src/orchestration-v2/runtimeLayer.test.ts b/apps/server/src/orchestration-v2/runtimeLayer.test.ts index 8410f3c6f14fc..914867d13e8e4 100644 --- a/apps/server/src/orchestration-v2/runtimeLayer.test.ts +++ b/apps/server/src/orchestration-v2/runtimeLayer.test.ts @@ -12528,10 +12528,45 @@ it.layer(layerSharedApplicationDataPlaneTest)("run output after a stop", (it) => status: "completed" | "interrupted", extra?: Partial>>, ) => updateRun(run, suffix, { status, completedAt: run.requestedAt, ...extra }); + // The stop is asked for while the provider has not settled it, so the run is still active. + const requestStop = (run: Effect.Success>, suffix: string) => + eventSink.write({ + events: [ + { + id: EventId.make(`${threadId}-${suffix}`), + type: "turn-item.updated", + threadId, + runId: run.id, + occurredAt: run.requestedAt, + payload: { + id: TurnItemId.make(`${threadId}-${suffix}`), + type: "run_interrupt_request", + threadId, + runId: run.id, + nodeId: run.rootNodeId, + providerThreadId: null, + providerTurnId: null, + nativeItemRef: null, + parentItemId: null, + ordinal: 90, + status: "completed", + title: "Interrupt requested", + startedAt: run.requestedAt, + completedAt: run.requestedAt, + updatedAt: run.requestedAt, + message: "Stopped by user", + }, + }, + ], + }); const submit = ( command: string, json: string, - caller?: { readonly callerRunId?: RunId; readonly callerAttemptId?: RunAttemptId }, + caller?: { + readonly callerRunId?: RunId; + readonly callerAttemptId?: RunAttemptId; + readonly requestedRunId?: RunId; + }, ) => threadManagement.submitRunOutput({ threadId, @@ -12546,6 +12581,7 @@ it.layer(layerSharedApplicationDataPlaneTest)("run output after a stop", (it) => latestRun, updateRun, finishRun, + requestStop, submit, }; }); @@ -12605,6 +12641,15 @@ it.layer(layerSharedApplicationDataPlaneTest)("run output after a stop", (it) => assert.equal(lateFromAttempt1._tag, "ThreadManagementRunOutputRejectedError"); assert.include(lateFromAttempt1.message, "no longer active"); + // A's late call that names A still fails when it arrives on B's rotated credential. + const lateFromAOnB = yield* submit("late-run-output-from-a-on-b", '{"from":"run-a"}', { + callerRunId: runB.id, + callerAttemptId: attempt2, + requestedRunId: runA.id, + }).pipe(Effect.flip); + assert.equal(lateFromAOnB._tag, "ThreadManagementRunOutputRejectedError"); + assert.include(lateFromAOnB.message, "no longer active"); + assert.isUndefined((yield* latestRun()).output); const acceptedB = yield* submit("late-run-output-from-b", '{"from":"run-b"}', { @@ -12640,6 +12685,21 @@ it.layer(layerSharedApplicationDataPlaneTest)("run output after a stop", (it) => (run) => run.id === runC.id, )!; assert.deepEqual(afterC.output?.value, { from: "continued" }); + // Resumed natively on its own bound credential, C has only A's prompt and names A. + const resumedNamingSource = yield* submit( + "run-output-resumed-naming-a", + '{"from":"resumed"}', + { + callerRunId: runC.id, + requestedRunId: runA.id, + }, + ); + assert.equal(resumedNamingSource.runId, runC.id); + assert.deepEqual( + (yield* orchestrator.getThreadProjection(threadId)).runs.find((run) => run.id === runC.id) + ?.output?.value, + { from: "resumed" }, + ); // A plain turn with no schema preserves the plain-turn guidance even for stale/unbound MCP callers. yield* finishRun(afterC, "run-c-completed", "completed"); @@ -12656,7 +12716,7 @@ it.layer(layerSharedApplicationDataPlaneTest)("run output after a stop", (it) => } if (scenario === "owed-run-and-wake") { - const { orchestrator, threadId, send, latestRun, finishRun, submit } = + const { orchestrator, threadId, send, latestRun, finishRun, requestStop, submit } = yield* setupOutputThread("owed-wake-output"); yield* send("run-a", { type: "object" }); @@ -12700,6 +12760,24 @@ it.layer(layerSharedApplicationDataPlaneTest)("run output after a stop", (it) => ?.output?.value, { from: "run-f" }, ); + + // A stopped wake keeps the owed run's credential, so what it submits is not kept either. + yield* finishRun(runF, "run-f-completed", "completed"); + yield* send("run-g", { type: "object" }); + const runG = yield* latestRun(); + yield* finishRun(runG, "run-g-completed", "completed"); + yield* send("run-h-wake"); + yield* requestStop(yield* latestRun(), "run-h-interrupt-request"); + const fromStoppedWake = yield* submit("run-output-from-stopped-wake", '{"from":"h"}', { + callerRunId: runG.id, + requestedRunId: runG.id, + }).pipe(Effect.flip); + assert.equal(fromStoppedWake._tag, "ThreadManagementRunOutputRejectedError"); + assert.include(fromStoppedWake.message, "was stopped"); + assert.isUndefined( + (yield* orchestrator.getThreadProjection(threadId)).runs.find((run) => run.id === runG.id) + ?.output, + ); return; } From 2c806d7d0731ca734f2cc778c2758cf9020f469b Mon Sep 17 00:00:00 2001 From: Victor Vogel Date: Tue, 24 Nov 2026 01:22:51 +0000 Subject: [PATCH 20/34] fix(server): only a thread's own background work keeps its MCP credential unbound A shared Codex session no longer unbinds a thread because another thread is busy. Turn start checks this thread's own work instead, so a turn that narrows browser access while that work runs keeps its credential, narrowed and unbound, rather than failing. An ACP snapshot load now also records the credential it loaded with, so the next turn does not reload the session again. --- .../Adapters/AcpAdapterV2.test.ts | 67 ++++ .../ProviderSessionManager.test.ts | 345 ++++++++++-------- .../ProviderSessionManager.ts | 21 +- packages/provider-acp/src/server/adapter.ts | 4 + 4 files changed, 275 insertions(+), 162 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts index 7221c0b2ee7dc..7f7efe61959f2 100644 --- a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts @@ -7017,6 +7017,73 @@ describe("AcpAdapterV2", () => { }).pipe(Effect.provide(layerTest)), ); + it.live("a snapshot load records its MCP credential, so the next turn does not reload", () => + Effect.gen(function* () { + const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const selfInvocation = yield* resolveSelfInvocation(); + const mockAgentPath = yield* bundledMockAgentPath; + const protocolEvents = yield* Queue.bounded(256); + const instanceId = ProviderInstanceId.make("acp-test-mcp-snapshot"); + const threadId = ThreadId.make("thread-acp-mcp-snapshot"); + const mcpSessions = yield* McpProviderSessions.McpProviderSessions; + const setMcp = (ordinal: number) => + mcpSessions.set({ + environmentId: EnvironmentId.make("environment-acp-mcp-snapshot"), + threadId, + providerSessionId: `mcp-session-acp-snapshot-${ordinal}`, + providerInstanceId: instanceId, + endpoint: "http://127.0.0.1:43123/mcp", + authorizationHeader: `Bearer acp-snapshot-${ordinal}-token`, + browserToolsAvailable: false, + }); + yield* setMcp(1); + const adapter = yield* makeAcpAdapterV2({ + instanceId, + flavor: { + driver: ACP_TEST_DRIVER, + capabilities: AcpProviderCapabilitiesV2, + makeRuntime: makeMockRuntime({ childProcessSpawner, mockAgentPath, protocolEvents }), + }, + selfInvocation, + clientTerminals: {}, + }); + const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ + runtimeMode: "full-access", + interactionMode: "default", + cwd: process.cwd(), + }); + const modelSelection = { instanceId, model: "default" } as const; + const runtime = yield* adapter.openSession({ + threadId, + providerSessionId: ProviderSessionId.make("provider-session-acp-mcp-snapshot"), + modelSelection, + runtimePolicy, + }); + const opened = yield* runtime.ensureThread({ threadId, modelSelection, runtimePolicy }); + const providerThread = { + ...opened, + nativeThreadRef: { ...opened.nativeThreadRef!, nativeId: "mock-session-snapshot" }, + }; + + yield* pollProtocolMethods(protocolEvents); + yield* setMcp(2); + yield* runtime.readThreadSnapshot({ providerThread }); + const reloads = (methods: ReadonlyArray) => + methods.filter((method) => method === "session/load" || method === "session/resume"); + assert.lengthOf(reloads(yield* pollProtocolMethods(protocolEvents)), 1); + yield* runtime.startTurn( + makeTurnInput({ + threadId, + providerThread, + instanceId, + runtimePolicy, + now: yield* DateTime.now, + }), + ); + assert.lengthOf(reloads(yield* pollProtocolMethods(protocolEvents)), 0); + }).pipe(Effect.provide(layerTest)), + ); + it.live( "reports mcpCredentialRotation none for non-loadable ACP agents without MCP-over-ACP", () => diff --git a/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts b/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts index 64b75b5ac77d7..5ee4e71dbee0e 100644 --- a/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts +++ b/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts @@ -3625,6 +3625,11 @@ it.effect.each([ description: "ProviderSessionManagerV2 keeps the loaded token, unbound, instead of reloading while background work is active", }, + { + scenario: "reload-blocked-exclusive" as const, + description: + "ProviderSessionManagerV2 keeps a single-thread runtime's credential, unbound, while its session has background work", + }, { scenario: "reload-when-required" as const, description: @@ -3886,6 +3891,105 @@ it.effect.each([ return; } + if (scenario === "reload-blocked-exclusive") { + const sessionBackgroundWorkProbe = yield* Ref.make>( + Effect.succeed(false), + ); + const effect = Effect.gen(function* () { + const { + eventSink, + idAllocator, + manager, + registry, + mcpSessions, + now, + threadId, + providerSessionId, + } = yield* setupSession("probe-race"); + const settings = yield* ServerSettings.ServerSettingsService; + // If a newer credential is published while the background-work probe awaits, the fallback + // skips releasing and overwriting it. + const probeRaceThreadId = threadId; + yield* eventSink.write({ + events: [ + yield* makeThreadCreatedEvent({ idAllocator, threadId: probeRaceThreadId, now }), + ], + }); + const raceRun1 = RunId.make("run-probe-race-1"); + yield* openFor(manager, providerSessionId, probeRaceThreadId, { + runId: raceRun1, + attemptId: RunAttemptId.make("attempt-probe-race-1"), + requireRunScopedMcp: true, + }); + const originalRaceConfig = yield* mcpSessions.read(probeRaceThreadId); + const originalRaceToken = rawBearer(originalRaceConfig); + const probeStarted = yield* Deferred.make(); + const releaseProbe = yield* Deferred.make(); + yield* Ref.set( + sessionBackgroundWorkProbe, + Deferred.succeed(probeStarted, undefined).pipe( + Effect.andThen(Deferred.await(releaseProbe)), + ), + ); + const racingOpen = yield* openFor(manager, providerSessionId, probeRaceThreadId, { + runId: RunId.make("run-probe-race-2"), + attemptId: RunAttemptId.make("attempt-probe-race-2"), + requireRunScopedMcp: true, + }).pipe(Effect.forkChild); + yield* Deferred.await(probeStarted); + const newerIssued = yield* registry.issue({ + threadId: probeRaceThreadId, + providerInstanceId: modelSelection.instanceId, + providerSessionId: originalRaceConfig!.providerSessionId, + runId: RunId.make("run-probe-race-3"), + attemptId: RunAttemptId.make("attempt-probe-race-3"), + }); + yield* mcpSessions.set(newerIssued.config); + yield* Deferred.succeed(releaseProbe, true); + yield* Fiber.join(racingOpen); + const afterRace = yield* mcpSessions.read(probeRaceThreadId); + assert.equal(afterRace?.authorizationHeader, newerIssued.config.authorizationHeader); + assert.isUndefined(afterRace?.runId); + // The older credential was not released or written back; the newer one became unbound for run 2. + assert.equal((yield* registry.resolve(originalRaceToken))?.thread.runId, raceRun1); + const newerToken = rawBearer(newerIssued.config); + const resolvedNewer = yield* registry.resolve(newerToken); + assert.isDefined(resolvedNewer); + assert.isUndefined(resolvedNewer!.thread.runId); + // Narrowing on a non-rotating turn strips preview from older retained thread tokens too, + // while re-enabling restores it only on the active credential. + for (const [enabled, ordinal] of [ + [false, 4], + [true, 5], + ] as const) { + yield* settings.updateSettings({ enableAgentBrowserAccess: enabled }); + yield* openFor(manager, providerSessionId, probeRaceThreadId, { + runId: RunId.make(`run-probe-race-${ordinal}`), + attemptId: RunAttemptId.make(`attempt-probe-race-${ordinal}`), + requireRunScopedMcp: true, + }); + assert.equal((yield* registry.resolve(newerToken))?.capabilities.has("preview"), enabled); + assert.isFalse( + (yield* registry.resolve(originalRaceToken))?.capabilities.has("preview") ?? true, + ); + } + + yield* manager.close(providerSessionId); + }); + + yield* effect.pipe( + Effect.provide( + withServerSettings({ + state, + idleTimeoutMs: 1_000, + capabilities: ExclusiveCapabilities, + hasPendingBackgroundWork: Ref.get(sessionBackgroundWorkProbe).pipe(Effect.flatten), + }), + ), + ); + return; + } + if (scenario === "reload-blocked") { const unloads = yield* Queue.unbounded(); const pendingBackgroundWork = yield* Ref.make(true); @@ -4015,135 +4119,108 @@ it.effect.each([ const loadedConfig = yield* mcpSessions.read(threadId); const loadedToken = rawBearer(loadedConfig); yield* resume(threadId, providerThread); + // This thread's own background work keeps its loaded token from the turn's start: nothing is + // staged or reloaded, and the token stops answering for run 1 so run 2 can submit. yield* openFor(manager, providerSessionId, threadId, { runId: run2, attemptId: attempt2, requireRunScopedMcp: true, }); - const rotatedToken = rawBearer(yield* mcpSessions.read(threadId)); - assert.notEqual(rotatedToken, loadedToken); - + assert.equal(rawBearer(yield* mcpSessions.read(threadId)), loadedToken); yield* resume(threadId, providerThread); - // Background work stayed alive (no unload): the turn runs on the loaded token, now unbound so - // its run can submit, and the unused token was revoked. assert.isTrue(Option.isNone(yield* Queue.poll(unloads))); const resolvedLoaded = yield* registry.resolve(loadedToken); assert.isDefined(resolvedLoaded); assert.isUndefined(resolvedLoaded?.thread.runId); assert.isUndefined(resolvedLoaded?.thread.attemptId); - assert.isUndefined(yield* registry.resolve(rotatedToken)); - assert.equal( - (yield* mcpSessions.read(threadId))?.authorizationHeader, - loadedConfig!.authorizationHeader, - ); + assert.isUndefined((yield* mcpSessions.read(threadId))?.runId); - // Also cover a thread initially attached to the shared session with an unbound (run-less) bearer: - // rolling back on blocked reload must keep that run-less bearer valid for running background work. - const { - threadId: unboundThreadId, - providerThread: unboundProviderThread, - loadedConfig: unboundLoadedConfig, - loadedToken: unboundLoadedToken, - } = yield* attachLoadedThread("bg-unbound"); - assert.isUndefined(unboundLoadedConfig.runId); - yield* openFor(manager, providerSessionId, unboundThreadId, { + // A thread attached with a run-less token keeps it the same way. + const unboundThread = yield* attachLoadedThread("bg-unbound"); + assert.isUndefined(unboundThread.loadedConfig.runId); + yield* openFor(manager, providerSessionId, unboundThread.threadId, { runId: RunId.make("run-bg-unbound-typed"), attemptId: RunAttemptId.make("attempt-bg-unbound-typed"), requireRunScopedMcp: true, }); - const unboundRotatedToken = rawBearer(yield* mcpSessions.read(unboundThreadId)); - assert.notEqual(unboundRotatedToken, unboundLoadedToken); - - yield* resume(unboundThreadId, unboundProviderThread); + yield* resume(unboundThread.threadId, unboundThread.providerThread); assert.isTrue(Option.isNone(yield* Queue.poll(unloads))); - const resolvedUnboundLoaded = yield* registry.resolve(unboundLoadedToken); - assert.isDefined(resolvedUnboundLoaded); - assert.isUndefined(resolvedUnboundLoaded?.thread.runId); - assert.isUndefined(yield* registry.resolve(unboundRotatedToken)); assert.equal( - (yield* mcpSessions.read(unboundThreadId))?.authorizationHeader, - unboundLoadedConfig!.authorizationHeader, + rawBearer(yield* mcpSessions.read(unboundThread.threadId)), + unboundThread.loadedToken, ); + assert.isDefined(yield* registry.resolve(unboundThread.loadedToken)); - // Enabling browser access (capability widening) before a blocked typed turn keeps the narrower - // loaded bearer valid on rollback, whereas disabling browser access (capability removal) revokes it. + // Browser access follows the setting on the kept token, both ways, and the turn still runs. const settings = yield* ServerSettings.ServerSettingsService; - yield* settings.updateSettings({ enableAgentBrowserAccess: false }); - const { - threadId: widenedThreadId, - providerThread: widenedProviderThread, - loadedConfig: narrowLoadedConfig, - loadedToken: narrowLoadedToken, - } = yield* attachLoadedThread("bg-widened"); - assert.isFalse(narrowLoadedConfig.browserToolsAvailable); - yield* settings.updateSettings({ enableAgentBrowserAccess: true }); - yield* openFor(manager, providerSessionId, widenedThreadId, { - runId: RunId.make("run-bg-widened-typed"), - attemptId: RunAttemptId.make("attempt-bg-widened-typed"), - requireRunScopedMcp: true, - }); - const widerRotatedConfig = yield* mcpSessions.read(widenedThreadId); - assert.isTrue(widerRotatedConfig?.browserToolsAvailable); - const widerRotatedToken = rawBearer(widerRotatedConfig); - yield* resume(widenedThreadId, widenedProviderThread); - const resolvedNarrow = yield* registry.resolve(narrowLoadedToken); - assert.isDefined(resolvedNarrow); - assert.isFalse(resolvedNarrow!.capabilities.has("preview")); - assert.isUndefined(yield* registry.resolve(widerRotatedToken)); - assert.equal( - (yield* mcpSessions.read(widenedThreadId))?.authorizationHeader, - narrowLoadedConfig!.authorizationHeader, - ); + for (const [enabled, slug] of [ + [true, "bg-widened"], + [false, "bg-narrowed"], + ] as const) { + yield* settings.updateSettings({ enableAgentBrowserAccess: !enabled }); + const kept = yield* attachLoadedThread(slug); + assert.equal(kept.loadedConfig.browserToolsAvailable, !enabled); + yield* settings.updateSettings({ enableAgentBrowserAccess: enabled }); + yield* openFor(manager, providerSessionId, kept.threadId, { + runId: RunId.make(`run-${slug}-typed`), + attemptId: RunAttemptId.make(`attempt-${slug}-typed`), + requireRunScopedMcp: true, + }); + yield* resume(kept.threadId, kept.providerThread); + assert.isTrue(Option.isNone(yield* Queue.poll(unloads))); + const keptConfig = yield* mcpSessions.read(kept.threadId); + assert.equal(rawBearer(keptConfig), kept.loadedToken); + assert.equal(keptConfig?.browserToolsAvailable, enabled); + const resolvedKept = yield* registry.resolve(kept.loadedToken); + assert.isDefined(resolvedKept); + assert.equal(resolvedKept!.capabilities.has("preview"), enabled); + assert.isUndefined(resolvedKept!.thread.runId); + } - // Capability removal revokes the previously wider bearer immediately and does not restore a dead token. - const { - threadId: narrowedThreadId, - providerThread: narrowedProviderThread, - loadedConfig: broadLoadedConfig, - loadedToken: broadLoadedToken, - } = yield* attachLoadedThread("bg-narrowed"); - assert.isTrue(broadLoadedConfig.browserToolsAvailable); - yield* settings.updateSettings({ enableAgentBrowserAccess: false }); - yield* openFor(manager, providerSessionId, narrowedThreadId, { - runId: RunId.make("run-bg-narrowed-typed"), - attemptId: RunAttemptId.make("attempt-bg-narrowed-typed"), + // Work that starts after the turn's check is caught at reload: the staged token is revoked + // and the thread keeps its loaded one, unbound. + yield* Ref.set(pendingBackgroundWork, false); + const lateWork = yield* attachLoadedThread("bg-late"); + yield* openFor(manager, providerSessionId, lateWork.threadId, { + runId: RunId.make("run-bg-late-typed"), + attemptId: RunAttemptId.make("attempt-bg-late-typed"), requireRunScopedMcp: true, }); - const narrowedRotatedToken = rawBearer(yield* mcpSessions.read(narrowedThreadId)); - const narrowedFailed = yield* resume(narrowedThreadId, narrowedProviderThread).pipe( - Effect.flip, - ); - assert.equal(narrowedFailed._tag, "ProviderAdapterMcpRotationBlockedError"); - assert.isUndefined(yield* registry.resolve(broadLoadedToken)); - assert.isUndefined(yield* registry.resolve(narrowedRotatedToken)); - assert.isUndefined(yield* mcpSessions.read(narrowedThreadId)); + const stagedToken = rawBearer(yield* mcpSessions.read(lateWork.threadId)); + assert.notEqual(stagedToken, lateWork.loadedToken); + yield* Ref.set(pendingBackgroundWork, true); + yield* resume(lateWork.threadId, lateWork.providerThread); + assert.isTrue(Option.isNone(yield* Queue.poll(unloads))); + assert.isUndefined(yield* registry.resolve(stagedToken)); + assert.equal(rawBearer(yield* mcpSessions.read(lateWork.threadId)), lateWork.loadedToken); + assert.isUndefined((yield* registry.resolve(lateWork.loadedToken))?.thread.runId); - // Once background work finishes, the next ordinary (non-typed) turn recovers a working - // MCP credential with browser access still disabled and reloads the thread cleanly. + // Once the work finishes, the next typed turn rotates and reloads, browser access still off. yield* Ref.set(pendingBackgroundWork, false); - const nextPlainRun = RunId.make("run-bg-narrowed-next-plain"); - yield* openFor(manager, providerSessionId, narrowedThreadId, { - runId: nextPlainRun, - attemptId: RunAttemptId.make("attempt-bg-narrowed-next-plain"), - requireRunScopedMcp: false, + const narrowed = yield* attachLoadedThread("bg-narrowed-next"); + const nextTypedRun = RunId.make("run-bg-narrowed-next-typed"); + yield* openFor(manager, providerSessionId, narrowed.threadId, { + runId: nextTypedRun, + attemptId: RunAttemptId.make("attempt-bg-narrowed-next-typed"), + requireRunScopedMcp: true, }); - yield* resume(narrowedThreadId, narrowedProviderThread); + yield* resume(narrowed.threadId, narrowed.providerThread); assert.isTrue(Option.isSome(yield* Queue.poll(unloads))); - const recoveredConfig = yield* mcpSessions.read(narrowedThreadId); + const recoveredConfig = yield* mcpSessions.read(narrowed.threadId); assert.isFalse(recoveredConfig?.browserToolsAvailable); const resolvedRecovered = yield* registry.resolve(rawBearer(recoveredConfig)); assert.isDefined(resolvedRecovered); assert.isFalse(resolvedRecovered!.capabilities.has("preview")); - assert.equal(resolvedRecovered!.thread.runId, nextPlainRun); - assert.equal(recoveredConfig!.providerSessionId, broadLoadedConfig.providerSessionId); - assert.notEqual(recoveredConfig!.credentialId, broadLoadedConfig.credentialId); - - // Also cover run-less open recovery after a cleared capability-removal rollback. - yield* mcpSessions.clear(narrowedThreadId); - yield* openFor(manager, providerSessionId, narrowedThreadId); - const runlessRecovered = yield* mcpSessions.read(narrowedThreadId); + assert.equal(resolvedRecovered!.thread.runId, nextTypedRun); + assert.equal(recoveredConfig!.providerSessionId, narrowed.loadedConfig.providerSessionId); + assert.notEqual(recoveredConfig!.credentialId, narrowed.loadedConfig.credentialId); + + // A run-less open recovers a cleared credential under the same owner session. + yield* mcpSessions.clear(narrowed.threadId); + yield* openFor(manager, providerSessionId, narrowed.threadId); + const runlessRecovered = yield* mcpSessions.read(narrowed.threadId); assert.isDefined(runlessRecovered); - assert.equal(runlessRecovered!.providerSessionId, broadLoadedConfig.providerSessionId); + assert.equal(runlessRecovered!.providerSessionId, narrowed.loadedConfig.providerSessionId); assert.isFalse(runlessRecovered!.browserToolsAvailable); // A failed unload may leave the thread loaded, where a resume ignores new config: keep the old credential. @@ -4170,72 +4247,20 @@ it.effect.each([ assert.isTrue(Option.isSome(yield* Queue.poll(unloads))); assert.isUndefined(yield* registry.resolve(loadedToken)); - // If a newer credential is published while the background-work probe awaits, the fallback - // skips releasing and overwriting it. - const probeRaceThreadId = ThreadId.make("thread-provider-session-manager-probe-race"); - yield* eventSink.write({ - events: [ - yield* makeThreadCreatedEvent({ idAllocator, threadId: probeRaceThreadId, now }), - ], - }); - const raceRun1 = RunId.make("run-probe-race-1"); - yield* openFor(manager, providerSessionId, probeRaceThreadId, { - runId: raceRun1, - attemptId: RunAttemptId.make("attempt-probe-race-1"), - requireRunScopedMcp: true, - }); - const originalRaceConfig = yield* mcpSessions.read(probeRaceThreadId); - const originalRaceToken = rawBearer(originalRaceConfig); - const probeStarted = yield* Deferred.make(); - const releaseProbe = yield* Deferred.make(); - yield* Ref.set( - sessionBackgroundWorkProbe, - Deferred.succeed(probeStarted, undefined).pipe( - Effect.andThen(Deferred.await(releaseProbe)), - ), - ); - const racingOpen = yield* openFor(manager, providerSessionId, probeRaceThreadId, { - runId: RunId.make("run-probe-race-2"), - attemptId: RunAttemptId.make("attempt-probe-race-2"), + // A shared session reloads only this thread, so another thread's background work does not + // keep this thread's credential unbound. + const busyElsewhere = yield* attachLoadedThread("busy-elsewhere"); + const threadWorkBefore = yield* Ref.get(pendingBackgroundWork); + yield* Ref.set(pendingBackgroundWork, false); + yield* Ref.set(sessionBackgroundWorkProbe, Effect.succeed(true)); + const busyElsewhereRun = RunId.make("run-busy-elsewhere-typed"); + yield* openFor(manager, providerSessionId, busyElsewhere.threadId, { + runId: busyElsewhereRun, + attemptId: RunAttemptId.make("attempt-busy-elsewhere-typed"), requireRunScopedMcp: true, - }).pipe(Effect.forkChild); - yield* Deferred.await(probeStarted); - const newerIssued = yield* registry.issue({ - threadId: probeRaceThreadId, - providerInstanceId: modelSelection.instanceId, - providerSessionId: originalRaceConfig!.providerSessionId, - runId: RunId.make("run-probe-race-3"), - attemptId: RunAttemptId.make("attempt-probe-race-3"), }); - yield* mcpSessions.set(newerIssued.config); - yield* Deferred.succeed(releaseProbe, true); - yield* Fiber.join(racingOpen); - const afterRace = yield* mcpSessions.read(probeRaceThreadId); - assert.equal(afterRace?.authorizationHeader, newerIssued.config.authorizationHeader); - assert.isUndefined(afterRace?.runId); - // The older credential was not released or written back; the newer one became unbound for run 2. - assert.equal((yield* registry.resolve(originalRaceToken))?.thread.runId, raceRun1); - const newerToken = rawBearer(newerIssued.config); - const resolvedNewer = yield* registry.resolve(newerToken); - assert.isDefined(resolvedNewer); - assert.isUndefined(resolvedNewer!.thread.runId); - // Narrowing on a non-rotating turn strips preview from older retained thread tokens too, - // while re-enabling restores it only on the active credential. - for (const [enabled, ordinal] of [ - [false, 4], - [true, 5], - ] as const) { - yield* settings.updateSettings({ enableAgentBrowserAccess: enabled }); - yield* openFor(manager, providerSessionId, probeRaceThreadId, { - runId: RunId.make(`run-probe-race-${ordinal}`), - attemptId: RunAttemptId.make(`attempt-probe-race-${ordinal}`), - requireRunScopedMcp: true, - }); - assert.equal((yield* registry.resolve(newerToken))?.capabilities.has("preview"), enabled); - assert.isFalse( - (yield* registry.resolve(originalRaceToken))?.capabilities.has("preview") ?? true, - ); - } + assert.equal((yield* mcpSessions.read(busyElsewhere.threadId))?.runId, busyElsewhereRun); + yield* Ref.set(pendingBackgroundWork, threadWorkBefore); // A failed linked-environment unload keeps the loaded MCP credential record so MCP refresh // still rolls back a staged credential instead of bypassing rotation. diff --git a/apps/server/src/orchestration-v2/ProviderSessionManager.ts b/apps/server/src/orchestration-v2/ProviderSessionManager.ts index 463f67b238379..167e2e7579a48 100644 --- a/apps/server/src/orchestration-v2/ProviderSessionManager.ts +++ b/apps/server/src/orchestration-v2/ProviderSessionManager.ts @@ -340,6 +340,7 @@ interface LiveSessionEntry { ThreadId, { readonly providerThread: string; + readonly thread: OrchestrationV2ProviderThread; readonly credential: McpProviderSession.McpProviderSessionConfig; } >; @@ -2085,7 +2086,7 @@ export const layerWithOptions = ( const markProviderThreadLoaded = (input: { readonly providerSessionId: ProviderSessionId; readonly threadId: ThreadId; - readonly providerThread: Parameters[0]; + readonly providerThread: OrchestrationV2ProviderThread; readonly providerThreadKey: string; readonly linkedEnvironments: boolean | null | undefined; readonly mcpCredential?: McpProviderSession.McpProviderSessionConfig | undefined; @@ -2103,6 +2104,7 @@ export const layerWithOptions = ( ? entry.loadedMcpCredentialByThread : new Map(entry.loadedMcpCredentialByThread).set(input.threadId, { providerThread: providerThreadRuntimeKey(input.providerThread), + thread: input.providerThread, credential: input.mcpCredential, }); const linkedEnvironmentsByThread = new Map(entry.linkedEnvironmentsByThread); @@ -2361,10 +2363,25 @@ export const layerWithOptions = ( } // A runtime that cannot take a new credential now (no way to deliver one, or a reload that // would end background work) keeps it unbound; the agent then names its run in the call. + // A shared session reloads only this thread, so only this thread's own work blocks it. + const loadedThread = (yield* Ref.get(sessions)) + .get(sessionKey(input.providerSessionId)) + ?.loadedMcpCredentialByThread.get(input.threadId)?.thread; + const pendingWork = + input.runtime.providerSession.capabilities.sessions + .supportsMultipleProviderThreadsPerSession && + input.runtime.unloadThread !== undefined + ? loadedThread === undefined || + input.runtime.hasPendingBackgroundWorkForThread === undefined + ? Effect.succeed(false) + : input.runtime.hasPendingBackgroundWorkForThread(loadedThread, { + includeSubagents: true, + }) + : (input.runtime.hasPendingBackgroundWork ?? Effect.succeed(false)); const cannotRotate = input.runtime.mcpCredentialRotation === "none" || (input.runtime.mcpCredentialRotation !== "live" && - (yield* (input.runtime.hasPendingBackgroundWork ?? Effect.succeed(false)).pipe( + (yield* pendingWork.pipe( Effect.catchCauseIf( (cause) => !Cause.hasInterruptsOnly(cause), () => Effect.succeed(true), diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts index ff022d74ae9be..17bdbe5c950cf 100644 --- a/packages/provider-acp/src/server/adapter.ts +++ b/packages/provider-acp/src/server/adapter.ts @@ -11125,11 +11125,15 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( const activated = yield* runtime .loadSession(sessionId, acpMcpActivation(mcpContext)) .pipe(Effect.onError(() => Ref.set(loadingSessionId, null))); + if (runtimeMcpBridge !== undefined && mcpContext.authorization !== undefined) { + runtimeMcpBridge.setAuthorization(mcpContext.authorization); + } rememberTerminalEnvironment( activated.sessionId, yield* readMcpContext(snapshotInput.providerThread.appThreadId), ); yield* Ref.set(activeSessionId, activated.sessionId); + yield* Ref.set(activeMcpAuthorization, mcpContext.authorization); yield* Ref.set(loadingSessionId, null); yield* setActiveSessionSetup(activated); yield* Ref.set(activeSelection, null); From 1d118da8aec20476a03311e3776b1020573ad60e Mon Sep 17 00:00:00 2001 From: Victor Vogel Date: Tue, 24 Nov 2026 01:23:06 +0000 Subject: [PATCH 21/34] fix(provider-acp): a reconnect after an MCP credential rotation no longer holds other calls The reconnect mutex is released once the connection is renegotiated, so one long tool call no longer blocks every other call on the connection. --- .../src/server/mcpOverAcpBridge.test.ts | 30 +++++++++++++++++++ .../src/server/mcpOverAcpBridge.ts | 28 ++++++++++++----- 2 files changed, 50 insertions(+), 8 deletions(-) diff --git a/packages/provider-acp/src/server/mcpOverAcpBridge.test.ts b/packages/provider-acp/src/server/mcpOverAcpBridge.test.ts index e856a7397feea..b7667b797c199 100644 --- a/packages/provider-acp/src/server/mcpOverAcpBridge.test.ts +++ b/packages/provider-acp/src/server/mcpOverAcpBridge.test.ts @@ -266,6 +266,11 @@ describe("AcpMcpOverAcpBridge", () => { description: "reconnects cleanly when auth rotates during initial initialize and rejects waiting calls from the prior generation", }, + { + scenario: "reconnect-releases-mutex" as const, + description: + "answers a reconnecting call while a long call from an earlier reconnect is pending", + }, { scenario: "error-and-malformed-initialize" as const, description: @@ -389,6 +394,31 @@ describe("AcpMcpOverAcpBridge", () => { return; } + if (scenario === "reconnect-releases-mutex") { + const slowCallStarted = Promise.withResolvers(); + const releaseSlowCall = Promise.withResolvers(); + const { bridge, init, callTool } = yield* makeStatefulBridge({ + onRequest: async (_auth, body) => { + if (body.params?.name === "slow_call") { + slowCallStarted.resolve(); + await releaseSlowCall.promise; + } + return undefined; + }, + }); + + yield* init(); + bridge.setAuthorization("Bearer run-2-token"); + const slow = yield* callTool("slow_call").pipe(Effect.forkChild); + yield* Effect.promise(() => slowCallStarted.promise); + // The slow call reconnected for run 2; the next rotation's reconnect must not wait on it. + bridge.setAuthorization("Bearer run-3-token"); + expect(yield* callTool()).toEqual({ content: [] }); + releaseSlowCall.resolve(); + expect(yield* Fiber.join(slow)).toEqual({ content: [] }); + return; + } + if (scenario === "init-race-and-waiting-rejection") { const initStarted = Promise.withResolvers(); const releaseInit = Promise.withResolvers(); diff --git a/packages/provider-acp/src/server/mcpOverAcpBridge.ts b/packages/provider-acp/src/server/mcpOverAcpBridge.ts index a40efd06ab65a..b711cb18803f7 100644 --- a/packages/provider-acp/src/server/mcpOverAcpBridge.ts +++ b/packages/provider-acp/src/server/mcpOverAcpBridge.ts @@ -115,12 +115,16 @@ export const makeAcpMcpOverAcpBridge = Effect.fn("AcpMcpOverAcpBridge.make")(fun : Effect.succeed(connection); }); - // Only initialization and auth-rotation reconnects need ordering; negotiated calls wait independently. - const untilNegotiated = (connection: Connection, effect: Effect.Effect) => + // Only initialization needs ordering; negotiated calls wait independently. The flag says + // whether the call already holds the mutex for first negotiation. + const untilNegotiated = ( + connection: Connection, + effect: (ordered: boolean) => Effect.Effect, + ) => Effect.suspend(() => - connection.protocolVersion === null || connection.needsReconnect - ? connection.mutex.withPermits(1)(effect) - : effect, + connection.protocolVersion === null + ? connection.mutex.withPermits(1)(effect(true)) + : effect(false), ); const postOnce = Effect.fn("AcpMcpOverAcpBridge.postOnce")(function* ( @@ -227,8 +231,7 @@ export const makeAcpMcpOverAcpBridge = Effect.fn("AcpMcpOverAcpBridge.make")(fun ): Effect.Effect, AcpMcpOverAcpError> => { const method = asEnvelope(message)?.method; const pinnedGeneration = authorizationGeneration; - return untilNegotiated( - connection, + return untilNegotiated(connection, (ordered) => Effect.gen(function* () { if (method !== "initialize") { while (true) { @@ -238,7 +241,16 @@ export const makeAcpMcpOverAcpBridge = Effect.fn("AcpMcpOverAcpBridge.make")(fun }); } if (!connection.needsReconnect) break; - yield* reconnectIfNeeded(connection); + // A reconnect holds the mutex only while it renegotiates, not for this request. + yield* ordered + ? reconnectIfNeeded(connection) + : connection.mutex.withPermits(1)( + Effect.suspend(() => + connection.needsReconnect && authorizationGeneration === pinnedGeneration + ? reconnectIfNeeded(connection) + : Effect.void, + ), + ); } } const requestGeneration = authorizationGeneration; From 109c1971357abce3f99a322c932700343f360b0d Mon Sep 17 00:00:00 2001 From: Victor Vogel Date: Tue, 24 Nov 2026 01:23:21 +0000 Subject: [PATCH 22/34] fix(server): a stopped wake's late result no longer lands on the run it answered A turn that may answer an owed result now gets its own MCP credential identity, while the owed run stays the target. A late call on a stopped wake's credential is turned down once the wake ends or a later turn starts. --- .../src/orchestration-v2/Orchestrator.ts | 2 +- .../ProviderSessionManager.test.ts | 15 ++++++++ .../ProviderSessionManager.ts | 20 +++------- .../src/orchestration-v2/runOutput.test.ts | 6 +-- apps/server/src/orchestration-v2/runOutput.ts | 5 +-- .../src/orchestration-v2/runtimeLayer.test.ts | 38 +++++++++++++++---- 6 files changed, 55 insertions(+), 31 deletions(-) diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 6a3413ea286bd..ec292fab8913e 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -12540,7 +12540,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio `Caller run ${command.callerRunId ?? "unknown"} is no longer active on thread ${command.threadId}.`, ); } - // A wake turn may reuse the owed run's credential, so its calls cannot be told apart. + // A wake on an unbound credential names the owed run, so its calls cannot be told apart. if ( active !== undefined && active.id !== run.id && diff --git a/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts b/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts index 5ee4e71dbee0e..27d86ba54ebd0 100644 --- a/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts +++ b/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts @@ -3646,6 +3646,7 @@ it.effect.each([ readonly runId?: RunId; readonly attemptId?: RunAttemptId; readonly requireRunScopedMcp?: boolean; + readonly owedOutputRunId?: RunId; }, ) => manager.open({ @@ -3725,6 +3726,20 @@ it.effect.each([ config1!.authorizationHeader, ); + // A wake that may answer run 1's owed result gets its own identity, so a stopped wake's late + // call cannot pass for run 1 once the wake ends. + const wakeRun = RunId.make("run-live-wake"); + yield* openFor(manager, providerSessionId, threadId, { + runId: wakeRun, + attemptId: RunAttemptId.make("attempt-live-wake"), + requireRunScopedMcp: false, + owedOutputRunId: run1, + }); + const wakeToken = rawBearer(yield* mcpSessions.read(threadId)); + assert.notEqual(wakeToken, token1); + assert.equal((yield* registry.resolve(wakeToken))?.thread.runId, wakeRun); + assert.equal((yield* registry.resolve(token1))?.thread.runId, run1); + const run2 = RunId.make("run-live-2"); const attempt2 = RunAttemptId.make("attempt-live-2"); yield* openFor(manager, providerSessionId, threadId, { diff --git a/apps/server/src/orchestration-v2/ProviderSessionManager.ts b/apps/server/src/orchestration-v2/ProviderSessionManager.ts index 167e2e7579a48..6474b990f6a21 100644 --- a/apps/server/src/orchestration-v2/ProviderSessionManager.ts +++ b/apps/server/src/orchestration-v2/ProviderSessionManager.ts @@ -725,14 +725,10 @@ export const layerWithOptions = ( else mcpTurnCheckedKeyByThread.set(threadId, turnKey); return new Map(current).set(key, { ...entry, mcpTurnCheckedKeyByThread }); }); - const threadRequiresRunScopedMcp = ( - threadId: ThreadId, - runId: RunId | undefined, - currentCredentialRunId?: RunId, - ) => + const threadRequiresRunScopedMcp = (threadId: ThreadId, runId: RunId | undefined) => projectionStore.getThreadRecords(threadId, ["runs"]).pipe( Effect.flatMap(({ runs }) => - runRequiresRunScopedMcp(runs, runId, currentCredentialRunId, () => + runRequiresRunScopedMcp(runs, runId, () => projectionStore.getThreadRecords(threadId, ["runs", "turnItems"], { turnItemTypes: ["user_message"], }), @@ -2338,16 +2334,12 @@ export const layerWithOptions = ( if (yield* retainCurrentMcpCredential(current, { unbindRun: false })) return; continue; } + // A wake answering an owed run gets its own identity, so its late calls stop counting + // once it ends, while the owed run stays the target. const rotateOnRunChange = input.requireRunScopedMcp !== undefined - ? input.requireRunScopedMcp || - (input.owedOutputRunId !== undefined && - current?.runId !== input.owedOutputRunId) - : yield* threadRequiresRunScopedMcp( - input.threadId, - input.runId, - current?.runId, - ).pipe( + ? input.requireRunScopedMcp || input.owedOutputRunId !== undefined + : yield* threadRequiresRunScopedMcp(input.threadId, input.runId).pipe( Effect.mapError( (cause) => new ProviderSessionOpenError({ diff --git a/apps/server/src/orchestration-v2/runOutput.test.ts b/apps/server/src/orchestration-v2/runOutput.test.ts index 3d712937c7f3a..d0ac0c9e5031e 100644 --- a/apps/server/src/orchestration-v2/runOutput.test.ts +++ b/apps/server/src/orchestration-v2/runOutput.test.ts @@ -88,7 +88,6 @@ it.effect("owed output follows only the newest started request inside the curren yield* runRequiresRunScopedMcp( [asked, correction, plain], plain.id, - correction.id, loadContext([asked, correction, plain]), ), ); @@ -109,7 +108,6 @@ it.effect("owed output follows only the newest started request inside the curren yield* runRequiresRunScopedMcp( schedRuns, plain.id, - undefined, loadContext(schedRuns, scheduledFresh.userMessageId), ), ); @@ -117,8 +115,6 @@ it.effect("owed output follows only the newest started request inside the curren const fresh = makeRun("run:fresh", 3, { status: "running", freshContext: true }); const freshRuns = [asked, fresh]; assert.isUndefined(yield* resolveOwedOutputRun(freshRuns, loadContext(freshRuns))); - assert.isFalse( - yield* runRequiresRunScopedMcp(freshRuns, fresh.id, undefined, loadContext(freshRuns)), - ); + assert.isFalse(yield* runRequiresRunScopedMcp(freshRuns, fresh.id, loadContext(freshRuns))); }), ); diff --git a/apps/server/src/orchestration-v2/runOutput.ts b/apps/server/src/orchestration-v2/runOutput.ts index 4ec95fe4b935b..f5386e48450ff 100644 --- a/apps/server/src/orchestration-v2/runOutput.ts +++ b/apps/server/src/orchestration-v2/runOutput.ts @@ -72,11 +72,10 @@ export const resolveOwedOutputRun = ( ); }; -/** Whether a turn needs its MCP credential rotated to match its run/attempt identity. */ +/** Whether a turn's MCP credential must name its run: it asked for a result or may answer an owed one. */ export const runRequiresRunScopedMcp = ( runs: ReadonlyArray, runId: RunId | undefined, - currentCredentialRunId: RunId | undefined, loadContextRecords: () => Effect.Effect< Pick, E, @@ -90,7 +89,7 @@ export const runRequiresRunScopedMcp = ( return Effect.succeed(true); } return resolveOwedOutputRun(runs, loadContextRecords).pipe( - Effect.map((owed) => owed !== undefined && currentCredentialRunId !== owed.id), + Effect.map((owed) => owed !== undefined), ); }; diff --git a/apps/server/src/orchestration-v2/runtimeLayer.test.ts b/apps/server/src/orchestration-v2/runtimeLayer.test.ts index 914867d13e8e4..18725cd3e84ab 100644 --- a/apps/server/src/orchestration-v2/runtimeLayer.test.ts +++ b/apps/server/src/orchestration-v2/runtimeLayer.test.ts @@ -12761,23 +12761,45 @@ it.layer(layerSharedApplicationDataPlaneTest)("run output after a stop", (it) => { from: "run-f" }, ); - // A stopped wake keeps the owed run's credential, so what it submits is not kept either. + // A stopped wake's result is not kept, on its own credential or on an unbound one that + // can only name the owed run. yield* finishRun(runF, "run-f-completed", "completed"); yield* send("run-g", { type: "object" }); const runG = yield* latestRun(); yield* finishRun(runG, "run-g-completed", "completed"); yield* send("run-h-wake"); - yield* requestStop(yield* latestRun(), "run-h-interrupt-request"); - const fromStoppedWake = yield* submit("run-output-from-stopped-wake", '{"from":"h"}', { - callerRunId: runG.id, - requestedRunId: runG.id, - }).pipe(Effect.flip); - assert.equal(fromStoppedWake._tag, "ThreadManagementRunOutputRejectedError"); - assert.include(fromStoppedWake.message, "was stopped"); + const runH = yield* latestRun(); + yield* requestStop(runH, "run-h-interrupt-request"); + for (const callerRunId of [runH.id, runG.id]) { + const fromStoppedWake = yield* submit( + `run-output-from-stopped-wake-${callerRunId}`, + '{"from":"h"}', + { callerRunId, requestedRunId: runG.id }, + ).pipe(Effect.flip); + assert.equal(fromStoppedWake._tag, "ThreadManagementRunOutputRejectedError"); + assert.include(fromStoppedWake.message, "was stopped"); + } + + // Once the stopped wake ends, its credential answers for nothing while the next wake's does. + yield* finishRun(runH, "run-h-interrupted", "interrupted"); + yield* send("run-i-wake"); + const runI = yield* latestRun(); + const lateFromStoppedWake = yield* submit( + "late-run-output-from-stopped-wake", + '{"from":"h"}', + { callerRunId: runH.id, requestedRunId: runG.id }, + ).pipe(Effect.flip); + assert.equal(lateFromStoppedWake._tag, "ThreadManagementRunOutputRejectedError"); + assert.include(lateFromStoppedWake.message, "no longer active"); assert.isUndefined( (yield* orchestrator.getThreadProjection(threadId)).runs.find((run) => run.id === runG.id) ?.output, ); + const fromNextWake = yield* submit("run-output-from-next-wake", '{"from":"i"}', { + callerRunId: runI.id, + requestedRunId: runG.id, + }); + assert.equal(fromNextWake.runId, runG.id); return; } From a6f644112b745619442d648a9ed0ef1931cfd34a Mon Sep 17 00:00:00 2001 From: Victor Vogel Date: Tue, 24 Nov 2026 01:23:36 +0000 Subject: [PATCH 23/34] fix(server): a typed result must name its run A runtime that updates its MCP credential live sends a late call on the newer run's credential, so a call that named no run could land on that run. Every submission now names its run, as its instructions already say. --- .../src/mcp/toolkits/thread/handlers.ts | 2 +- .../ThreadLaunchService.test.ts | 1 + .../ThreadManagementService.test.ts | 1 + .../ThreadManagementService.ts | 10 +++--- .../src/orchestration-v2/runtimeLayer.test.ts | 33 +++++++++++++++++-- 5 files changed, 39 insertions(+), 8 deletions(-) diff --git a/apps/server/src/mcp/toolkits/thread/handlers.ts b/apps/server/src/mcp/toolkits/thread/handlers.ts index 39ff22316ee03..598e65e6350db 100644 --- a/apps/server/src/mcp/toolkits/thread/handlers.ts +++ b/apps/server/src/mcp/toolkits/thread/handlers.ts @@ -288,7 +288,7 @@ export const layer = McpToolAccess.toLayer(ThreadToolkit, { Effect.gen(function* () { const { scope, threads } = yield* readCaller(); if (scope.thread === undefined) return yield* unavailable(); - // A credential bound to its run outranks the argument; an unbound one has only the argument. + // A bound credential names the caller; the argument names the run the result is for. const callerRunId = scope.thread.runId ?? input.runId; return yield* threads .submitRunOutput({ diff --git a/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts b/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts index 0bda3145bc97d..f89f21b4a88d6 100644 --- a/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts +++ b/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts @@ -677,6 +677,7 @@ it.effect("a run asked for a result stores what its agent submits once it fits t commandId: CommandId.make(command), json, callerRunId: askedRunId, + requestedRunId: askedRunId, }); const rejected = yield* submit("command:output:bad", '{"verdict":"maybe"}').pipe(Effect.flip); diff --git a/apps/server/src/orchestration-v2/ThreadManagementService.test.ts b/apps/server/src/orchestration-v2/ThreadManagementService.test.ts index a4155b888e737..f34c2a3dcee98 100644 --- a/apps/server/src/orchestration-v2/ThreadManagementService.test.ts +++ b/apps/server/src/orchestration-v2/ThreadManagementService.test.ts @@ -557,6 +557,7 @@ it.effect( commandId: CommandId.make("command:thread-management:owed"), json: '{"head":"abc"}', callerRunId: wakeRunId, + requestedRunId: runId, }); expect(accepted.runId).toBe(runId); expect(submitted).toMatchObject([ diff --git a/apps/server/src/orchestration-v2/ThreadManagementService.ts b/apps/server/src/orchestration-v2/ThreadManagementService.ts index 9f419cf155426..e2e7e76a9b811 100644 --- a/apps/server/src/orchestration-v2/ThreadManagementService.ts +++ b/apps/server/src/orchestration-v2/ThreadManagementService.ts @@ -1077,14 +1077,16 @@ const make = Effect.gen(function* () { problem: "This turn was not asked for a result. Reply in your message instead.", }); } - // Without it a stopped run's late call cannot be told from the active run's. - if (input.callerRunId === undefined) { + // Without it a stopped run's late call cannot be told from the active run's, even on a bound + // credential: a runtime that updates its credential live sends a late call on the newer one. + const requestedRunId = input.requestedRunId; + if (requestedRunId === undefined) { return yield* new ThreadManagementRunOutputRejectedError({ threadId: input.threadId, problem: "Pass `runId` as this turn's instructions gave it.", }); } - const callerRunId = input.callerRunId; + const callerRunId = input.callerRunId ?? requestedRunId; const matchesRun = (candidate: OrchestrationV2Run) => candidate.id === callerRunId && (input.callerAttemptId === undefined || candidate.activeAttemptId === input.callerAttemptId); @@ -1104,7 +1106,7 @@ const make = Effect.gen(function* () { }; // Accept the active run, or the un-stopped completed run whose own owed output is targeted. if ( - (input.requestedRunId !== undefined && !continuesNamedRun(input.requestedRunId)) || + !continuesNamedRun(requestedRunId) || (!matchesRun(active) && !(run.id !== active.id && matchesRun(run))) ) { return yield* new ThreadManagementRunOutputRejectedError({ diff --git a/apps/server/src/orchestration-v2/runtimeLayer.test.ts b/apps/server/src/orchestration-v2/runtimeLayer.test.ts index 18725cd3e84ab..2169b7b22571a 100644 --- a/apps/server/src/orchestration-v2/runtimeLayer.test.ts +++ b/apps/server/src/orchestration-v2/runtimeLayer.test.ts @@ -12238,7 +12238,7 @@ it.layer(layerSharedApplicationDataPlaneTest)("run output after a stop", (it) => threadId, commandId: CommandId.make(`runtime-layer-owed-output-submit-${key}`), json, - ...(callerRunId === undefined ? {} : { callerRunId }), + ...(callerRunId === undefined ? {} : { callerRunId, requestedRunId: callerRunId }), }); const refused = Effect.fn(function* (key: string) { const rejected = yield* submit(key).pipe(Effect.flip); @@ -12439,6 +12439,7 @@ it.layer(layerSharedApplicationDataPlaneTest)("run output after a stop", (it) => commandId: CommandId.make("runtime-layer-stopped-output-submit"), json: "{}", callerRunId: run.id, + requestedRunId: run.id, }) .pipe(Effect.flip); assert.equal(rejected._tag, "ThreadManagementRunOutputRejectedError"); @@ -12572,10 +12573,13 @@ it.layer(layerSharedApplicationDataPlaneTest)("run output after a stop", (it) => threadId, commandId: CommandId.make(`runtime-layer-${command}`), json, + // Unless a case says otherwise, the call names the run its caller is. + ...(caller?.callerRunId === undefined ? {} : { requestedRunId: caller.callerRunId }), ...caller, }); return { orchestrator, + threadManagement, threadId, send, latestRun, @@ -12605,8 +12609,16 @@ it.layer(layerSharedApplicationDataPlaneTest)("run output after a stop", (it) => ])("$description", ({ scenario }) => Effect.gen(function* () { if (scenario === "stopped-run-or-stale-attempt") { - const { orchestrator, threadId, send, latestRun, updateRun, finishRun, submit } = - yield* setupOutputThread("late-stopped-run"); + const { + orchestrator, + threadManagement, + threadId, + send, + latestRun, + updateRun, + finishRun, + submit, + } = yield* setupOutputThread("late-stopped-run"); // Run A starts with a schema, then is stopped while its submission is in flight. yield* send("run-a", { type: "object" }); @@ -12650,6 +12662,20 @@ it.layer(layerSharedApplicationDataPlaneTest)("run output after a stop", (it) => assert.equal(lateFromAOnB._tag, "ThreadManagementRunOutputRejectedError"); assert.include(lateFromAOnB.message, "no longer active"); + // A runtime that updates its credential live sends A's late call on B's credential, so a + // call that names no run is not taken for B. + const unnamedOnB = yield* threadManagement + .submitRunOutput({ + threadId, + commandId: CommandId.make("runtime-layer-late-unnamed-run-output-on-b"), + json: '{"from":"run-a"}', + callerRunId: runB.id, + callerAttemptId: attempt2, + }) + .pipe(Effect.flip); + assert.equal(unnamedOnB._tag, "ThreadManagementRunOutputRejectedError"); + assert.include(unnamedOnB.message, "runId"); + assert.isUndefined((yield* latestRun()).output); const acceptedB = yield* submit("late-run-output-from-b", '{"from":"run-b"}', { @@ -12753,6 +12779,7 @@ it.layer(layerSharedApplicationDataPlaneTest)("run output after a stop", (it) => const runF = yield* latestRun(); const acceptedFromF = yield* submit("late-run-output-from-f", '{"from":"run-f"}', { callerRunId: runF.id, + requestedRunId: runE.id, }); assert.equal(acceptedFromF.runId, runE.id); assert.deepEqual( From e730495d163d75a7714a4786a60124a304d539e3 Mon Sep 17 00:00:00 2001 From: Victor Vogel Date: Tue, 24 Nov 2026 01:37:21 +0000 Subject: [PATCH 24/34] fix(server): a provider-started wake and a typed continuation submit for their own run A wake the provider already started runs on the MCP credential it holds, so it keeps that one, unbound, instead of rotating to a credential the provider never receives. A typed continuation is always prompted with its own runId, and a submission must name exactly the run it is for, so a stopped run's late call cannot land on the run that continues it. --- .../ProviderSessionManager.test.ts | 15 +++ .../ProviderSessionManager.ts | 10 +- .../ProviderTurnStartService.test.ts | 101 +++++++++--------- .../ProviderTurnStartService.ts | 9 +- .../ThreadManagementService.ts | 17 +-- .../src/orchestration-v2/runtimeLayer.test.ts | 20 ++-- 6 files changed, 90 insertions(+), 82 deletions(-) diff --git a/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts b/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts index 27d86ba54ebd0..2f295c45b4a78 100644 --- a/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts +++ b/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts @@ -3647,6 +3647,7 @@ it.effect.each([ readonly attemptId?: RunAttemptId; readonly requireRunScopedMcp?: boolean; readonly owedOutputRunId?: RunId; + readonly providerStartedTurn?: boolean; }, ) => manager.open({ @@ -3740,6 +3741,20 @@ it.effect.each([ assert.equal((yield* registry.resolve(wakeToken))?.thread.runId, wakeRun); assert.equal((yield* registry.resolve(token1))?.thread.runId, run1); + // A wake the provider already started runs on the credential it holds, so that one stays, + // unbound: the agent answers run 1 by naming it. + yield* openFor(manager, providerSessionId, threadId, { + runId: RunId.make("run-live-provider-wake"), + attemptId: RunAttemptId.make("attempt-live-provider-wake"), + requireRunScopedMcp: false, + owedOutputRunId: run1, + providerStartedTurn: true, + }); + assert.equal(rawBearer(yield* mcpSessions.read(threadId)), wakeToken); + const providerWake = yield* registry.resolve(wakeToken); + assert.isDefined(providerWake); + assert.isUndefined(providerWake!.thread.runId); + const run2 = RunId.make("run-live-2"); const attempt2 = RunAttemptId.make("attempt-live-2"); yield* openFor(manager, providerSessionId, threadId, { diff --git a/apps/server/src/orchestration-v2/ProviderSessionManager.ts b/apps/server/src/orchestration-v2/ProviderSessionManager.ts index 6474b990f6a21..5c95384f9366e 100644 --- a/apps/server/src/orchestration-v2/ProviderSessionManager.ts +++ b/apps/server/src/orchestration-v2/ProviderSessionManager.ts @@ -257,6 +257,8 @@ export interface ProviderSessionManagerV2Shape { readonly attemptId?: RunAttemptId; readonly requireRunScopedMcp?: boolean; readonly owedOutputRunId?: RunId; + /** The provider already started this turn natively, on the credential it holds. */ + readonly providerStartedTurn?: boolean; readonly resumeFromSession?: OrchestrationV2ProviderSession; readonly initialNativeThreadId?: string; readonly initialProviderItemIdentityVersion?: 2; @@ -2229,6 +2231,7 @@ export const layerWithOptions = ( readonly attemptId?: RunAttemptId | undefined; readonly requireRunScopedMcp?: boolean | undefined; readonly owedOutputRunId?: RunId | undefined; + readonly providerStartedTurn?: boolean | undefined; }) { if (options.configureMcp === false) return; let reservedCredentialId: string | undefined; @@ -2353,8 +2356,9 @@ export const layerWithOptions = ( if (yield* retainCurrentMcpCredential(current, { unbindRun: false })) return; continue; } - // A runtime that cannot take a new credential now (no way to deliver one, or a reload that - // would end background work) keeps it unbound; the agent then names its run in the call. + // A turn that cannot take a new credential now (the provider already started it, no way to + // deliver one, or a reload that would end background work) keeps it unbound; the agent + // then names its run in the call. // A shared session reloads only this thread, so only this thread's own work blocks it. const loadedThread = (yield* Ref.get(sessions)) .get(sessionKey(input.providerSessionId)) @@ -2371,6 +2375,7 @@ export const layerWithOptions = ( }) : (input.runtime.hasPendingBackgroundWork ?? Effect.succeed(false)); const cannotRotate = + input.providerStartedTurn === true || input.runtime.mcpCredentialRotation === "none" || (input.runtime.mcpCredentialRotation !== "live" && (yield* pendingWork.pipe( @@ -4028,6 +4033,7 @@ export const layerWithOptions = ( attemptId: input.attemptId, requireRunScopedMcp: input.requireRunScopedMcp, owedOutputRunId: input.owedOutputRunId, + providerStartedTurn: input.providerStartedTurn, }); } else if ( options.configureMcp !== false && diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts index 8f5d68bc82eb4..0e83963b67890 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts @@ -493,6 +493,7 @@ function makeLocalCommandHarness(input: { readonly previousNativeSession?: boolean; readonly previousMessages?: ReadonlyArray; readonly createdBy?: "agent" | "system"; + readonly creationSource?: "provider"; readonly scheduledTaskId?: ScheduledTaskId; readonly logoutFailure?: string; readonly openFailure?: unknown; @@ -595,7 +596,7 @@ function makeLocalCommandHarness(input: { attachments: [], streaming: false, createdBy: input.createdBy ?? "user", - creationSource: input.createdBy === undefined ? "web" : "mcp", + creationSource: input.creationSource ?? (input.createdBy === undefined ? "web" : "mcp"), ...(input.scheduledTaskId === undefined ? {} : { scheduledTaskId: input.scheduledTaskId }), createdAt: now, updatedAt: now, @@ -2415,56 +2416,54 @@ effectIt.effect("sends new steering text when restarting a manual continuation", expect(harness.startTurn.mock.calls[0]?.[0].message.text).toBe("New steering instruction"); expect(harness.startRootRun.mock.calls[0]?.[0].resume).toBe(false); - // An unbound MCP credential cannot supply runId, so typed continuations prompt with their own runId. - const unboundManual = makeLocalCommandHarness({ - text: "", - manualContinuation: true, - outputSchema: { type: "object" }, - mcpSession: "unbound", - sideChat: { contextRun: "delivered" }, - }); - yield* unboundManual.start; - const unboundManualTurn = unboundManual.startTurn.mock.calls[0]?.[0]; - expect(unboundManualTurn?.resume).toBeUndefined(); - expect(unboundManualTurn?.message.text).toContain("Continue where you left off."); - expect(unboundManualTurn?.message.text).toContain("run-native-account-command"); - expect(unboundManualTurn?.inlineContextLength).toBeUndefined(); - - // A bound MCP credential supplies runId itself, so native resume keeps sending no prompt text. - const boundManual = makeLocalCommandHarness({ - text: "", - manualContinuation: true, - outputSchema: { type: "object" }, - mcpSession: "bound", - sideChat: { contextRun: "delivered" }, - }); - yield* boundManual.start; - const boundManualTurn = boundManual.startTurn.mock.calls[0]?.[0]; - expect(boundManualTurn?.resume).toBe(true); - expect(boundManualTurn?.message.text).toBe(""); - - // An unbound typed restart continuation strips restartContinuationOfRunId; a bound one keeps it. - const unboundRestart = makeLocalCommandHarness({ - text: "Continue where you left off.", - restartContinuation: true, - outputSchema: { type: "object" }, - mcpSession: "unbound", - sideChat: { contextRun: "delivered" }, - }); - yield* unboundRestart.start; - expect(unboundRestart.startTurn.mock.calls[0]?.[0].restartContinuationOfRunId).toBeUndefined(); - - const boundRestart = makeLocalCommandHarness({ - text: "Continue where you left off.", - restartContinuation: true, - outputSchema: { type: "object" }, - mcpSession: "bound", - sideChat: { contextRun: "delivered" }, - }); - yield* boundRestart.start; - expect(boundRestart.startTurn.mock.calls[0]?.[0].restartContinuationOfRunId).toBe( - "stopped-run", - ); + // A typed continuation prompts with its own runId on any credential: a call naming the run it + // continues may be that stopped run's late one. + for (const mcpSession of ["unbound", "bound"] as const) { + const manual = makeLocalCommandHarness({ + text: "", + manualContinuation: true, + outputSchema: { type: "object" }, + mcpSession, + sideChat: { contextRun: "delivered" }, + }); + yield* manual.start; + const manualTurn = manual.startTurn.mock.calls[0]?.[0]; + expect(manualTurn?.resume).toBeUndefined(); + expect(manualTurn?.message.text).toContain("Continue where you left off."); + expect(manualTurn?.message.text).toContain("run-native-account-command"); + expect(manualTurn?.inlineContextLength).toBeUndefined(); + + const restart = makeLocalCommandHarness({ + text: "Continue where you left off.", + restartContinuation: true, + outputSchema: { type: "object" }, + mcpSession, + sideChat: { contextRun: "delivered" }, + }); + yield* restart.start; + expect(restart.startTurn.mock.calls[0]?.[0].restartContinuationOfRunId).toBeUndefined(); + } + }), +); + +effectIt.effect("opens a turn the provider started on the MCP credential it holds", () => + Effect.gen(function* () { + for (const [creationSource, expected] of [ + ["provider", true], + [undefined, undefined], + ] as const) { + const harness = makeLocalCommandHarness({ + text: "Continue", + createdBy: "agent", + ...(creationSource === undefined ? {} : { creationSource }), + sideChat: { contextRun: "delivered" }, + }); + yield* harness.start; + const [opened] = harness.open.mock.calls[0] as unknown as [ + { readonly providerStartedTurn?: boolean }, + ]; + expect(opened.providerStartedTurn).toBe(expected); + } }), ); diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts index 94689fd8e12e3..87e5187955121 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts @@ -1043,6 +1043,9 @@ export const layer: Layer.Layer< attemptId: attempt.id, requireRunScopedMcp: run.outputSchema !== undefined, ...(owedOutputRun === undefined ? {} : { owedOutputRunId: owedOutputRun.id }), + ...(message?.createdBy === "agent" && message.creationSource === "provider" + ? { providerStartedTurn: true } + : {}), ...(existingSessionProjection === undefined ? {} : { resumeFromSession: existingSessionProjection }), @@ -2010,9 +2013,9 @@ export const layer: Layer.Layer< needsOutputRunIdCheck && Option.isSome(mcpSessions) ? yield* mcpSessions.value.read(projection.thread.id) : undefined; - // An unbound MCP credential cannot supply run.id, so a typed continuation must prompt with it. - const needsPromptedOutputRunId = - needsOutputRunIdCheck && mcpSession !== undefined && mcpSession.runId !== run.id; + // A typed continuation must prompt with its own run.id: the agent names it, and a call naming + // the run it continues may be that stopped run's late one. + const needsPromptedOutputRunId = needsOutputRunIdCheck && mcpSession !== undefined; const runningProviderThread: OrchestrationV2ProviderThread = { ...loadedProviderThread, contextUsage: handoffUsage, diff --git a/apps/server/src/orchestration-v2/ThreadManagementService.ts b/apps/server/src/orchestration-v2/ThreadManagementService.ts index e2e7e76a9b811..cfd432d62cd2b 100644 --- a/apps/server/src/orchestration-v2/ThreadManagementService.ts +++ b/apps/server/src/orchestration-v2/ThreadManagementService.ts @@ -1090,23 +1090,10 @@ const make = Effect.gen(function* () { const matchesRun = (candidate: OrchestrationV2Run) => candidate.id === callerRunId && (input.callerAttemptId === undefined || candidate.activeAttemptId === input.callerAttemptId); - // A continuation that resumes natively on a bound credential still has only the earlier - // run's prompt, so the run named in the call may be one the target continues. - const continuesNamedRun = (named: RunId) => { - let current: OrchestrationV2Run | undefined = run; - for (let hops = 0; current !== undefined && hops <= records.runs.length; hops++) { - if (current.id === named) return true; - const continued: RunId | undefined = - current.restartContinuationOfRunId ?? - current.usageLimitContinuationOfRunId ?? - current.manualContinuationOfRunId; - current = records.runs.find((candidate) => candidate.id === continued); - } - return false; - }; // Accept the active run, or the un-stopped completed run whose own owed output is targeted. + // The run named in the call must be that target, even when a bound credential names another. if ( - !continuesNamedRun(requestedRunId) || + requestedRunId !== run.id || (!matchesRun(active) && !(run.id !== active.id && matchesRun(run))) ) { return yield* new ThreadManagementRunOutputRejectedError({ diff --git a/apps/server/src/orchestration-v2/runtimeLayer.test.ts b/apps/server/src/orchestration-v2/runtimeLayer.test.ts index 2169b7b22571a..c13a32ad71b62 100644 --- a/apps/server/src/orchestration-v2/runtimeLayer.test.ts +++ b/apps/server/src/orchestration-v2/runtimeLayer.test.ts @@ -12711,20 +12711,18 @@ it.layer(layerSharedApplicationDataPlaneTest)("run output after a stop", (it) => (run) => run.id === runC.id, )!; assert.deepEqual(afterC.output?.value, { from: "continued" }); - // Resumed natively on its own bound credential, C has only A's prompt and names A. - const resumedNamingSource = yield* submit( - "run-output-resumed-naming-a", - '{"from":"resumed"}', - { - callerRunId: runC.id, - requestedRunId: runA.id, - }, - ); - assert.equal(resumedNamingSource.runId, runC.id); + // A's late call naming A on C's live-updated credential does not overwrite C's result; C is + // prompted with its own runId. + const lateFromAOnC = yield* submit("run-output-late-a-on-c", '{"from":"late-a"}', { + callerRunId: runC.id, + requestedRunId: runA.id, + }).pipe(Effect.flip); + assert.equal(lateFromAOnC._tag, "ThreadManagementRunOutputRejectedError"); + assert.include(lateFromAOnC.message, "no longer active"); assert.deepEqual( (yield* orchestrator.getThreadProjection(threadId)).runs.find((run) => run.id === runC.id) ?.output?.value, - { from: "resumed" }, + { from: "continued" }, ); // A plain turn with no schema preserves the plain-turn guidance even for stale/unbound MCP callers. From 6fc130a24320dfa9bf5539af35625761cd653fc5 Mon Sep 17 00:00:00 2001 From: Victor Vogel Date: Tue, 24 Nov 2026 01:43:20 +0000 Subject: [PATCH 25/34] fix(server): turn start checks a Codex thread's own work under the id its turns use The turn-start check now takes the provider thread as the thread records it. A new Codex thread is loaded as an object with a different id than the one its turns run under, so the check found no work and staged a credential the reload step then had to roll back. --- .../ProviderSessionManager.test.ts | 42 ++++++++++++++++--- .../ProviderSessionManager.ts | 36 +++++++++------- 2 files changed, 58 insertions(+), 20 deletions(-) diff --git a/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts b/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts index 2f295c45b4a78..ebb710a920df3 100644 --- a/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts +++ b/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts @@ -21,6 +21,7 @@ import { ProviderDriverKind, ProviderInstanceId, type ProviderSessionId, + ProviderThreadId, RunAttemptId, RunId, ThreadId, @@ -533,7 +534,9 @@ const makeProviderAdapter = Effect.fnUntraced(function* ( readonly initialProviderItemIdentityVersion?: 2; }) => Effect.Effect; readonly hasPendingBackgroundWork?: Effect.Effect; - readonly hasPendingBackgroundWorkForThread?: Effect.Effect; + readonly hasPendingBackgroundWorkForThread?: ( + providerThread: OrchestrationV2ProviderThread, + ) => Effect.Effect; readonly backgroundTasksEndWithProcess?: boolean; readonly hangSessionScopeClose?: boolean; readonly startTurn?: Effect.Effect< @@ -667,7 +670,7 @@ const makeProviderAdapter = Effect.fnUntraced(function* ( ...(options.hasPendingBackgroundWorkForThread === undefined ? {} : { - hasPendingBackgroundWorkForThread: () => options.hasPendingBackgroundWorkForThread!, + hasPendingBackgroundWorkForThread: options.hasPendingBackgroundWorkForThread, }), ensureThread: () => unimplemented("ensureThread unused in test"), resumeThread: (threadInput) => @@ -740,7 +743,9 @@ function layerTest(input: { readonly paused: Deferred.Deferred; }; readonly hasPendingBackgroundWork?: Effect.Effect; - readonly hasPendingBackgroundWorkForThread?: Effect.Effect; + readonly hasPendingBackgroundWorkForThread?: ( + providerThread: OrchestrationV2ProviderThread, + ) => Effect.Effect; readonly backgroundTasksEndWithProcess?: boolean; readonly hangSessionScopeClose?: boolean; readonly startTurn?: Effect.Effect< @@ -4038,6 +4043,19 @@ it.effect.each([ threadId, providerSessionId, } = yield* setupSession("bg-no-unload"); + const providerThreadRecorded = ( + recordedThreadId: ThreadId, + recorded: OrchestrationV2ProviderThread, + ) => + idAllocator.allocate.event({ threadId: recordedThreadId }).pipe( + Effect.map((id) => ({ + id, + type: "provider-thread.updated" as const, + threadId: recordedThreadId, + occurredAt: now, + payload: recorded, + })), + ); const run1 = RunId.make("run-bg-1"); const run2 = RunId.make("run-bg-2"); const attempt1 = RunAttemptId.make("attempt-bg-1"); @@ -4061,6 +4079,7 @@ it.effect.each([ providerThreadId: providerThread.id, now, }), + yield* providerThreadRecorded(threadId, providerThread), ], }); const runtime = yield* openFor(manager, providerSessionId, threadId, { @@ -4088,12 +4107,19 @@ it.effect.each([ now, }); yield* eventSink.write({ - events: [yield* makeThreadCreatedEvent({ idAllocator, threadId: nextThreadId, now })], + events: [ + yield* makeThreadCreatedEvent({ idAllocator, threadId: nextThreadId, now }), + yield* providerThreadRecorded(nextThreadId, nextProviderThread), + ], }); yield* openFor(manager, providerSessionId, nextThreadId); const loadedConfig = yield* mcpSessions.read(nextThreadId); const loadedToken = rawBearer(loadedConfig); - yield* resume(nextThreadId, nextProviderThread); + // Loaded as an object whose id is not the recorded one, as a new Codex thread is. + yield* resume(nextThreadId, { + ...nextProviderThread, + id: ProviderThreadId.make(`loaded-as:${name}`), + }); return { threadId: nextThreadId, providerThread: nextProviderThread, @@ -4343,7 +4369,11 @@ it.effect.each([ idleTimeoutMs: 1_000, unloads, hasPendingBackgroundWork: Ref.get(sessionBackgroundWorkProbe).pipe(Effect.flatten), - hasPendingBackgroundWorkForThread: Ref.get(pendingBackgroundWork), + // The adapter tracks a thread's work under the id its turns started with. + hasPendingBackgroundWorkForThread: (probed) => + probed.id.startsWith("loaded-as:") + ? Effect.succeed(false) + : Ref.get(pendingBackgroundWork), beforeUnload: Ref.get(failUnload).pipe( Effect.flatMap((fail) => (fail ? Effect.die("unload failed") : Effect.void)), ), diff --git a/apps/server/src/orchestration-v2/ProviderSessionManager.ts b/apps/server/src/orchestration-v2/ProviderSessionManager.ts index 5c95384f9366e..9dd4738a76919 100644 --- a/apps/server/src/orchestration-v2/ProviderSessionManager.ts +++ b/apps/server/src/orchestration-v2/ProviderSessionManager.ts @@ -342,7 +342,6 @@ interface LiveSessionEntry { ThreadId, { readonly providerThread: string; - readonly thread: OrchestrationV2ProviderThread; readonly credential: McpProviderSession.McpProviderSessionConfig; } >; @@ -2084,7 +2083,7 @@ export const layerWithOptions = ( const markProviderThreadLoaded = (input: { readonly providerSessionId: ProviderSessionId; readonly threadId: ThreadId; - readonly providerThread: OrchestrationV2ProviderThread; + readonly providerThread: Parameters[0]; readonly providerThreadKey: string; readonly linkedEnvironments: boolean | null | undefined; readonly mcpCredential?: McpProviderSession.McpProviderSessionConfig | undefined; @@ -2102,7 +2101,6 @@ export const layerWithOptions = ( ? entry.loadedMcpCredentialByThread : new Map(entry.loadedMcpCredentialByThread).set(input.threadId, { providerThread: providerThreadRuntimeKey(input.providerThread), - thread: input.providerThread, credential: input.mcpCredential, }); const linkedEnvironmentsByThread = new Map(entry.linkedEnvironmentsByThread); @@ -2356,24 +2354,34 @@ export const layerWithOptions = ( if (yield* retainCurrentMcpCredential(current, { unbindRun: false })) return; continue; } - // A turn that cannot take a new credential now (the provider already started it, no way to - // deliver one, or a reload that would end background work) keeps it unbound; the agent - // then names its run in the call. - // A shared session reloads only this thread, so only this thread's own work blocks it. - const loadedThread = (yield* Ref.get(sessions)) + const loadedKey = (yield* Ref.get(sessions)) .get(sessionKey(input.providerSessionId)) - ?.loadedMcpCredentialByThread.get(input.threadId)?.thread; + ?.loadedMcpCredentialByThread.get(input.threadId)?.providerThread; + const probeThread = input.runtime.hasPendingBackgroundWorkForThread; + // A shared session reloads only this thread, so only this thread's own work blocks it. + // The probe takes the thread as recorded: the adapter tracks its turns under that id. const pendingWork = input.runtime.providerSession.capabilities.sessions .supportsMultipleProviderThreadsPerSession && input.runtime.unloadThread !== undefined - ? loadedThread === undefined || - input.runtime.hasPendingBackgroundWorkForThread === undefined + ? loadedKey === undefined || probeThread === undefined ? Effect.succeed(false) - : input.runtime.hasPendingBackgroundWorkForThread(loadedThread, { - includeSubagents: true, - }) + : projectionStore.getThreadRecords(input.threadId, ["providerThreads"]).pipe( + Effect.flatMap(({ providerThreads }) => { + const loaded = providerThreads.find( + (candidate) => providerThreadRuntimeKey(candidate) === loadedKey, + ); + return loaded === undefined + ? Effect.succeed(false) + : probeThread(loaded, { includeSubagents: true }); + }), + // Like a failed probe, a failed read keeps the thread's credential. + Effect.orElseSucceed(() => true), + ) : (input.runtime.hasPendingBackgroundWork ?? Effect.succeed(false)); + // A turn that cannot take a new credential now (the provider already started it, no way to + // deliver one, or a reload that would end background work) keeps it unbound; the agent + // then names its run in the call. const cannotRotate = input.providerStartedTurn === true || input.runtime.mcpCredentialRotation === "none" || From 395f8ee1281071c2ca282af1eeacc6c212baa275 Mon Sep 17 00:00:00 2001 From: Victor Vogel Date: Tue, 24 Nov 2026 02:04:16 +0000 Subject: [PATCH 26/34] fix(server): a typed resume on a provider without native resume is prompted instead of refused A typed manual resume is now always prompted with its output note, so it no longer needs native resume and starts on providers that lack it. --- .../ProviderTurnStartService.test.ts | 15 ++++++++++ .../ProviderTurnStartService.ts | 28 ++++++++++--------- 2 files changed, 30 insertions(+), 13 deletions(-) diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts index 0e83963b67890..a02983e6ad914 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts @@ -2490,6 +2490,21 @@ effectIt.effect("refuses unsupported resume instead of manufacturing a user prom }), ]), ); + + // A typed resume is prompted with its own output note, which needs no native resume. + const typed = makeLocalCommandHarness({ + text: "", + manualContinuation: true, + nativeResumeUnsupported: true, + outputSchema: { type: "object" }, + mcpSession: "bound", + sideChat: { contextRun: "delivered" }, + }); + yield* typed.start; + const typedTurn = typed.startTurn.mock.calls[0]?.[0]; + expect(typedTurn?.resume).toBeUndefined(); + expect(typedTurn?.message.text).toContain("run-native-account-command"); + expect(typed.settledRuns).not.toContain("failed"); }), ); diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts index 87e5187955121..2bd40fb5cab7a 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts @@ -1988,12 +1988,25 @@ export const layer: Layer.Layer< sideChatHandoff !== undefined || restartNote !== "" || noteContinuation; - // Pending context turns the resume into a prompted turn, which needs no native resume. + const needsOutputRunIdCheck = + outputNote !== "" && + ((manualResume && unsentResumeMessage === undefined) || + (run.restartContinuationOfRunId !== undefined && !noteContinuation)); + const mcpSession = + needsOutputRunIdCheck && Option.isSome(mcpSessions) + ? yield* mcpSessions.value.read(projection.thread.id) + : undefined; + // A typed continuation must prompt with its own run.id: the agent names it, and a call naming + // the run it continues may be that stopped run's late one. + const needsPromptedOutputRunId = needsOutputRunIdCheck && mcpSession !== undefined; + // Pending context or an output note turns the resume into a prompted turn, which needs no + // native resume. if ( manualResume && unsentResumeMessage === undefined && session.resumeTurn === undefined && - !carriesPendingContext + !carriesPendingContext && + !needsPromptedOutputRunId ) { yield* settleStartFailure({ signal: "resume-unsupported", @@ -2005,17 +2018,6 @@ export const layer: Layer.Layer< }); return; } - const needsOutputRunIdCheck = - outputNote !== "" && - ((manualResume && unsentResumeMessage === undefined) || - (run.restartContinuationOfRunId !== undefined && !noteContinuation)); - const mcpSession = - needsOutputRunIdCheck && Option.isSome(mcpSessions) - ? yield* mcpSessions.value.read(projection.thread.id) - : undefined; - // A typed continuation must prompt with its own run.id: the agent names it, and a call naming - // the run it continues may be that stopped run's late one. - const needsPromptedOutputRunId = needsOutputRunIdCheck && mcpSession !== undefined; const runningProviderThread: OrchestrationV2ProviderThread = { ...loadedProviderThread, contextUsage: handoffUsage, From e49dd6dcf021725d26a7f403ff3f0568b80c83ef Mon Sep 17 00:00:00 2001 From: Victor Vogel Date: Tue, 24 Nov 2026 06:09:29 +0000 Subject: [PATCH 27/34] fix(server): MCP credential refreshes show their startup step --- .../Adapters/ClaudeAdapterV2.test.ts | 12 +++++ .../Adapters/ClaudeAdapterV2.ts | 5 +- packages/provider-acp/src/server/adapter.ts | 2 +- .../provider-muse/src/server/adapter.test.ts | 50 +++++++++++++++---- packages/provider-muse/src/server/adapter.ts | 2 +- 5 files changed, 57 insertions(+), 14 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts index c7dc7852ca7a2..46bce28944fa3 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts @@ -26433,7 +26433,19 @@ describe("ClaudeAdapterV2 background wake turns", () => { return; } + const eventsBeforeRotation = harness.events.length; yield* harness.runtime.startTurn(yield* turnInput(2, "Second turn.")); + // The awaited in-place MCP update is a startup step, cleared whether it succeeds or not. + assert.deepEqual( + harness.events + .slice(eventsBeforeRotation) + .flatMap((event) => + event.type === "provider_session.updated" + ? [event.providerSession.startupPhase ?? null] + : [], + ), + ["mcp", null], + ); if (mode === "fallback-replace") { assert.equal(harness.processQueues.length, 2); yield* Queue.offer( diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts index 7e698886fb156..9e334871cbe2f 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts @@ -13548,7 +13548,10 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( candidate.query.setMcpServers === undefined ) return; - yield* candidate.query.setMcpServers(mcpOverrides.mcpServers); + yield* reportStartupPhase("mcp").pipe( + Effect.andThen(candidate.query.setMcpServers(mcpOverrides.mcpServers)), + Effect.ensuring(Effect.suspend(() => reportStartupPhase(undefined))), + ); candidate.mcpAuthorization = mcpSession?.authorizationHeader; if (candidate.queryPolicyKeyWithoutMcpAuth === getQueryPolicyKeyWithoutMcpAuth()) { candidate.queryPolicyKey = queryPolicyKey; diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts index ab80dfca2efc9..3727474074a4a 100644 --- a/packages/provider-acp/src/server/adapter.ts +++ b/packages/provider-acp/src/server/adapter.ts @@ -8279,7 +8279,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( yield* Ref.set(loadingSessionId, sessionId); const agent = installedAgentCapabilities(); const activated = yield* Effect.gen(function* () { - if (!canLoadOrResume()) { + if (agent?.loadSession !== true && agent?.sessionCapabilities?.resume == null) { return yield* new ProviderAdapter.ProviderAdapterProtocolError({ driver, detail: `ACP driver cannot load or resume session ${sessionId}`, diff --git a/packages/provider-muse/src/server/adapter.test.ts b/packages/provider-muse/src/server/adapter.test.ts index 476ccf616ceb3..a37c4536585db 100644 --- a/packages/provider-muse/src/server/adapter.test.ts +++ b/packages/provider-muse/src/server/adapter.test.ts @@ -272,6 +272,19 @@ const makeHarness = Effect.fnUntraced(function* ( return { adapter, runtime, providerThread, takeEvent, allEvents, policy, eventsEnded }; }); +const setMcp = (ordinal: number) => + Effect.flatMap(McpProviderSessions.McpProviderSessions, (mcpSessions) => + mcpSessions.set({ + environmentId: EnvironmentId.make("test-environment"), + threadId: THREAD_ID, + providerSessionId: `test-session-${ordinal}`, + providerInstanceId: INSTANCE_ID, + endpoint: "http://127.0.0.1:43210/mcp", + authorizationHeader: `Bearer muse-run-${ordinal}-token`, + browserToolsAvailable: false, + }), + ); + const preallocatedProviderThread = Effect.fnUntraced(function* () { const now = yield* DateTime.now; return { @@ -427,17 +440,6 @@ describe("MuseAdapterV2", () => { it.effect("re-resumes with rotated MCP credentials on the next turn", () => Effect.gen(function* () { - const mcpSessions = yield* McpProviderSessions.McpProviderSessions; - const setMcp = (ordinal: number) => - mcpSessions.set({ - environmentId: EnvironmentId.make("test-environment"), - threadId: THREAD_ID, - providerSessionId: `test-session-${ordinal}`, - providerInstanceId: INSTANCE_ID, - endpoint: "http://127.0.0.1:43210/mcp", - authorizationHeader: `Bearer muse-run-${ordinal}-token`, - browserToolsAvailable: false, - }); yield* setMcp(1); const fake = yield* makeFakeMuse(); fake.host.initializeResult.grantedCapabilities.push("sessionMcp"); @@ -468,6 +470,32 @@ describe("MuseAdapterV2", () => { }).pipe(Effect.scoped, Effect.provide(testLayer)), ); + it.effect( + "reports the resume phase when a rotated credential re-resumes without a native id", + () => + Effect.gen(function* () { + yield* setMcp(1); + const fake = yield* makeFakeMuse(); + fake.host.initializeResult.grantedCapabilities.push("sessionMcp"); + const harness = yield* makeHarness(fake, INSTANCE_ID); + yield* fake.takeCall("session/start"); + + yield* setMcp(2); + yield* harness.runtime.ensureThread({ + threadId: THREAD_ID, + modelSelection: modelSelection(), + runtimePolicy, + }); + yield* fake.takeCall("session/resume"); + yield* harness.takeEvent( + "provider_session.updated", + (event) => event.providerSession.startupPhase === "resume", + ); + const cleared = yield* harness.takeEvent("provider_session.updated"); + assert.isUndefined(cleared.providerSession.startupPhase); + }).pipe(Effect.scoped, Effect.provide(testLayer)), + ); + it.effect("selects the runtime mode's permission profile on native start and resume", () => Effect.gen(function* () { for (const [runtimeMode, profile, approvalMode] of [ diff --git a/packages/provider-muse/src/server/adapter.ts b/packages/provider-muse/src/server/adapter.ts index b4ad8c935f8e7..c58c764ce59c4 100644 --- a/packages/provider-muse/src/server/adapter.ts +++ b/packages/provider-muse/src/server/adapter.ts @@ -1978,7 +1978,7 @@ export const makeMuseAdapterV2 = Effect.fn("makeMuseAdapterV2")(function* ( : undefined; const startModel = yield* resolveModel(args.modelSelection); const permissionProfile = musePermissionProfile(args.runtimePolicy.runtimeMode); - if (requestedId) yield* reportStartupPhase("resume"); + if (resumeExistingId) yield* reportStartupPhase("resume"); const result = yield* request( resumeExistingId ? "session/resume" : "session/start", resumeExistingId From dc7860435896bb56f37fbe96c8693c4d753786e5 Mon Sep 17 00:00:00 2001 From: Victor Vogel Date: Tue, 24 Nov 2026 23:27:07 +0000 Subject: [PATCH 28/34] refactor(server): drop the separate owed-run turn option and skip owed-run reads that cannot matter --- .../src/orchestration-v2/Orchestrator.ts | 17 ++- .../ProviderSessionManager.test.ts | 7 +- .../ProviderSessionManager.ts | 138 ++++++++---------- .../ProviderTurnStartService.ts | 7 +- .../ThreadManagementService.ts | 14 +- 5 files changed, 84 insertions(+), 99 deletions(-) diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index e5a28ef86622f..b5f4491997c15 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -12534,12 +12534,14 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio }); // The service picks the active run, but the run can end before this command is its turn. A // turn that completed without its result still owes it, and a later turn may give it. - const owed = yield* resolveOwedOutputRun(projection.runs, () => - projectionStore.getThreadRecords(command.threadId, ["runs", "turnItems"], { - turnItemTypes: ["user_message"], - }), - ).pipe(mapDispatchError(command)); - const owes = owed?.id === run.id; + const owes = + run.status === "completed" && + run.output === undefined && + (yield* resolveOwedOutputRun(projection.runs, () => + projectionStore.getThreadRecords(command.threadId, ["runs", "turnItems"], { + turnItemTypes: ["user_message"], + }), + ).pipe(mapDispatchError(command)))?.id === run.id; if (!isActiveRun(run) && !owes) { return yield* rejectOutput( "inactive", @@ -12556,8 +12558,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio active = candidate; } } - const matchesRun = (candidate: OrchestrationV2Run | undefined) => - candidate !== undefined && + const matchesRun = (candidate: OrchestrationV2Run) => (command.callerRunId === undefined || candidate.id === command.callerRunId) && (command.callerAttemptId === undefined || candidate.activeAttemptId === command.callerAttemptId); diff --git a/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts b/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts index ebb710a920df3..92f45992df724 100644 --- a/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts +++ b/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts @@ -3651,7 +3651,6 @@ it.effect.each([ readonly runId?: RunId; readonly attemptId?: RunAttemptId; readonly requireRunScopedMcp?: boolean; - readonly owedOutputRunId?: RunId; readonly providerStartedTurn?: boolean; }, ) => @@ -3738,8 +3737,7 @@ it.effect.each([ yield* openFor(manager, providerSessionId, threadId, { runId: wakeRun, attemptId: RunAttemptId.make("attempt-live-wake"), - requireRunScopedMcp: false, - owedOutputRunId: run1, + requireRunScopedMcp: true, }); const wakeToken = rawBearer(yield* mcpSessions.read(threadId)); assert.notEqual(wakeToken, token1); @@ -3751,8 +3749,7 @@ it.effect.each([ yield* openFor(manager, providerSessionId, threadId, { runId: RunId.make("run-live-provider-wake"), attemptId: RunAttemptId.make("attempt-live-provider-wake"), - requireRunScopedMcp: false, - owedOutputRunId: run1, + requireRunScopedMcp: true, providerStartedTurn: true, }); assert.equal(rawBearer(yield* mcpSessions.read(threadId)), wakeToken); diff --git a/apps/server/src/orchestration-v2/ProviderSessionManager.ts b/apps/server/src/orchestration-v2/ProviderSessionManager.ts index 9dd4738a76919..758e3e95d18fa 100644 --- a/apps/server/src/orchestration-v2/ProviderSessionManager.ts +++ b/apps/server/src/orchestration-v2/ProviderSessionManager.ts @@ -256,7 +256,6 @@ export interface ProviderSessionManagerV2Shape { readonly runId?: RunId; readonly attemptId?: RunAttemptId; readonly requireRunScopedMcp?: boolean; - readonly owedOutputRunId?: RunId; /** The provider already started this turn natively, on the credential it holds. */ readonly providerStartedTurn?: boolean; readonly resumeFromSession?: OrchestrationV2ProviderSession; @@ -1781,42 +1780,29 @@ export const layerWithOptions = ( ([entry]) => Option.match(entry, { onNone: () => Effect.void, - onSome: (entry) => - // Revoke recorded credentials after process death, except those held by live replacements. - Ref.get(sessions).pipe( - Effect.flatMap((current) => - Effect.forEach( - entry.mcpCredentialIdsByThread, - ([threadId, mcpCredentialIds]) => - Effect.forEach( - mcpCredentialIds, - (mcpCredentialId) => - Effect.gen(function* () { - // Only holders of this credential may prevent its revocation; stale credentials must not leak it. - // An attached replacement holds only the thread's current one, which it may not have recorded yet. - const threadCurrent = yield* mcpSessions.read(threadId); - const isThreadCurrent = - threadCurrent !== undefined && - McpProviderSession.mcpCredentialIdOf(threadCurrent) === - mcpCredentialId; - const heldElsewhere = - isMcpCredentialReserved(threadId, mcpCredentialId) || - Array.from(current.values()).some( - (other) => - other !== entry && - ((isThreadCurrent && other.attachedThreadIds.has(threadId)) || - other.mcpCredentialIdsByThread - .get(threadId) - ?.has(mcpCredentialId) === true), - ); - if (!heldElsewhere) yield* clearMcpSession(threadId, mcpCredentialId); - }), - { discard: true }, - ), - { discard: true }, - ), - ), - ), + // Revoke recorded credentials after process death, except those held by live replacements. + onSome: Effect.fnUntraced(function* (entry) { + const others = [...(yield* Ref.get(sessions)).values()].filter( + (other) => other !== entry, + ); + for (const [threadId, mcpCredentialIds] of entry.mcpCredentialIdsByThread) { + const current = others.some((other) => other.attachedThreadIds.has(threadId)) + ? yield* mcpSessions.read(threadId) + : undefined; + const currentId = current && McpProviderSession.mcpCredentialIdOf(current); + for (const id of mcpCredentialIds) { + // Only holders of this credential may prevent its revocation; stale credentials must not leak it. + // An attached replacement holds only the thread's current one, which it may not have recorded yet. + if ( + id !== currentId && + !isMcpCredentialReserved(threadId, id) && + !others.some((other) => other.mcpCredentialIdsByThread.get(threadId)?.has(id)) + ) { + yield* clearMcpSession(threadId, id); + } + } + } + }), }), ).pipe( Effect.catchCause((cause) => @@ -2228,7 +2214,6 @@ export const layerWithOptions = ( readonly runId: RunId; readonly attemptId?: RunAttemptId | undefined; readonly requireRunScopedMcp?: boolean | undefined; - readonly owedOutputRunId?: RunId | undefined; readonly providerStartedTurn?: boolean | undefined; }) { if (options.configureMcp === false) return; @@ -2339,7 +2324,7 @@ export const layerWithOptions = ( // once it ends, while the owed run stays the target. const rotateOnRunChange = input.requireRunScopedMcp !== undefined - ? input.requireRunScopedMcp || input.owedOutputRunId !== undefined + ? input.requireRunScopedMcp : yield* threadRequiresRunScopedMcp(input.threadId, input.runId).pipe( Effect.mapError( (cause) => @@ -2354,45 +2339,48 @@ export const layerWithOptions = ( if (yield* retainCurrentMcpCredential(current, { unbindRun: false })) return; continue; } - const loadedKey = (yield* Ref.get(sessions)) - .get(sessionKey(input.providerSessionId)) - ?.loadedMcpCredentialByThread.get(input.threadId)?.providerThread; - const probeThread = input.runtime.hasPendingBackgroundWorkForThread; // A shared session reloads only this thread, so only this thread's own work blocks it. // The probe takes the thread as recorded: the adapter tracks its turns under that id. - const pendingWork = - input.runtime.providerSession.capabilities.sessions - .supportsMultipleProviderThreadsPerSession && - input.runtime.unloadThread !== undefined - ? loadedKey === undefined || probeThread === undefined - ? Effect.succeed(false) - : projectionStore.getThreadRecords(input.threadId, ["providerThreads"]).pipe( - Effect.flatMap(({ providerThreads }) => { - const loaded = providerThreads.find( - (candidate) => providerThreadRuntimeKey(candidate) === loadedKey, - ); - return loaded === undefined - ? Effect.succeed(false) - : probeThread(loaded, { includeSubagents: true }); - }), - // Like a failed probe, a failed read keeps the thread's credential. - Effect.orElseSucceed(() => true), - ) - : (input.runtime.hasPendingBackgroundWork ?? Effect.succeed(false)); + const reloadBlocked = Effect.gen(function* () { + if ( + !input.runtime.providerSession.capabilities.sessions + .supportsMultipleProviderThreadsPerSession || + input.runtime.unloadThread === undefined + ) { + return yield* input.runtime.hasPendingBackgroundWork ?? Effect.succeed(false); + } + const probeThread = input.runtime.hasPendingBackgroundWorkForThread; + const loadedKey = (yield* Ref.get(sessions)) + .get(sessionKey(input.providerSessionId)) + ?.loadedMcpCredentialByThread.get(input.threadId)?.providerThread; + if (loadedKey === undefined || probeThread === undefined) return false; + const { providerThreads } = yield* projectionStore.getThreadRecords( + input.threadId, + ["providerThreads"], + ); + const loaded = providerThreads.find( + (candidate) => providerThreadRuntimeKey(candidate) === loadedKey, + ); + return loaded === undefined + ? false + : yield* probeThread(loaded, { includeSubagents: true }); + }).pipe( + // Like a failed probe, a failed read keeps the thread's credential. + Effect.orElseSucceed(() => true), + Effect.catchCauseIf( + (cause) => !Cause.hasInterruptsOnly(cause), + () => Effect.succeed(true), + ), + ); // A turn that cannot take a new credential now (the provider already started it, no way to // deliver one, or a reload that would end background work) keeps it unbound; the agent // then names its run in the call. - const cannotRotate = - input.providerStartedTurn === true || - input.runtime.mcpCredentialRotation === "none" || - (input.runtime.mcpCredentialRotation !== "live" && - (yield* pendingWork.pipe( - Effect.catchCauseIf( - (cause) => !Cause.hasInterruptsOnly(cause), - () => Effect.succeed(true), - ), - ))); - if (cannotRotate && current !== undefined) { + if ( + current !== undefined && + (input.providerStartedTurn === true || + input.runtime.mcpCredentialRotation === "none" || + (input.runtime.mcpCredentialRotation !== "live" && (yield* reloadBlocked))) + ) { if (yield* retainCurrentMcpCredential(current, { unbindRun: true })) return; continue; } @@ -4040,7 +4028,6 @@ export const layerWithOptions = ( runId: input.runId, attemptId: input.attemptId, requireRunScopedMcp: input.requireRunScopedMcp, - owedOutputRunId: input.owedOutputRunId, providerStartedTurn: input.providerStartedTurn, }); } else if ( @@ -4095,8 +4082,7 @@ export const layerWithOptions = ( ? { runId: input.runId, attemptId: input.attemptId, - rotateOnRunChange: - input.requireRunScopedMcp === true || input.owedOutputRunId !== undefined, + rotateOnRunChange: input.requireRunScopedMcp === true, } : undefined, ); diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts index 5f8c79e5bacb6..b24e8a5bbb2c3 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts @@ -70,7 +70,7 @@ import { isSlashCommandMessage, withInlineContext, } from "./ContextHandoffDelivery.ts"; -import { isProviderCommand, outputInstructions, resolveOwedOutputRun } from "./runOutput.ts"; +import { isProviderCommand, outputInstructions, runRequiresRunScopedMcp } from "./runOutput.ts"; import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter"; import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions"; import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator"; @@ -1030,7 +1030,7 @@ export const layer: Layer.Layer< brokenNativeThread && providerThread.nativeThreadRef !== null && !(yield* providerSessions.isLive(providerSessionId)); - const owedOutputRun = yield* resolveOwedOutputRun(projection.runs, () => + const requireRunScopedMcp = yield* runRequiresRunScopedMcp(projection.runs, run.id, () => projectionStore.getThreadRecords(input.threadId, ["runs", "turnItems"], { turnItemTypes: ["user_message"], }), @@ -1043,8 +1043,7 @@ export const layer: Layer.Layer< runtimePolicy: resolvedRuntimePolicy, runId: run.id, attemptId: attempt.id, - requireRunScopedMcp: run.outputSchema !== undefined, - ...(owedOutputRun === undefined ? {} : { owedOutputRunId: owedOutputRun.id }), + requireRunScopedMcp, ...(message?.createdBy === "agent" && message.creationSource === "provider" ? { providerStartedTurn: true } : {}), diff --git a/apps/server/src/orchestration-v2/ThreadManagementService.ts b/apps/server/src/orchestration-v2/ThreadManagementService.ts index 90c2de5282e2a..33221b5c6e708 100644 --- a/apps/server/src/orchestration-v2/ThreadManagementService.ts +++ b/apps/server/src/orchestration-v2/ThreadManagementService.ts @@ -1066,12 +1066,14 @@ const make = Effect.gen(function* () { // A turn that ended without its result still owes it: the agent may have ended it to wait // for something, and answer from the turn that woke it. Only the newest started run asked for // one can owe it, and only while the agent's conversation still reaches it. - const owed = yield* resolveOwedOutputRun(records.runs, () => - orchestrator.getThreadRecords(input.threadId, ["runs", "turnItems"], { - turnItemTypes: ["user_message"], - }), - ); - const run = active?.outputSchema !== undefined ? active : owed; + const run = + active === undefined || active.outputSchema !== undefined + ? active + : yield* resolveOwedOutputRun(records.runs, () => + orchestrator.getThreadRecords(input.threadId, ["runs", "turnItems"], { + turnItemTypes: ["user_message"], + }), + ); // Check whether a result is expected before caller identity so plain turns keep their message. if (active === undefined || run?.outputSchema === undefined) { return yield* new ThreadManagementRunOutputRejectedError({ From b29dfc37c38220c99bc6a1247d58ce736f2562dd Mon Sep 17 00:00:00 2001 From: Victor Vogel Date: Wed, 25 Nov 2026 01:43:22 +0000 Subject: [PATCH 29/34] refactor(provider-acp): drop the unread initialize-result store on session setup --- packages/provider-acp/src/server/adapter.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts index bc456be970fd7..b5d95188bd479 100644 --- a/packages/provider-acp/src/server/adapter.ts +++ b/packages/provider-acp/src/server/adapter.ts @@ -2415,7 +2415,6 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( agentRequests.clear(); nativeChildren.clear(); yield* Ref.set(activeSessionSetup, setup); - yield* Ref.set(installedInitializeResult, setup.initializeResult); yield* resetPublishedCatalogKey; }); const activeSelection = yield* Ref.make(null); From b8605e069966c80d0c5bd629048daaf71cc2a076 Mon Sep 17 00:00:00 2001 From: Victor Vogel Date: Wed, 25 Nov 2026 02:03:20 +0000 Subject: [PATCH 30/34] fix(provider-acp): a credential-only session reload no longer re-advertises an unchanged model catalog --- .../Adapters/AcpAdapterV2.test.ts | 100 ++++++++++++++++++ packages/provider-acp/src/server/adapter.ts | 6 +- 2 files changed, 104 insertions(+), 2 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts index 082d97c0a1dec..abda00b84d80a 100644 --- a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts @@ -7192,6 +7192,106 @@ describe("AcpAdapterV2", () => { }).pipe(Effect.provide(layerTest)), ); + it.live( + "preserves lastCatalogKey across a same-session MCP credential reload with an unchanged catalog", + () => + Effect.gen(function* () { + const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const selfInvocation = yield* resolveSelfInvocation(); + const mockAgentPath = yield* bundledMockAgentPath; + const protocolEvents = yield* Queue.bounded(256); + const instanceId = ProviderInstanceId.make("acp-test-mcp-rotate-catalog-key"); + const threadId = ThreadId.make("thread-acp-mcp-rotate-catalog-key"); + const mcpSessions = yield* McpProviderSessions.McpProviderSessions; + const setMcp = (ordinal: number) => + mcpSessions.set({ + environmentId: EnvironmentId.make("environment-acp-mcp-rotate-catalog-key"), + threadId, + providerSessionId: `mcp-session-acp-rotate-catalog-key-${ordinal}`, + providerInstanceId: instanceId, + endpoint: "http://127.0.0.1:43123/mcp", + authorizationHeader: `Bearer acp-catalog-run-${ordinal}-token`, + browserToolsAvailable: false, + }); + yield* setMcp(1); + const publications: Array<{ + readonly catalogKey: string; + readonly lastCatalogKey: string | null | undefined; + }> = []; + const adapter = yield* makeAcpAdapterV2({ + instanceId, + flavor: { + driver: ACP_TEST_DRIVER, + capabilities: AcpProviderCapabilitiesV2, + onSessionConfigurationUpdate: (configOptions, modeState, modelState, updateOptions) => + Effect.sync(() => { + const catalogKey = JSON.stringify({ configOptions, modeState, modelState }); + publications.push({ + catalogKey, + lastCatalogKey: updateOptions?.lastCatalogKey, + }); + return catalogKey; + }), + makeRuntime: makeMockRuntime({ + childProcessSpawner, + mockAgentPath, + protocolEvents, + }), + }, + selfInvocation, + clientTerminals: {}, + }); + const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ + runtimeMode: "full-access", + interactionMode: "default", + cwd: process.cwd(), + }); + const modelSelection = { instanceId, model: "default" } as const; + const runtime = yield* adapter.openSession({ + threadId, + providerSessionId: ProviderSessionId.make("provider-session-acp-mcp-rotate-catalog-key"), + modelSelection, + runtimePolicy, + }); + const providerThread = yield* runtime.ensureThread({ + threadId, + modelSelection, + runtimePolicy, + }); + + assert.isAbove(publications.length, 0); + const preReloadCount = publications.length; + const preReloadKey = publications.at(-1)!.catalogKey; + assert.isNull(publications[0]!.lastCatalogKey); + + yield* pollProtocolMethods(protocolEvents); + yield* setMcp(2); + yield* runtime.startTurn( + makeTurnInput({ + threadId, + providerThread, + instanceId, + runtimePolicy, + now: yield* DateTime.now, + }), + ); + + const methodsAfterRotate = yield* pollProtocolMethods(protocolEvents); + assert.isTrue( + methodsAfterRotate.includes("session/load") || + methodsAfterRotate.includes("session/resume"), + `expected session/load or session/resume after token rotation, got ${JSON.stringify(methodsAfterRotate)}`, + ); + + const postReloadPublications = publications.slice(preReloadCount); + assert.isAbove(postReloadPublications.length, 0); + for (const publication of postReloadPublications) { + assert.equal(publication.catalogKey, preReloadKey); + assert.equal(publication.lastCatalogKey, preReloadKey); + } + }).pipe(Effect.provide(layerTest)), + ); + it.live("a snapshot load records its MCP credential, so the next turn does not reload", () => Effect.gen(function* () { const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts index b5d95188bd479..a8e6269bd8a77 100644 --- a/packages/provider-acp/src/server/adapter.ts +++ b/packages/provider-acp/src/server/adapter.ts @@ -2414,8 +2414,10 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( rootForegroundWork = undefined; agentRequests.clear(); nativeChildren.clear(); - yield* Ref.set(activeSessionSetup, setup); - yield* resetPublishedCatalogKey; + const previousSetup = yield* Ref.getAndSet(activeSessionSetup, setup); + if (previousSetup === null || previousSetup.sessionId !== setup.sessionId) { + yield* resetPublishedCatalogKey; + } }); const activeSelection = yield* Ref.make(null); const activeInteractionMode = yield* Ref.make(null); From d7ccb32d898a3be15bb0d46cf137df64eb7204eb Mon Sep 17 00:00:00 2001 From: Victor Vogel Date: Wed, 25 Nov 2026 02:16:44 +0000 Subject: [PATCH 31/34] fix(provider-acp): only a credential-only reload keeps the published catalog key --- .../Adapters/AcpAdapterV2.test.ts | 97 +++++++++++++++++++ packages/provider-acp/src/server/adapter.ts | 13 ++- 2 files changed, 106 insertions(+), 4 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts index abda00b84d80a..15b181bb4ad62 100644 --- a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts @@ -7292,6 +7292,103 @@ describe("AcpAdapterV2", () => { }).pipe(Effect.provide(layerTest)), ); + it.live( + "resets lastCatalogKey across a replacement runtime that reuses the same session id", + () => + Effect.gen(function* () { + const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const selfInvocation = yield* resolveSelfInvocation(); + const mockAgentPath = yield* bundledMockAgentPath; + const protocolEvents = yield* Queue.bounded(256); + const instanceId = ProviderInstanceId.make("acp-test-replace-same-id-catalog-key"); + const threadId = ThreadId.make("thread-acp-replace-same-id-catalog-key"); + const publications: Array<{ + readonly catalogKey: string; + readonly lastCatalogKey: string | null | undefined; + }> = []; + const adapter = yield* makeAcpAdapterV2({ + instanceId, + flavor: { + driver: ACP_TEST_DRIVER, + capabilities: AcpProviderCapabilitiesV2, + onSessionConfigurationUpdate: (configOptions, modeState, modelState, updateOptions) => + Effect.sync(() => { + const catalogKey = JSON.stringify({ configOptions, modeState, modelState }); + publications.push({ + catalogKey, + lastCatalogKey: updateOptions?.lastCatalogKey, + }); + return catalogKey; + }), + makeRuntime: makeMockRuntime({ + childProcessSpawner, + mockAgentPath, + protocolEvents, + }), + }, + selfInvocation, + clientTerminals: {}, + }); + const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ + runtimeMode: "full-access", + interactionMode: "default", + cwd: process.cwd(), + }); + const modelSelection = { instanceId, model: "default" } as const; + const runtime = yield* adapter.openSession({ + threadId, + providerSessionId: ProviderSessionId.make( + "provider-session-acp-replace-same-id-catalog-key", + ), + modelSelection, + runtimePolicy, + }); + const original = yield* runtime.ensureThread({ + threadId, + modelSelection, + runtimePolicy, + }); + + assert.isAbove(publications.length, 0); + assert.isNull(publications[0]!.lastCatalogKey); + const preReplaceCount = publications.length; + + yield* pollProtocolMethods(protocolEvents); + const replacement = yield* runtime.ensureThread({ + threadId, + modelSelection, + runtimePolicy, + existingProviderThread: { ...original, nativeThreadRef: null }, + forceNewNativeThread: true, + }); + assert.equal(replacement.nativeThreadRef?.nativeId, original.nativeThreadRef?.nativeId); + + yield* runtime.startTurn( + makeTurnInput({ + threadId, + providerThread: replacement, + instanceId, + runtimePolicy, + now: yield* DateTime.now, + }), + ); + yield* runtime.events.pipe( + Stream.takeUntil((event) => event.type === "turn.terminal"), + Stream.runDrain, + ); + + const methodsAfterReplace = yield* pollProtocolMethods(protocolEvents); + assert.isTrue( + methodsAfterReplace.includes("session/new"), + `expected session/new for replacement runtime, got ${JSON.stringify(methodsAfterReplace)}`, + ); + + const postReplacePublications = publications.slice(preReplaceCount); + assert.isAbove(postReplacePublications.length, 0); + assert.isNull(postReplacePublications[0]!.lastCatalogKey); + }).pipe(Effect.provide(layerTest)), + ); + it.live("a snapshot load records its MCP credential, so the next turn does not reload", () => Effect.gen(function* () { const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts index a8e6269bd8a77..d9daba5216d06 100644 --- a/packages/provider-acp/src/server/adapter.ts +++ b/packages/provider-acp/src/server/adapter.ts @@ -2398,6 +2398,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( }); const setActiveSessionSetup = Effect.fnUntraced(function* ( setup: AcpSessionRuntime.AcpSessionRuntimeStartResult, + setupOptions?: { readonly keepPublishedCatalogKey?: boolean }, ) { followsAgentWorkState = flavor.followAgentWorkState === true && @@ -2414,8 +2415,8 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( rootForegroundWork = undefined; agentRequests.clear(); nativeChildren.clear(); - const previousSetup = yield* Ref.getAndSet(activeSessionSetup, setup); - if (previousSetup === null || previousSetup.sessionId !== setup.sessionId) { + yield* Ref.set(activeSessionSetup, setup); + if (setupOptions?.keepPublishedCatalogKey !== true) { yield* resetPublishedCatalogKey; } }); @@ -9806,7 +9807,9 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( const activated = yield* activateSession(requestedSessionId, turnInput.threadId); yield* Ref.set(activeSessionId, activated.sessionId); yield* Ref.set(loadingSessionId, null); - yield* setActiveSessionSetup(activated); + yield* setActiveSessionSetup(activated, { + keepPublishedCatalogKey: mcpReloadRequired, + }); yield* configureSession(activated, turnInput.modelSelection, turnInput.runtimePolicy); yield* Ref.set(activeSelection, turnInput.modelSelection); yield* Ref.set(activeInteractionMode, turnInput.runtimePolicy.interactionMode); @@ -10606,7 +10609,9 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( ); yield* Ref.set(activeSessionId, activated.sessionId); yield* Ref.set(loadingSessionId, null); - yield* setActiveSessionSetup(activated); + yield* setActiveSessionSetup(activated, { + keepPublishedCatalogKey: mcpReloadRequired, + }); yield* configureSession(activated, nextSelection, nextRuntimePolicy); yield* Ref.set(activeSelection, nextSelection); yield* Ref.set(activeInteractionMode, nextRuntimePolicy.interactionMode); From d71df86a3624a083330d4c7ac83978b24b5fddcc Mon Sep 17 00:00:00 2001 From: Victor Vogel Date: Wed, 25 Nov 2026 15:46:04 +0000 Subject: [PATCH 32/34] chore: retrigger checks after merge From 42fa9ba81edcdde420a2def2820233c4ae95856e Mon Sep 17 00:00:00 2001 From: Victor Vogel Date: Wed, 25 Nov 2026 16:42:44 +0000 Subject: [PATCH 33/34] chore: retrigger checks after merge From ec9fe033de3e7895733eba606f9c382f485d623c Mon Sep 17 00:00:00 2001 From: Victor Vogel Date: Wed, 25 Nov 2026 19:37:46 +0000 Subject: [PATCH 34/34] chore: retrigger checks after merge