diff --git a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts index 43db1b82b63a..ce2e1141943e 100644 --- a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts @@ -25,10 +25,12 @@ import { assert, beforeAll, describe, it } from "@effect/vitest"; import { CheckpointId, EnvironmentId, + MessageId, type ModelSelection, ProviderDriverKind, ProviderInstanceId, ProviderSessionId, + RunId, ThreadId, type OrchestrationV2ProviderThread, type OrchestrationV2TurnItem, @@ -12618,6 +12620,798 @@ describe("AcpAdapterV2", () => { ]); }).pipe(Effect.provide(layerTest)), ); + + it.live( + "delivers MCP appContext once per session, skips slash commands, and resends after unsuccessful turns, compaction, or runtime restart", + () => + Effect.gen(function* () { + const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const selfInvocation = yield* resolveSelfInvocation(); + const mockAgentPath = yield* bundledMockAgentPath; + type RuntimeService = AcpSessionRuntime.AcpSessionRuntime["Service"]; + let sessionUpdateHandler: Parameters[0] | undefined; + let runtimeCount = 0; + let cancelCalled: Deferred.Deferred | undefined; + const prompts: Array = []; + const queuedResponses: Array< + | { readonly _tag: "immediate"; readonly response: EffectAcpSchema.PromptResponse } + | { + readonly _tag: "gated"; + readonly started: Deferred.Deferred; + readonly gate: Deferred.Deferred; + } + > = []; + const instanceId = ProviderInstanceId.make("acp-test-app-context-lifecycle"); + const threadId = ThreadId.make("thread-acp-app-context-lifecycle"); + const idAllocator = yield* IdAllocator.IdAllocatorV2; + const adapter = yield* makeAcpAdapterV2({ + instanceId, + selfInvocation, + flavor: { + driver: ACP_TEST_DRIVER, + capabilities: AcpProviderCapabilitiesV2, + restartRuntimeAfterInterrupt: true, + makeRuntime: makeMockRuntime({ + childProcessSpawner, + mockAgentPath, + wrapRuntime: (runtime) => { + runtimeCount += 1; + return { + ...runtime, + handleSessionUpdate: (handler) => + Effect.sync(() => { + sessionUpdateHandler = handler; + }).pipe(Effect.andThen(runtime.handleSessionUpdate(handler))), + cancel: Effect.suspend(() => + cancelCalled === undefined + ? Effect.void + : Deferred.succeed(cancelCalled, undefined).pipe(Effect.asVoid), + ), + prompt: (payload, promptOptions) => + Effect.gen(function* () { + prompts.push( + payload.prompt + .flatMap((block) => (block.type === "text" ? [block.text] : [])) + .join("\n"), + ); + if (promptOptions?.dispatched) { + yield* Deferred.succeed(promptOptions.dispatched, undefined); + } + const next = queuedResponses.shift(); + if (next === undefined) { + return { stopReason: "end_turn" as const }; + } + if (next._tag === "immediate") { + return next.response; + } + yield* Deferred.succeed(next.started, undefined); + return yield* Deferred.await(next.gate); + }), + }; + }, + }), + }, + }); + 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-app-context-lifecycle"), + modelSelection, + runtimePolicy, + }); + const providerThread = yield* runtime.ensureThread({ + threadId, + modelSelection, + runtimePolicy, + }); + const sessionId = providerThread.nativeThreadRef?.nativeId; + if (sessionId == null) return assert.fail("expected native session id"); + let ordinal = 0; + const runTurn = (input: { + readonly text: string; + readonly note: string; + readonly response?: EffectAcpSchema.PromptResponse; + }) => + Effect.gen(function* () { + ordinal += 1; + if (input.response !== undefined) { + queuedResponses.push({ _tag: "immediate", response: input.response }); + } + yield* runtime.startTurn({ + ...makeTurnInput({ + threadId, + providerThread, + instanceId, + runtimePolicy, + now: yield* DateTime.now, + ordinal, + messageText: input.text, + }), + appContext: [{ key: "mcp_app_item-1", text: input.note }], + }); + const events = Array.from( + yield* runtime.events.pipe( + Stream.takeUntil((event) => event.type === "turn.terminal"), + Stream.runCollect, + ), + ); + const terminal = events.at(-1); + return { + prompt: prompts.at(-1) ?? "", + status: terminal?.type === "turn.terminal" ? terminal.status : null, + }; + }); + + const tag = (note: string) => `${note}`; + + // An unsuccessful stop reason must not mark appContext delivered. + const refusedTurn = yield* runTurn({ + text: "Refused attempt", + note: "Created Jira issue PROJ-42", + response: { stopReason: "refusal" }, + }); + assert.include(refusedTurn.prompt, tag("Created Jira issue PROJ-42")); + + // Interrupted turns must not mark appContext delivered even if the prompt answers end_turn. + const interruptedStarted = yield* Deferred.make(); + const interruptedGate = yield* Deferred.make(); + cancelCalled = yield* Deferred.make(); + queuedResponses.push({ + _tag: "gated", + started: interruptedStarted, + gate: interruptedGate, + }); + ordinal += 1; + const interruptedOrdinal = ordinal; + yield* runtime.startTurn({ + ...makeTurnInput({ + threadId, + providerThread, + instanceId, + runtimePolicy, + now: yield* DateTime.now, + ordinal: interruptedOrdinal, + messageText: "Interrupted attempt", + }), + appContext: [{ key: "mcp_app_item-1", text: "Created Jira issue PROJ-42" }], + }); + yield* Deferred.await(interruptedStarted); + assert.include(prompts.at(-1) ?? "", tag("Created Jira issue PROJ-42")); + const interruptFiber = yield* runtime + .interruptTurn({ + providerThread, + providerTurnId: idAllocator.derive.providerTurn({ + driver: ACP_TEST_DRIVER, + nativeTurnId: acpScopedNativeId( + instanceId, + `${sessionId}:turn:${interruptedOrdinal}`, + ), + }), + }) + .pipe(Effect.forkScoped); + yield* Deferred.await(cancelCalled); + yield* Deferred.succeed(interruptedGate, { stopReason: "end_turn" }); + yield* Fiber.join(interruptFiber); + yield* runtime.events.pipe( + Stream.takeUntil((event) => event.type === "turn.terminal"), + Stream.runDrain, + ); + + // Native slash commands skip appContext injection; the next normal turn sends it. + const slashTurn = yield* runTurn({ + text: " /repro-skill", + note: "Created Jira issue PROJ-42", + }); + assert.equal(slashTurn.status, "completed"); + assert.notInclude(slashTurn.prompt, "external_mcp_app_item-1"); + + const deliveredTurn = yield* runTurn({ + text: "What did the app report?", + note: "Created Jira issue PROJ-42", + }); + assert.equal(deliveredTurn.status, "completed"); + assert.include(deliveredTurn.prompt, tag("Created Jira issue PROJ-42")); + + // Unchanged note is not resent; changed note is sent once. + const unchangedTurn = yield* runTurn({ + text: "Follow up", + note: "Created Jira issue PROJ-42", + }); + assert.notInclude(unchangedTurn.prompt, "external_mcp_app_item-1"); + + const changedTurn = yield* runTurn({ + text: "Updated check", + note: "Updated Jira issue PROJ-43", + }); + assert.include(changedTurn.prompt, tag("Updated Jira issue PROJ-43")); + + const afterChangeTurn = yield* runTurn({ + text: "Second follow up", + note: "Updated Jira issue PROJ-43", + }); + assert.notInclude(afterChangeTurn.prompt, "external_mcp_app_item-1"); + + // Compaction clears delivered appContext so the next turn resends it. + yield* sessionUpdateHandler!({ + sessionId, + update: { + sessionUpdate: "compaction_update", + compactionId: "compact-app-context", + status: "completed", + }, + }); + const postCompactTurn = yield* runTurn({ + text: "After compaction", + note: "Updated Jira issue PROJ-43", + }); + assert.include(postCompactTurn.prompt, tag("Updated Jira issue PROJ-43")); + + const afterPostCompactTurn = yield* runTurn({ + text: "Already resent after compaction", + note: "Updated Jira issue PROJ-43", + }); + assert.notInclude(afterPostCompactTurn.prompt, "external_mcp_app_item-1"); + + // Runtime restart clears delivered appContext even when resuming the same session id. + const restartStarted = yield* Deferred.make(); + const restartGate = yield* Deferred.make(); + cancelCalled = yield* Deferred.make(); + queuedResponses.push({ + _tag: "gated", + started: restartStarted, + gate: restartGate, + }); + ordinal += 1; + const restartOrdinal = ordinal; + yield* runtime.startTurn({ + ...makeTurnInput({ + threadId, + providerThread, + instanceId, + runtimePolicy, + now: yield* DateTime.now, + ordinal: restartOrdinal, + messageText: "Trigger restart", + }), + appContext: [{ key: "mcp_app_item-1", text: "Updated Jira issue PROJ-43" }], + }); + yield* Deferred.await(restartStarted); + const restartInterruptFiber = yield* runtime + .interruptTurn({ + providerThread, + providerTurnId: idAllocator.derive.providerTurn({ + driver: ACP_TEST_DRIVER, + nativeTurnId: acpScopedNativeId(instanceId, `${sessionId}:turn:${restartOrdinal}`), + }), + requestRuntimeRestart: true, + }) + .pipe(Effect.forkScoped); + yield* Deferred.await(cancelCalled); + yield* Deferred.succeed(restartGate, { stopReason: "cancelled" }); + yield* Fiber.join(restartInterruptFiber); + yield* runtime.events.pipe( + Stream.takeUntil((event) => event.type === "turn.terminal"), + Stream.runDrain, + ); + + const postRestartTurn = yield* runTurn({ + text: "After runtime restart", + note: "Updated Jira issue PROJ-43", + }); + assert.isAbove(runtimeCount, 1); + assert.include(postRestartTurn.prompt, tag("Updated Jira issue PROJ-43")); + }).pipe(Effect.provide(layerTest)), + ); + + it.live( + "delivers changed appContext on steersWithPrompt and preserves undelivered notes on slash or failed steer", + () => + Effect.gen(function* () { + const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const selfInvocation = yield* resolveSelfInvocation(); + const mockAgentPath = yield* bundledMockAgentPath; + const idAllocator = yield* IdAllocator.IdAllocatorV2; + const prompts: Array = []; + const promptGates: Array<{ + readonly started: Deferred.Deferred; + readonly gate: Deferred.Deferred< + EffectAcpSchema.PromptResponse, + EffectAcpErrors.AcpError + >; + }> = []; + const queueGate = () => + Effect.gen(function* () { + const entry = { + started: yield* Deferred.make(), + gate: yield* Deferred.make< + EffectAcpSchema.PromptResponse, + EffectAcpErrors.AcpError + >(), + }; + promptGates.push(entry); + return entry; + }); + const instanceId = ProviderInstanceId.make("acp-test-app-context-steer-prompt"); + const threadId = ThreadId.make("thread-acp-app-context-steer-prompt"); + const adapter = yield* makeAcpAdapterV2({ + instanceId, + selfInvocation, + flavor: { + driver: ACP_TEST_DRIVER, + capabilities: AcpProviderCapabilitiesV2, + steersWithPrompt: () => true, + makeRuntime: makeMockRuntime({ + childProcessSpawner, + mockAgentPath, + wrapRuntime: (runtime) => ({ + ...runtime, + prompt: (payload, promptOptions) => + Effect.gen(function* () { + prompts.push( + payload.prompt + .flatMap((block) => (block.type === "text" ? [block.text] : [])) + .join("\n"), + ); + if (promptOptions?.dispatched) { + yield* Deferred.succeed(promptOptions.dispatched, undefined); + } + const next = promptGates.shift(); + if (next === undefined) return { stopReason: "end_turn" as const }; + yield* Deferred.succeed(next.started, undefined); + return yield* Deferred.await(next.gate); + }), + }), + }), + }, + }); + 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-app-context-steer-prompt", + ), + modelSelection, + runtimePolicy, + }); + const providerThread = yield* runtime.ensureThread({ + threadId, + modelSelection, + runtimePolicy, + }); + const sessionId = providerThread.nativeThreadRef?.nativeId; + if (sessionId == null) return assert.fail("expected native session id"); + const tag = (note: string) => `${note}`; + const providerTurnIdFor = (ordinal: number) => + idAllocator.derive.providerTurn({ + driver: ACP_TEST_DRIVER, + nativeTurnId: acpScopedNativeId(instanceId, `${sessionId}:turn:${ordinal}`), + }); + const steer = (ordinal: number, text: string, note: string) => + runtime.steerTurn({ + threadId, + runId: RunId.make(`run:${threadId}:${ordinal}`), + providerThread, + providerTurnId: providerTurnIdFor(ordinal), + message: { + createdBy: "user", + creationSource: "web", + messageId: MessageId.make(`steer-${ordinal}-${prompts.length}`), + text, + attachments: [], + }, + appContext: [{ key: "mcp_app_item-1", text: note }], + }); + + const turn1Initial = yield* queueGate(); + yield* runtime.startTurn({ + ...makeTurnInput({ + threadId, + providerThread, + instanceId, + runtimePolicy, + now: yield* DateTime.now, + ordinal: 1, + messageText: "Start turn 1", + }), + appContext: [{ key: "mcp_app_item-1", text: "Note A" }], + }); + yield* Deferred.await(turn1Initial.started); + assert.include(prompts.at(-1) ?? "", tag("Note A")); + + // Unchanged note does not repeat on steer. + const steer1 = yield* queueGate(); + yield* steer(1, "Keep going", "Note A"); + yield* Deferred.await(steer1.started); + assert.notInclude(prompts.at(-1) ?? "", "external_mcp_app_item-1"); + yield* Deferred.succeed(turn1Initial.gate, { stopReason: "end_turn" }); + + // Slash steer skips appContext so the next normal steer carries the changed note. + const steerSlash = yield* queueGate(); + yield* steer(1, "/status", "Note B"); + yield* Deferred.await(steerSlash.started); + assert.notInclude(prompts.at(-1) ?? "", "external_mcp_app_item-1"); + yield* Deferred.succeed(steer1.gate, { stopReason: "end_turn" }); + + const steerChanged = yield* queueGate(); + yield* steer(1, "Use updated note", "Note B"); + yield* Deferred.await(steerChanged.started); + assert.include(prompts.at(-1) ?? "", tag("Note B")); + yield* Deferred.succeed(steerSlash.gate, { stopReason: "end_turn" }); + + // Second steer with the same note does not resend it. + const steerSame = yield* queueGate(); + yield* steer(1, "One more detail", "Note B"); + yield* Deferred.await(steerSame.started); + assert.notInclude(prompts.at(-1) ?? "", "external_mcp_app_item-1"); + yield* Deferred.succeed(steerChanged.gate, { stopReason: "end_turn" }); + yield* Deferred.succeed(steerSame.gate, { stopReason: "end_turn" }); + yield* runtime.events.pipe( + Stream.takeUntil((event) => event.type === "turn.terminal"), + Stream.runDrain, + ); + + // Turn 2 inherits delivered Note B; a failed prompt steer with Note C does not mark Note C delivered. + const turn2Initial = yield* queueGate(); + yield* runtime.startTurn({ + ...makeTurnInput({ + threadId, + providerThread, + instanceId, + runtimePolicy, + now: yield* DateTime.now, + ordinal: 2, + messageText: "Start turn 2", + }), + appContext: [{ key: "mcp_app_item-1", text: "Note B" }], + }); + yield* Deferred.await(turn2Initial.started); + assert.notInclude(prompts.at(-1) ?? "", "external_mcp_app_item-1"); + + const steerFailed = yield* queueGate(); + yield* steer(2, "Try Note C", "Note C"); + yield* Deferred.await(steerFailed.started); + assert.include(prompts.at(-1) ?? "", tag("Note C")); + yield* Deferred.succeed(turn2Initial.gate, { stopReason: "end_turn" }); + yield* Deferred.fail( + steerFailed.gate, + new EffectAcpErrors.AcpRequestError({ + code: -32603, + errorMessage: "Steer prompt rejected", + method: "session/prompt", + }), + ); + const turn2Events = Array.from( + yield* runtime.events.pipe( + Stream.takeUntil((event) => event.type === "turn.terminal"), + Stream.runCollect, + ), + ); + const turn2Terminal = turn2Events.at(-1); + assert.equal( + turn2Terminal?.type === "turn.terminal" ? turn2Terminal.status : null, + "failed", + ); + + // Turn 3 must resend Note C because the failed steer did not deliver it. + yield* runtime.startTurn({ + ...makeTurnInput({ + threadId, + providerThread, + instanceId, + runtimePolicy, + now: yield* DateTime.now, + ordinal: 3, + messageText: "Start turn 3", + }), + appContext: [{ key: "mcp_app_item-1", text: "Note C" }], + }); + yield* runtime.events.pipe( + Stream.takeUntil((event) => event.type === "turn.terminal"), + Stream.runDrain, + ); + assert.include(prompts.at(-1) ?? "", tag("Note C")); + }).pipe(Effect.provide(layerTest)), + ); + + it.live( + "delivers changed appContext on native flavor.steering and preserves undelivered notes on failure", + () => + Effect.gen(function* () { + const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const selfInvocation = yield* resolveSelfInvocation(); + const mockAgentPath = yield* bundledMockAgentPath; + const idAllocator = yield* IdAllocator.IdAllocatorV2; + type RuntimeService = AcpSessionRuntime.AcpSessionRuntime["Service"]; + let sessionUpdateHandler: Parameters[0] | undefined; + const prompts: Array = []; + const steeredTexts: Array = []; + const steerOutcomes: Array< + | { readonly _tag: "accept" } + | { readonly _tag: "fail" } + | { + readonly _tag: "waitId"; + readonly steerId: string; + readonly sent: Deferred.Deferred; + } + > = []; + const promptGates: Array<{ + readonly started: Deferred.Deferred; + readonly gate: Deferred.Deferred; + }> = []; + const queueGate = () => + Effect.gen(function* () { + const entry = { + started: yield* Deferred.make(), + gate: yield* Deferred.make(), + }; + promptGates.push(entry); + return entry; + }); + const instanceId = ProviderInstanceId.make("acp-test-app-context-native-steer"); + const threadId = ThreadId.make("thread-acp-app-context-native-steer"); + const adapter = yield* makeAcpAdapterV2({ + instanceId, + selfInvocation, + flavor: { + driver: ACP_TEST_DRIVER, + capabilities: { + ...AcpProviderCapabilitiesV2, + turns: { + ...AcpProviderCapabilitiesV2.turns, + supportsActiveSteering: true, + }, + }, + steering: { + send: (_runtime, _sessionId, text) => + Effect.gen(function* () { + steeredTexts.push(text); + const outcome = steerOutcomes.shift() ?? { _tag: "accept" as const }; + if (outcome._tag === "fail") { + return yield* new EffectAcpErrors.AcpRequestError({ + code: -32603, + errorMessage: "Steering rejected", + method: "_test/steer", + }); + } + if (outcome._tag === "waitId") { + yield* Deferred.succeed(outcome.sent, undefined); + return outcome.steerId; + } + return undefined; + }), + injectedSteerId: (notification) => { + if (notification.update.sessionUpdate !== "session_info_update") return undefined; + const meta = notification.update._meta as + | { readonly injectedSteerId?: string } + | undefined; + return meta?.injectedSteerId; + }, + }, + makeRuntime: makeMockRuntime({ + childProcessSpawner, + mockAgentPath, + wrapRuntime: (runtime) => ({ + ...runtime, + handleSessionUpdate: (handler) => + Effect.sync(() => { + sessionUpdateHandler = handler; + }).pipe(Effect.andThen(runtime.handleSessionUpdate(handler))), + prompt: (payload, promptOptions) => + Effect.gen(function* () { + prompts.push( + payload.prompt + .flatMap((block) => (block.type === "text" ? [block.text] : [])) + .join("\n"), + ); + if (promptOptions?.dispatched) { + yield* Deferred.succeed(promptOptions.dispatched, undefined); + } + const next = promptGates.shift(); + if (next === undefined) return { stopReason: "end_turn" as const }; + yield* Deferred.succeed(next.started, undefined); + return yield* Deferred.await(next.gate); + }), + }), + }), + }, + }); + 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-app-context-native-steer", + ), + modelSelection, + runtimePolicy, + }); + const providerThread = yield* runtime.ensureThread({ + threadId, + modelSelection, + runtimePolicy, + }); + const sessionId = providerThread.nativeThreadRef?.nativeId; + if (sessionId == null) return assert.fail("expected native session id"); + const tag = (note: string) => `${note}`; + const providerTurnIdFor = (ordinal: number) => + idAllocator.derive.providerTurn({ + driver: ACP_TEST_DRIVER, + nativeTurnId: acpScopedNativeId(instanceId, `${sessionId}:turn:${ordinal}`), + }); + const steer = (ordinal: number, text: string, note: string) => + runtime.steerTurn({ + threadId, + runId: RunId.make(`run:${threadId}:${ordinal}`), + providerThread, + providerTurnId: providerTurnIdFor(ordinal), + message: { + createdBy: "user", + creationSource: "web", + messageId: MessageId.make(`native-steer-${ordinal}-${steeredTexts.length}`), + text, + attachments: [], + }, + appContext: [{ key: "mcp_app_item-1", text: note }], + }); + + const turn1 = yield* queueGate(); + yield* runtime.startTurn({ + ...makeTurnInput({ + threadId, + providerThread, + instanceId, + runtimePolicy, + now: yield* DateTime.now, + ordinal: 1, + messageText: "Start native turn 1", + }), + appContext: [{ key: "mcp_app_item-1", text: "Note A" }], + }); + yield* Deferred.await(turn1.started); + assert.include(prompts.at(-1) ?? "", tag("Note A")); + + // Unchanged note is omitted on native steer. + steerOutcomes.push({ _tag: "accept" }); + yield* steer(1, "Keep working", "Note A"); + assert.equal(steeredTexts.at(-1), "Keep working"); + + // Slash steer skips appContext injection. + steerOutcomes.push({ _tag: "accept" }); + yield* steer(1, "/status", "Note B"); + assert.equal(steeredTexts.at(-1), "/status"); + + // Rejected steering.send must not mark Note B delivered. + steerOutcomes.push({ _tag: "fail" }); + const failedExit = yield* Effect.exit(steer(1, "Failed steer", "Note B")); + assert.isTrue(Exit.isFailure(failedExit)); + assert.include(steeredTexts.at(-1) ?? "", tag("Note B")); + + // Next steer with Note B resends it and marks it delivered once accepted. + steerOutcomes.push({ _tag: "accept" }); + yield* steer(1, "Retry Note B", "Note B"); + assert.include(steeredTexts.at(-1) ?? "", tag("Note B")); + + // Repeated steer with Note B omits it. + steerOutcomes.push({ _tag: "accept" }); + yield* steer(1, "After Note B", "Note B"); + assert.equal(steeredTexts.at(-1), "After Note B"); + + // Completing turn 1 must not clobber Note B with Turn 1's earlier Note A. + yield* Deferred.succeed(turn1.gate, { stopReason: "end_turn" }); + yield* runtime.events.pipe( + Stream.takeUntil((event) => event.type === "turn.terminal"), + Stream.runDrain, + ); + + const turn2 = yield* queueGate(); + yield* runtime.startTurn({ + ...makeTurnInput({ + threadId, + providerThread, + instanceId, + runtimePolicy, + now: yield* DateTime.now, + ordinal: 2, + messageText: "Start native turn 2", + }), + appContext: [{ key: "mcp_app_item-1", text: "Note B" }], + }); + yield* Deferred.await(turn2.started); + assert.notInclude(prompts.at(-1) ?? "", "external_mcp_app_item-1"); + + // A queued steer whose turn settles before injection must not mark Note C delivered. + const droppedSteerSent = yield* Deferred.make(); + steerOutcomes.push({ + _tag: "waitId", + steerId: "steer-dropped-1", + sent: droppedSteerSent, + }); + const droppedSteerFiber = yield* Effect.forkScoped( + Effect.exit(steer(2, "Dropped steer", "Note C")), + ); + yield* Deferred.await(droppedSteerSent); + yield* Deferred.succeed(turn2.gate, { stopReason: "end_turn" }); + const droppedExit = yield* Fiber.join(droppedSteerFiber); + assert.isTrue(Exit.isFailure(droppedExit)); + yield* runtime.events.pipe( + Stream.takeUntil((event) => event.type === "turn.terminal"), + Stream.runDrain, + ); + + // Turn 3 must resend Note C; also verify injected steerId delivery works when notified. + const turn3 = yield* queueGate(); + yield* runtime.startTurn({ + ...makeTurnInput({ + threadId, + providerThread, + instanceId, + runtimePolicy, + now: yield* DateTime.now, + ordinal: 3, + messageText: "Start native turn 3", + }), + appContext: [{ key: "mcp_app_item-1", text: "Note C" }], + }); + yield* Deferred.await(turn3.started); + assert.include(prompts.at(-1) ?? "", tag("Note C")); + + const injectedSteerSent = yield* Deferred.make(); + steerOutcomes.push({ + _tag: "waitId", + steerId: "steer-injected-1", + sent: injectedSteerSent, + }); + const injectedSteerFiber = yield* Effect.forkScoped(steer(3, "Injected steer", "Note D")); + yield* Deferred.await(injectedSteerSent); + yield* sessionUpdateHandler!({ + sessionId, + update: { + sessionUpdate: "session_info_update", + _meta: { injectedSteerId: "steer-injected-1" }, + }, + }); + yield* Fiber.join(injectedSteerFiber); + assert.include(steeredTexts.at(-1) ?? "", tag("Note D")); + yield* Deferred.succeed(turn3.gate, { stopReason: "end_turn" }); + yield* runtime.events.pipe( + Stream.takeUntil((event) => event.type === "turn.terminal"), + Stream.runDrain, + ); + + // Turn 4 sees Note D already delivered. + yield* runtime.startTurn({ + ...makeTurnInput({ + threadId, + providerThread, + instanceId, + runtimePolicy, + now: yield* DateTime.now, + ordinal: 4, + messageText: "Start native turn 4", + }), + appContext: [{ key: "mcp_app_item-1", text: "Note D" }], + }); + yield* runtime.events.pipe( + Stream.takeUntil((event) => event.type === "turn.terminal"), + Stream.runDrain, + ); + assert.notInclude(prompts.at(-1) ?? "", "external_mcp_app_item-1"); + }).pipe(Effect.provide(layerTest)), + ); }); describe("acpPostSettleContinuationOfferEvidence", () => { diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts index 8905317d20f5..c1ec17474f58 100644 --- a/packages/provider-acp/src/server/adapter.ts +++ b/packages/provider-acp/src/server/adapter.ts @@ -164,6 +164,34 @@ function isAgentBusyPromptError(error: EffectAcpErrors.AcpError): boolean { ); } +type AcpAppContextEntry = NonNullable< + ProviderAdapter.ProviderAdapterV2TurnInput["appContext"] +>[number]; + +function formatAcpAppContextEntry(entry: AcpAppContextEntry): string { + return `${entry.text}`; +} + +function unsentAcpAppContext( + appContext: ProviderAdapter.ProviderAdapterV2TurnInput["appContext"], + seen: ReadonlyMap | undefined, + isNativeSlashCommand: boolean, +): ReadonlyArray { + if (isNativeSlashCommand || appContext === undefined || appContext.length === 0) return []; + return appContext.filter((entry) => seen?.get(entry.key) !== entry.text); +} + +function mergeAcpAppContext( + base: ReadonlyMap | undefined, + entries: ReadonlyArray, +): ReadonlyMap { + const merged = new Map(base); + for (const entry of entries) { + merged.set(entry.key, entry.text); + } + return merged; +} + function sendPromptWhenIdle( turn: { readonly interrupted: boolean; readonly finalized: boolean }, prompt: () => Effect.Effect, @@ -1667,6 +1695,9 @@ interface ActiveAcpTurn { readonly completed: Deferred.Deferred; readonly itemOrdinals: Map; readonly outgoingPrompt?: ReadonlyArray | undefined; + appContextOffered?: ReadonlyMap | undefined; + readonly appContextCommittedSequence: Map; + appContextSequence: number; consumedPromptMessageId?: string; readonly user: ActiveTextStream; readonly assistant: ActiveTextStream; @@ -2343,6 +2374,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( >(null); const promptInstructionStates = yield* Ref.make(new Map()); const promptRuntimeInstructions = yield* Ref.make(new Map()); + const deliveredAppContext = yield* Ref.make(new Map>()); // Unique markers keep delayed prompt completions from clearing later compactions. const compactionMarkers = yield* Ref.make(new Map()); // ACP may patch a completed compaction again; each compaction id marks its session once. @@ -2365,6 +2397,17 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( yield* Ref.update(compactionMarkers, (current) => new Map(current).set(sessionId, Symbol()), ); + yield* Ref.update(deliveredAppContext, (current) => { + if (!current.has(sessionId)) return current; + const updated = new Map(current); + updated.delete(sessionId); + return updated; + }); + const currentTurn = yield* Ref.get(activeTurn); + if (currentTurn !== null && currentTurn.nativeThreadId === sessionId) { + currentTurn.appContextOffered = undefined; + currentTurn.appContextCommittedSequence.clear(); + } }); const advertisedCommandNames = yield* SubscriptionRef.make( new Map>(), @@ -8004,6 +8047,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( yield* Ref.set(activeInteractionMode, null); yield* Ref.set(promptInstructionStates, new Map()); yield* Ref.set(promptRuntimeInstructions, new Map()); + yield* Ref.set(deliveredAppContext, new Map()); yield* Ref.set(compactionMarkers, new Map()); yield* Ref.set(completedCompactionIds, new Set()); yield* Ref.set(providerTurns, new Map()); @@ -9108,6 +9152,12 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( // while the prompt is prepared still resends the notes in this prompt. const previousInstructionState = (yield* Ref.get(promptInstructionStates)).get(sessionId); const compactionMarker = (yield* Ref.get(compactionMarkers)).get(sessionId); + const deliveredContext = (yield* Ref.get(deliveredAppContext)).get(sessionId); + const appContextEntries = unsentAcpAppContext( + turnInput.appContext, + deliveredContext, + isNativeSlashCommand, + ); const text = t3AcpPromptWithInstructions({ prompt: messageText, state: instructionState, @@ -9140,6 +9190,14 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( detail: "ACP turn requires non-empty text or attachments", }); } + if (appContextEntries.length > 0) { + prompt.unshift( + ...appContextEntries.map((entry) => ({ + type: "text" as const, + text: formatAcpAppContextEntry(entry), + })), + ); + } if (sendRuntimeInstructions) { prompt.push({ type: "text", text: runtimeInstructions }); } @@ -9147,6 +9205,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( prompt, instructionState: text === messageText ? undefined : instructionState, runtimeInstructions: sendRuntimeInstructions ? runtimeInstructions : undefined, + appContextEntries, compactionMarker, }; }); @@ -9165,12 +9224,44 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( // A failed prompt may have been dropped, so the fresh runtime sends T3's notes again. yield* Ref.set(promptInstructionStates, new Map()); yield* Ref.set(promptRuntimeInstructions, new Map()); + yield* Ref.set(deliveredAppContext, new Map()); yield* Ref.set(compactionMarkers, new Map()); yield* Ref.set(completedCompactionIds, new Set()); yield* Ref.set(snapshot, emptySnapshotState()); return true; }); + const commitAcpAppContext = Effect.fnUntraced(function* (input: { + readonly context: ActiveAcpTurn; + readonly entries: ReadonlyArray; + readonly compactionMarker: symbol | undefined; + readonly sequence: number; + }) { + if (input.entries.length === 0) return; + if ( + (yield* Ref.get(compactionMarkers)).get(input.context.nativeThreadId) !== + input.compactionMarker + ) { + return; + } + const freshEntries = input.entries.filter( + (entry) => + (input.context.appContextCommittedSequence.get(entry.key) ?? 0) < input.sequence, + ); + if (freshEntries.length === 0) return; + for (const entry of freshEntries) { + input.context.appContextCommittedSequence.set(entry.key, input.sequence); + } + yield* Ref.update(deliveredAppContext, (current) => { + const updated = new Map(current); + updated.set( + input.context.nativeThreadId, + mergeAcpAppContext(current.get(input.context.nativeThreadId), freshEntries), + ); + return updated; + }); + }); + /** Follows a turn's `session/prompt`; a prompt-steer's prompt supersedes the one before. */ const followPrompt = ( context: ActiveAcpTurn, @@ -9183,11 +9274,28 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( | Effect.Success>> | undefined; readonly promptParts: Effect.Success> | null; + readonly appContext?: + | { + readonly entries: ReadonlyArray; + readonly offered: ReadonlyMap | undefined; + readonly before: ReadonlyMap | undefined; + readonly compactionMarker: symbol | undefined; + readonly sequence: number; + } + | undefined; readonly compactSession: AcpAdapterV2Flavor["compactSession"]; }, ): Effect.Effect => { const sequence = ++context.promptSequence; const superseded = () => context.promptSequence !== sequence; + const rollbackOfferedAppContext = () => { + if ( + settle.appContext?.offered !== undefined && + context.appContextOffered === settle.appContext.offered + ) { + context.appContextOffered = settle.appContext.before; + } + }; return prompt(superseded).pipe( // Settle the wire before the completion callback's permit so a settled-soft // Stop sees the native return. Capture usage only before finalize: a late @@ -9230,6 +9338,21 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( updated.set(context.nativeThreadId, promptParts.runtimeInstructions); return updated; }); + if ( + !context.interrupted && + !(context.finalized && context.finalizedStatus !== "completed") + ) { + if (settle.appContext !== undefined) { + yield* commitAcpAppContext({ + context, + entries: settle.appContext.entries, + compactionMarker: settle.appContext.compactionMarker, + sequence: settle.appContext.sequence, + }); + } + } else { + rollbackOfferedAppContext(); + } yield* Ref.update(compactionMarkers, (current) => { if (promptParts?.instructionState === undefined) return current; const observedMarker = promptParts.compactionMarker; @@ -9242,6 +9365,8 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( updated.delete(context.nativeThreadId); return updated; }); + } else { + rollbackOfferedAppContext(); } if (context.finalized || followsAgentWorkState || superseded()) return; // ACP v2 reports a failed prompt through its idle stop reason, not an RPC error. @@ -9363,6 +9488,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( runRuntimeCallbackAtGeneration( settle.generation, Effect.gen(function* () { + rollbackOfferedAppContext(); if (context.finalized || superseded()) return; const error = Cause.findError(cause); // Native close rejects prompts cancelled before insertion with -32800. @@ -9566,6 +9692,18 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( (yield* Ref.get(activeSessionSetup))?.initializeResult.protocolVersion === 2 ? promptParts?.prompt : undefined, + appContextOffered: + promptParts !== null && + promptParts.appContextEntries.length > 0 && + (yield* Ref.get(compactionMarkers)).get(requestedSessionId) === + promptParts.compactionMarker + ? mergeAcpAppContext( + (yield* Ref.get(deliveredAppContext)).get(requestedSessionId), + promptParts.appContextEntries, + ) + : undefined, + appContextCommittedSequence: new Map(), + appContextSequence: 0, user: { current: null, nextSegment: 0, closedNamedSegments: new Map() }, assistant: { current: null, nextSegment: 0, closedNamedSegments: new Map() }, reasoning: { current: null, nextSegment: 0, closedNamedSegments: new Map() }, @@ -9773,6 +9911,16 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( const compactSession = isCompactionMessage(turnInput.message) ? flavor.compactSession : undefined; + const initialAppContext = + promptParts !== null && promptParts.appContextEntries.length > 0 + ? { + entries: promptParts.appContextEntries, + offered: context.appContextOffered, + before: undefined, + compactionMarker: promptParts.compactionMarker, + sequence: ++context.appContextSequence, + } + : undefined; yield* followPrompt( context, (superseded) => @@ -9788,7 +9936,13 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( stopReason: "end_turn", } satisfies EffectAcpSchema.PromptResponse), ), - { generation: promptGeneration, checkPromptOutcome, promptParts, compactSession }, + { + generation: promptGeneration, + checkPromptOutcome, + promptParts, + appContext: initialAppContext, + compactSession, + }, ).pipe(Effect.forkIn(sessionScope)); }, (effect, turnInput) => @@ -9815,6 +9969,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( const steerWithPrompt = Effect.fn("AcpAdapterV2.steerWithPrompt")(function* ( turnInput: ProviderAdapter.ProviderAdapterV2SteerInput, ) { + const isNativeSlashCommand = turnInput.message.text.trimStart().startsWith("/"); const text = yield* providerMessageTextWithAttachmentPaths({ text: turnInput.message.text, attachments: turnInput.message.attachments, @@ -9849,6 +10004,43 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( generation, Effect.gen(function* () { if (context.finalized || context.interrupted) return false; + const compactionMarker = (yield* Ref.get(compactionMarkers)).get( + context.nativeThreadId, + ); + const seenAppContext = + context.appContextOffered ?? + (yield* Ref.get(deliveredAppContext)).get(context.nativeThreadId); + const appContextEntries = unsentAcpAppContext( + turnInput.appContext, + seenAppContext, + isNativeSlashCommand, + ); + const appContextBefore = context.appContextOffered; + const appContextOffered = + appContextEntries.length === 0 + ? undefined + : mergeAcpAppContext(seenAppContext, appContextEntries); + const steerAppContext = + appContextOffered === undefined + ? undefined + : { + entries: appContextEntries, + offered: appContextOffered, + before: appContextBefore, + compactionMarker, + sequence: ++context.appContextSequence, + }; + if (appContextOffered !== undefined) { + context.appContextOffered = appContextOffered; + } + const steerPrompt: Array = [ + ...appContextEntries.map((entry) => ({ + type: "text" as const, + text: formatAcpAppContextEntry(entry), + })), + { type: "text", text }, + ...attachmentBlocks, + ]; // The steer prompt carries the turn on, also past a prompt that already settled. const released = context.foregroundIdle; context.foregroundIdle = yield* Deferred.make(); @@ -9881,7 +10073,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( context, () => runtime.prompt( - { prompt: [{ type: "text", text }, ...attachmentBlocks] }, + { prompt: steerPrompt }, { dispatched, released: releasedForSteer }, ), superseded, @@ -9890,6 +10082,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( generation, checkPromptOutcome, promptParts: null, + appContext: steerAppContext, compactSession: undefined, }, ).pipe(Effect.forkIn(sessionScope)); @@ -10222,26 +10415,69 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( resolveAttachmentPath: host.resolveAttachmentPath, resolveExtractedTextPath: host.resolveExtractedTextPath, }); + const images = yield* imageAttachmentBlocks(turnInput.message.attachments); + const isNativeSlashCommand = turnInput.message.text.trimStart().startsWith("/"); + const compactionMarker = (yield* Ref.get(compactionMarkers)).get( + context.nativeThreadId, + ); + const seenAppContext = + context.appContextOffered ?? + (yield* Ref.get(deliveredAppContext)).get(context.nativeThreadId); + const appContextEntries = unsentAcpAppContext( + turnInput.appContext, + seenAppContext, + isNativeSlashCommand, + ); + const steerText = + appContextEntries.length === 0 + ? text + : text.length > 0 + ? `${appContextEntries.map(formatAcpAppContextEntry).join("\n")}\n\n${text}` + : appContextEntries.map(formatAcpAppContextEntry).join("\n"); + const appContextSequence = + appContextEntries.length === 0 ? 0 : ++context.appContextSequence; const steerId = yield* steering.send( runtime, context.nativeThreadId, - text, - yield* imageAttachmentBlocks(turnInput.message.attachments), + steerText, + images, ); - if (steerId === undefined) return; - const injected = steerInjection(steerId); - // The agent reads a steer at its next step. One that lands after the last - // step is dropped, and the turn settles right after; the orchestrator then - // sends it as a follow-up. The bound keeps Stop from queueing behind a tool. - const outcome = yield* Effect.raceFirst( - Deferred.await(injected).pipe(Effect.as("injected" as const)), - Deferred.await(context.promptWireSettled).pipe(Effect.as("settled" as const)), - ).pipe(Effect.timeoutOption(STEER_DELIVERY_BOUND)); - steerInjections.delete(steerId); - if (Option.contains(outcome, "settled") && !(yield* Deferred.isDone(injected))) { - return yield* new ProviderAdapter.ProviderAdapterProtocolError({ - driver, - detail: `Provider turn ${turnInput.providerTurnId} ended before it read the steering message.`, + let steerConfirmed = true; + if (steerId !== undefined) { + const injected = steerInjection(steerId); + // The agent reads a steer at its next step. One that lands after the last + // step is dropped, and the turn settles right after; the orchestrator then + // sends it as a follow-up. The bound keeps Stop from queueing behind a tool. + const outcome = yield* Effect.raceFirst( + Deferred.await(injected).pipe(Effect.as("injected" as const)), + Deferred.await(context.promptWireSettled).pipe(Effect.as("settled" as const)), + ).pipe(Effect.timeoutOption(STEER_DELIVERY_BOUND)); + steerInjections.delete(steerId); + if (Option.contains(outcome, "settled") && !(yield* Deferred.isDone(injected))) { + return yield* new ProviderAdapter.ProviderAdapterProtocolError({ + driver, + detail: `Provider turn ${turnInput.providerTurnId} ended before it read the steering message.`, + }); + } + // A steer still unread at the bound may yet be dropped, so its notes stay unsent. + steerConfirmed = yield* Deferred.isDone(injected); + } + if ( + steerConfirmed && + appContextEntries.length > 0 && + !context.interrupted && + (yield* Ref.get(compactionMarkers)).get(context.nativeThreadId) === compactionMarker + ) { + context.appContextOffered = mergeAcpAppContext( + context.appContextOffered ?? + (yield* Ref.get(deliveredAppContext)).get(context.nativeThreadId), + appContextEntries, + ); + yield* commitAcpAppContext({ + context, + entries: appContextEntries, + compactionMarker, + sequence: appContextSequence, }); } },