diff --git a/apps/server/src/mcp/McpInvocationContext.ts b/apps/server/src/mcp/McpInvocationContext.ts index 9bd2f08f37445..13e4475e2172e 100644 --- a/apps/server/src/mcp/McpInvocationContext.ts +++ b/apps/server/src/mcp/McpInvocationContext.ts @@ -8,6 +8,8 @@ import { type ProviderInstanceId, type ProviderInteractionMode, type OrchestrationV2LinkedSender, + type RunAttemptId, + type RunId, type RuntimeMode, type ThreadId, } from "@t3tools/contracts"; @@ -32,6 +34,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..34ec6e63632d2 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,9 @@ export const layer = Layer.succeed( }), resolve: () => Effect.undefined, 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 9a7142cea3dfa..d29f27c99ce92 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,18 @@ export interface McpSessionRegistryShape { rawToken: string, ) => 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; + /** 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; @@ -48,6 +64,7 @@ interface AliveMark { } interface CredentialRecord { + readonly credentialId: string; readonly tokenHash: string; readonly scope: McpInvocationContext.McpThreadInvocationScope; readonly lastAlive: AliveMark; @@ -71,6 +88,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 +140,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 +155,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 +171,22 @@ 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, + }); + const threadTokens: Array = []; + for (const [hash, record] of next) { + if (record.scope.thread.threadId === scope.thread.threadId) { + threadTokens.push(hash); + } + } + for (let index = 0; index < threadTokens.length - MAX_CREDENTIALS_PER_THREAD; index += 1) { + next.delete(threadTokens[index]!); + } return { records: next }; }); return { @@ -154,7 +194,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 +251,60 @@ const makeWithOptions = Effect.fn("McpSessionRegistry.make")(function* ( issue, resolve, touch, + 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 }) => { + 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 next === undefined ? { records } : { 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/mcp/toolkits/core.test.ts b/apps/server/src/mcp/toolkits/core.test.ts index c1d35ace86940..e81f2de5b47b6 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, @@ -1695,3 +1696,150 @@ 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<{ + readonly threadId: ThreadId; + 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"); + const runB = RunId.make("run-b"); + const attemptB = RunAttemptId.make("attempt-b"); + + let rejectNext: { readonly problem: string; readonly cause?: unknown } | 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, + requestedRunId: input.requestedRunId, + }); + if (rejectNext !== undefined) { + const rejection = rejectNext; + rejectNext = undefined; + return Effect.fail( + new ThreadManagement.ThreadManagementRunOutputRejectedError({ + threadId: input.threadId, + problem: rejection.problem, + ...(rejection.cause === undefined ? {} : { cause: rejection.cause }), + }), + ); + } + return Effect.succeed({ runId: runB }); + }, + }), + ), + ); + + const callWith = ( + 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!; + 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: { + ...baseThread, + ...(runId === undefined ? {} : { runId }), + ...(attemptId === undefined ? {} : { attemptId }), + }, + }), + Effect.provideService(McpSchema.McpServerClient, client), + ); + }); + + const expectInvalidRequest = ( + result: Effect.Success>, + message: string, + ) => { + expect(result.isError).toBe(true); + expect(declaredFailure(result)).toEqual({ + _tag: "OrchestratorMcpFailure", + code: "invalid_request", + message, + }); + }; + + 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, + ); + + // 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 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 }); + }).pipe(Effect.provide(serverLayer)); + expect(calls).toEqual([ + { + threadId, + 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 220ed39eb3c81..598e65e6350db 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"; @@ -287,11 +288,18 @@ export const layer = McpToolAccess.toLayer(ThreadToolkit, { Effect.gen(function* () { const { scope, threads } = yield* readCaller(); if (scope.thread === undefined) return yield* unavailable(); + // 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({ threadId: scope.thread.threadId, commandId: yield* newCommandId(), json: input.json, + ...(callerRunId === undefined ? {} : { callerRunId }), + ...(input.runId === undefined ? {} : { requestedRunId: input.runId }), + ...(scope.thread.attemptId === undefined + ? {} + : { callerAttemptId: scope.thread.attemptId }), }) .pipe( Effect.mapError((error) => @@ -299,10 +307,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/mcp/toolkits/thread/tools.ts b/apps/server/src/mcp/toolkits/thread/tools.ts index 9803e8b4fa690..177cabe22482b 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 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({ 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/Adapters/AcpAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts index 2b88d684f6d23..7b3f73c1f172b 100644 --- a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts @@ -1387,6 +1387,7 @@ describe("AcpAdapterV2", () => { const promptRuntimes: Array = []; const promptTexts: Array = []; const watchedSessions: Array = []; + const restartedActivationCalls: Array = []; const adapter = yield* makeAcpAdapterV2({ instanceId, selfInvocation: yield* resolveSelfInvocation(), @@ -1414,20 +1415,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 }; + }), + }; + }, }), }, }); @@ -1476,6 +1526,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"); @@ -7235,6 +7290,418 @@ 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; + 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: { + 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* setMcp(2); + 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 mcpServers = rawProtocolRequestParam(reloadRequestEvent!, "mcpServers") as + | ReadonlyArray<{ + name?: string; + env?: ReadonlyArray<{ name: string; value: string }>; + }> + | undefined; + 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( + "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( + "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; + 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", + () => + 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 1f682f5e05a7c..012791df15ec9 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts @@ -3851,6 +3851,8 @@ describe("ClaudeAdapterV2 background wake turns", () => { offerAndWait: (message: SDKMessage) => Effect.Effect, ) => Effect.Effect; readonly renameSession?: ClaudeAdapterV2.ClaudeAgentSdkQuerySession["renameSession"]; + readonly setMcpServers?: ClaudeAdapterV2.ClaudeAgentSdkQuerySession["setMcpServers"]; + readonly omitSetMcpServers?: boolean; readonly applyFlagSettings?: ClaudeAdapterV2.ClaudeAgentSdkQuerySession["applyFlagSettings"]; readonly stopTask?: ( taskId: string, @@ -3901,6 +3903,7 @@ describe("ClaudeAdapterV2 background wake turns", () => { const permissionModeChanges: Array = []; const renameCalls: Array = []; const liveSelectionChanges: Array = []; + const setMcpServersCalls: Array> = []; const continuationRequests: Array = []; const continuationReceipts = @@ -4041,6 +4044,18 @@ describe("ClaudeAdapterV2 background wake turns", () => { Effect.sync(() => { renameCalls.push(title); }).pipe(Effect.andThen(() => options?.renameSession?.(title) ?? 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: @@ -4133,6 +4148,7 @@ describe("ClaudeAdapterV2 background wake turns", () => { permissionModeChanges, renameCalls, liveSelectionChanges, + setMcpServersCalls, continuationRequests, continuationReceipts, events, @@ -11850,9 +11866,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 }); @@ -11898,6 +11916,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) { @@ -11920,6 +11953,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; @@ -11954,10 +11988,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)), @@ -26608,6 +26648,222 @@ 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", + }, + { + 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, + ...(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 setMcp = (ordinal: number) => + mcpSessions.set({ + environmentId: EnvironmentId.make(`environment-claude-mcp-${mode}`), + threadId: harness.threadId, + 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); + } + 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" || 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* setMcp(2); + + if (isContinuationMode) { + const continuationTurn = yield* turnInput(2, "Background task completed.", { + 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(yield* turnInput(2, "Second turn.")) + .pipe(Effect.flip); + assert.instanceOf( + rejected.cause, + ClaudeAdapterV2.ClaudeBackgroundWorkBlocksQueryReplacementError, + ); + assert.equal(harness.processQueues.length, 1); + assert.isTrue(yield* harness.hasPendingBackgroundWork); + 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( + 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 a745fa7c8159b..be93593ac4f7e 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts @@ -794,6 +794,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: ( @@ -2066,6 +2069,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: () => @@ -3975,6 +4015,32 @@ export function claudeEffectiveQueryPolicyKey( }); } +function claudeEffectiveQueryPolicyKeyWithoutMcpAuth( + queryPolicy: ClaudeRuntimeQueryPolicy, + mcpOverrides: { + readonly allowedTools?: ReadonlyArray; + readonly mcpServers?: ClaudeQueryOptions["mcpServers"]; + }, + workspace?: ProviderAdapter.ProviderAdapterV2RuntimePolicy["workspace"], +): string { + 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, + mcpServers: { + ...mcpOverrides.mcpServers, + "t3-code": { ...t3Server, headers: restHeaders }, + }, + }, + workspace, + ); +} + type ClaudeToolItemType = Extract< OrchestrationV2TurnItem["type"], "command_execution" | "file_change" | "dynamic_tool" | "web_search" @@ -5571,7 +5637,9 @@ interface ClaudeLiveQueryContext { readonly settingsCwd: string | null; readonly launchArgSettings: ClaudeSdkSettings | undefined; readonly query: ClaudeAgentSdkQuerySession; - readonly queryPolicyKey: string; + queryPolicyKey: string; + readonly queryPolicyKeyWithoutMcpAuth: string; + mcpAuthorization: string | undefined; selection: CompiledClaudeModelSelection; readonly program: string | undefined; readonly startedWithApiModelId: string; @@ -13603,8 +13671,37 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( 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 === getQueryPolicyKeyWithoutMcpAuth() && + mcpOverrides.mcpServers !== undefined && + candidate.query.setMcpServers !== undefined; + const syncMcpServersLive = Effect.fnUntraced(function* ( + candidate: ClaudeLiveQueryContext, + ) { + if ( + mcpOverrides.mcpServers === undefined || + candidate.query.setMcpServers === undefined + ) + return; + 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; + } + }); // Continuations drain existing output without prompting; retain the live process regardless of selection. if ( existing !== null && @@ -13612,14 +13709,43 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( !existing.stopping && isClaudeProviderContinuationTurn(turnInput) ) { + // 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, + reason: "continuation_query", + }); + if ( + mcpOverrides.mcpServers === undefined || + existing.query.setMcpServers === undefined + ) { + return yield* rotationBlocked(); + } + yield* syncMcpServersLive(existing).pipe( + Effect.catchCauseIf( + (cause) => !Cause.hasInterruptsOnly(cause), + () => + Effect.logWarning("orchestration-v2.claude-live-mcp-refresh-failed", { + threadId: turnInput.threadId, + reason: "continuation", + }).pipe(Effect.andThen(Effect.fail(rotationBlocked()))), + ), + ); + } return existing; } + const policyCompatible = + existing !== null && + (existing.queryPolicyKey === queryPolicyKey || canUpdateMcpLive(existing)); let replaceStaleProcess = false; if ( !turnInput.resume && existing !== null && existing.nativeThreadId === nativeThreadId && - existing.queryPolicyKey === queryPolicyKey && + policyCompatible && !existing.stopping && // A pinned head already decides where a fresh process resumes. resumeSessionAt === undefined @@ -13646,7 +13772,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( const reuseLaunchSettings = existing !== null && existing.nativeThreadId === nativeThreadId && - existing.queryPolicyKey === queryPolicyKey && + policyCompatible && !existing.stopping; const readLaunchSettings = readClaudeLaunchArgSettings({ settings: adapterOptions.settings, @@ -13669,7 +13795,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( !turnInput.resume && existing !== null && existing.nativeThreadId === nativeThreadId && - existing.queryPolicyKey === queryPolicyKey && + policyCompatible && !existing.stopping && existing.startedWithApiModelId !== compiledSelection.apiModelId && claudeProgramWasReplaced(existing.program, yield* readProgram) && @@ -13679,7 +13805,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( !turnInput.resume && existing !== null && existing.nativeThreadId === nativeThreadId && - existing.queryPolicyKey === queryPolicyKey && + policyCompatible && !existing.stopping && !replaceStaleProcess && existing.selection.queryIdentity !== compiledSelection.queryIdentity && @@ -13694,29 +13820,45 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( !turnInput.resume && existing !== null && existing.nativeThreadId === nativeThreadId && - existing.queryPolicyKey === queryPolicyKey && + policyCompatible && !existing.stopping && !replaceStaleProcess && 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. @@ -13884,6 +14026,8 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( launchArgSettings, query: querySession, queryPolicyKey, + queryPolicyKeyWithoutMcpAuth: getQueryPolicyKeyWithoutMcpAuth(), + mcpAuthorization: mcpSession?.authorizationHeader, selection: compiledSelection, program, startedWithApiModelId: compiledSelection.apiModelId, @@ -14919,6 +15063,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 773c9bc574c9c..aca6075858ffa 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts @@ -3049,6 +3049,173 @@ 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; + 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, + 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), + ...configRead(2, "config/read initial"), + ...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" } }, + }, + ...configRead(5, "config/read reload"), + { + 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* setMcp(2); + 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 f5279d24116fd..6c3b6dd2392b1 100644 --- a/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts @@ -5876,6 +5876,65 @@ 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; + 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) => + 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 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"); + }); + + yield* runTurn(); + yield* setMcp(2); + yield* runTurn(); + }), + ); + 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 6d8245c81a41a..025abff7aa2a6 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -95,7 +95,7 @@ import { } from "./contextBoundary.ts"; import { isPlaceholderThreadTitle } from "./placeholderThreadTitle.ts"; import { combinePullRequestWatchWakes, type PullRequestWatchWake } from "./pullRequestWatch.ts"; -import { outputRequestProblem } from "./runOutput.ts"; +import { outputRequestProblem, resolveOwedOutputRun } from "./runOutput.ts"; import { recordThreadOpen } from "@t3tools/shared/paletteSearch"; import { isSlashCommand } from "@t3tools/shared/composerTrigger"; import { @@ -233,6 +233,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", { @@ -12519,23 +12531,65 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio cause: `Run ${command.runId} was not asked for a result.`, }); } - // 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 owes = run.status === "completed" && run.output === undefined; - if (!isActiveRun(run) && !owes) { - return yield* new OrchestratorDispatchError({ + const rejectOutput = (reason: RunOutputDispatchRejectionError["reason"], detail: string) => + new OrchestratorDispatchError({ commandId: command.commandId, commandType: command.type, - cause: `Run ${command.runId} is ${run.status} and takes no result.`, + 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 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", + `Run ${command.runId} is ${run.status} and takes no result.`, + ); + } + if (command.callerRunId !== undefined || command.callerAttemptId !== undefined) { + 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) => + (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* rejectOutput( + "stale_caller", + `Caller run ${command.callerRunId ?? "unknown"} is no longer active on thread ${command.threadId}.`, + ); + } + // A wake on an unbound credential names the owed run, so its calls cannot be told apart. + if ( + active !== undefined && + active.id !== run.id && + (yield* stopReachedRun(command, command.threadId, active.id)) + ) { + 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: `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 e6652c5963905..92f45992df724 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,8 @@ import { ProviderDriverKind, ProviderInstanceId, type ProviderSessionId, + ProviderThreadId, + RunAttemptId, RunId, ThreadId, TurnItemId, @@ -364,6 +367,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* () { @@ -479,15 +528,22 @@ const makeProviderAdapter = Effect.fnUntraced(function* ( readonly mcpConfigs?: Ref.Ref< ReadonlyArray >; + readonly mcpCredentialRotation?: "live" | "reload" | "none"; readonly beforeOpen?: (input: { readonly providerSessionId: ProviderSessionId; 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; + readonly startTurn?: Effect.Effect< + void, + ProviderAdapter.ProviderAdapterProtocolError, + McpProviderSessions.McpProviderSessions + >; readonly interruptTurn?: Effect.Effect; readonly beforeUnload?: Effect.Effect; readonly unloads?: Queue.Queue; @@ -563,10 +619,22 @@ 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, providerSessionId: input.providerSessionId, + ...(options.mcpCredentialRotation === undefined + ? {} + : { mcpCredentialRotation: options.mcpCredentialRotation }), ...(options.normalizeThreadLoadModelSelection === undefined ? {} : { normalizeThreadLoadModelSelection: options.normalizeThreadLoadModelSelection }), @@ -602,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) => @@ -610,9 +678,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) => ({ @@ -660,6 +728,7 @@ function layerTest(input: { readonly mcpConfigs?: Ref.Ref< ReadonlyArray >; + readonly mcpCredentialRotation?: "live" | "reload" | "none"; readonly beforeOpen?: (input: { readonly providerSessionId: ProviderSessionId; readonly initialProviderItemIdentityVersion?: 2; @@ -674,10 +743,16 @@ 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; + readonly startTurn?: Effect.Effect< + void, + ProviderAdapter.ProviderAdapterProtocolError, + McpProviderSessions.McpProviderSessions + >; readonly interruptTurn?: Effect.Effect; readonly beforeUnload?: Effect.Effect; readonly unloads?: Queue.Queue; @@ -716,6 +791,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 ? {} @@ -2236,6 +2314,127 @@ it.effect.each([ ({ start }) => idleReleaseAroundRun(start), ); +it.effect( + "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; + const manager = yield* ProviderSessionManager.ProviderSessionManagerV2; + const registry = yield* McpSessionRegistry.McpSessionRegistry; + const mcpSessions = yield* McpProviderSessions.McpProviderSessions; + const projectionStore = yield* ProjectionStore.ProjectionStoreV2; + const now = yield* DateTime.now; + const providerSessionId = yield* idAllocator.allocate.providerSession({ + providerInstanceId: modelSelection.instanceId, + threadId, + }); + const providerThread = makeProviderThread({ + idAllocator, + threadId, + providerSessionId, + now, + nativeThreadId: `native-${threadId}`, + }); + const run1 = idAllocator.derive.run({ threadId, ordinal: 1 }); + const attempt1 = idAllocator.derive.runAttempt({ runId: run1, attemptOrdinal: 1 }); + const run2 = idAllocator.derive.run({ threadId, ordinal: 2 }); + 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 }); + yield* eventSink.write({ + events: [ + yield* makeThreadCreatedEvent({ idAllocator, threadId, now }), + 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" }, + }), + ], + }); + + const runtime = yield* manager.open({ + threadId, + providerSessionId, + modelSelection, + runtimePolicy, + runId: run1, + attemptId: attempt1, + requireRunScopedMcp: true, + }); + const token1 = rawBearer(yield* mcpSessions.read(threadId)); + assert.equal((yield* registry.resolve(token1))?.thread.runId, run1); + + const messageId = yield* idAllocator.allocate.message({ threadId, ordinal: 3 }); + yield* runtime.compactThread!({ + appThread: (yield* projectionStore.getThreadProjection(threadId)).thread, + threadId, + runId: run3, + runOrdinal: 3, + providerTurnOrdinal: 3, + attemptId: attempt3, + rootNodeId: idAllocator.derive.rootNode({ runId: run3 }), + providerThread, + modelSelection, + runtimePolicy, + message: { + createdBy: "user", + creationSource: "web", + messageId, + text: "/compact", + attachments: [], + }, + }); + + 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); + }).pipe( + 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]); + }), + }), + ), + ); + }), +); + it.effect.each(["session metadata", "session status changes", "provider work"] as const)( "ProviderSessionManagerV2 expires idle sessions according to %s", (activity) => @@ -3415,6 +3614,835 @@ 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 keeps a non-rotatable runtime's credential, unbound, for a second typed run", + }, + { + scenario: "reload-blocked" as const, + 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: + "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); + const openFor = ( + manager: ProviderSessionManager.ProviderSessionManagerV2Shape, + providerSessionId: ProviderSessionId, + threadId: ThreadId, + turn?: { + readonly runId?: RunId; + readonly attemptId?: RunAttemptId; + readonly requireRunScopedMcp?: boolean; + readonly providerStartedTurn?: boolean; + }, + ) => + manager.open({ + threadId, + providerSessionId, + modelSelection, + runtimePolicy, + ...turn, + }); + 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-${slug}`); + const providerSessionId = yield* idAllocator.allocate.providerSession({ + providerInstanceId: modelSelection.instanceId, + threadId, + }); + return { + eventSink, + idAllocator, + manager, + registry, + mcpSessions, + now, + threadId, + providerSessionId, + }; + }); + 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 })], + }); + + const run1 = RunId.make("run-live-1"); + const attempt1 = RunAttemptId.make("attempt-live-1"); + yield* openFor(manager, providerSessionId, threadId, { + runId: run1, + attemptId: attempt1, + requireRunScopedMcp: true, + }); + const config1 = yield* mcpSessions.read(threadId); + 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* openFor(manager, providerSessionId, threadId, { + runId: RunId.make("run-live-plain"), + attemptId: RunAttemptId.make("attempt-live-plain"), + requireRunScopedMcp: false, + }); + assert.equal( + (yield* mcpSessions.read(threadId))?.authorizationHeader, + 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: true, + }); + 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); + + // 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: true, + 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, { + runId: run2, + attemptId: attempt2, + requireRunScopedMcp: true, + }); + const config2 = yield* mcpSessions.read(threadId); + const token2 = rawBearer(config2); + 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, + 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 providerThread = makeProviderThread({ + idAllocator, + threadId, + providerSessionId, + now, + }); + yield* eventSink.write({ + events: [ + yield* makeThreadCreatedEvent({ idAllocator, threadId, now }), + yield* makeRunCreatedEvent({ + idAllocator, + threadId, + runId: run1, + 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" }, + }), + ], + }); + + yield* openFor(manager, providerSessionId, threadId, { + runId: run1, + attemptId: RunAttemptId.make("attempt-none-1"), + requireRunScopedMcp: true, + }); + const config1 = yield* mcpSessions.read(threadId); + 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* 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* openFor(manager, providerSessionId, threadId, { + 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 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* openFor(manager, providerSessionId, threadId, { + 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); + 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 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); + }); + + yield* effect.pipe( + Effect.provide( + withServerSettings({ state, idleTimeoutMs: 1_000, mcpCredentialRotation: "none" }), + ), + ); + 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); + const sessionBackgroundWorkProbe = yield* Ref.make>( + Effect.succeed(false), + ); + const failUnload = yield* Ref.make(false); + const effect = Effect.gen(function* () { + const { + eventSink, + idAllocator, + manager, + registry, + mcpSessions, + now, + 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"); + const attempt2 = RunAttemptId.make("attempt-bg-2"); + const providerThread = makeProviderThread({ + idAllocator, + threadId, + providerSessionId, + now, + }); + yield* eventSink.write({ + events: [ + yield* makeThreadCreatedEvent({ idAllocator, threadId, now }), + yield* makeRunCreatedEvent({ + idAllocator, + threadId, + runId: run1, + attemptId: attempt1, + nodeId: NodeId.make("node-bg-1"), + userMessageId: MessageId.make("msg-bg-1"), + providerThreadId: providerThread.id, + now, + }), + yield* providerThreadRecorded(threadId, providerThread), + ], + }); + const runtime = yield* openFor(manager, providerSessionId, threadId, { + runId: run1, + 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}`); + const nextProviderThread = makeProviderThread({ + idAllocator, + threadId: nextThreadId, + providerSessionId, + now, + }); + yield* eventSink.write({ + 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); + // 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, + loadedConfig: loadedConfig!, + 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* 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, + }); + assert.equal(rawBearer(yield* mcpSessions.read(threadId)), loadedToken); + yield* resume(threadId, providerThread); + 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* mcpSessions.read(threadId))?.runId); + + // 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, + }); + yield* resume(unboundThread.threadId, unboundThread.providerThread); + assert.isTrue(Option.isNone(yield* Queue.poll(unloads))); + assert.equal( + rawBearer(yield* mcpSessions.read(unboundThread.threadId)), + unboundThread.loadedToken, + ); + assert.isDefined(yield* registry.resolve(unboundThread.loadedToken)); + + // Browser access follows the setting on the kept token, both ways, and the turn still runs. + const settings = yield* ServerSettings.ServerSettingsService; + 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); + } + + // 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 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 the work finishes, the next typed turn rotates and reloads, browser access still off. + yield* Ref.set(pendingBackgroundWork, 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(narrowed.threadId, narrowed.providerThread); + assert.isTrue(Option.isSome(yield* Queue.poll(unloads))); + 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, 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, 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. + // Once the unload fault clears, retrying the same run and attempt succeeds with a bound credential. + 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, + }); + + // Once background work finishes, reloading a thread whose loaded credential became unbound + // during keepLoaded retires that old unbound credential. + yield* openFor(manager, providerSessionId, threadId, { + runId: RunId.make("run-bg-3-retire"), + attemptId: RunAttemptId.make("attempt-bg-3-retire"), + requireRunScopedMcp: true, + }); + yield* resume(threadId, providerThread); + assert.isTrue(Option.isSome(yield* Queue.poll(unloads))); + assert.isUndefined(yield* registry.resolve(loadedToken)); + + // 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, + }); + 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. + yield* Ref.set(sessionBackgroundWorkProbe, Effect.succeed(false)); + const linksFail = yield* attachLoadedThread("links-unload-fail"); + yield* settings.updateSettings({ linkedEnvironmentsEnabled: true }); + 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"), + }); + + // 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 detachFail = yield* attachLoadedThread("detach-unload-fail"); + yield* eventSink.write({ + events: [ + { + id: yield* idAllocator.allocate.event({ threadId: detachFail.threadId }), + type: "provider-thread.updated", + threadId: detachFail.threadId, + occurredAt: now, + payload: detachFail.providerThread, + }, + ], + }); + yield* Ref.set(failUnload, 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, + }); + + yield* manager.close(providerSessionId); + }); + + yield* effect.pipe( + Effect.provide( + withServerSettings({ + state, + idleTimeoutMs: 1_000, + unloads, + hasPendingBackgroundWork: Ref.get(sessionBackgroundWorkProbe).pipe(Effect.flatten), + // 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)), + ), + }), + ), + ); + return; + } + + const unloads = yield* Queue.unbounded(); + const effect = Effect.gen(function* () { + const { eventSink, idAllocator, manager, mcpSessions, now, threadId, providerSessionId } = + yield* setupSession("shared-rotate"); + yield* eventSink.write({ + events: [yield* makeThreadCreatedEvent({ idAllocator, threadId, now })], + }); + + const run1 = RunId.make("run-shared-1"); + const runtime = yield* openFor(manager, providerSessionId, threadId, { + 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.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. + yield* openFor(manager, providerSessionId, threadId, { + 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. + yield* openFor(manager, providerSessionId, threadId, { + runId: RunId.make("run-shared-3"), + attemptId: RunAttemptId.make("attempt-shared-3"), + requireRunScopedMcp: true, + }); + const token3 = (yield* mcpSessions.read(threadId))?.authorizationHeader; + assert.isDefined(token3); + assert.notEqual(token3, token1); + yield* runtime.resumeThread({ + threadId, + providerThread, + modelSelection, + runtimePolicy, + }); + assert.deepEqual([...(yield* Queue.takeAll(unloads))], ["unload:native-thread"]); + assert.equal((yield* Ref.get(state)).resumeCount, 2); + 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 291ac02272a26..758e3e95d18fa 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, @@ -44,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, @@ -55,10 +57,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, @@ -249,6 +253,11 @@ export interface ProviderSessionManagerV2Shape { readonly providerSessionId: ProviderSessionId; readonly modelSelection: ModelSelection; readonly runtimePolicy: ProviderAdapter.ProviderAdapterV2RuntimePolicy; + readonly runId?: RunId; + readonly attemptId?: RunAttemptId; + readonly requireRunScopedMcp?: boolean; + /** The provider already started this turn natively, on the credential it holds. */ + readonly providerStartedTurn?: boolean; readonly resumeFromSession?: OrchestrationV2ProviderSession; readonly initialNativeThreadId?: string; readonly initialProviderItemIdentityVersion?: 2; @@ -327,11 +336,23 @@ export class ProviderSessionManagerV2 extends Context.Service< interface LiveSessionEntry { readonly attachedThreadIds: ReadonlySet; readonly loadedProviderThreadKeyByThread: ReadonlyMap; + /** Native thread and credential that were active when this thread was last loaded natively. */ + readonly loadedMcpCredentialByThread: ReadonlyMap< + ThreadId, + { + readonly providerThread: string; + readonly credential: 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; @@ -426,7 +447,7 @@ function isLoadKeyFor( providerThread: Parameters[0], ): boolean { return ( - loadKey === undefined || + loadKey !== undefined && (JSON.parse(loadKey) as { providerThread: string }).providerThread === providerThreadRuntimeKey(providerThread) ); @@ -589,6 +610,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. */ @@ -611,24 +633,139 @@ 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); + ids.add(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 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.credential) !== credentialId + ) { + continue; + } + next ??= new Map(current); + const loadedMcpCredentialByThread = new Map(entry.loadedMcpCredentialByThread); + loadedMcpCredentialByThread.set(threadId, { ...loaded, credential: updatedCredential }); + next.set(key, { ...entry, loadedMcpCredentialByThread }); + } + 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 || + (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); + return new Map(current).set(key, { ...entry, mcpTurnCheckedKeyByThread }); + }); + const threadRequiresRunScopedMcp = (threadId: ThreadId, runId: RunId | undefined) => + projectionStore.getThreadRecords(threadId, ["runs"]).pipe( + Effect.flatMap(({ runs }) => + runRequiresRunScopedMcp(runs, runId, () => + projectionStore.getThreadRecords(threadId, ["runs", "turnItems"], { + turnItemTypes: ["user_message"], + }), + ), + ), + ); /** Serialize prepares per thread so concurrent rotations cannot revoke each other's credentials. */ const prepareMcpSession = ( threadId: ThreadId, providerInstanceId: ProviderInstanceId, + turn?: { + readonly runId?: RunId | undefined; + readonly attemptId?: RunAttemptId | undefined; + readonly rotateOnRunChange?: boolean | undefined; + readonly ownerSessionId?: string | undefined; + }, ): 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* () { // 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( @@ -644,40 +781,71 @@ 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); - const rawToken = existing.authorizationHeader.replace(/^Bearer\s+/, ""); + reserveMcpCredential(threadId, existingCredentialId); + const rawToken = rawBearerToken(existing); // Interrupted resolution must release the reservation before the caller learns of it. const resolved = yield* mcpSessionRegistry .resolve(rawToken) .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, @@ -691,8 +859,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) => @@ -700,10 +873,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); } }), @@ -1603,30 +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.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); - }, - { 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) => @@ -1838,6 +2014,10 @@ export const layerWithOptions = ( attachedThreadIds.delete(input.threadId); const loadedProviderThreadKeyByThread = new Map(entry.loadedProviderThreadKeyByThread); loadedProviderThreadKeyByThread.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); @@ -1845,6 +2025,8 @@ export const layerWithOptions = ( ...entry, attachedThreadIds, loadedProviderThreadKeyByThread, + mcpTurnCheckedKeyByThread, + mcpOwnerSessionIdByThread, linkedEnvironmentsByThread, }); return updated; @@ -1887,8 +2069,10 @@ 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; }) => Ref.update(sessions, (current) => { const key = sessionKey(input.providerSessionId); @@ -1898,6 +2082,13 @@ export const layerWithOptions = ( } const loadedProviderThreadKeyByThread = new Map(entry.loadedProviderThreadKeyByThread); loadedProviderThreadKeyByThread.set(input.threadId, input.providerThreadKey); + const loadedMcpCredentialByThread = + input.mcpCredential === undefined + ? entry.loadedMcpCredentialByThread + : new Map(entry.loadedMcpCredentialByThread).set(input.threadId, { + providerThread: providerThreadRuntimeKey(input.providerThread), + credential: input.mcpCredential, + }); const linkedEnvironmentsByThread = new Map(entry.linkedEnvironmentsByThread); if ( input.linkedEnvironments !== undefined && @@ -1909,15 +2100,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, + })), + ), ), ); @@ -1947,17 +2145,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) { @@ -1993,8 +2186,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), @@ -2010,6 +2204,211 @@ 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 | undefined; + readonly requireRunScopedMcp?: boolean | undefined; + readonly providerStartedTurn?: boolean | undefined; + }) { + 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 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 resolved = yield* mcpSessionRegistry.resolve(rawBearerToken(latest)); + 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); + } + yield* recordMcpTurnChecked(input.providerSessionId, input.threadId, turnKey); + return true; + }), + ); + }; + 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) + ) { + 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 + : yield* threadRequiresRunScopedMcp(input.threadId, input.runId).pipe( + Effect.mapError( + (cause) => + new ProviderSessionOpenError({ + instanceId: input.providerInstanceId, + providerSessionId: input.providerSessionId, + cause, + }), + ), + ); + if (!rotateOnRunChange && current !== undefined) { + if (yield* retainCurrentMcpCredential(current, { unbindRun: false })) return; + continue; + } + // 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 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. + if ( + current !== undefined && + (input.providerStartedTurn === true || + input.runtime.mcpCredentialRotation === "none" || + (input.runtime.mcpCredentialRotation !== "live" && (yield* reloadBlocked))) + ) { + if (yield* retainCurrentMcpCredential(current, { unbindRun: true })) 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, + attemptId: input.attemptId, + 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); + return; + } + }).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 = ( @@ -2193,6 +2592,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; @@ -2249,10 +2671,13 @@ 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, ); @@ -2287,10 +2712,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) => @@ -2378,7 +2821,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) => @@ -2393,6 +2844,267 @@ 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 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 || + !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* () { + 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 + ? false + : yield* entry.runtime + .hasPendingBackgroundWorkForThread(input.providerThread, { + includeSubagents: true, + }) + .pipe( + Effect.catchCauseIf( + (cause) => !Cause.hasInterruptsOnly(cause), + () => Effect.succeed(true), + ), + ); + // 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 = ( + reason: ProviderAdapter.ProviderAdapterMcpRotationBlockedError["reason"], + ) => + 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; + } + 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 resolvedLoaded = yield* mcpSessionRegistry.resolve( + rawBearerToken(loadedCredential), + ); + // Capability removals revoke immediately; the thread then holds no working token. + if (resolvedLoaded === undefined) { + if (rollback.revokeStaged) { + yield* mcpSessions.clear(input.threadId); + } + yield* recordMcpTurnChecked( + input.providerSessionId, + input.threadId, + undefined, + entry.runtime, + ); + return yield* new ProviderAdapter.ProviderAdapterMcpRotationBlockedError({ + driver: entry.runtime.driver, + providerSessionId: input.providerSessionId, + providerThreadId: input.providerThread.id, + reason, + }); + } + yield* mcpSessionRegistry.releaseRunBinding(loadedCredentialId); + const { + runId: _runId, + attemptId: _attemptId, + ...withoutRun + } = loadedCredential; + const unbound: McpProviderSession.McpProviderSessionConfig = { + ...withoutRun, + browserToolsAvailable: resolvedLoaded.capabilities.has("preview"), + capabilities: resolvedLoaded.capabilities, + }; + if (rollback.revokeStaged) { + yield* mcpSessions.set(unbound); + } + yield* syncLoadedMcpCredential(input.threadId, loadedCredentialId, unbound); + }), + ); + if (hasPendingWork) { + return yield* keepLoaded("background_work"); + } + const unloadingCredential = yield* Ref.modify(sessions, (current) => { + const latest = current.get(key); + 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); + return [ + latestLoaded.credential, + new Map(current).set(key, { + ...latest, + loadedProviderThreadKeyByThread, + }), + ] as const; + }); + if (unloadingCredential === undefined) return; + const unloaded = yield* unloadThread({ providerThread: input.providerThread }).pipe( + Effect.timeout(UNLOAD_THREAD_TIMEOUT_MS), + 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) { + // 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("reload_failed"); + } + 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); + } + }), + ); + }, + ); + /** An exclusive runtime configures MCP at open, so it reopens once nothing would be lost. */ const releaseForLinkedEnvironments = Effect.fn( "ProviderSessionManager.releaseForLinkedEnvironments", @@ -2536,7 +3248,7 @@ export const layerWithOptions = ( const busyTurn = ( input: Pick< ProviderAdapter.ProviderAdapterV2TurnInput, - "threadId" | "providerThread" | "runOrdinal" | "runId" + "threadId" | "providerThread" | "runOrdinal" | "runId" | "attemptId" >, run: () => Effect.Effect, ) => @@ -2585,7 +3297,27 @@ export const layerWithOptions = ( ), ), ), - 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( @@ -2625,11 +3357,12 @@ 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, + providerThread, providerThreadKey: providerThreadLoadKey({ runtime, providerThread, @@ -2637,6 +3370,7 @@ export const layerWithOptions = ( runtimePolicy: input.runtimePolicy, }), linkedEnvironments, + mcpCredential, }), ), Effect.map(({ loaded }) => loaded), @@ -2676,6 +3410,13 @@ export const layerWithOptions = ( providerThread: input.providerThread, }), ), + Effect.andThen( + unloadForMcpCredential({ + providerSessionId, + threadId, + providerThread: input.providerThread, + }), + ), Effect.andThen( isProviderThreadLoaded({ providerSessionId, threadId, providerThreadKey }), ), @@ -2684,13 +3425,15 @@ 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, + providerThread, providerThreadKey: providerThreadLoadKey({ runtime, providerThread, @@ -2702,6 +3445,7 @@ export const layerWithOptions = ( : { runtimePolicy: input.runtimePolicy }), }), linkedEnvironments, + mcpCredential, }), ), Effect.map(({ loaded }) => loaded), @@ -2716,11 +3460,12 @@ 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, + providerThread, providerThreadKey: providerThreadLoadKey({ runtime, providerThread, @@ -2732,6 +3477,7 @@ export const layerWithOptions = ( : { runtimePolicy: input.runtimePolicy }), }), linkedEnvironments, + mcpCredential, }), ), Effect.map(({ loaded }) => loaded), @@ -3273,6 +4019,47 @@ 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, + attemptId: input.attemptId, + requireRunScopedMcp: input.requireRunScopedMcp, + providerStartedTurn: input.providerStartedTurn, + }); + } 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; } @@ -3291,6 +4078,13 @@ export const layerWithOptions = ( const prepared = yield* prepareMcpSession( input.threadId, input.modelSelection.instanceId, + input.runId !== undefined + ? { + runId: input.runId, + attemptId: input.attemptId, + rotateOnRunChange: input.requireRunScopedMcp === true, + } + : undefined, ); const mcpCredentialId = prepared.mcpCredentialId; let reservationDropped = mcpCredentialId === undefined; @@ -3366,12 +4160,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, @@ -3588,26 +4391,46 @@ 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); + // 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); + 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); const idleUnloadFibers: Array> = []; for (const [providerThreadId, pending] of entry.idleThreadUnloads) { @@ -3619,8 +4442,11 @@ export const layerWithOptions = ( ...entry, attachedThreadIds, loadedProviderThreadKeyByThread, + loadedMcpCredentialByThread, + mcpTurnCheckedKeyByThread, + mcpOwnerSessionIdByThread, linkedEnvironmentsByThread, - mcpCredentialIdByThread, + mcpCredentialIdsByThread, idleThreadUnloads, }; const updated = new Map(current); @@ -3629,6 +4455,7 @@ export const layerWithOptions = ( Option.some({ entry: updatedEntry, idleUnloadFibers, + detachedCredentialId, }), updated, ] as const; @@ -3638,17 +4465,17 @@ export const layerWithOptions = ( discard: true, }); } - const detached = Option.map(detachResult, (result) => result.entry); // 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, @@ -3658,8 +4485,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) { @@ -3673,13 +4500,48 @@ 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; } yield* unloadThread({ providerThread }).pipe( Effect.timeout(UNLOAD_THREAD_TIMEOUT_MS), + Effect.tap(() => + Ref.update(sessions, (current) => { + const latest = current.get(key); + if ( + latest?.runtime !== detachedEntry.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 460a6056eb7f2..8b0ba9988f6d6 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts @@ -83,6 +83,7 @@ import { CodexProviderCapabilitiesV2 } from "./Adapters/CodexAdapterV2.ts"; import * as ProjectionMaintenance from "./ProjectionMaintenance.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"; @@ -475,6 +476,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; @@ -491,6 +495,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; @@ -546,6 +551,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, @@ -591,7 +598,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, @@ -1236,7 +1243,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(() => @@ -1447,6 +1459,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, + }), + }), + ]), ), ), ); @@ -2390,6 +2419,55 @@ 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); + + // 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); + } }), ); @@ -2416,6 +2494,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"); }), ); @@ -3451,6 +3544,46 @@ 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 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: blockedError, + }); + + 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: + "Cannot refresh MCP credentials while background work is running on this thread.", + }, + }, + ]); + }), +); + 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 33d549f548938..586155462df12 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts @@ -70,8 +70,9 @@ import { isSlashCommandMessage, withInlineContext, } from "./ContextHandoffDelivery.ts"; -import { isProviderCommand, outputInstructions } 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"; import * as ProjectionStore from "./ProjectionStore.ts"; import { unsentManualContinuationSource } from "@t3tools/shared/orchestrationV2ManualContinuation"; @@ -210,6 +211,7 @@ const PROMPT_REFUSAL_TAGS = [ "ClaudeAppendSystemPromptMissingValueError", "ClaudeSettingsLaunchArgError", "ClaudeMcpRegistrationTimeoutError", + "ProviderAdapterMcpRotationBlockedError", ] as const; const refusedBeforePrompt = (error: unknown): boolean => @@ -358,6 +360,7 @@ export const layer: Layer.Layer< const setupScripts = yield* ProjectSetupScriptRunner.ProjectSetupScriptRunner; 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; @@ -1067,12 +1070,23 @@ export const layer: Layer.Layer< brokenNativeThread && providerThread.nativeThreadRef !== null && !(yield* providerSessions.isLive(providerSessionId)); + const requireRunScopedMcp = yield* runRequiresRunScopedMcp(projection.runs, run.id, () => + projectionStore.getThreadRecords(input.threadId, ["runs", "turnItems"], { + turnItemTypes: ["user_message"], + }), + ); const sessionResult = yield* Effect.result( providerSessions.open({ threadId: projection.thread.id, providerSessionId, modelSelection: run.modelSelection, runtimePolicy: resolvedRuntimePolicy, + runId: run.id, + attemptId: attempt.id, + requireRunScopedMcp, + ...(message?.createdBy === "agent" && message.creationSource === "provider" + ? { providerStartedTurn: true } + : {}), ...(existingSessionProjection === undefined ? {} : { resumeFromSession: existingSessionProjection }), @@ -1198,10 +1212,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)}`; + ? "" + : 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, @@ -1895,11 +1910,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, or the provider may have - // resumed it without answering. A fresh session would split the conversation. + // Another client or active background work owns the native thread, or the provider may + // have resumed it without answering. A fresh session would split the conversation. if ( resumed._tag === "Failure" && (resumed.failure._tag === "ProviderAdapterThreadInUseError" || + resumed.failure._tag === "ProviderAdapterMcpRotationBlockedError" || outcomeUnknown(resumed.failure)) ) { return yield* loadFromProvider(Effect.fail(resumed.failure)); @@ -2078,12 +2094,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", @@ -2311,7 +2340,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 = @@ -2322,10 +2352,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 = slashCommand ? userText : withInlineContext(context, requestText); const operation = turnInput.resume && !prompted @@ -2345,9 +2380,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. @@ -2410,9 +2445,10 @@ export const layer: Layer.Layer< }), ), ); - const deliverySession = carriesPendingContext - ? makeDeliverySession(session, startWithHandoffs) - : session; + const deliverySession = + carriesPendingContext || needsPromptedOutputRunId + ? makeDeliverySession(session, startWithHandoffs) + : session; return runExecution.startRootRun({ commandId: CommandId.make(`command:effect:provider-turn.start:${run.id}`), appThread: projection.thread, diff --git a/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts b/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts index 98434fa4967b1..5b609310b5974 100644 --- a/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts +++ b/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts @@ -671,11 +671,14 @@ 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, + 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 0b9450c7c0fe2..26d3c20660f6e 100644 --- a/apps/server/src/orchestration-v2/ThreadManagementService.test.ts +++ b/apps/server/src/orchestration-v2/ThreadManagementService.test.ts @@ -556,6 +556,8 @@ it.effect( threadId, 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 a928d46a1764f..2ae7cd7826e81 100644 --- a/apps/server/src/orchestration-v2/ThreadManagementService.ts +++ b/apps/server/src/orchestration-v2/ThreadManagementService.ts @@ -39,6 +39,7 @@ import { ProviderInstanceId, type ProviderSessionId, resolveProjectProviderInstanceEnabled, + type RunAttemptId, RunId, type ScheduledTaskId, ThreadId, @@ -72,11 +73,12 @@ import * as ThreadCommandExecutor from "./ThreadCommandExecutor.ts"; import { DispatchModeLimit, exceededDispatchModeLimit } from "./DispatchModeLimit.ts"; import { projectTurnItemForDetail } from "./WireProjection.ts"; import { cancelledBeforeStart } from "./RestartBackgroundNote.ts"; -import { contextBoundaryOrdinal } from "./contextBoundary.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, outputRequestProblem, resolveOwedOutputRun } from "./runOutput.ts"; + +const isRunOutputDispatchRejectionError = Schema.is(Orchestrator.RunOutputDispatchRejectionError); export type ThreadManagementSendMode = "auto" | "queue" | "steer" | "restart"; @@ -496,6 +498,9 @@ export interface ThreadManagementServiceShape { readonly threadId: ThreadId; readonly commandId: CommandId; readonly json: string; + readonly callerRunId?: RunId; + readonly callerAttemptId?: RunAttemptId; + readonly requestedRunId?: RunId; }) => Effect.Effect<{ readonly runId: RunId }, ThreadManagementFailure>; readonly assertProviderInstanceEnabled: (input: { readonly projectId: ProjectId; @@ -1061,29 +1066,45 @@ 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 asked = records.runs - .filter( - (candidate) => - candidate.outputSchema !== undefined && - candidate.status !== "queued" && - !cancelledBeforeStart(candidate), - ) - .toSorted((left, right) => right.ordinal - left.ordinal)[0]; - const owing = asked?.status === "completed" && asked.output === undefined ? asked : undefined; - const forgotten = - owing !== undefined && - records.runs.some((later) => later.freshContext === true && later.ordinal > owing.ordinal) && - contextBoundaryOrdinal( - yield* orchestrator.getThreadRecords(input.threadId, ["runs", "turnItems"]), - ) > owing.ordinal; - const owed = forgotten ? undefined : owing; - 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({ threadId: input.threadId, 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, 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 ?? requestedRunId; + 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. + // The run named in the call must be that target, even when a bound credential names another. + if ( + requestedRunId !== run.id || + (!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)) { return yield* new ThreadManagementRunOutputRejectedError({ @@ -1097,8 +1118,26 @@ const make = Effect.gen(function* () { commandId: input.commandId, threadId: input.threadId, runId: run.id, + 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.", + cause: error, + }), + ) + : Effect.fail(error), + }), + ); return { runId: run.id }; }); diff --git a/apps/server/src/orchestration-v2/runOutput.test.ts b/apps/server/src/orchestration-v2/runOutput.test.ts index c27365a5c86c4..d0ac0c9e5031e 100644 --- a/apps/server/src/orchestration-v2/runOutput.test.ts +++ b/apps/server/src/orchestration-v2/runOutput.test.ts @@ -1,8 +1,21 @@ import { assert, it } from "@effect/vitest"; +import { + MessageId, + type OrchestrationV2Run, + type OrchestrationV2TurnItem, + RunId, + ScheduledTaskId, +} from "@t3tools/contracts"; import * as Effect from "effect/Effect"; import * as Result from "effect/Result"; -import { checkOutput, outputRequestProblem } from "./runOutput.ts"; +import { + checkOutput, + latestOwedOutputRun, + outputRequestProblem, + resolveOwedOutputRun, + runRequiresRunScopedMcp, +} from "./runOutput.ts"; const open = { type: "object", properties: { verdict: { type: "string" } }, required: ["verdict"] }; const closed = { ...open, additionalProperties: false }; @@ -23,3 +36,85 @@ it("a command its provider runs itself cannot be asked for a result", () => { } assert.isNull(outputRequestProblem(open, { text: "Review the changes" })); }); + +it.effect("owed output follows only the newest started request inside the current context", () => + Effect.gen(function* () { + const makeRun = ( + id: string, + ordinal: number, + fields: Partial = {}, + ): OrchestrationV2Run => + ({ + id: RunId.make(id), + ordinal, + status: "completed", + startedAt: null, + userMessageId: MessageId.make(`msg:${id}`), + ...fields, + }) as unknown as OrchestrationV2Run; + + const asked = makeRun("run:asked", 1, { outputSchema: open }); + const queued = makeRun("run:queued", 2, { status: "queued", outputSchema: open }); + const cancelledNeverStarted = makeRun("run:cancelled", 3, { + status: "cancelled", + startedAt: null, + outputSchema: open, + }); + assert.equal(latestOwedOutputRun([asked, queued, cancelledNeverStarted])?.id, asked.id); + + // Once a newer started request answers, the earlier unanswered request no longer owes output. + const correction = makeRun("run:correction", 4, { + outputSchema: open, + output: { value: { verdict: "merge" }, submittedAt: "2026-01-01T00:00:00.000Z" }, + }); + const plain = makeRun("run:plain", 5, { status: "running" }); + let contextLoads = 0; + const loadContext = (runs: ReadonlyArray, scheduled?: MessageId) => () => { + contextLoads += 1; + const turnItems = + scheduled === undefined + ? [] + : ([ + { + type: "user_message", + messageId: scheduled, + scheduledTaskId: ScheduledTaskId.make("sched:1"), + }, + ] as unknown as ReadonlyArray); + return Effect.succeed({ runs, turnItems }); + }; + assert.isUndefined(latestOwedOutputRun([asked, correction, plain])); + assert.isFalse( + yield* runRequiresRunScopedMcp( + [asked, correction, plain], + plain.id, + loadContext([asked, correction, plain]), + ), + ); + assert.equal(contextLoads, 0); + + // A scheduled fresh-context run keeps the owed run reachable; an unscheduled one forgets it. + const scheduledFresh = makeRun("run:sched-fresh", 2, { + status: "completed", + freshContext: true, + }); + const schedRuns = [asked, scheduledFresh, plain]; + assert.equal( + (yield* resolveOwedOutputRun(schedRuns, loadContext(schedRuns, scheduledFresh.userMessageId))) + ?.id, + asked.id, + ); + assert.isTrue( + yield* runRequiresRunScopedMcp( + schedRuns, + plain.id, + loadContext(schedRuns, scheduledFresh.userMessageId), + ), + ); + + 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, loadContext(freshRuns))); + }), +); diff --git a/apps/server/src/orchestration-v2/runOutput.ts b/apps/server/src/orchestration-v2/runOutput.ts index 20d76ecff009d..f5386e48450ff 100644 --- a/apps/server/src/orchestration-v2/runOutput.ts +++ b/apps/server/src/orchestration-v2/runOutput.ts @@ -1,10 +1,98 @@ -import { parseGoalCommand } from "@t3tools/contracts"; +import { + type OrchestrationV2Run, + type OrchestrationV2ThreadProjection, + 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"; +import { cancelledBeforeStart } from "./RestartBackgroundNote.ts"; +import { contextBoundaryOrdinal } from "./contextBoundary.ts"; + +/** + * Latest completed run on the thread that still owes a typed result, ignoring context boundaries. + * Only the newest started run asked for a result can owe it. + */ +export function latestOwedOutputRun< + TRun extends { + readonly id: RunId; + readonly ordinal: number; + readonly status: OrchestrationV2Run["status"]; + readonly startedAt?: OrchestrationV2Run["startedAt"]; + readonly restartContinuationOfRunId?: OrchestrationV2Run["restartContinuationOfRunId"]; + readonly outputSchema?: unknown; + readonly output?: unknown; + }, +>(runs: ReadonlyArray): TRun | undefined { + let asked: TRun | undefined; + for (const candidate of runs) { + if ( + candidate.outputSchema !== undefined && + candidate.status !== "queued" && + !cancelledBeforeStart({ + status: candidate.status, + startedAt: candidate.startedAt ?? null, + ...(candidate.restartContinuationOfRunId === undefined + ? {} + : { restartContinuationOfRunId: candidate.restartContinuationOfRunId }), + }) && + (asked === undefined || candidate.ordinal > asked.ordinal) + ) { + asked = candidate; + } + } + return asked?.status === "completed" && asked.output === undefined ? asked : undefined; +} + +/** + * Latest completed run that still owes a typed result and remains reachable in the agent's + * current conversation. Loads `turnItems` only when a later fresh-context run exists. + */ +export const resolveOwedOutputRun = ( + runs: ReadonlyArray, + loadContextRecords: () => Effect.Effect< + Pick, + E, + R + >, +): Effect.Effect => { + const owing = latestOwedOutputRun(runs); + if ( + owing === undefined || + !runs.some((later) => later.freshContext === true && later.ordinal > owing.ordinal) + ) { + return Effect.succeed(owing); + } + return loadContextRecords().pipe( + Effect.map((records) => (contextBoundaryOrdinal(records) > owing.ordinal ? undefined : owing)), + ); +}; + +/** 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, + loadContextRecords: () => Effect.Effect< + Pick, + E, + R + >, +): Effect.Effect => { + if ( + runId !== undefined && + runs.some((candidate) => candidate.id === runId && candidate.outputSchema !== undefined) + ) { + return Effect.succeed(true); + } + return resolveOwedOutputRun(runs, loadContextRecords).pipe( + Effect.map((owed) => owed !== undefined), + ); +}; + type OutputSchema = Readonly>; // A schema built from JSON Schema needs no services, which its `Schema.Top` type cannot say. @@ -46,10 +134,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 370fd7deb9ade..6fd842eff11d8 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, @@ -12493,11 +12494,12 @@ it.layer(layerSharedApplicationDataPlaneTest)("run output after a stop", (it) => ], }); }); - const submit = (key: string, json = '{"head":"abc"}') => + const submit = (key: string, callerRunId?: RunId, json = '{"head":"abc"}') => threadManagement.submitRunOutput({ threadId, commandId: CommandId.make(`runtime-layer-owed-output-submit-${key}`), json, + ...(callerRunId === undefined ? {} : { callerRunId, requestedRunId: callerRunId }), }); const refused = Effect.fn(function* (key: string) { const rejected = yield* submit(key).pipe(Effect.flip); @@ -12508,7 +12510,7 @@ it.layer(layerSharedApplicationDataPlaneTest)("run output after a stop", (it) => yield* complete("asked"); yield* send("woken"); - const accepted = yield* submit("asked"); + const accepted = yield* submit("asked", asked.id); assert.equal(accepted.runId, asked.id); const after = yield* orchestrator.getThreadProjection(threadId); assert.deepEqual(after.runs.find((run) => run.id === asked.id)?.output?.value, { @@ -12518,13 +12520,13 @@ it.layer(layerSharedApplicationDataPlaneTest)("run output after a stop", (it) => // Its reply was lost, and the retry comes once the next step's turn asked for a result. yield* complete("woken"); yield* send("next", { type: "object" }); - assert.equal((yield* submit("asked")).runId, asked.id); + assert.equal((yield* submit("asked", asked.id)).runId, asked.id); assert.isUndefined((yield* runOf("next")).output); // A correction gave the result `next` owed, so a later plain turn owes nothing. yield* complete("next"); yield* send("correction", { type: "object" }); - yield* submit("correction"); + yield* submit("correction", (yield* runOf("correction")).id); yield* complete("correction"); yield* send("plain"); yield* refused("plain"); @@ -12697,13 +12699,483 @@ it.layer(layerSharedApplicationDataPlaneTest)("run output after a stop", (it) => threadId, commandId: CommandId.make("runtime-layer-stopped-output-submit"), json: "{}", + callerRunId: run.id, + requestedRunId: run.id, }) .pipe(Effect.flip); - assert.include(String((rejected as { cause?: unknown }).cause), "was stopped"); + 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); }), ); + + 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" }, + options?: { readonly freshContext?: boolean; readonly scheduledTaskId?: ScheduledTaskId }, + ) => + 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 }), + ...(options?.freshContext === undefined ? {} : { freshContext: options.freshContext }), + ...(options?.scheduledTaskId === undefined + ? {} + : { scheduledTaskId: options.scheduledTaskId }), + dispatchMode: { type: "start_immediately" }, + }); + 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 finishRun = ( + run: Effect.Success>, + suffix: string, + 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; + readonly requestedRunId?: RunId; + }, + ) => + threadManagement.submitRunOutput({ + 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, + updateRun, + finishRun, + requestStop, + submit, + }; + }); + + 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, + 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" }); + const runA = yield* latestRun(); + yield* finishRun(runA, "run-a-interrupted", "interrupted"); + + // Run B starts with a compatible schema and attempt 2 active. + yield* send("run-b", { type: "object" }); + const runB = yield* latestRun(); + const attempt1 = RunAttemptId.make(`${runB.id}:attempt:1`); + const attempt2 = RunAttemptId.make(`${runB.id}:attempt:2`); + 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* submit("anonymous-run-output", '{"from":"anonymous"}').pipe( + Effect.flip, + ); + assert.equal(anonymous._tag, "ThreadManagementRunOutputRejectedError"); + assert.include(anonymous.message, "runId"); + + 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* submit( + "late-run-output-from-attempt-1", + '{"from":"attempt-1"}', + { callerRunId: runB.id, callerAttemptId: attempt1 }, + ).pipe(Effect.flip); + 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"); + + // 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"}', { + callerRunId: runB.id, + callerAttemptId: attempt2, + }); + assert.equal(acceptedB.runId, runB.id); + 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* finishRun(afterB, "run-b-completed", "completed"); + yield* send("run-c", { type: "object" }); + 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* latestRun()).output); + const acceptedViaContinuation = yield* submit( + "run-output-via-continuation", + '{"from":"continued"}', + { callerRunId: runC.id }, + ); + assert.equal(acceptedViaContinuation.runId, runC.id); + const afterC = (yield* orchestrator.getThreadProjection(threadId)).runs.find( + (run) => run.id === runC.id, + )!; + assert.deepEqual(afterC.output?.value, { from: "continued" }); + // 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: "continued" }, + ); + + // A plain turn with no schema preserves the plain-turn guidance even for stale/unbound MCP callers. + yield* finishRun(afterC, "run-c-completed", "completed"); + yield* send("run-plain"); + 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* 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, threadId, send, latestRun, finishRun, requestStop, submit } = + yield* setupOutputThread("owed-wake-output"); + + yield* send("run-a", { type: "object" }); + const runA = yield* latestRun(); + yield* finishRun(runA, "run-a-interrupted", "interrupted"); + + yield* send("run-c", { type: "object" }); + const runC = yield* latestRun(); + yield* finishRun(runC, "run-c-completed", "completed"); + yield* send("run-d-wake"); + 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* submit("late-run-output-from-c", '{"from":"run-c"}', { + callerRunId: runC.id, + }); + assert.equal(acceptedFromC.runId, runC.id); + assert.deepEqual( + (yield* orchestrator.getThreadProjection(threadId)).runs.find((run) => run.id === runC.id) + ?.output?.value, + { from: "run-c" }, + ); + + yield* finishRun(runD, "run-d-completed", "completed"); + yield* send("run-e", { type: "object" }); + const runE = yield* latestRun(); + 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, + requestedRunId: runE.id, + }); + assert.equal(acceptedFromF.runId, runE.id); + assert.deepEqual( + (yield* orchestrator.getThreadProjection(threadId)).runs.find((run) => run.id === runE.id) + ?.output?.value, + { from: "run-f" }, + ); + + // 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"); + 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; + } + + const { orchestrator, threadId, send, latestRun, finishRun } = yield* setupOutputThread( + "completed-before-dispatch", + ); + 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* 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. + const beforeSched = yield* completeWithAttempt("run-before-sched"); + yield* send("run-sched-fresh", undefined, { + freshContext: true, + scheduledTaskId: ScheduledTaskId.make("runtime-layer-sched-fresh-task"), + }); + 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.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. + const beforeFresh = yield* completeWithAttempt("run-before-fresh"); + yield* send("run-unscheduled-fresh", undefined, { freshContext: true }); + 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"); + 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. + const first = yield* completeWithAttempt("run-first"); + yield* send("run-superseded", { type: "object" }); + 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"); + }), + ); }); 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 3b16fb53af2d4..190093a3378e2 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"; @@ -1542,6 +1546,88 @@ 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 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: runA.scope!, + operation: "open", + input: { reuseExistingTab: false, show: false }, + }); + const tabId = PreviewTabId.make(opened.tabId!); + + 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); + expect(runB.scope?.thread.runId).toBe("run-b"); + + yield* broker.invoke({ + scope: runB.scope!, + 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: runB.scope!, + tabId, + operation: "evaluate", + input: { expression: "ownedAfterRotation()" }, + }); + expect(evaluated).toBe("evaluated"); + + const separateSession = yield* issueScope("run-c"); + expect(separateSession.config.providerSessionId).not.toBe(runA.config.providerSessionId); + const foreign = yield* broker + .invoke({ + scope: separateSession.scope!, + 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/apps/server/src/provider/agentContextBudget.json b/apps/server/src/provider/agentContextBudget.json index 6ee87b39f01a3..31f8663888b82 100644 --- a/apps/server/src/provider/agentContextBudget.json +++ b/apps/server/src/provider/agentContextBudget.json @@ -1,5 +1,5 @@ { "claudeSystemAppendBytes": 6245, "codexAdditionalContextBytes": 7639, - "mcpToolListJsonBytes": 62140 + "mcpToolListJsonBytes": 62137 } diff --git a/packages/contracts/src/orchestrationV2.ts b/packages/contracts/src/orchestrationV2.ts index 9064d5bd19fbb..30bc76088861f 100644 --- a/packages/contracts/src/orchestrationV2.ts +++ b/packages/contracts/src/orchestrationV2.ts @@ -3852,6 +3852,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 bb715a6883366..47c349bcba388 100644 --- a/packages/provider-acp/src/server/adapter.ts +++ b/packages/provider-acp/src/server/adapter.ts @@ -2343,6 +2343,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( @@ -2362,6 +2364,8 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( } | null>(null); const activeSessionSetup = yield* Ref.make(null); + const installedInitializeResult = + yield* Ref.make(null); const lastPublishedCatalogKey = yield* Ref.make<{ readonly epoch: number; readonly key: string | null; @@ -2399,6 +2403,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( }); const setActiveSessionSetup = Effect.fnUntraced(function* ( setup: AcpSessionRuntime.AcpSessionRuntimeStartResult, + setupOptions?: { readonly keepPublishedCatalogKey?: boolean }, ) { followsAgentWorkState = flavor.followAgentWorkState === true && @@ -2416,7 +2421,9 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( agentRequests.clear(); nativeChildren.clear(); yield* Ref.set(activeSessionSetup, setup); - yield* resetPublishedCatalogKey; + if (setupOptions?.keepPublishedCatalogKey !== true) { + yield* resetPublishedCatalogKey; + } }); const activeSelection = yield* Ref.make(null); const activeInteractionMode = yield* Ref.make(null); @@ -8059,8 +8066,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* ( @@ -8240,7 +8251,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); @@ -8297,10 +8310,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( @@ -8310,9 +8325,19 @@ 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 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 canLoadOrResume = () => { + const agent = installedAgentCapabilities(); + return agent?.loadSession === true || agent?.sessionCapabilities?.resume != null; + }; + const usesMcpOverAcp = () => + installedAgentCapabilities()?.mcpCapabilities?.acp === true && + runtimeMcpBridge !== undefined; const supportsImagePrompts = acpSupportsImagePrompts({ flavorSupportsImagePrompts: flavor.supportsImagePrompts, negotiatedImage: @@ -8333,25 +8358,65 @@ 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* () { - if (!canLoadSession && !canResumeSession) { + if (agent?.loadSession !== true && agent?.sessionCapabilities?.resume == null) { return yield* new ProviderAdapter.ProviderAdapterProtocolError({ driver, detail: `ACP driver cannot load or resume session ${sessionId}`, }); } yield* reportStartupPhase("resume"); - return canLoadSession + return agent?.loadSession === true ? yield* runtime.loadSession(sessionId, activationOptions) : yield* runtime.resumeSession(sessionId, activationOptions); }).pipe( Effect.onError(() => Ref.set(loadingSessionId, null)), Effect.ensuring(Effect.suspend(() => reportStartupPhase(undefined))), ); - 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; readonly providerThreadId: ProviderThreadId }, + ) { + const currentMcpContext = yield* readMcpContext(threadId); + if (currentMcpContext.authorization === (yield* Ref.get(activeMcpAuthorization))) { + return false; + } + if ( + usesMcpOverAcp() && + runtimeMcpBridge !== undefined && + currentMcpContext.authorization !== undefined + ) { + rememberTerminalEnvironment(sessionId, currentMcpContext); + runtimeMcpBridge.setAuthorization(currentMcpContext.authorization); + yield* Ref.set(activeMcpAuthorization, currentMcpContext.authorization); + return false; + } + 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({ + driver, + providerSessionId: input.providerSessionId, + providerThreadId: options.providerThreadId, + reason: "background_work", + }); + } + 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, ) { @@ -9420,9 +9485,11 @@ 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); yield* Ref.set(activeSessionSetup, null); yield* resetPublishedCatalogKey; yield* Ref.set(activeSelection, null); @@ -9765,13 +9832,27 @@ 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 currentSessionId = yield* Ref.get(activeSessionId); + const mcpReloadRequired = + !restartAfterInterrupt && + currentSessionId === requestedSessionId && + (yield* syncMcpCredentialForSession(requestedSessionId, turnInput.threadId, { + allowReload: !isContinuationTurn, + providerThreadId: turnInput.providerThread.id, + })); const needsSessionActivation = - (yield* Ref.get(activeSessionId)) !== requestedSessionId || restartAfterInterrupt; + currentSessionId !== requestedSessionId || restartAfterInterrupt || mcpReloadRequired; if (needsSessionActivation) { 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); @@ -9832,10 +9913,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()); @@ -10386,7 +10463,13 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( get providerSession() { return providerSession; }, - canResumeAfterRestart: canLoadSession || canResumeSession, + get canResumeAfterRestart() { + return canLoadOrResume(); + }, + get mcpCredentialRotation() { + if (usesMcpOverAcp()) return "live" as const; + return canLoadOrResume() ? ("reload" as const) : ("none" as const); + }, events: Stream.fromEffectRepeat(Queue.take(events)), ...(flavor.getModelContextWindow === undefined ? {} @@ -10543,17 +10626,45 @@ 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 currentSessionId = yield* Ref.get(activeSessionId); + const mcpReloadRequired = + !restartAfterInterrupt && + currentSessionId === sessionId && + (yield* syncMcpCredentialForSession( + sessionId, + threadInput.providerThread.appThreadId, + { providerThreadId: threadInput.providerThread.id }, + ).pipe(Effect.tapError(() => restorePreviousItemIdentity))); + if ( + currentSessionId !== 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* setActiveSessionSetup(activated, { + keepPublishedCatalogKey: mcpReloadRequired, + }); yield* configureSession(activated, nextSelection, nextRuntimePolicy); yield* Ref.set(activeSelection, nextSelection); yield* Ref.set(activeInteractionMode, nextRuntimePolicy.interactionMode); @@ -10570,14 +10681,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, + }), ), ), ), @@ -11120,7 +11233,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", @@ -11135,11 +11248,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); @@ -11245,7 +11362,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", @@ -11254,7 +11372,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) { @@ -11274,11 +11392,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..b7667b797c199 100644 --- a/packages/provider-acp/src/server/mcpOverAcpBridge.test.ts +++ b/packages/provider-acp/src/server/mcpOverAcpBridge.test.ts @@ -254,4 +254,264 @@ 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: "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: + "fails reconnect when initialize returns an error or malformed envelope without sending notifications/initialized", + }, + ])("$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 slowCallStarted = Promise.withResolvers(); + const releaseSlowCall = Promise.withResolvers(); + const { bridge, seen, init, callTool } = yield* makeStatefulBridge({ + onRequest: async (_auth, body) => { + if (body.params?.name === "slow_call") { + slowCallStarted.resolve(); + await releaseSlowCall.promise; + } + return undefined; + }, + }); + + yield* init(); + const inFlight = yield* callTool("slow_call").pipe(Effect.forkChild); + yield* Effect.promise(() => slowCallStarted.promise); + + // 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); + + // 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" }, + { 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" }, + { authorization: "Bearer run-2-token", sessionId: "session-2", method: "tools/call" }, + ]); + 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(); + const reconnect3Started = Promise.withResolvers(); + const releaseReconnect3 = Promise.withResolvers(); + 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 === "initialize" && auth === "Bearer run-3-token") { + reconnect3Started.resolve(); + await releaseReconnect3.promise; + } + return undefined; + }, + }); + + // 1. Auth rotates while initial initialize is still in flight; subsequent call must reconnect. + 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* 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* callTool().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; + } + + let nextInitMode: "ok" | "error" | "malformed" = "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 (mode === "malformed") { + return jsonResponse({ jsonrpc: "2.0", id: body.id }); + } + return undefined; + }, + }); + yield* init(); + bridge.setAuthorization("Bearer run-2-token"); + nextInitMode = "error"; + expect((yield* callTool().pipe(Effect.flip)).message).toContain("initialize rejected"); + nextInitMode = "malformed"; + 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* callTool()).toEqual({ content: [] }); + expect(seen.map((entry) => entry.method)).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"; + expect((yield* init().pipe(Effect.flip)).message).toContain("initialize rejected"); + nextInitMode = "malformed"; + const explicitMalformed = yield* init().pipe(Effect.flip); + expect(explicitMalformed._tag).toBe("AcpMcpOverAcpError"); + expect(explicitMalformed.message).toContain("valid initialize response"); + 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 779076a622b5b..b711cb18803f7 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,174 @@ export const makeAcpMcpOverAcpBridge = Effect.fn("AcpMcpOverAcpBridge.make")(fun : Effect.succeed(connection); }); - // Only initialization needs ordering; negotiated calls may 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.mutex.withPermits(1)(effect) : effect, + connection.protocolVersion === null + ? connection.mutex.withPermits(1)(effect(true)) + : effect(false), ); - const sendNow = ( + const postOnce = Effect.fn("AcpMcpOverAcpBridge.postOnce")(function* ( connection: Connection, message: unknown, - ): Effect.Effect, AcpMcpOverAcpError> => - untilNegotiated( + 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, + ) { + 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> => { + const method = asEnvelope(message)?.method; + const pinnedGeneration = authorizationGeneration; + return untilNegotiated(connection, (ordered) => 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 (true) { + if (authorizationGeneration !== pinnedGeneration) { + return yield* new AcpMcpOverAcpError({ + message: "MCP credentials rotated while the request was waiting to send.", + }); + } + if (!connection.needsReconnect) break; + // 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 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, @@ -183,6 +305,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({ @@ -191,7 +315,7 @@ export const makeAcpMcpOverAcpBridge = Effect.fn("AcpMcpOverAcpBridge.make")(fun method: "DELETE", signal, headers: { - authorization: options.authorization, + authorization: disconnectAuthorization, "mcp-session-id": sessionId, ...(connection.protocolVersion === null ? {} @@ -218,8 +342,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 {}; @@ -240,12 +373,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", @@ -263,6 +402,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) { @@ -274,6 +418,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 4bb8088f16fd5..c1df29f024b7a 100644 --- a/packages/provider-core/src/server/ProviderAdapter.ts +++ b/packages/provider-core/src/server/ProviderAdapter.ts @@ -321,6 +321,31 @@ export class ProviderAdapterThreadInUseError extends Schema.TaggedError()( + "ProviderAdapterMcpRotationBlockedError", + { + driver: ProviderDriverKind, + providerSessionId: ProviderSessionId, + providerThreadId: ProviderThreadId, + reason: Schema.Literals(["background_work", "reload_failed", "continuation_query"]), + }, +) { + override get message(): string { + switch (this.reason) { + case "background_work": + return "Cannot refresh MCP credentials while background work is running on this thread."; + case "reload_failed": + return "Could not reload the thread to refresh MCP credentials."; + case "continuation_query": + return "Cannot refresh MCP credentials on a retained Claude continuation query."; + } + } +} + /** * The user sent `/compact` to a driver whose session has no native compaction. */ @@ -546,6 +571,7 @@ export const ProviderAdapterV2Error = Schema.Union([ ProviderAdapterCloseSessionError, ProviderAdapterResumeThreadError, ProviderAdapterThreadInUseError, + ProviderAdapterMcpRotationBlockedError, ProviderAdapterEnsureThreadError, ProviderAdapterReadThreadSnapshotError, ProviderAdapterRollbackThreadError, @@ -774,6 +800,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 871820d22bb9d..a796e32c69a01 100644 --- a/packages/provider-core/src/server/failure.ts +++ b/packages/provider-core/src/server/failure.ts @@ -150,6 +150,7 @@ function curatedCauseMessages(cause: unknown): { case "CodexAppServerRetiredError": 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 3b21fcf951ec4..819900b69c82b 100644 --- a/packages/provider-cursor/src/server/adapter.test.ts +++ b/packages/provider-cursor/src/server/adapter.test.ts @@ -3473,21 +3473,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); // A restricted turn starts no command the checkout names; the user's own file still applies. yield* fileSystem.writeFileString( path.join(home, ".cursor", "projects", projectDirectory, "mcp-disabled.json"), @@ -3499,7 +3509,7 @@ describe("CursorAdapterV2", () => { yield* sendTurn(4 + index, { ...runtimePolicy, runtimeMode }); assert.deepEqual(sentWith[3 + index], { repro: { command: "node", args: [`${home}/shadowed.mjs`], cwd: projectRoot }, - ...t3Servers, + ...rotatedT3Servers, }); } yield* fileSystem.writeFileString( diff --git a/packages/provider-cursor/src/server/adapter.ts b/packages/provider-cursor/src/server/adapter.ts index 63f8e22aa8b89..a8c4022dd6d25 100644 --- a/packages/provider-cursor/src/server/adapter.ts +++ b/packages/provider-cursor/src/server/adapter.ts @@ -3291,6 +3291,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 b446bbf7f741a..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 { @@ -425,6 +438,64 @@ describe("MuseAdapterV2", () => { }).pipe(Effect.scoped, Effect.provide(testLayer)), ); + it.effect("re-resumes with rotated MCP credentials on the next turn", () => + Effect.gen(function* () { + yield* setMcp(1); + 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* setMcp(2); + 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( + "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 1bfe44d44b599..c58c764ce59c4 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 hasT3Mcp = false; @@ -1925,6 +1926,7 @@ export const makeMuseAdapterV2 = Effect.fn("makeMuseAdapterV2")(function* ( relaunchable = false; thread = undefined; nativeSessionId = undefined; + registeredMcpAuthorization = undefined; yield* updateSession("ready", null); } if (active) @@ -1938,17 +1940,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 && !sameThread) { + return yield* protocolError("Open a new host to attach another Muse session"); + } + if ( + thread !== undefined && + (mcpSession === undefined || + registeredMcpAuthorization === mcpSession.authorizationHeader) + ) { return thread; - if (thread) 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", @@ -1968,10 +1978,10 @@ 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( - requestedId ? "session/resume" : "session/start", - requestedId + resumeExistingId ? "session/resume" : "session/start", + resumeExistingId ? { excludeItems: true, ...(config ? { config } : {}), permissionProfile } : { workspaceRoot: cwd, @@ -1984,7 +1994,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); @@ -1998,10 +2008,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 ? { @@ -2112,6 +2123,20 @@ 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 !== undefined && + 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); @@ -2296,6 +2321,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 5e0b34c029111..331da779816f1 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, @@ -352,6 +353,63 @@ 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"); + 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", + { + 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* setMcp(2); + 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 39376b09c0b59..ef7ac209cf0f3 100644 --- a/packages/provider-opencode/src/server/adapter.ts +++ b/packages/provider-opencode/src/server/adapter.ts @@ -1098,19 +1098,29 @@ export const makeOpenCodeAdapterV2 = Effect.fn("makeOpenCodeAdapterV2")(function hasT3Mcp, mcpSession?.capabilities?.has("device") === true, ); - 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 = mcp.authorizationHeader; + }); + yield* syncT3Mcp(mcpSession); const now = yield* DateTime.now; let sessionEntity: OrchestrationV2ProviderSession = { @@ -3631,6 +3641,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( () => @@ -3756,6 +3767,7 @@ export const makeOpenCodeAdapterV2 = Effect.fn("makeOpenCodeAdapterV2")(function ); } yield* applyPermissionRules(state, turnInput.runtimePolicy); + 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-opencode/src/server/v2/adapter.ts b/packages/provider-opencode/src/server/v2/adapter.ts index 21d0f36bcb1fa..4bced3fd084ed 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"; @@ -4440,14 +4441,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 @@ -4493,6 +4493,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({ agentFeedback: mcpAvailable ? (turnInput.agentFeedback ?? "off") : "off", @@ -4631,6 +4645,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* () { @@ -4869,6 +4888,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 45cb7c08eb22e..61e3184180b5f 100644 --- a/packages/provider-pi/src/server/adapter.test.ts +++ b/packages/provider-pi/src/server/adapter.test.ts @@ -2236,14 +2236,75 @@ 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; + 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; + 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* setMcp(2); + 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 1ce21cfb7c903..3b325e5d3a1fc 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,30 @@ 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; + 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 = bearerTokenFromAuthorizationHeader(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), @@ -542,11 +566,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, @@ -3433,6 +3463,7 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( instanceId: options.instanceId, driver: PI_PROVIDER, providerSessionId: input.providerSessionId, + mcpCredentialRotation: "live", get providerSession() { return sessionEntity; }, @@ -3523,6 +3554,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 c4ea594d8472e..a58ef13c0aa16 100644 --- a/packages/provider-pi/src/server/mcpBridge.testkit.ts +++ b/packages/provider-pi/src/server/mcpBridge.testkit.ts @@ -63,6 +63,13 @@ 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(); @@ -70,6 +77,7 @@ export async function loadMcpBridge( 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 +113,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,15 +148,21 @@ 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), @@ -224,6 +249,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 e3eaedf339bf7..63a0eb2366619 100644 --- a/packages/provider-pi/src/server/mcpExtensionSource.test.ts +++ b/packages/provider-pi/src/server/mcpExtensionSource.test.ts @@ -174,6 +174,173 @@ 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 }) => { + 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 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(bridge); + + 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(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); + 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"); + 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; + } + + 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 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; + const waitingFirstRead = tool.execute("late-from-run-a", { stale: true }); + await firstReadStarted.promise; + bridge.setBearerTokenFile("run-2-token"); + releaseFirstRead.resolve(); + 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(bridge); + const waitingGen2 = tool.execute("waiting-gen2", { stale: true }); + await initStarted.promise; + bridge.setBearerTokenFile("run-3-token"); + releaseInit.resolve(); + await expectRotatedRejection(waitingGen2); + }); }); describe("Pi MCP tool exposure", () => { diff --git a/packages/provider-pi/src/server/mcpExtensionSource.ts b/packages/provider-pi/src/server/mcpExtensionSource.ts index 7fbddfa2d98fc..8152868f514bc 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,31 @@ 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 headers = (): Record => { + const syncToken = async () => { + if (tokenFile === undefined) return; + try { + const next = (await NodeFSP.readFile(tokenFile, "utf8")).trim(); + 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. + } + }; + + 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 +206,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 +239,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 +261,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 +294,15 @@ function createMcpClient(endpoint: string, token: string) { return tools; }, async callTool(name: string, args: Record, signal?: AbortSignal) { + const pinnedGeneration = authGeneration; + 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); + } return request("tools/call", { name, arguments: args }, signal); }, }; @@ -411,7 +467,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 = () => { @@ -540,6 +596,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(); @@ -550,7 +607,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..5c8c3c576dc92 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, @@ -159,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; } @@ -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 }), } : {}), },