diff --git a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts index b18fa1df947f1..32d6b8172abf2 100644 --- a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts @@ -1082,6 +1082,8 @@ const openSessionWithRunningCommand = Effect.fn("openSessionWithRunningCommand") commandInput: Record, /** The prompt launches one agy 1.5 subagent instead; its records live below this profile. */ detachedChildProfile?: string, + /** agy 1.5.11 answers a steered prompt once the next one arrives, which runs to `releaseSteer`. */ + steering?: { readonly agentVersion: string; readonly holdsFirstPrompt: boolean }, ) { const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; const path = yield* Path.Path; @@ -1103,6 +1105,12 @@ const openSessionWithRunningCommand = Effect.fn("openSessionWithRunningCommand") rawInput: { CommandLine: "node fetch_throughput.mjs", ...commandInput }, } as const; let cancels = 0; + const prompts: Array<{ + readonly prompt: ReadonlyArray; + readonly released: Deferred.Deferred | undefined; + }> = []; + const steered = yield* Deferred.make(); + const releaseSteer = yield* Deferred.make(); let terminate: AntigravityAdapterV2RuntimeInput["onTermination"]; const usage = { sessionUpdate: "usage_update", used: 9000, size: 1048576 } as const; const offers: Array = []; @@ -1121,7 +1129,10 @@ const openSessionWithRunningCommand = Effect.fn("openSessionWithRunningCommand") command: process.execPath, args: [mockAgentPath], cwd: input.cwd, - env: { T3_ACP_ANTIGRAVITY: "1" }, + env: { + T3_ACP_ANTIGRAVITY: "1", + ...(steering === undefined ? {} : { T3_ACP_AGENT_VERSION: steering.agentVersion }), + }, }, }).pipe( Effect.provideService(SecureRandom.SecureRandom, crypto), @@ -1138,8 +1149,17 @@ const openSessionWithRunningCommand = Effect.fn("openSessionWithRunningCommand") Effect.sync(() => { requestPermission = handler; }).pipe(Effect.andThen(runtime.handleRequestPermission(handler))), - prompt: () => + prompt: (payload, promptOptions) => Effect.gen(function* () { + prompts.push({ prompt: payload.prompt, released: promptOptions?.released }); + if (promptOptions?.dispatched !== undefined) { + yield* Deferred.succeed(promptOptions.dispatched, undefined); + } + if (prompts.length > 1) { + yield* Deferred.succeed(steered, undefined); + yield* Deferred.await(releaseSteer); + return { stopReason: "end_turn" as const }; + } yield* send( detachedChildProfile === undefined ? { sessionUpdate: "tool_call", ...command, status: "in_progress" } @@ -1157,6 +1177,7 @@ const openSessionWithRunningCommand = Effect.fn("openSessionWithRunningCommand") content: { type: "text", text: "I'll render once the fetch finishes." }, }); yield* send(usage); + if (steering?.holdsFirstPrompt === true) yield* Deferred.await(steered); return { stopReason: "end_turn" as const }; }), })), @@ -1264,6 +1285,8 @@ const openSessionWithRunningCommand = Effect.fn("openSessionWithRunningCommand") ? Effect.die("the adapter must handle permission requests") : requestPermission(...args), cancels: () => cancels, + prompts, + releaseSteer: Deferred.succeed(releaseSteer, undefined), runtimeDies: Effect.suspend( () => terminate?.( @@ -1375,6 +1398,156 @@ describe("AntigravityAdapterV2 work after the prompt ends", () => { }).pipe(Effect.provide(layerSession)), ); + // agy 1.5.11 reads a prompt sent mid-turn as a steer: it answers the running prompt end_turn + // and goes on under the new one. session/cancel would end its running commands and subagents. + it.effect("steers a running prompt with the next one and leaves its work running", () => + Effect.gen(function* () { + const opened = yield* openSessionWithRunningCommand({}, undefined, { + agentVersion: "1.5.11", + holdsFirstPrompt: true, + }); + const { session, providerThread, command, usage, send, startTurn, until } = opened; + assert.isTrue(session.providerSession.capabilities.turns.supportsActiveSteering); + yield* startTurn(1, false); + const started = yield* until( + (event) => + event.type === "turn_item.updated" && + event.turnItem.nativeItemRef?.nativeId === command.toolCallId, + ); + const providerTurnId = started.flatMap((event) => + event.type === "provider_turn.updated" ? [event.providerTurn.id] : [], + )[0]!; + yield* send({ + sessionUpdate: "tool_call", + toolCallId: "call_artist", + kind: "other", + title: "Run invoke_subagent", + status: "completed", + rawInput: { Role: "Artist", Prompt: "Paint the scooter" }, + }); + + yield* session.steerTurn({ + threadId: ThreadId.make("thread-antigravity-wake"), + runId: RunId.make("run-antigravity-wake-1"), + providerThread, + providerTurnId, + message: { + messageId: MessageId.make("message-antigravity-steer"), + text: "Use opus subagents from now on", + attachments: [], + createdBy: "user", + creationSource: "web", + }, + }); + assert.equal(opened.cancels(), 0, "a steer must not cancel the agent's work"); + assert.lengthOf(opened.prompts, 2); + assert.deepEqual(opened.prompts[1]!.prompt, [ + { type: "text", text: "Use opus subagents from now on" }, + ]); + assert.isTrue( + yield* Deferred.isDone(opened.prompts[0]!.released!), + "the steered prompt frees the runtime for the steer", + ); + // The steered prompt has answered end_turn; the turn must outlast the finalize debounce. + yield* TestClock.adjust("10 seconds"); + + yield* send({ + sessionUpdate: "tool_call_update", + ...command, + status: "completed", + rawOutput: { output: "Command exited with code 0.", exit_code: 0 }, + }); + yield* send({ + sessionUpdate: "agent_message_chunk", + content: { type: "text", text: "Switching to opus subagents." }, + }); + yield* send(usage); + yield* opened.releaseSteer; + const run = [...started, ...(yield* until((event) => event.type === "turn.terminal"))]; + const terminal = run.at(-1); + assert.equal(terminal?.type === "turn.terminal" && terminal.status, "completed"); + assert.include(JSON.stringify(run), "Switching to opus subagents."); + const finished = run.findLast( + (event) => + event.type === "turn_item.updated" && + event.turnItem.nativeItemRef?.nativeId === command.toolCallId, + ); + assert.equal(finished?.type === "turn_item.updated" && finished.turnItem.status, "completed"); + const subagentStatuses = run.flatMap((event) => + event.type === "subagent.updated" ? [event.subagent.status] : [], + ); + assert.notInclude(subagentStatuses, "interrupted"); + assert.equal(subagentStatuses.at(-1), "idle"); + }).pipe(Effect.provide(layerSession)), + ); + + it.effect("steers a run held open by a detached subagent without stopping it", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const profile = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-antigravity-kids-" }); + const records = (conversationId: string, kind: string) => + path.join(profile, "antigravity-acp", "brain", conversationId, ".system_generated", kind); + const write = (directory: string, name: string, value: unknown) => + fileSystem + .makeDirectory(directory, { recursive: true }) + .pipe( + Effect.andThen( + fileSystem.writeFileString(path.join(directory, name), JSON.stringify(value)), + ), + ); + yield* write(records("mock-session-1", "subagents"), "child-1.json", {}); + yield* write(records("child-1", "messages"), "launch.json", { + sender: "mock-session-1", + sourceMetadata: { tool: { toolCall: { id: "call_research", name: "invoke_subagent" } } }, + }); + const opened = yield* openSessionWithRunningCommand({}, profile, { + agentVersion: "1.5.11", + holdsFirstPrompt: false, + }); + const { session, providerThread, usage, send, startTurn, until, throughPromptSettled } = + opened; + yield* startTurn(1, false); + const prompt = yield* throughPromptSettled; + const providerTurnId = prompt.flatMap((event) => + event.type === "provider_turn.updated" ? [event.providerTurn.id] : [], + )[0]!; + yield* TestClock.adjust("10 minutes"); + + yield* session.steerTurn({ + threadId: ThreadId.make("thread-antigravity-wake"), + runId: RunId.make("run-antigravity-wake-1"), + providerThread, + providerTurnId, + message: { + messageId: MessageId.make("message-antigravity-steer"), + text: "Also check the footnotes", + attachments: [], + createdBy: "user", + creationSource: "web", + }, + }); + assert.equal(opened.cancels(), 0, "a steer must not cancel the agent's subagents"); + assert.lengthOf(opened.prompts, 2); + yield* write(records("mock-session-1", "messages"), "report.json", { sender: "child-1" }); + yield* send({ + sessionUpdate: "agent_message_chunk", + content: { type: "text", text: "I'll have the footnotes checked too." }, + }); + yield* send(usage); + yield* opened.releaseSteer; + const run = [...prompt, ...(yield* until((event) => event.type === "turn.terminal"))]; + const terminal = run.at(-1); + assert.equal(terminal?.type === "turn.terminal" && terminal.status, "completed"); + assert.include(JSON.stringify(run), "I'll have the footnotes checked too."); + const subagentStatuses = run.flatMap((event) => + event.type === "subagent.updated" ? [event.subagent.status] : [], + ); + assert.notInclude(subagentStatuses, "interrupted"); + assert.equal(subagentStatuses.at(-1), "idle"); + }).pipe(Effect.provide(layerSession)), + ); + // Files as agy 1.5.12 wrote them: the launch sits in the child's inbox, and the child's report // lands in the parent's inbox with no session update. Only the agent's own reply follows. it.effect.each([ diff --git a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts index 0307c4ba18822..21dcd613b55e9 100644 --- a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts @@ -23,6 +23,7 @@ import { antigravityAppendsSystemPrompt, antigravityPermissionMode, antigravityRuntimeModeForSessionMode, + antigravitySteersWithPrompt, applyAntigravityAcpModelSelection, buildAntigravityPrompt, type AntigravityAcpRuntimeInput, @@ -254,6 +255,8 @@ export function makeAntigravityAcpAdapterFlavor( // session/cancel ends the agent's running commands, so only Stop sends it once the prompt // has ended. A message sent while a command runs leaves the command alone. preserveRuntimeOnSettledInterrupt: true, + // `agy acp` reads a prompt sent mid-turn as a steer; cancel-and-restart killed its subagents. + steersWithPrompt: antigravitySteersWithPrompt, ...(options.onSessionEvent === undefined ? {} : { onSessionEvent: options.onSessionEvent }), applyModelSelection: Effect.fn("AntigravityAdapterV2.applyModelSelection")(function* ({ runtime, diff --git a/apps/server/src/provider/acp/AntigravityAcpSupport.ts b/apps/server/src/provider/acp/AntigravityAcpSupport.ts index 7fd64e2534fa7..67dff6d07b039 100644 --- a/apps/server/src/provider/acp/AntigravityAcpSupport.ts +++ b/apps/server/src/provider/acp/AntigravityAcpSupport.ts @@ -88,6 +88,15 @@ export function isQualifiedAntigravityRelease(version: string | null | undefined // `agy acp` 1.5.1 offers every model to every ACP client; older runtimes allowlist editors. const OPEN_MODEL_ACCESS_RELEASE = [1, 5, 1] as const; +// `agy acp` 1.5.0 steers a running turn with the next prompt; the 1.4 harness queues it. +const PROMPT_STEERING_RELEASE = [1, 5, 0] as const; + +export const antigravitySteersWithPrompt = ( + initializeResult: EffectAcpSchema.InitializeResponse, +) => { + const parsed = parseAntigravityVersion(initializeResult.agentInfo?.version); + return parsed !== undefined && compareVersions(parsed, PROMPT_STEERING_RELEASE) >= 0; +}; /** * 1.4.5 appends `systemPrompt.append` to its system instructions on new, load and resume, and diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts index 7ae4c2dee8b62..f1c49c9838bc4 100644 --- a/packages/provider-acp/src/server/adapter.ts +++ b/packages/provider-acp/src/server/adapter.ts @@ -158,9 +158,10 @@ function isAgentBusyPromptError(error: EffectAcpErrors.AcpError): boolean { function sendPromptWhenIdle( turn: { readonly interrupted: boolean; readonly finalized: boolean }, prompt: () => Effect.Effect, + superseded: () => boolean = () => false, ): Effect.Effect { - // A Stop can land during the wait, so the flags are rechecked before each resend. - const stopped = () => turn.interrupted || turn.finalized; + // A Stop or a prompt-steer can land during the wait, so both are rechecked before each resend. + const stopped = () => turn.interrupted || turn.finalized || superseded(); return prompt().pipe( Effect.catchIf( (error) => isAgentBusyPromptError(error) && !stopped(), @@ -168,7 +169,7 @@ function sendPromptWhenIdle( Effect.sleep(ACP_BUSY_PROMPT_RETRY_INTERVAL).pipe( Effect.andThen( Effect.suspend(() => - stopped() ? Effect.fail(error) : sendPromptWhenIdle(turn, prompt), + stopped() ? Effect.fail(error) : sendPromptWhenIdle(turn, prompt, superseded), ), ), ), @@ -297,6 +298,28 @@ class AcpModelSelectionError extends Schema.TaggedError( } } +/** A prompt-steered turn spans several prompts, each reporting its own usage. */ +function addAcpUsage( + total: EffectAcpSchema.Usage | undefined, + usage: EffectAcpSchema.Usage | null | undefined, +): EffectAcpSchema.Usage | undefined { + if (usage == null) return total; + if (total === undefined) return usage; + const optional = (left: number | null | undefined, right: number | null | undefined) => + left == null && right == null ? {} : { value: (left ?? 0) + (right ?? 0) }; + const thought = optional(total.thoughtTokens, usage.thoughtTokens); + const cachedRead = optional(total.cachedReadTokens, usage.cachedReadTokens); + const cachedWrite = optional(total.cachedWriteTokens, usage.cachedWriteTokens); + return { + totalTokens: total.totalTokens + usage.totalTokens, + inputTokens: total.inputTokens + usage.inputTokens, + outputTokens: total.outputTokens + usage.outputTokens, + ...("value" in thought ? { thoughtTokens: thought.value } : {}), + ...("value" in cachedRead ? { cachedReadTokens: cachedRead.value } : {}), + ...("value" in cachedWrite ? { cachedWriteTokens: cachedWrite.value } : {}), + }; +} + /** * Maps one per-turn usage sample (flavors with reportsPerTurnPromptUsage) * directly onto TurnTokenUsage: the response's counters already cover exactly @@ -531,6 +554,13 @@ export interface AcpAdapterV2Flavor { notification: EffectAcpSchema.SessionNotification, ) => string | undefined; }; + /** + * Steers with another `session/prompt` while one runs: the agent answers the running prompt + * `end_turn` and carries the turn on under the new one, leaving its tools and subagents alone. + */ + readonly steersWithPrompt?: ( + initializeResult: AcpSessionRuntime.AcpSessionRuntimeStartResult["initializeResult"], + ) => boolean; /** * Native fork from an earlier turn. `nativeTurnId` reads the agent's id for a running * turn's prompt, which the turn keeps as its native ref; forking from that turn sends @@ -908,6 +938,7 @@ function negotiatedCapabilities( started: AcpSessionRuntime.AcpSessionRuntimeStartResult, modelOptionArrivesLate: boolean, forksFromTurn: boolean, + steersWithPrompt: boolean, ): OrchestrationV2ProviderCapabilities { const agent = started.initializeResult.agentCapabilities ?? {}; const session = agent.sessionCapabilities; @@ -930,6 +961,10 @@ function negotiatedCapabilities( canForkThread: canFork, canForkFromTurn: canFork && forksFromTurn, }, + turns: { + ...base.turns, + supportsActiveSteering: base.turns.supportsActiveSteering || steersWithPrompt, + }, tools: { ...base.tools, supportsMcpTools: true, @@ -1621,11 +1656,14 @@ interface ActiveAcpTurn { promptSettled: boolean; promptSettledStatus: "completed" | "interrupted" | "failed" | "cancelled" | null; workAccepted: boolean; - readonly promptWireSettled: Deferred.Deferred; + /** Settles with the turn's latest prompt; a prompt-steer replaces a settled one. */ + promptWireSettled: Deferred.Deferred; /** Completed once `session/prompt` is the runtime's active prompt. */ readonly promptDispatched: Deferred.Deferred; /** Frees the runtime for the next prompt while the agent still holds this one's response. */ - readonly foregroundIdle: Deferred.Deferred; + foregroundIdle: Deferred.Deferred; + /** Counts the turn's prompts; only the latest one settles the turn. */ + promptSequence: number; /** Clock millis just before `session/prompt` was handed to the runtime. */ promptSentAt: number | null; /** Completed when an update after dispatch matches `cancelAfterPromptStarts.isStart`. */ @@ -7827,11 +7865,13 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( yield* setActiveSessionSetup(started); rememberTerminalEnvironment(started.sessionId, yield* readMcpContext(input.threadId)); yield* runtime.drainEvents; + const steersWithPrompt = flavor.steersWithPrompt?.(started.initializeResult) === true; const capabilities = negotiatedCapabilities( yield* readCapabilities, started, flavor.modelOptionArrivesLate === true, flavor.forkFromTurn?.supported(started.initializeResult) === true, + steersWithPrompt, ); const canLoadSession = started.initializeResult.agentCapabilities?.loadSession === true; const canResumeSession = @@ -8659,6 +8699,49 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( return blocks; }); + const promptAttachmentBlocks = Effect.fnUntraced(function* ( + messageText: string, + attachments: ReadonlyArray, + ) { + if (!supportsImagePrompts && attachments.some(isProviderNativeImageAttachment)) { + return yield* new ProviderAdapter.ProviderAdapterProtocolError({ + driver, + detail: "ACP driver did not negotiate image prompt support", + }); + } + if (!flavor.buildAttachmentPrompt) return yield* imageAttachmentBlocks(attachments); + const setup = yield* Ref.get(activeSessionSetup); + const modelOption = findModelConfigOption(yield* runtime.getConfigOptions); + const currentModelId = modelOption?.currentValue; + return yield* flavor + .buildAttachmentPrompt({ + text: messageText, + attachments, + resolveAttachmentPath: host.resolveAttachmentPath, + promptCapabilities: setup?.initializeResult.agentCapabilities?.promptCapabilities, + agentVersion: setup?.initializeResult.agentInfo?.version, + currentModel: + typeof currentModelId !== "string" || modelOption === undefined + ? undefined + : { + id: currentModelId, + name: flattenSelectChoices(modelOption.options).find( + (choice) => choice.value === currentModelId, + )?.name, + }, + }) + .pipe( + Effect.mapError( + (cause) => + new ProviderAdapter.ProviderAdapterProtocolError({ + driver, + detail: "Failed to build ACP attachment prompt", + payload: cause, + }), + ), + ); + }); + const resolvePromptParts = Effect.fnUntraced(function* ( turnInput: ProviderAdapter.ProviderAdapterV2TurnInput, sessionId: string, @@ -8687,51 +8770,10 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( resolveExtractedTextPath: host.resolveExtractedTextPath, }); const isNativeSlashCommand = userText.trimStart().startsWith("/"); - if ( - !supportsImagePrompts && - turnInput.message.attachments.some(isProviderNativeImageAttachment) - ) { - return yield* new ProviderAdapter.ProviderAdapterProtocolError({ - driver, - detail: "ACP driver did not negotiate image prompt support", - }); - } - const attachmentBlocks = flavor.buildAttachmentPrompt - ? [] - : yield* imageAttachmentBlocks(turnInput.message.attachments); - if (flavor.buildAttachmentPrompt) { - const setup = yield* Ref.get(activeSessionSetup); - const modelOption = findModelConfigOption(yield* runtime.getConfigOptions); - const currentModelId = modelOption?.currentValue; - const blocks = yield* flavor - .buildAttachmentPrompt({ - text: messageText, - attachments: turnInput.message.attachments, - resolveAttachmentPath: host.resolveAttachmentPath, - promptCapabilities: setup?.initializeResult.agentCapabilities?.promptCapabilities, - agentVersion: setup?.initializeResult.agentInfo?.version, - currentModel: - typeof currentModelId !== "string" || modelOption === undefined - ? undefined - : { - id: currentModelId, - name: flattenSelectChoices(modelOption.options).find( - (choice) => choice.value === currentModelId, - )?.name, - }, - }) - .pipe( - Effect.mapError( - (cause) => - new ProviderAdapter.ProviderAdapterProtocolError({ - driver, - detail: "Failed to build ACP attachment prompt", - payload: cause, - }), - ), - ); - attachmentBlocks.push(...blocks); - } + const attachmentBlocks = yield* promptAttachmentBlocks( + messageText, + turnInput.message.attachments, + ); // Read delivery state after the awaits above, so a compaction that lands // while the prompt is prepared still resends the notes in this prompt. const previousInstructionState = (yield* Ref.get(promptInstructionStates)).get(sessionId); @@ -8797,6 +8839,194 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( return true; }); + /** Follows a turn's `session/prompt`; a prompt-steer's prompt supersedes the one before. */ + const followPrompt = ( + context: ActiveAcpTurn, + prompt: ( + superseded: () => boolean, + ) => Effect.Effect, + settle: { + readonly generation: number; + readonly checkPromptOutcome: + | Effect.Success>> + | undefined; + readonly promptParts: Effect.Success> | null; + readonly compactSession: AcpAdapterV2Flavor["compactSession"]; + }, + ) => { + const sequence = ++context.promptSequence; + const superseded = () => context.promptSequence !== sequence; + 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 + // response must not flip a settled turn. + Effect.tap((result) => + Effect.suspend(() => { + if (flavor.reportsPerTurnPromptUsage === true && !context.finalized) { + context.promptUsage = addAcpUsage(context.promptUsage, result.usage); + } + return superseded() + ? Effect.void + : Deferred.succeed(context.promptWireSettled, undefined).pipe(Effect.asVoid); + }), + ), + Effect.tap(() => options.testHooks?.afterPromptWireSettled?.() ?? Effect.void), + Effect.flatMap((result) => + runRuntimeCallbackAtGeneration( + settle.generation, + Effect.gen(function* () { + // Record delivery only for this runtime: a replacement can reuse the session id. + // Grok cancels locally, refusals discard the prompt, and errors need a retry. + // Native compaction sends no prompt, and the compacted session needs the notes. + if (settle.compactSession !== undefined) { + yield* markSessionCompacted(context.nativeThreadId); + } else if ( + result.stopReason !== "cancelled" && + result.stopReason !== "refusal" && + result.stopReason !== "error" + ) { + const promptParts = settle.promptParts; + yield* Ref.update(promptInstructionStates, (current) => { + if (promptParts?.instructionState === undefined) return current; + const updated = new Map(current); + updated.set(context.nativeThreadId, promptParts.instructionState); + return updated; + }); + yield* Ref.update(promptRuntimeInstructions, (current) => { + if (promptParts?.runtimeInstructions === undefined) return current; + const updated = new Map(current); + updated.set(context.nativeThreadId, promptParts.runtimeInstructions); + return updated; + }); + yield* Ref.update(compactionMarkers, (current) => { + if (promptParts?.instructionState === undefined) return current; + const observedMarker = promptParts.compactionMarker; + if ( + observedMarker === undefined || + current.get(context.nativeThreadId) !== observedMarker + ) + return current; + const updated = new Map(current); + updated.delete(context.nativeThreadId); + return updated; + }); + } + if (context.finalized || followsAgentWorkState || superseded()) return; + // ACP v2 reports a failed prompt through its idle stop reason, not an RPC error. + const hiddenFailure = + settle.checkPromptOutcome === undefined || + context.interrupted || + result.stopReason === "error" || + result.stopReason === "cancelled" + ? undefined + : yield* settle.checkPromptOutcome(result); + if (hiddenFailure !== undefined) { + yield* Ref.set(runtimeRestartRequired, true); + } + const failure = + hiddenFailure?.failure ?? + (context.interrupted + ? undefined + : stopReasonFailure(result.stopReason, result.error)); + const status = + failure !== undefined + ? "failed" + : result.stopReason === "cancelled" + ? context.interrupted + ? "interrupted" + : "cancelled" + : "completed"; + if (defersFinalizeForBackgroundWork && !context.interrupted) { + context.promptSettled = true; + context.promptSettledStatus = status; + for (const [taskId, completion] of context.backgroundCommands) { + if (completion === null) continue; + yield* finishRegisteredBackgroundTool({ taskId, ...completion }); + } + } + if (failure !== undefined) { + yield* terminalizeOpenForegroundTools(context, "failed"); + // Unlike an RPC failure, the agent survives an idle error, so its + // background tools and subagents keep reporting to this run. + yield* finalizeTurn(context, "failed", failure, { + childTurnsContinue: hasSurvivingBackgroundWork(context), + ...(hiddenFailure === undefined + ? {} + : { threadDisposition: hiddenFailure.threadDisposition }), + }); + return; + } + yield* idleReportedSubagents(context); + if (context.finalized) return; + if ( + defersFinalizeForBackgroundWork && + !context.interrupted && + hasDeferredBackgroundWork(context) + ) { + yield* closeTextStreams(context); + yield* ( + options.testHooks?.afterPromptSettledWithBackgroundWork?.() ?? Effect.void + ); + return; + } + yield* finalizeTurn(context, status); + }), + ).pipe( + Effect.andThen(() => options.testHooks?.afterPromptCallback?.() ?? Effect.void), + Effect.asVoid, + ), + ), + Effect.catchCause((cause) => + runRuntimeCallbackAtGeneration( + settle.generation, + Effect.gen(function* () { + if (context.finalized || superseded()) return; + const error = Cause.findError(cause); + // Native close rejects prompts cancelled before insertion with -32800. + const interrupted = + context.interrupted || + (pendingStopCloseTurn === context && + Result.isSuccess(error) && + error.success._tag === "AcpRequestError" && + error.success.code === -32800); + const failure = Cause.squash(cause); + if (!interrupted && flavor.restartRuntimeAfterPromptError?.(failure) === true) { + yield* Ref.set(runtimeRestartRequired, true); + } + // An agent that answered with an error may still finish tools it started, + // never pending ones; any other failure means its process or pipe is gone. + const agentAnswered = + Result.isSuccess(error) && error.success._tag === "AcpRequestError"; + if (!interrupted) { + yield* terminalizeOpenForegroundTools(context, "failed", { + unstartedOnly: agentAnswered, + }); + } + yield* finalizeTurn( + context, + interrupted ? "interrupted" : "failed", + flavor.promptFailure?.(failure) ?? + makeProviderFailure({ + cause: failure, + class: "provider_error", + }), + ).pipe( + Effect.andThen( + Effect.logWarning("orchestration-v2.acp-prompt-failed", { + driver, + providerSessionId: input.providerSessionId, + providerThreadId: context.input.providerThread.id, + providerTurnId: context.providerTurnId, + cause, + }), + ), + ); + }), + ).pipe(Effect.asVoid), + ), + ); + }; + const startTurnUnlocked = Effect.fn("AcpAdapterV2.startTurn")( function* (turnInput: ProviderAdapter.ProviderAdapterV2TurnInput) { yield* awaitRuntimeTeardown(); @@ -8967,6 +9197,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( promptWireSettled, promptDispatched, foregroundIdle: yield* Deferred.make(), + promptSequence: 0, promptSentAt: null, promptStarted, promptUsage: undefined, @@ -9142,185 +9373,23 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( const compactSession = isCompactionMessage(turnInput.message) ? flavor.compactSession : undefined; - yield* ( - compactSession === undefined - ? sendPromptWhenIdle(context, () => - runtime.prompt({ prompt: promptParts!.prompt }, promptOptions), - ) - : Deferred.succeed(context.promptDispatched, undefined).pipe( - Effect.andThen(compactSession.compact(runtime, requestedSessionId)), - Effect.as({ stopReason: "end_turn" } satisfies EffectAcpSchema.PromptResponse), - ) - ).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 - // response must not flip a settled turn. - Effect.tap((result) => - Effect.sync(() => { - if (flavor.reportsPerTurnPromptUsage === true && !context.finalized) { - context.promptUsage = result.usage ?? undefined; - } - }).pipe( - Effect.andThen( - Deferred.succeed(context.promptWireSettled, undefined).pipe(Effect.asVoid), - ), - ), - ), - Effect.tap(() => options.testHooks?.afterPromptWireSettled?.() ?? Effect.void), - Effect.flatMap((result) => - runRuntimeCallbackAtGeneration( - promptGeneration, - Effect.gen(function* () { - // Record delivery only for this runtime: a replacement can reuse the session id. - // Grok cancels locally, refusals discard the prompt, and errors need a retry. - // Native compaction sends no prompt, and the compacted session needs the notes. - if (compactSession !== undefined) { - yield* markSessionCompacted(requestedSessionId); - } else if ( - result.stopReason !== "cancelled" && - result.stopReason !== "refusal" && - result.stopReason !== "error" - ) { - yield* Ref.update(promptInstructionStates, (current) => { - if (promptParts?.instructionState === undefined) return current; - const updated = new Map(current); - updated.set(requestedSessionId, promptParts.instructionState); - return updated; - }); - yield* Ref.update(promptRuntimeInstructions, (current) => { - if (promptParts?.runtimeInstructions === undefined) return current; - const updated = new Map(current); - updated.set(requestedSessionId, promptParts.runtimeInstructions); - return updated; - }); - yield* Ref.update(compactionMarkers, (current) => { - if (promptParts?.instructionState === undefined) return current; - const observedMarker = promptParts.compactionMarker; - if ( - observedMarker === undefined || - current.get(requestedSessionId) !== observedMarker - ) - return current; - const updated = new Map(current); - updated.delete(requestedSessionId); - return updated; - }); - } - if (context.finalized || followsAgentWorkState) return; - // ACP v2 reports a failed prompt through its idle stop reason, not an RPC error. - const hiddenFailure = - checkPromptOutcome === undefined || - context.interrupted || - result.stopReason === "error" || - result.stopReason === "cancelled" - ? undefined - : yield* checkPromptOutcome(result); - if (hiddenFailure !== undefined) { - yield* Ref.set(runtimeRestartRequired, true); - } - const failure = - hiddenFailure?.failure ?? - (context.interrupted - ? undefined - : stopReasonFailure(result.stopReason, result.error)); - const status = - failure !== undefined - ? "failed" - : result.stopReason === "cancelled" - ? context.interrupted - ? "interrupted" - : "cancelled" - : "completed"; - if (defersFinalizeForBackgroundWork && !context.interrupted) { - context.promptSettled = true; - context.promptSettledStatus = status; - for (const [taskId, completion] of context.backgroundCommands) { - if (completion === null) continue; - yield* finishRegisteredBackgroundTool({ taskId, ...completion }); - } - } - if (failure !== undefined) { - yield* terminalizeOpenForegroundTools(context, "failed"); - // Unlike an RPC failure, the agent survives an idle error, so its - // background tools and subagents keep reporting to this run. - yield* finalizeTurn(context, "failed", failure, { - childTurnsContinue: hasSurvivingBackgroundWork(context), - ...(hiddenFailure === undefined - ? {} - : { threadDisposition: hiddenFailure.threadDisposition }), - }); - return; - } - yield* idleReportedSubagents(context); - if (context.finalized) return; - if ( - defersFinalizeForBackgroundWork && - !context.interrupted && - hasDeferredBackgroundWork(context) - ) { - yield* closeTextStreams(context); - yield* ( - options.testHooks?.afterPromptSettledWithBackgroundWork?.() ?? Effect.void - ); - return; - } - yield* finalizeTurn(context, status); - }), - ).pipe( - Effect.andThen(() => options.testHooks?.afterPromptCallback?.() ?? Effect.void), - Effect.asVoid, - ), - ), - Effect.catchCause((cause) => - runRuntimeCallbackAtGeneration( - promptGeneration, - Effect.gen(function* () { - if (context.finalized) return; - const error = Cause.findError(cause); - // Native close rejects prompts cancelled before insertion with -32800. - const interrupted = - context.interrupted || - (pendingStopCloseTurn === context && - Result.isSuccess(error) && - error.success._tag === "AcpRequestError" && - error.success.code === -32800); - const failure = Cause.squash(cause); - if (!interrupted && flavor.restartRuntimeAfterPromptError?.(failure) === true) { - yield* Ref.set(runtimeRestartRequired, true); - } - // An agent that answered with an error may still finish tools it started, - // never pending ones; any other failure means its process or pipe is gone. - const agentAnswered = - Result.isSuccess(error) && error.success._tag === "AcpRequestError"; - if (!interrupted) { - yield* terminalizeOpenForegroundTools(context, "failed", { - unstartedOnly: agentAnswered, - }); - } - yield* finalizeTurn( + yield* followPrompt( + context, + (superseded) => + compactSession === undefined + ? sendPromptWhenIdle( context, - interrupted ? "interrupted" : "failed", - flavor.promptFailure?.(failure) ?? - makeProviderFailure({ - cause: failure, - class: "provider_error", - }), - ).pipe( - Effect.andThen( - Effect.logWarning("orchestration-v2.acp-prompt-failed", { - driver, - providerSessionId: input.providerSessionId, - providerThreadId: turnInput.providerThread.id, - providerTurnId, - cause, - }), - ), - ); - }), - ).pipe(Effect.asVoid), - ), - Effect.forkIn(sessionScope), - ); + () => runtime.prompt({ prompt: promptParts!.prompt }, promptOptions), + superseded, + ) + : Deferred.succeed(context.promptDispatched, undefined).pipe( + Effect.andThen(compactSession.compact(runtime, requestedSessionId)), + Effect.as({ + stopReason: "end_turn", + } satisfies EffectAcpSchema.PromptResponse), + ), + { generation: promptGeneration, checkPromptOutcome, promptParts, compactSession }, + ).pipe(Effect.forkIn(sessionScope)); }, (effect, turnInput) => effect.pipe( @@ -9343,6 +9412,110 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( return yield* runtimeTransitionPermit.withPermit(startTurnUnlocked(turnInput)); }); + const steerWithPrompt = Effect.fn("AcpAdapterV2.steerWithPrompt")(function* ( + turnInput: ProviderAdapter.ProviderAdapterV2SteerInput, + ) { + const text = yield* providerMessageTextWithAttachmentPaths({ + text: turnInput.message.text, + attachments: turnInput.message.attachments, + resolveAttachmentPath: host.resolveAttachmentPath, + resolveExtractedTextPath: host.resolveExtractedTextPath, + }); + const attachmentBlocks = yield* promptAttachmentBlocks( + text, + turnInput.message.attachments, + ); + const dispatched = yield* runtimeTransitionPermit.withPermit( + Effect.gen(function* () { + const context = yield* Ref.get(activeTurn); + if ( + context === null || + context.finalized || + context.interrupted || + context.providerTurnId !== turnInput.providerTurnId + ) { + return yield* new ProviderAdapter.ProviderAdapterProtocolError({ + driver, + detail: `Provider turn ${turnInput.providerTurnId} is not active and cannot be steered.`, + }); + } + // A wake turn has no prompt of its own to steer; its reply ends the run soon. + if (context.promptSequence === 0) { + return yield* new ProviderAdapter.ProviderAdapterSteerDeclinedError({ + driver, + providerThreadId: turnInput.providerThread.id, + providerTurnId: turnInput.providerTurnId, + }); + } + const generation = yield* Ref.get(runtimeCallbackGeneration); + const checkPromptOutcome = + flavor.watchPromptOutcome === undefined + ? undefined + : yield* flavor.watchPromptOutcome(context.nativeThreadId); + const dispatched = yield* Deferred.make(); + const steered = yield* runRuntimeCallbackAtGeneration( + generation, + Effect.gen(function* () { + if (context.finalized || context.interrupted) return false; + // The steer prompt carries the turn on, also past a prompt that already settled. + const released = context.foregroundIdle; + context.foregroundIdle = yield* Deferred.make(); + if (yield* Deferred.isDone(context.promptWireSettled)) { + context.promptWireSettled = yield* Deferred.make(); + } + context.promptSettled = false; + context.promptSettledStatus = null; + context.backgroundFinalizeGeneration += 1; + context.promptSentAt = yield* Clock.currentTimeMillis; + context.lastProgressAt = context.promptSentAt; + const watchdog = context.inactivityWatchdog; + context.inactivityWatchdog = undefined; + if (watchdog !== undefined) { + yield* Fiber.interrupt(watchdog).pipe(Effect.forkDetach, Effect.asVoid); + } + if (promptInactivityTimeoutMillis !== undefined) { + context.inactivityWatchdog = yield* watchPromptInactivity( + context, + generation, + promptInactivityTimeoutMillis, + ).pipe(Effect.forkIn(sessionScope)); + } + const releasedForSteer = context.foregroundIdle; + yield* followPrompt( + context, + (superseded) => + sendPromptWhenIdle( + context, + () => + runtime.prompt( + { prompt: [{ type: "text", text }, ...attachmentBlocks] }, + { dispatched, released: releasedForSteer }, + ), + superseded, + ), + { + generation, + checkPromptOutcome, + promptParts: null, + compactSession: undefined, + }, + ).pipe(Effect.forkIn(sessionScope)); + yield* Deferred.succeed(released, undefined); + return true; + }), + ); + if (!Option.contains(steered, true)) { + return yield* new ProviderAdapter.ProviderAdapterProtocolError({ + driver, + detail: `Provider turn ${turnInput.providerTurnId} ended before it could be steered.`, + }); + } + return dispatched; + }), + ); + yield* Deferred.await(dispatched); + }); + yield* Effect.addFinalizer(() => Effect.gen(function* () { yield* continuationPermit.withPermit( @@ -9609,6 +9782,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( : {}), steerTurn: Effect.fn("AcpAdapterV2.steerTurn")( function* (turnInput) { + if (steersWithPrompt) return yield* steerWithPrompt(turnInput); const steering = flavor.steering; // A text-only steer leaves attachments to the orchestrator's restart. if ( @@ -9671,7 +9845,8 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( (effect, turnInput) => effect.pipe( Effect.mapError((cause) => - cause._tag === "ProviderAdapterSteerRunUnsupportedError" + cause._tag === "ProviderAdapterSteerRunUnsupportedError" || + cause._tag === "ProviderAdapterSteerDeclinedError" ? cause : new ProviderAdapter.ProviderAdapterSteerRunError({ driver,