@devries-cameron20 / t3code-1 / commits / cfd24da4a7
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

fix(server): steering an Antigravity turn no longer stops its subagents (#39165)

Co-authored-by: Julius Marminge <julius0216@outlook.com>

Denis Bolba committed Nov 19, 2026 at 18:20 UTC cfd24da4a7ed4df50962ee05c19a51da86389d1c
4 files changed +591 -231
apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts
+175 -2
@@ -1082,6 +1082,8 @@ const openSessionWithRunningCommand = Effect.fn("openSessionWithRunningCommand")
1082 commandInput: Record<string, unknown>,
1083 /** The prompt launches one agy 1.5 subagent instead; its records live below this profile. */
1084 detachedChildProfile?: string,
1085 + /** agy 1.5.11 answers a steered prompt once the next one arrives, which runs to `releaseSteer`. */
1086 + steering?: { readonly agentVersion: string; readonly holdsFirstPrompt: boolean },
1087 ) {
1088 const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
1089 const path = yield* Path.Path;
@@ -1103,6 +1105,12 @@ const openSessionWithRunningCommand = Effect.fn("openSessionWithRunningCommand")
1105 rawInput: { CommandLine: "node fetch_throughput.mjs", ...commandInput },
1106 } as const;
1107 let cancels = 0;
1108 + const prompts: Array<{
1109 + readonly prompt: ReadonlyArray<EffectAcpSchema.ContentBlock>;
1110 + readonly released: Deferred.Deferred<void> | undefined;
1111 + }> = [];
1112 + const steered = yield* Deferred.make<void>();
1113 + const releaseSteer = yield* Deferred.make<void>();
1114 let terminate: AntigravityAdapterV2RuntimeInput["onTermination"];
1115 const usage = { sessionUpdate: "usage_update", used: 9000, size: 1048576 } as const;
1116 const offers: Array<ProviderContinuationRequests.ProviderContinuationRequest> = [];
@@ -1121,7 +1129,10 @@ const openSessionWithRunningCommand = Effect.fn("openSessionWithRunningCommand")
1129 command: process.execPath,
1130 args: [mockAgentPath],
1131 cwd: input.cwd,
1124 - env: { T3_ACP_ANTIGRAVITY: "1" },
1132 + env: {
1133 + T3_ACP_ANTIGRAVITY: "1",
1134 + ...(steering === undefined ? {} : { T3_ACP_AGENT_VERSION: steering.agentVersion }),
1135 + },
1136 },
1137 }).pipe(
1138 Effect.provideService(SecureRandom.SecureRandom, crypto),
@@ -1138,8 +1149,17 @@ const openSessionWithRunningCommand = Effect.fn("openSessionWithRunningCommand")
1149 Effect.sync(() => {
1150 requestPermission = handler;
1151 }).pipe(Effect.andThen(runtime.handleRequestPermission(handler))),
1141 - prompt: () =>
1152 + prompt: (payload, promptOptions) =>
1153 Effect.gen(function* () {
1154 + prompts.push({ prompt: payload.prompt, released: promptOptions?.released });
1155 + if (promptOptions?.dispatched !== undefined) {
1156 + yield* Deferred.succeed(promptOptions.dispatched, undefined);
1157 + }
1158 + if (prompts.length > 1) {
1159 + yield* Deferred.succeed(steered, undefined);
1160 + yield* Deferred.await(releaseSteer);
1161 + return { stopReason: "end_turn" as const };
1162 + }
1163 yield* send(
1164 detachedChildProfile === undefined
1165 ? { sessionUpdate: "tool_call", ...command, status: "in_progress" }
@@ -1157,6 +1177,7 @@ const openSessionWithRunningCommand = Effect.fn("openSessionWithRunningCommand")
1177 content: { type: "text", text: "I'll render once the fetch finishes." },
1178 });
1179 yield* send(usage);
1180 + if (steering?.holdsFirstPrompt === true) yield* Deferred.await(steered);
1181 return { stopReason: "end_turn" as const };
1182 }),
1183 })),
@@ -1264,6 +1285,8 @@ const openSessionWithRunningCommand = Effect.fn("openSessionWithRunningCommand")
1285 ? Effect.die("the adapter must handle permission requests")
1286 : requestPermission(...args),
1287 cancels: () => cancels,
1288 + prompts,
1289 + releaseSteer: Deferred.succeed(releaseSteer, undefined),
1290 runtimeDies: Effect.suspend(
1291 () =>
1292 terminate?.(
@@ -1375,6 +1398,156 @@ describe("AntigravityAdapterV2 work after the prompt ends", () => {
1398 }).pipe(Effect.provide(layerSession)),
1399 );
1400
1401 + // agy 1.5.11 reads a prompt sent mid-turn as a steer: it answers the running prompt end_turn
1402 + // and goes on under the new one. session/cancel would end its running commands and subagents.
1403 + it.effect("steers a running prompt with the next one and leaves its work running", () =>
1404 + Effect.gen(function* () {
1405 + const opened = yield* openSessionWithRunningCommand({}, undefined, {
1406 + agentVersion: "1.5.11",
1407 + holdsFirstPrompt: true,
1408 + });
1409 + const { session, providerThread, command, usage, send, startTurn, until } = opened;
1410 + assert.isTrue(session.providerSession.capabilities.turns.supportsActiveSteering);
1411 + yield* startTurn(1, false);
1412 + const started = yield* until(
1413 + (event) =>
1414 + event.type === "turn_item.updated" &&
1415 + event.turnItem.nativeItemRef?.nativeId === command.toolCallId,
1416 + );
1417 + const providerTurnId = started.flatMap((event) =>
1418 + event.type === "provider_turn.updated" ? [event.providerTurn.id] : [],
1419 + )[0]!;
1420 + yield* send({
1421 + sessionUpdate: "tool_call",
1422 + toolCallId: "call_artist",
1423 + kind: "other",
1424 + title: "Run invoke_subagent",
1425 + status: "completed",
1426 + rawInput: { Role: "Artist", Prompt: "Paint the scooter" },
1427 + });
1428 +
1429 + yield* session.steerTurn({
1430 + threadId: ThreadId.make("thread-antigravity-wake"),
1431 + runId: RunId.make("run-antigravity-wake-1"),
1432 + providerThread,
1433 + providerTurnId,
1434 + message: {
1435 + messageId: MessageId.make("message-antigravity-steer"),
1436 + text: "Use opus subagents from now on",
1437 + attachments: [],
1438 + createdBy: "user",
1439 + creationSource: "web",
1440 + },
1441 + });
1442 + assert.equal(opened.cancels(), 0, "a steer must not cancel the agent's work");
1443 + assert.lengthOf(opened.prompts, 2);
1444 + assert.deepEqual(opened.prompts[1]!.prompt, [
1445 + { type: "text", text: "Use opus subagents from now on" },
1446 + ]);
1447 + assert.isTrue(
1448 + yield* Deferred.isDone(opened.prompts[0]!.released!),
1449 + "the steered prompt frees the runtime for the steer",
1450 + );
1451 + // The steered prompt has answered end_turn; the turn must outlast the finalize debounce.
1452 + yield* TestClock.adjust("10 seconds");
1453 +
1454 + yield* send({
1455 + sessionUpdate: "tool_call_update",
1456 + ...command,
1457 + status: "completed",
1458 + rawOutput: { output: "Command exited with code 0.", exit_code: 0 },
1459 + });
1460 + yield* send({
1461 + sessionUpdate: "agent_message_chunk",
1462 + content: { type: "text", text: "Switching to opus subagents." },
1463 + });
1464 + yield* send(usage);
1465 + yield* opened.releaseSteer;
1466 + const run = [...started, ...(yield* until((event) => event.type === "turn.terminal"))];
1467 + const terminal = run.at(-1);
1468 + assert.equal(terminal?.type === "turn.terminal" && terminal.status, "completed");
1469 + assert.include(JSON.stringify(run), "Switching to opus subagents.");
1470 + const finished = run.findLast(
1471 + (event) =>
1472 + event.type === "turn_item.updated" &&
1473 + event.turnItem.nativeItemRef?.nativeId === command.toolCallId,
1474 + );
1475 + assert.equal(finished?.type === "turn_item.updated" && finished.turnItem.status, "completed");
1476 + const subagentStatuses = run.flatMap((event) =>
1477 + event.type === "subagent.updated" ? [event.subagent.status] : [],
1478 + );
1479 + assert.notInclude(subagentStatuses, "interrupted");
1480 + assert.equal(subagentStatuses.at(-1), "idle");
1481 + }).pipe(Effect.provide(layerSession)),
1482 + );
1483 +
1484 + it.effect("steers a run held open by a detached subagent without stopping it", () =>
1485 + Effect.gen(function* () {
1486 + const fileSystem = yield* FileSystem.FileSystem;
1487 + const path = yield* Path.Path;
1488 + const profile = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-antigravity-kids-" });
1489 + const records = (conversationId: string, kind: string) =>
1490 + path.join(profile, "antigravity-acp", "brain", conversationId, ".system_generated", kind);
1491 + const write = (directory: string, name: string, value: unknown) =>
1492 + fileSystem
1493 + .makeDirectory(directory, { recursive: true })
1494 + .pipe(
1495 + Effect.andThen(
1496 + fileSystem.writeFileString(path.join(directory, name), JSON.stringify(value)),
1497 + ),
1498 + );
1499 + yield* write(records("mock-session-1", "subagents"), "child-1.json", {});
1500 + yield* write(records("child-1", "messages"), "launch.json", {
1501 + sender: "mock-session-1",
1502 + sourceMetadata: { tool: { toolCall: { id: "call_research", name: "invoke_subagent" } } },
1503 + });
1504 + const opened = yield* openSessionWithRunningCommand({}, profile, {
1505 + agentVersion: "1.5.11",
1506 + holdsFirstPrompt: false,
1507 + });
1508 + const { session, providerThread, usage, send, startTurn, until, throughPromptSettled } =
1509 + opened;
1510 + yield* startTurn(1, false);
1511 + const prompt = yield* throughPromptSettled;
1512 + const providerTurnId = prompt.flatMap((event) =>
1513 + event.type === "provider_turn.updated" ? [event.providerTurn.id] : [],
1514 + )[0]!;
1515 + yield* TestClock.adjust("10 minutes");
1516 +
1517 + yield* session.steerTurn({
1518 + threadId: ThreadId.make("thread-antigravity-wake"),
1519 + runId: RunId.make("run-antigravity-wake-1"),
1520 + providerThread,
1521 + providerTurnId,
1522 + message: {
1523 + messageId: MessageId.make("message-antigravity-steer"),
1524 + text: "Also check the footnotes",
1525 + attachments: [],
1526 + createdBy: "user",
1527 + creationSource: "web",
1528 + },
1529 + });
1530 + assert.equal(opened.cancels(), 0, "a steer must not cancel the agent's subagents");
1531 + assert.lengthOf(opened.prompts, 2);
1532 + yield* write(records("mock-session-1", "messages"), "report.json", { sender: "child-1" });
1533 + yield* send({
1534 + sessionUpdate: "agent_message_chunk",
1535 + content: { type: "text", text: "I'll have the footnotes checked too." },
1536 + });
1537 + yield* send(usage);
1538 + yield* opened.releaseSteer;
1539 + const run = [...prompt, ...(yield* until((event) => event.type === "turn.terminal"))];
1540 + const terminal = run.at(-1);
1541 + assert.equal(terminal?.type === "turn.terminal" && terminal.status, "completed");
1542 + assert.include(JSON.stringify(run), "I'll have the footnotes checked too.");
1543 + const subagentStatuses = run.flatMap((event) =>
1544 + event.type === "subagent.updated" ? [event.subagent.status] : [],
1545 + );
1546 + assert.notInclude(subagentStatuses, "interrupted");
1547 + assert.equal(subagentStatuses.at(-1), "idle");
1548 + }).pipe(Effect.provide(layerSession)),
1549 + );
1550 +
1551 // Files as agy 1.5.12 wrote them: the launch sits in the child's inbox, and the child's report
1552 // lands in the parent's inbox with no session update. Only the agent's own reply follows.
1553 it.effect.each([
apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts
+3
@@ -23,6 +23,7 @@ import {
23 antigravityAppendsSystemPrompt,
24 antigravityPermissionMode,
25 antigravityRuntimeModeForSessionMode,
26 + antigravitySteersWithPrompt,
27 applyAntigravityAcpModelSelection,
28 buildAntigravityPrompt,
29 type AntigravityAcpRuntimeInput,
@@ -254,6 +255,8 @@ export function makeAntigravityAcpAdapterFlavor(
255 // session/cancel ends the agent's running commands, so only Stop sends it once the prompt
256 // has ended. A message sent while a command runs leaves the command alone.
257 preserveRuntimeOnSettledInterrupt: true,
258 + // `agy acp` reads a prompt sent mid-turn as a steer; cancel-and-restart killed its subagents.
259 + steersWithPrompt: antigravitySteersWithPrompt,
260 ...(options.onSessionEvent === undefined ? {} : { onSessionEvent: options.onSessionEvent }),
261 applyModelSelection: Effect.fn("AntigravityAdapterV2.applyModelSelection")(function* ({
262 runtime,
apps/server/src/provider/acp/AntigravityAcpSupport.ts
+9
@@ -88,6 +88,15 @@ export function isQualifiedAntigravityRelease(version: string | null | undefined
88
89 // `agy acp` 1.5.1 offers every model to every ACP client; older runtimes allowlist editors.
90 const OPEN_MODEL_ACCESS_RELEASE = [1, 5, 1] as const;
91 +// `agy acp` 1.5.0 steers a running turn with the next prompt; the 1.4 harness queues it.
92 +const PROMPT_STEERING_RELEASE = [1, 5, 0] as const;
93 +
94 +export const antigravitySteersWithPrompt = (
95 + initializeResult: EffectAcpSchema.InitializeResponse,
96 +) => {
97 + const parsed = parseAntigravityVersion(initializeResult.agentInfo?.version);
98 + return parsed !== undefined && compareVersions(parsed, PROMPT_STEERING_RELEASE) >= 0;
99 +};
100
101 /**
102 * 1.4.5 appends `systemPrompt.append` to its system instructions on new, load and resume, and
packages/provider-acp/src/server/adapter.ts
+404 -229
@@ -158,9 +158,10 @@ function isAgentBusyPromptError(error: EffectAcpErrors.AcpError): boolean {
158 function sendPromptWhenIdle<A>(
159 turn: { readonly interrupted: boolean; readonly finalized: boolean },
160 prompt: () => Effect.Effect<A, EffectAcpErrors.AcpError>,
161 + superseded: () => boolean = () => false,
162 ): Effect.Effect<A, EffectAcpErrors.AcpError> {
162 - // A Stop can land during the wait, so the flags are rechecked before each resend.
163 - const stopped = () => turn.interrupted || turn.finalized;
163 + // A Stop or a prompt-steer can land during the wait, so both are rechecked before each resend.
164 + const stopped = () => turn.interrupted || turn.finalized || superseded();
165 return prompt().pipe(
166 Effect.catchIf(
167 (error) => isAgentBusyPromptError(error) && !stopped(),
@@ -168,7 +169,7 @@ function sendPromptWhenIdle<A>(
169 Effect.sleep(ACP_BUSY_PROMPT_RETRY_INTERVAL).pipe(
170 Effect.andThen(
171 Effect.suspend(() =>
171 - stopped() ? Effect.fail(error) : sendPromptWhenIdle(turn, prompt),
172 + stopped() ? Effect.fail(error) : sendPromptWhenIdle(turn, prompt, superseded),
173 ),
174 ),
175 ),
@@ -297,6 +298,28 @@ class AcpModelSelectionError extends Schema.TaggedError<AcpModelSelectionError>(
298 }
299 }
300
301 +/** A prompt-steered turn spans several prompts, each reporting its own usage. */
302 +function addAcpUsage(
303 + total: EffectAcpSchema.Usage | undefined,
304 + usage: EffectAcpSchema.Usage | null | undefined,
305 +): EffectAcpSchema.Usage | undefined {
306 + if (usage == null) return total;
307 + if (total === undefined) return usage;
308 + const optional = (left: number | null | undefined, right: number | null | undefined) =>
309 + left == null && right == null ? {} : { value: (left ?? 0) + (right ?? 0) };
310 + const thought = optional(total.thoughtTokens, usage.thoughtTokens);
311 + const cachedRead = optional(total.cachedReadTokens, usage.cachedReadTokens);
312 + const cachedWrite = optional(total.cachedWriteTokens, usage.cachedWriteTokens);
313 + return {
314 + totalTokens: total.totalTokens + usage.totalTokens,
315 + inputTokens: total.inputTokens + usage.inputTokens,
316 + outputTokens: total.outputTokens + usage.outputTokens,
317 + ...("value" in thought ? { thoughtTokens: thought.value } : {}),
318 + ...("value" in cachedRead ? { cachedReadTokens: cachedRead.value } : {}),
319 + ...("value" in cachedWrite ? { cachedWriteTokens: cachedWrite.value } : {}),
320 + };
321 +}
322 +
323 /**
324 * Maps one per-turn usage sample (flavors with reportsPerTurnPromptUsage)
325 * directly onto TurnTokenUsage: the response's counters already cover exactly
@@ -531,6 +554,13 @@ export interface AcpAdapterV2Flavor {
554 notification: EffectAcpSchema.SessionNotification,
555 ) => string | undefined;
556 };
557 + /**
558 + * Steers with another `session/prompt` while one runs: the agent answers the running prompt
559 + * `end_turn` and carries the turn on under the new one, leaving its tools and subagents alone.
560 + */
561 + readonly steersWithPrompt?: (
562 + initializeResult: AcpSessionRuntime.AcpSessionRuntimeStartResult["initializeResult"],
563 + ) => boolean;
564 /**
565 * Native fork from an earlier turn. `nativeTurnId` reads the agent's id for a running
566 * turn's prompt, which the turn keeps as its native ref; forking from that turn sends
@@ -908,6 +938,7 @@ function negotiatedCapabilities(
938 started: AcpSessionRuntime.AcpSessionRuntimeStartResult,
939 modelOptionArrivesLate: boolean,
940 forksFromTurn: boolean,
941 + steersWithPrompt: boolean,
942 ): OrchestrationV2ProviderCapabilities {
943 const agent = started.initializeResult.agentCapabilities ?? {};
944 const session = agent.sessionCapabilities;
@@ -930,6 +961,10 @@ function negotiatedCapabilities(
961 canForkThread: canFork,
962 canForkFromTurn: canFork && forksFromTurn,
963 },
964 + turns: {
965 + ...base.turns,
966 + supportsActiveSteering: base.turns.supportsActiveSteering || steersWithPrompt,
967 + },
968 tools: {
969 ...base.tools,
970 supportsMcpTools: true,
@@ -1621,11 +1656,14 @@ interface ActiveAcpTurn {
1656 promptSettled: boolean;
1657 promptSettledStatus: "completed" | "interrupted" | "failed" | "cancelled" | null;
1658 workAccepted: boolean;
1624 - readonly promptWireSettled: Deferred.Deferred<void, never>;
1659 + /** Settles with the turn's latest prompt; a prompt-steer replaces a settled one. */
1660 + promptWireSettled: Deferred.Deferred<void, never>;
1661 /** Completed once `session/prompt` is the runtime's active prompt. */
1662 readonly promptDispatched: Deferred.Deferred<void, never>;
1663 /** Frees the runtime for the next prompt while the agent still holds this one's response. */
1628 - readonly foregroundIdle: Deferred.Deferred<void>;
1664 + foregroundIdle: Deferred.Deferred<void>;
1665 + /** Counts the turn's prompts; only the latest one settles the turn. */
1666 + promptSequence: number;
1667 /** Clock millis just before `session/prompt` was handed to the runtime. */
1668 promptSentAt: number | null;
1669 /** Completed when an update after dispatch matches `cancelAfterPromptStarts.isStart`. */
@@ -7827,11 +7865,13 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
7865 yield* setActiveSessionSetup(started);
7866 rememberTerminalEnvironment(started.sessionId, yield* readMcpContext(input.threadId));
7867 yield* runtime.drainEvents;
7868 + const steersWithPrompt = flavor.steersWithPrompt?.(started.initializeResult) === true;
7869 const capabilities = negotiatedCapabilities(
7870 yield* readCapabilities,
7871 started,
7872 flavor.modelOptionArrivesLate === true,
7873 flavor.forkFromTurn?.supported(started.initializeResult) === true,
7874 + steersWithPrompt,
7875 );
7876 const canLoadSession = started.initializeResult.agentCapabilities?.loadSession === true;
7877 const canResumeSession =
@@ -8659,6 +8699,49 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
8699 return blocks;
8700 });
8701
8702 + const promptAttachmentBlocks = Effect.fnUntraced(function* (
8703 + messageText: string,
8704 + attachments: ReadonlyArray<ChatAttachment>,
8705 + ) {
8706 + if (!supportsImagePrompts && attachments.some(isProviderNativeImageAttachment)) {
8707 + return yield* new ProviderAdapter.ProviderAdapterProtocolError({
8708 + driver,
8709 + detail: "ACP driver did not negotiate image prompt support",
8710 + });
8711 + }
8712 + if (!flavor.buildAttachmentPrompt) return yield* imageAttachmentBlocks(attachments);
8713 + const setup = yield* Ref.get(activeSessionSetup);
8714 + const modelOption = findModelConfigOption(yield* runtime.getConfigOptions);
8715 + const currentModelId = modelOption?.currentValue;
8716 + return yield* flavor
8717 + .buildAttachmentPrompt({
8718 + text: messageText,
8719 + attachments,
8720 + resolveAttachmentPath: host.resolveAttachmentPath,
8721 + promptCapabilities: setup?.initializeResult.agentCapabilities?.promptCapabilities,
8722 + agentVersion: setup?.initializeResult.agentInfo?.version,
8723 + currentModel:
8724 + typeof currentModelId !== "string" || modelOption === undefined
8725 + ? undefined
8726 + : {
8727 + id: currentModelId,
8728 + name: flattenSelectChoices(modelOption.options).find(
8729 + (choice) => choice.value === currentModelId,
8730 + )?.name,
8731 + },
8732 + })
8733 + .pipe(
8734 + Effect.mapError(
8735 + (cause) =>
8736 + new ProviderAdapter.ProviderAdapterProtocolError({
8737 + driver,
8738 + detail: "Failed to build ACP attachment prompt",
8739 + payload: cause,
8740 + }),
8741 + ),
8742 + );
8743 + });
8744 +
8745 const resolvePromptParts = Effect.fnUntraced(function* (
8746 turnInput: ProviderAdapter.ProviderAdapterV2TurnInput,
8747 sessionId: string,
@@ -8687,51 +8770,10 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
8770 resolveExtractedTextPath: host.resolveExtractedTextPath,
8771 });
8772 const isNativeSlashCommand = userText.trimStart().startsWith("/");
8690 - if (
8691 - !supportsImagePrompts &&
8692 - turnInput.message.attachments.some(isProviderNativeImageAttachment)
8693 - ) {
8694 - return yield* new ProviderAdapter.ProviderAdapterProtocolError({
8695 - driver,
8696 - detail: "ACP driver did not negotiate image prompt support",
8697 - });
8698 - }
8699 - const attachmentBlocks = flavor.buildAttachmentPrompt
8700 - ? []
8701 - : yield* imageAttachmentBlocks(turnInput.message.attachments);
8702 - if (flavor.buildAttachmentPrompt) {
8703 - const setup = yield* Ref.get(activeSessionSetup);
8704 - const modelOption = findModelConfigOption(yield* runtime.getConfigOptions);
8705 - const currentModelId = modelOption?.currentValue;
8706 - const blocks = yield* flavor
8707 - .buildAttachmentPrompt({
8708 - text: messageText,
8709 - attachments: turnInput.message.attachments,
8710 - resolveAttachmentPath: host.resolveAttachmentPath,
8711 - promptCapabilities: setup?.initializeResult.agentCapabilities?.promptCapabilities,
8712 - agentVersion: setup?.initializeResult.agentInfo?.version,
8713 - currentModel:
8714 - typeof currentModelId !== "string" || modelOption === undefined
8715 - ? undefined
8716 - : {
8717 - id: currentModelId,
8718 - name: flattenSelectChoices(modelOption.options).find(
8719 - (choice) => choice.value === currentModelId,
8720 - )?.name,
8721 - },
8722 - })
8723 - .pipe(
8724 - Effect.mapError(
8725 - (cause) =>
8726 - new ProviderAdapter.ProviderAdapterProtocolError({
8727 - driver,
8728 - detail: "Failed to build ACP attachment prompt",
8729 - payload: cause,
8730 - }),
8731 - ),
8732 - );
8733 - attachmentBlocks.push(...blocks);
8734 - }
8773 + const attachmentBlocks = yield* promptAttachmentBlocks(
8774 + messageText,
8775 + turnInput.message.attachments,
8776 + );
8777 // Read delivery state after the awaits above, so a compaction that lands
8778 // while the prompt is prepared still resends the notes in this prompt.
8779 const previousInstructionState = (yield* Ref.get(promptInstructionStates)).get(sessionId);
@@ -8797,6 +8839,194 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
8839 return true;
8840 });
8841
8842 + /** Follows a turn's `session/prompt`; a prompt-steer's prompt supersedes the one before. */
8843 + const followPrompt = (
8844 + context: ActiveAcpTurn,
8845 + prompt: (
8846 + superseded: () => boolean,
8847 + ) => Effect.Effect<EffectAcpSchema.PromptResponse, EffectAcpErrors.AcpError>,
8848 + settle: {
8849 + readonly generation: number;
8850 + readonly checkPromptOutcome:
8851 + | Effect.Success<ReturnType<NonNullable<AcpAdapterV2Flavor["watchPromptOutcome"]>>>
8852 + | undefined;
8853 + readonly promptParts: Effect.Success<ReturnType<typeof resolvePromptParts>> | null;
8854 + readonly compactSession: AcpAdapterV2Flavor["compactSession"];
8855 + },
8856 + ) => {
8857 + const sequence = ++context.promptSequence;
8858 + const superseded = () => context.promptSequence !== sequence;
8859 + return prompt(superseded).pipe(
8860 + // Settle the wire before the completion callback's permit so a settled-soft
8861 + // Stop sees the native return. Capture usage only before finalize: a late
8862 + // response must not flip a settled turn.
8863 + Effect.tap((result) =>
8864 + Effect.suspend(() => {
8865 + if (flavor.reportsPerTurnPromptUsage === true && !context.finalized) {
8866 + context.promptUsage = addAcpUsage(context.promptUsage, result.usage);
8867 + }
8868 + return superseded()
8869 + ? Effect.void
8870 + : Deferred.succeed(context.promptWireSettled, undefined).pipe(Effect.asVoid);
8871 + }),
8872 + ),
8873 + Effect.tap(() => options.testHooks?.afterPromptWireSettled?.() ?? Effect.void),
8874 + Effect.flatMap((result) =>
8875 + runRuntimeCallbackAtGeneration(
8876 + settle.generation,
8877 + Effect.gen(function* () {
8878 + // Record delivery only for this runtime: a replacement can reuse the session id.
8879 + // Grok cancels locally, refusals discard the prompt, and errors need a retry.
8880 + // Native compaction sends no prompt, and the compacted session needs the notes.
8881 + if (settle.compactSession !== undefined) {
8882 + yield* markSessionCompacted(context.nativeThreadId);
8883 + } else if (
8884 + result.stopReason !== "cancelled" &&
8885 + result.stopReason !== "refusal" &&
8886 + result.stopReason !== "error"
8887 + ) {
8888 + const promptParts = settle.promptParts;
8889 + yield* Ref.update(promptInstructionStates, (current) => {
8890 + if (promptParts?.instructionState === undefined) return current;
8891 + const updated = new Map(current);
8892 + updated.set(context.nativeThreadId, promptParts.instructionState);
8893 + return updated;
8894 + });
8895 + yield* Ref.update(promptRuntimeInstructions, (current) => {
8896 + if (promptParts?.runtimeInstructions === undefined) return current;
8897 + const updated = new Map(current);
8898 + updated.set(context.nativeThreadId, promptParts.runtimeInstructions);
8899 + return updated;
8900 + });
8901 + yield* Ref.update(compactionMarkers, (current) => {
8902 + if (promptParts?.instructionState === undefined) return current;
8903 + const observedMarker = promptParts.compactionMarker;
8904 + if (
8905 + observedMarker === undefined ||
8906 + current.get(context.nativeThreadId) !== observedMarker
8907 + )
8908 + return current;
8909 + const updated = new Map(current);
8910 + updated.delete(context.nativeThreadId);
8911 + return updated;
8912 + });
8913 + }
8914 + if (context.finalized || followsAgentWorkState || superseded()) return;
8915 + // ACP v2 reports a failed prompt through its idle stop reason, not an RPC error.
8916 + const hiddenFailure =
8917 + settle.checkPromptOutcome === undefined ||
8918 + context.interrupted ||
8919 + result.stopReason === "error" ||
8920 + result.stopReason === "cancelled"
8921 + ? undefined
8922 + : yield* settle.checkPromptOutcome(result);
8923 + if (hiddenFailure !== undefined) {
8924 + yield* Ref.set(runtimeRestartRequired, true);
8925 + }
8926 + const failure =
8927 + hiddenFailure?.failure ??
8928 + (context.interrupted
8929 + ? undefined
8930 + : stopReasonFailure(result.stopReason, result.error));
8931 + const status =
8932 + failure !== undefined
8933 + ? "failed"
8934 + : result.stopReason === "cancelled"
8935 + ? context.interrupted
8936 + ? "interrupted"
8937 + : "cancelled"
8938 + : "completed";
8939 + if (defersFinalizeForBackgroundWork && !context.interrupted) {
8940 + context.promptSettled = true;
8941 + context.promptSettledStatus = status;
8942 + for (const [taskId, completion] of context.backgroundCommands) {
8943 + if (completion === null) continue;
8944 + yield* finishRegisteredBackgroundTool({ taskId, ...completion });
8945 + }
8946 + }
8947 + if (failure !== undefined) {
8948 + yield* terminalizeOpenForegroundTools(context, "failed");
8949 + // Unlike an RPC failure, the agent survives an idle error, so its
8950 + // background tools and subagents keep reporting to this run.
8951 + yield* finalizeTurn(context, "failed", failure, {
8952 + childTurnsContinue: hasSurvivingBackgroundWork(context),
8953 + ...(hiddenFailure === undefined
8954 + ? {}
8955 + : { threadDisposition: hiddenFailure.threadDisposition }),
8956 + });
8957 + return;
8958 + }
8959 + yield* idleReportedSubagents(context);
8960 + if (context.finalized) return;
8961 + if (
8962 + defersFinalizeForBackgroundWork &&
8963 + !context.interrupted &&
8964 + hasDeferredBackgroundWork(context)
8965 + ) {
8966 + yield* closeTextStreams(context);
8967 + yield* (
8968 + options.testHooks?.afterPromptSettledWithBackgroundWork?.() ?? Effect.void
8969 + );
8970 + return;
8971 + }
8972 + yield* finalizeTurn(context, status);
8973 + }),
8974 + ).pipe(
8975 + Effect.andThen(() => options.testHooks?.afterPromptCallback?.() ?? Effect.void),
8976 + Effect.asVoid,
8977 + ),
8978 + ),
8979 + Effect.catchCause((cause) =>
8980 + runRuntimeCallbackAtGeneration(
8981 + settle.generation,
8982 + Effect.gen(function* () {
8983 + if (context.finalized || superseded()) return;
8984 + const error = Cause.findError(cause);
8985 + // Native close rejects prompts cancelled before insertion with -32800.
8986 + const interrupted =
8987 + context.interrupted ||
8988 + (pendingStopCloseTurn === context &&
8989 + Result.isSuccess(error) &&
8990 + error.success._tag === "AcpRequestError" &&
8991 + error.success.code === -32800);
8992 + const failure = Cause.squash(cause);
8993 + if (!interrupted && flavor.restartRuntimeAfterPromptError?.(failure) === true) {
8994 + yield* Ref.set(runtimeRestartRequired, true);
8995 + }
8996 + // An agent that answered with an error may still finish tools it started,
8997 + // never pending ones; any other failure means its process or pipe is gone.
8998 + const agentAnswered =
8999 + Result.isSuccess(error) && error.success._tag === "AcpRequestError";
9000 + if (!interrupted) {
9001 + yield* terminalizeOpenForegroundTools(context, "failed", {
9002 + unstartedOnly: agentAnswered,
9003 + });
9004 + }
9005 + yield* finalizeTurn(
9006 + context,
9007 + interrupted ? "interrupted" : "failed",
9008 + flavor.promptFailure?.(failure) ??
9009 + makeProviderFailure({
9010 + cause: failure,
9011 + class: "provider_error",
9012 + }),
9013 + ).pipe(
9014 + Effect.andThen(
9015 + Effect.logWarning("orchestration-v2.acp-prompt-failed", {
9016 + driver,
9017 + providerSessionId: input.providerSessionId,
9018 + providerThreadId: context.input.providerThread.id,
9019 + providerTurnId: context.providerTurnId,
9020 + cause,
9021 + }),
9022 + ),
9023 + );
9024 + }),
9025 + ).pipe(Effect.asVoid),
9026 + ),
9027 + );
9028 + };
9029 +
9030 const startTurnUnlocked = Effect.fn("AcpAdapterV2.startTurn")(
9031 function* (turnInput: ProviderAdapter.ProviderAdapterV2TurnInput) {
9032 yield* awaitRuntimeTeardown();
@@ -8967,6 +9197,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
9197 promptWireSettled,
9198 promptDispatched,
9199 foregroundIdle: yield* Deferred.make<void>(),
9200 + promptSequence: 0,
9201 promptSentAt: null,
9202 promptStarted,
9203 promptUsage: undefined,
@@ -9142,185 +9373,23 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
9373 const compactSession = isCompactionMessage(turnInput.message)
9374 ? flavor.compactSession
9375 : undefined;
9145 - yield* (
9146 - compactSession === undefined
9147 - ? sendPromptWhenIdle(context, () =>
9148 - runtime.prompt({ prompt: promptParts!.prompt }, promptOptions),
9149 - )
9150 - : Deferred.succeed(context.promptDispatched, undefined).pipe(
9151 - Effect.andThen(compactSession.compact(runtime, requestedSessionId)),
9152 - Effect.as({ stopReason: "end_turn" } satisfies EffectAcpSchema.PromptResponse),
9153 - )
9154 - ).pipe(
9155 - // Settle the wire before the completion callback's permit so a settled-soft
9156 - // Stop sees the native return. Capture usage only before finalize: a late
9157 - // response must not flip a settled turn.
9158 - Effect.tap((result) =>
9159 - Effect.sync(() => {
9160 - if (flavor.reportsPerTurnPromptUsage === true && !context.finalized) {
9161 - context.promptUsage = result.usage ?? undefined;
9162 - }
9163 - }).pipe(
9164 - Effect.andThen(
9165 - Deferred.succeed(context.promptWireSettled, undefined).pipe(Effect.asVoid),
9166 - ),
9167 - ),
9168 - ),
9169 - Effect.tap(() => options.testHooks?.afterPromptWireSettled?.() ?? Effect.void),
9170 - Effect.flatMap((result) =>
9171 - runRuntimeCallbackAtGeneration(
9172 - promptGeneration,
9173 - Effect.gen(function* () {
9174 - // Record delivery only for this runtime: a replacement can reuse the session id.
9175 - // Grok cancels locally, refusals discard the prompt, and errors need a retry.
9176 - // Native compaction sends no prompt, and the compacted session needs the notes.
9177 - if (compactSession !== undefined) {
9178 - yield* markSessionCompacted(requestedSessionId);
9179 - } else if (
9180 - result.stopReason !== "cancelled" &&
9181 - result.stopReason !== "refusal" &&
9182 - result.stopReason !== "error"
9183 - ) {
9184 - yield* Ref.update(promptInstructionStates, (current) => {
9185 - if (promptParts?.instructionState === undefined) return current;
9186 - const updated = new Map(current);
9187 - updated.set(requestedSessionId, promptParts.instructionState);
9188 - return updated;
9189 - });
9190 - yield* Ref.update(promptRuntimeInstructions, (current) => {
9191 - if (promptParts?.runtimeInstructions === undefined) return current;
9192 - const updated = new Map(current);
9193 - updated.set(requestedSessionId, promptParts.runtimeInstructions);
9194 - return updated;
9195 - });
9196 - yield* Ref.update(compactionMarkers, (current) => {
9197 - if (promptParts?.instructionState === undefined) return current;
9198 - const observedMarker = promptParts.compactionMarker;
9199 - if (
9200 - observedMarker === undefined ||
9201 - current.get(requestedSessionId) !== observedMarker
9202 - )
9203 - return current;
9204 - const updated = new Map(current);
9205 - updated.delete(requestedSessionId);
9206 - return updated;
9207 - });
9208 - }
9209 - if (context.finalized || followsAgentWorkState) return;
9210 - // ACP v2 reports a failed prompt through its idle stop reason, not an RPC error.
9211 - const hiddenFailure =
9212 - checkPromptOutcome === undefined ||
9213 - context.interrupted ||
9214 - result.stopReason === "error" ||
9215 - result.stopReason === "cancelled"
9216 - ? undefined
9217 - : yield* checkPromptOutcome(result);
9218 - if (hiddenFailure !== undefined) {
9219 - yield* Ref.set(runtimeRestartRequired, true);
9220 - }
9221 - const failure =
9222 - hiddenFailure?.failure ??
9223 - (context.interrupted
9224 - ? undefined
9225 - : stopReasonFailure(result.stopReason, result.error));
9226 - const status =
9227 - failure !== undefined
9228 - ? "failed"
9229 - : result.stopReason === "cancelled"
9230 - ? context.interrupted
9231 - ? "interrupted"
9232 - : "cancelled"
9233 - : "completed";
9234 - if (defersFinalizeForBackgroundWork && !context.interrupted) {
9235 - context.promptSettled = true;
9236 - context.promptSettledStatus = status;
9237 - for (const [taskId, completion] of context.backgroundCommands) {
9238 - if (completion === null) continue;
9239 - yield* finishRegisteredBackgroundTool({ taskId, ...completion });
9240 - }
9241 - }
9242 - if (failure !== undefined) {
9243 - yield* terminalizeOpenForegroundTools(context, "failed");
9244 - // Unlike an RPC failure, the agent survives an idle error, so its
9245 - // background tools and subagents keep reporting to this run.
9246 - yield* finalizeTurn(context, "failed", failure, {
9247 - childTurnsContinue: hasSurvivingBackgroundWork(context),
9248 - ...(hiddenFailure === undefined
9249 - ? {}
9250 - : { threadDisposition: hiddenFailure.threadDisposition }),
9251 - });
9252 - return;
9253 - }
9254 - yield* idleReportedSubagents(context);
9255 - if (context.finalized) return;
9256 - if (
9257 - defersFinalizeForBackgroundWork &&
9258 - !context.interrupted &&
9259 - hasDeferredBackgroundWork(context)
9260 - ) {
9261 - yield* closeTextStreams(context);
9262 - yield* (
9263 - options.testHooks?.afterPromptSettledWithBackgroundWork?.() ?? Effect.void
9264 - );
9265 - return;
9266 - }
9267 - yield* finalizeTurn(context, status);
9268 - }),
9269 - ).pipe(
9270 - Effect.andThen(() => options.testHooks?.afterPromptCallback?.() ?? Effect.void),
9271 - Effect.asVoid,
9272 - ),
9273 - ),
9274 - Effect.catchCause((cause) =>
9275 - runRuntimeCallbackAtGeneration(
9276 - promptGeneration,
9277 - Effect.gen(function* () {
9278 - if (context.finalized) return;
9279 - const error = Cause.findError(cause);
9280 - // Native close rejects prompts cancelled before insertion with -32800.
9281 - const interrupted =
9282 - context.interrupted ||
9283 - (pendingStopCloseTurn === context &&
9284 - Result.isSuccess(error) &&
9285 - error.success._tag === "AcpRequestError" &&
9286 - error.success.code === -32800);
9287 - const failure = Cause.squash(cause);
9288 - if (!interrupted && flavor.restartRuntimeAfterPromptError?.(failure) === true) {
9289 - yield* Ref.set(runtimeRestartRequired, true);
9290 - }
9291 - // An agent that answered with an error may still finish tools it started,
9292 - // never pending ones; any other failure means its process or pipe is gone.
9293 - const agentAnswered =
9294 - Result.isSuccess(error) && error.success._tag === "AcpRequestError";
9295 - if (!interrupted) {
9296 - yield* terminalizeOpenForegroundTools(context, "failed", {
9297 - unstartedOnly: agentAnswered,
9298 - });
9299 - }
9300 - yield* finalizeTurn(
9376 + yield* followPrompt(
9377 + context,
9378 + (superseded) =>
9379 + compactSession === undefined
9380 + ? sendPromptWhenIdle(
9381 context,
9302 - interrupted ? "interrupted" : "failed",
9303 - flavor.promptFailure?.(failure) ??
9304 - makeProviderFailure({
9305 - cause: failure,
9306 - class: "provider_error",
9307 - }),
9308 - ).pipe(
9309 - Effect.andThen(
9310 - Effect.logWarning("orchestration-v2.acp-prompt-failed", {
9311 - driver,
9312 - providerSessionId: input.providerSessionId,
9313 - providerThreadId: turnInput.providerThread.id,
9314 - providerTurnId,
9315 - cause,
9316 - }),
9317 - ),
9318 - );
9319 - }),
9320 - ).pipe(Effect.asVoid),
9321 - ),
9322 - Effect.forkIn(sessionScope),
9323 - );
9382 + () => runtime.prompt({ prompt: promptParts!.prompt }, promptOptions),
9383 + superseded,
9384 + )
9385 + : Deferred.succeed(context.promptDispatched, undefined).pipe(
9386 + Effect.andThen(compactSession.compact(runtime, requestedSessionId)),
9387 + Effect.as({
9388 + stopReason: "end_turn",
9389 + } satisfies EffectAcpSchema.PromptResponse),
9390 + ),
9391 + { generation: promptGeneration, checkPromptOutcome, promptParts, compactSession },
9392 + ).pipe(Effect.forkIn(sessionScope));
9393 },
9394 (effect, turnInput) =>
9395 effect.pipe(
@@ -9343,6 +9412,110 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
9412 return yield* runtimeTransitionPermit.withPermit(startTurnUnlocked(turnInput));
9413 });
9414
9415 + const steerWithPrompt = Effect.fn("AcpAdapterV2.steerWithPrompt")(function* (
9416 + turnInput: ProviderAdapter.ProviderAdapterV2SteerInput,
9417 + ) {
9418 + const text = yield* providerMessageTextWithAttachmentPaths({
9419 + text: turnInput.message.text,
9420 + attachments: turnInput.message.attachments,
9421 + resolveAttachmentPath: host.resolveAttachmentPath,
9422 + resolveExtractedTextPath: host.resolveExtractedTextPath,
9423 + });
9424 + const attachmentBlocks = yield* promptAttachmentBlocks(
9425 + text,
9426 + turnInput.message.attachments,
9427 + );
9428 + const dispatched = yield* runtimeTransitionPermit.withPermit(
9429 + Effect.gen(function* () {
9430 + const context = yield* Ref.get(activeTurn);
9431 + if (
9432 + context === null ||
9433 + context.finalized ||
9434 + context.interrupted ||
9435 + context.providerTurnId !== turnInput.providerTurnId
9436 + ) {
9437 + return yield* new ProviderAdapter.ProviderAdapterProtocolError({
9438 + driver,
9439 + detail: `Provider turn ${turnInput.providerTurnId} is not active and cannot be steered.`,
9440 + });
9441 + }
9442 + // A wake turn has no prompt of its own to steer; its reply ends the run soon.
9443 + if (context.promptSequence === 0) {
9444 + return yield* new ProviderAdapter.ProviderAdapterSteerDeclinedError({
9445 + driver,
9446 + providerThreadId: turnInput.providerThread.id,
9447 + providerTurnId: turnInput.providerTurnId,
9448 + });
9449 + }
9450 + const generation = yield* Ref.get(runtimeCallbackGeneration);
9451 + const checkPromptOutcome =
9452 + flavor.watchPromptOutcome === undefined
9453 + ? undefined
9454 + : yield* flavor.watchPromptOutcome(context.nativeThreadId);
9455 + const dispatched = yield* Deferred.make<void, never>();
9456 + const steered = yield* runRuntimeCallbackAtGeneration(
9457 + generation,
9458 + Effect.gen(function* () {
9459 + if (context.finalized || context.interrupted) return false;
9460 + // The steer prompt carries the turn on, also past a prompt that already settled.
9461 + const released = context.foregroundIdle;
9462 + context.foregroundIdle = yield* Deferred.make<void>();
9463 + if (yield* Deferred.isDone(context.promptWireSettled)) {
9464 + context.promptWireSettled = yield* Deferred.make<void, never>();
9465 + }
9466 + context.promptSettled = false;
9467 + context.promptSettledStatus = null;
9468 + context.backgroundFinalizeGeneration += 1;
9469 + context.promptSentAt = yield* Clock.currentTimeMillis;
9470 + context.lastProgressAt = context.promptSentAt;
9471 + const watchdog = context.inactivityWatchdog;
9472 + context.inactivityWatchdog = undefined;
9473 + if (watchdog !== undefined) {
9474 + yield* Fiber.interrupt(watchdog).pipe(Effect.forkDetach, Effect.asVoid);
9475 + }
9476 + if (promptInactivityTimeoutMillis !== undefined) {
9477 + context.inactivityWatchdog = yield* watchPromptInactivity(
9478 + context,
9479 + generation,
9480 + promptInactivityTimeoutMillis,
9481 + ).pipe(Effect.forkIn(sessionScope));
9482 + }
9483 + const releasedForSteer = context.foregroundIdle;
9484 + yield* followPrompt(
9485 + context,
9486 + (superseded) =>
9487 + sendPromptWhenIdle(
9488 + context,
9489 + () =>
9490 + runtime.prompt(
9491 + { prompt: [{ type: "text", text }, ...attachmentBlocks] },
9492 + { dispatched, released: releasedForSteer },
9493 + ),
9494 + superseded,
9495 + ),
9496 + {
9497 + generation,
9498 + checkPromptOutcome,
9499 + promptParts: null,
9500 + compactSession: undefined,
9501 + },
9502 + ).pipe(Effect.forkIn(sessionScope));
9503 + yield* Deferred.succeed(released, undefined);
9504 + return true;
9505 + }),
9506 + );
9507 + if (!Option.contains(steered, true)) {
9508 + return yield* new ProviderAdapter.ProviderAdapterProtocolError({
9509 + driver,
9510 + detail: `Provider turn ${turnInput.providerTurnId} ended before it could be steered.`,
9511 + });
9512 + }
9513 + return dispatched;
9514 + }),
9515 + );
9516 + yield* Deferred.await(dispatched);
9517 + });
9518 +
9519 yield* Effect.addFinalizer(() =>
9520 Effect.gen(function* () {
9521 yield* continuationPermit.withPermit(
@@ -9609,6 +9782,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
9782 : {}),
9783 steerTurn: Effect.fn("AcpAdapterV2.steerTurn")(
9784 function* (turnInput) {
9785 + if (steersWithPrompt) return yield* steerWithPrompt(turnInput);
9786 const steering = flavor.steering;
9787 // A text-only steer leaves attachments to the orchestrator's restart.
9788 if (
@@ -9671,7 +9845,8 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
9845 (effect, turnInput) =>
9846 effect.pipe(
9847 Effect.mapError((cause) =>
9674 - cause._tag === "ProviderAdapterSteerRunUnsupportedError"
9848 + cause._tag === "ProviderAdapterSteerRunUnsupportedError" ||
9849 + cause._tag === "ProviderAdapterSteerDeclinedError"
9850 ? cause
9851 : new ProviderAdapter.ProviderAdapterSteerRunError({
9852 driver,