@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 03:37 UTC

main
ts 10,698 lines 462 KB
Raw
1 // @effect-diagnostics nodeBuiltinImport:off
2
3 import {
4 type ChatAttachment,
5 type ModelSelection,
6 type OrchestrationV2ConversationMessage,
7 type OrchestrationV2ExecutionNode,
8 type OrchestrationV2PlanArtifact,
9 type OrchestrationV2PlanStep,
10 type OrchestrationV2ProviderCapabilities,
11 type OrchestrationV2ProviderFailure,
12 type OrchestrationV2ProviderRetry,
13 type OrchestrationV2ProviderSession,
14 type OrchestrationV2ProviderThread,
15 type OrchestrationV2ProviderThreadNativeMetadata,
16 type OrchestrationV2ProviderTurn,
17 type OrchestrationV2RuntimeRequest,
18 type OrchestrationV2Subagent,
19 type OrchestrationV2TurnItem,
20 type OrchestrationV2UserInputQuestion,
21 type OrchestrationV2WebSearchResult,
22 type ProviderApprovalDecision,
23 type ProviderApprovalOption,
24 type ProviderInstanceId,
25 type ProviderInteractionMode,
26 type ProviderDriverKind,
27 type ProviderRequestKind,
28 type ProviderThreadId,
29 type ProviderUserInputAnswers,
30 type RuntimeMode,
31 type RuntimeRequestId,
32 type ThreadTokenUsageSnapshot,
33 type ThreadId,
34 isRuntimeModeAbove,
35 type TurnTokenUsage,
36 } from "@t3tools/contracts";
37 import { AgentScope, AgentScopeThreadId } from "@t3tools/shared/AgentScope";
38 import * as HostProcess from "@t3tools/shared/HostProcess";
39 import { HTML_RENDER_TOOL_NAME } from "@t3tools/shared/htmlRender";
40 import { modelSelectionsEqual } from "@t3tools/shared/model";
41 import { type SelfInvocation, selfInvocationArgs } from "@t3tools/shared/nodeRuntime";
42 import { resolveT3McpToolId } from "@t3tools/shared/t3McpToolPresentation";
43 import {
44 compactDynamicToolOutput,
45 htmlRenderFromToolItem,
46 mcpToolResultOutput,
47 } from "@t3tools/shared/toolOutput";
48 import { FILE_HEADERS_ONLY, formatPatch, structuredPatch } from "diff";
49 import * as Cause from "effect/Cause";
50 import * as Clock from "effect/Clock";
51 import * as SecureRandom from "effect/crypto/SecureRandom";
52 import * as DateTime from "effect/DateTime";
53 import * as Deferred from "effect/Deferred";
54 import * as Duration from "effect/Duration";
55 import * as Effect from "effect/Effect";
56 import * as Equal from "effect/Equal";
57 import * as Exit from "effect/Exit";
58 import * as FileSystem from "effect/FileSystem";
59 import * as Fiber from "effect/Fiber";
60 import * as Option from "effect/Option";
61 import * as Queue from "effect/Queue";
62 import * as Ref from "effect/Ref";
63 import * as Result from "effect/Result";
64 import * as Schema from "effect/Schema";
65 import * as Scope from "effect/Scope";
66 import * as Semaphore from "effect/Semaphore";
67 import * as Stream from "effect/Stream";
68 import * as SubscriptionRef from "effect/SubscriptionRef";
69 import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
70 import * as EffectAcpErrors from "effect-acp/errors";
71 import type * as EffectAcpProtocol from "effect-acp/protocol";
72 import type * as EffectAcpSchema from "effect-acp/compat";
73
74 import { formatReadToolLabel, formatSearchToolLabel } from "@t3tools/shared/toolActivity";
75 import { isWorkspaceImagePreviewPath } from "@t3tools/shared/mediaPreview";
76 import * as ProviderHost from "@t3tools/provider-core/server/ProviderHost";
77 import { makeAcpMcpOverAcpBridge, type AcpMcpOverAcpBridge } from "./mcpOverAcpBridge.ts";
78 import { mcpToolPresentation } from "@t3tools/provider-core/server/mcpToolPresentation";
79 import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
80 import * as McpProviderSession from "@t3tools/provider-core/server/mcpSession";
81 import {
82 applyAcpAgentTerminalUpdate,
83 acpContentBlockDisplayText,
84 embeddedTerminalIdsFromSessionUpdate,
85 extractMcpToolCallIdentity,
86 findModelConfigOption,
87 mergeToolCallState,
88 parsePermissionRequest,
89 parseSessionUpdateEvent,
90 toolCallVisibleOutputChanged,
91 withTrackedPermissionToolCall,
92 type AcpPlanUpdate,
93 type AcpAgentTerminalState,
94 type AcpSessionModeState,
95 type AcpToolCallState,
96 } from "./runtimeModel.ts";
97 import {
98 acpClientExecuteDisposition,
99 acpMcpToolApprovalElicitationDisposition,
100 acpPermissionDisposition,
101 type AcpPermissionDisposition,
102 makeAcpClientPolicyGrants,
103 unknownRecord,
104 } from "./clientPolicy.ts";
105 import { parseElicitationForm } from "./elicitationForm.ts";
106 import {
107 makeAcpClientTerminals,
108 resolveEmbeddedTerminalContent,
109 type AcpClientTerminals,
110 } from "./clientTerminals.ts";
111 import {
112 ACP_EMPTY_OPTION_VALUE,
113 ACP_SESSION_MODE_OPTION_ID,
114 flattenSelectChoices,
115 } from "./sessionConfig.ts";
116 import * as AcpSessionRuntime from "./AcpSessionRuntime.ts";
117 import {
118 t3AcpPromptWithInstructions,
119 type T3AcpInstructionState,
120 } from "@t3tools/provider-core/server/orchestrationInstructions";
121 import { buildRuntimeInstructions } from "@t3tools/provider-core/server/runtimeInstructions";
122 import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
123 import type * as ProviderContinuationRequests from "@t3tools/provider-core/server/ProviderContinuationRequests";
124 import {
125 type BackgroundWork,
126 type BackgroundWorkReport,
127 backgroundWorkNotification,
128 } from "@t3tools/provider-core/server/notification";
129 import {
130 makeProviderFailure,
131 makeProviderRetryTurnItem,
132 } from "@t3tools/provider-core/server/failure";
133 import { acpSelectionTransition } from "@t3tools/provider-core/server/selectionTransition";
134 import {
135 isProviderNativeImageAttachment,
136 providerMessageTextWithAttachmentPaths,
137 } from "@t3tools/provider-core/server/attachmentPrompt";
138 import {
139 makeSubagentChildThread,
140 makeSubagentConversationArtifacts,
141 subagentThreadTitle,
142 } from "@t3tools/provider-core/server/subagentProjection";
143 import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
144
145 export const ACP_PROTOCOL = "acp.ndjson-jsonrpc" as const;
146
147 // Grok summaries can trail hydrated tools by over two seconds; shorter waits split the wake.
148 const ACP_DEFERRED_FINALIZE_DEBOUNCE: Duration.Input = "3000 millis";
149 // A model can stay silent this long before the first token of a reply the agent started itself.
150 const ACP_OPEN_REPLY_QUIET_LIMIT: Duration.Input = "2 minutes";
151 const ACP_BUSY_PROMPT_RETRY_INTERVAL: Duration.Input = "1 second";
152 // Agents such as omp advertise a loaded session's commands shortly after answering session/load.
153 const ACP_LOADED_COMMANDS_WAIT: Duration.Input = "2 seconds";
154 const ACP_PROMPT_INACTIVITY_SLICE_MILLIS = 60_000;
155 const ACP_HOST_SLEEP_TOLERANCE_MILLIS = 10_000;
156
157 // pi-agent-core agents (oh-my-pi) end a turn while background work runs and reject
158 // prompts until it finishes; the prompt is resent rather than failing the turn.
159 function isAgentBusyPromptError(error: EffectAcpErrors.AcpError): boolean {
160 return (
161 error._tag === "AcpRequestError" && error.errorMessage.startsWith("Agent is already processing")
162 );
163 }
164
165 function sendPromptWhenIdle<A>(
166 turn: { readonly interrupted: boolean; readonly finalized: boolean },
167 prompt: () => Effect.Effect<A, EffectAcpErrors.AcpError>,
168 superseded: () => boolean = () => false,
169 ): Effect.Effect<A, EffectAcpErrors.AcpError> {
170 // A Stop or a prompt-steer can land during the wait, so both are rechecked before each resend.
171 const stopped = () => turn.interrupted || turn.finalized || superseded();
172 return prompt().pipe(
173 Effect.catchIf(
174 (error) => isAgentBusyPromptError(error) && !stopped(),
175 (error) =>
176 Effect.sleep(ACP_BUSY_PROMPT_RETRY_INTERVAL).pipe(
177 Effect.andThen(
178 Effect.suspend(() =>
179 stopped() ? Effect.fail(error) : sendPromptWhenIdle(turn, prompt, superseded),
180 ),
181 ),
182 ),
183 ),
184 );
185 }
186
187 /**
188 * Emit first chunks and segment-close events immediately; coalesce later chunks into full-text snapshots.
189 * This avoids quadratic output; scheduled flushes can run late under host load.
190 */
191 const ACP_TEXT_FLUSH_INTERVAL: Duration.Input = "50 millis";
192 // Subagent messages are stored as finished, so they skip the server's paragraph
193 // throttle and every snapshot is persisted. Match that throttle's 400 ms cadence.
194 const ACP_SUBAGENT_TEXT_FLUSH_INTERVAL: Duration.Input = "400 millis";
195
196 // Output of the running prompt. Session metadata and unknown updates do not reset its timeout.
197 const ACP_PROMPT_ACTIVITY_UPDATES: ReadonlySet<string> = new Set([
198 "agent_message",
199 "agent_message_chunk",
200 "agent_thought",
201 "agent_thought_chunk",
202 "tool_call",
203 "tool_call_update",
204 "tool_call_content_chunk",
205 "terminal_output_chunk",
206 "terminal_update",
207 "plan",
208 "plan_update",
209 "plan_removed",
210 "compaction_update",
211 "compaction_summary_chunk",
212 ]);
213
214 export interface AcpAdapterV2RuntimeInput {
215 readonly cwd: string;
216 readonly runtimePolicy: ProviderAdapter.ProviderAdapterV2RuntimePolicy;
217 readonly mcpServers: ReadonlyArray<EffectAcpSchema.McpServer>;
218 readonly acpMcpServers?: ReadonlyArray<EffectAcpSchema.McpServer>;
219 readonly httpMcpServers?: ReadonlyArray<EffectAcpSchema.McpServer>;
220 readonly processEnvironment?: NodeJS.ProcessEnv;
221 readonly resumeSessionId?: string;
222 readonly interruptPromptOnCancel?: boolean;
223 readonly sessionMeta?: NonNullable<AcpSessionRuntime.AcpSessionRuntimeOptions["sessionMeta"]>;
224 readonly clientCapabilities: EffectAcpSchema.InitializeRequest["clientCapabilities"];
225 readonly clientInfo: AcpSessionRuntime.AcpSessionRuntimeOptions["clientInfo"];
226 readonly requestLogger?: NonNullable<AcpSessionRuntime.AcpSessionRuntimeOptions["requestLogger"]>;
227 readonly protocolLogging: NonNullable<
228 AcpSessionRuntime.AcpSessionRuntimeOptions["protocolLogging"]
229 >;
230 readonly onTermination: NonNullable<AcpSessionRuntime.AcpSessionRuntimeOptions["onTermination"]>;
231 readonly onOutgoingResponseFailure?: AcpSessionRuntime.AcpSessionRuntimeOptions["onOutgoingResponseFailure"];
232 readonly onOutgoingResponse?: AcpSessionRuntime.AcpSessionRuntimeOptions["onOutgoingResponse"];
233 readonly onIncomingRequest?: AcpSessionRuntime.AcpSessionRuntimeOptions["onIncomingRequest"];
234 }
235
236 export type AcpAdapterV2NativeLogging = Pick<
237 AcpSessionRuntime.AcpSessionRuntimeOptions,
238 "requestLogger" | "protocolLogging"
239 >;
240
241 export interface AcpAdapterV2UserInputRequest {
242 readonly nativeItemId: string;
243 readonly nativeRequestId: string;
244 readonly questions: ReadonlyArray<OrchestrationV2UserInputQuestion>;
245 }
246
247 export interface AcpAdapterV2ExtensionContext {
248 readonly runtime: AcpSessionRuntime.AcpSessionRuntime["Service"];
249 readonly reportProviderRetry: (input: {
250 readonly sessionId: string;
251 readonly failure: OrchestrationV2ProviderFailure;
252 }) => Effect.Effect<void>;
253 readonly finishSubagent: (notice: {
254 readonly sessionId: string;
255 readonly childSessionId: string;
256 readonly status: "completed" | "failed" | "cancelled";
257 readonly result: string | null;
258 }) => Effect.Effect<void>;
259 readonly applyBackgroundTaskMutation: (mutation: {
260 readonly sessionId: string;
261 readonly taskId: string;
262 readonly status: "running" | "completed" | "failed";
263 readonly output?: string;
264 readonly report?: BackgroundWork;
265 }) => Effect.Effect<void>;
266 /** For compactions reported outside ACP `compaction_update`. */
267 readonly markSessionCompacted: (sessionId: string) => Effect.Effect<void>;
268 /**
269 * For agents that hold `session/prompt` past their foreground work on ACP v1. An idle settles
270 * the run only after a `running` report during it, so an earlier prompt's idle cannot.
271 */
272 readonly reportForegroundWork: (notice: {
273 readonly sessionId: string;
274 readonly state: "running" | "idle";
275 }) => Effect.Effect<void>;
276 readonly requestUserInput: (
277 input: AcpAdapterV2UserInputRequest,
278 requestContext: EffectAcpProtocol.AcpRequestContext,
279 ) => Effect.Effect<
280 {
281 readonly acknowledgeNativeResponse: Effect.Effect<void, EffectAcpErrors.AcpError>;
282 readonly answers: ProviderUserInputAnswers | null;
283 },
284 EffectAcpErrors.AcpError
285 >;
286 readonly captureProposedPlan: (input: { readonly planMarkdown: string }) => Effect.Effect<void>;
287 readonly lastProposedPlanMarkdown: Effect.Effect<string | undefined>;
288 }
289
290 /**
291 * Raised when an agent does not accept the session's model selection: the
292 * session's model option does not offer it, or the agent answers the write
293 * with invalid params. `makeProviderFailure` shows its message to the user;
294 * the agent's reply stays on `cause`.
295 */
296 class AcpModelSelectionError extends Schema.TaggedError<AcpModelSelectionError>()(
297 "AcpModelSelectionError",
298 {
299 model: Schema.String,
300 cause: Schema.Defect(),
301 },
302 ) {
303 override get message(): string {
304 return `The agent did not accept the model "${this.model}". Choose another model for this provider, then retry.`;
305 }
306 }
307
308 /** A prompt-steered turn spans several prompts, each reporting its own usage. */
309 function addAcpUsage(
310 total: EffectAcpSchema.Usage | undefined,
311 usage: EffectAcpSchema.Usage | null | undefined,
312 ): EffectAcpSchema.Usage | undefined {
313 if (usage == null) return total;
314 if (total === undefined) return usage;
315 const optional = (left: number | null | undefined, right: number | null | undefined) =>
316 left == null && right == null ? {} : { value: (left ?? 0) + (right ?? 0) };
317 const thought = optional(total.thoughtTokens, usage.thoughtTokens);
318 const cachedRead = optional(total.cachedReadTokens, usage.cachedReadTokens);
319 const cachedWrite = optional(total.cachedWriteTokens, usage.cachedWriteTokens);
320 return {
321 totalTokens: total.totalTokens + usage.totalTokens,
322 inputTokens: total.inputTokens + usage.inputTokens,
323 outputTokens: total.outputTokens + usage.outputTokens,
324 ...("value" in thought ? { thoughtTokens: thought.value } : {}),
325 ...("value" in cachedRead ? { cachedReadTokens: cachedRead.value } : {}),
326 ...("value" in cachedWrite ? { cachedWriteTokens: cachedWrite.value } : {}),
327 };
328 }
329
330 /**
331 * Maps one per-turn usage sample (flavors with reportsPerTurnPromptUsage)
332 * directly onto TurnTokenUsage: the response's counters already cover exactly
333 * this prompt.
334 */
335 export function acpPerTurnPromptUsage(
336 usage: EffectAcpSchema.Usage | null | undefined,
337 hasSubagents: boolean,
338 terminalStatus: OrchestrationV2ProviderTurn["status"],
339 geminiUsage = false,
340 ): TurnTokenUsage {
341 if (usage == null) {
342 return { usageScope: "main_agent", usageStatus: "unavailable", hasSubagents };
343 }
344 const inputTokens = geminiUsage
345 ? usage.inputTokens + (usage.cachedReadTokens ?? 0)
346 : usage.inputTokens;
347 const outputTokens = usage.outputTokens;
348 // TurnTokenUsage contract: input includes cache read + write and reasoning
349 // is a subset of output, so clamp counters that exceed their parent and
350 // drop the ones the agent left unset. Cache writes are capped at whatever
351 // cache reads leave of input, so the pair cannot exceed it.
352 const clampSubset = (value: number | null | undefined, parent: number) =>
353 value == null ? undefined : Math.min(value, parent);
354 const cachedInputTokens = clampSubset(usage.cachedReadTokens, inputTokens);
355 const cacheCreationTokens = clampSubset(
356 usage.cachedWriteTokens,
357 inputTokens - (cachedInputTokens ?? 0),
358 );
359 const reasoningTokens = clampSubset(usage.thoughtTokens, outputTokens);
360 return {
361 usageScope: "main_agent",
362 usageStatus: terminalStatus === "completed" ? "complete" : "partial",
363 hasSubagents,
364 inputTokens,
365 outputTokens,
366 ...(cachedInputTokens === undefined ? {} : { cachedInputTokens }),
367 ...(cacheCreationTokens === undefined ? {} : { cacheCreationTokens }),
368 ...(reasoningTokens === undefined ? {} : { reasoningTokens }),
369 };
370 }
371
372 interface AcpPromptOutcomeFailure {
373 readonly failure: OrchestrationV2ProviderFailure;
374 readonly threadDisposition: "reusable" | "broken";
375 /** The native session can carry on: the turn resends this prompt once before failing. */
376 readonly resumeWith?: string;
377 }
378
379 export interface AcpAdapterV2Flavor {
380 readonly buildAttachmentPrompt?: (input: {
381 readonly text: string;
382 readonly attachments: ReadonlyArray<ChatAttachment>;
383 readonly resolveAttachmentPath: (attachment: ChatAttachment) => string | null;
384 readonly promptCapabilities: EffectAcpSchema.AgentCapabilities["promptCapabilities"];
385 }) => Effect.Effect<ReadonlyArray<EffectAcpSchema.ContentBlock>, EffectAcpErrors.AcpError>;
386 readonly promptFailure?: (cause: unknown) => OrchestrationV2ProviderFailure;
387 /** The flavor's runtime refuses a version the policy rates broken when it starts. */
388 readonly checksVersionAtHandshake?: boolean;
389 /**
390 * Runs before `session/prompt`. The returned check sees a prompt the agent ended
391 * without an error or cancel, and reports a failure its stop reason hid. A reported
392 * failure restarts the runtime before the next turn. A `broken` thread's native
393 * history is unusable, so the next turn falls back to a fresh session.
394 */
395 readonly watchPromptOutcome?: (
396 sessionId: string,
397 ) => Effect.Effect<
398 (result: EffectAcpSchema.PromptResponse) => Effect.Effect<AcpPromptOutcomeFailure | undefined>
399 >;
400 readonly requiresSignIn?: (cause: unknown) => boolean;
401 /**
402 * Runs before attachment paths, T3 instructions and native slash-command detection,
403 * so a rewrite can turn the user's text into a native command.
404 */
405 readonly rewriteUserText?: (
406 text: string,
407 turnInput: ProviderAdapter.ProviderAdapterV2TurnInput,
408 ) => Effect.Effect<string, never, ChildProcessSpawner.ChildProcessSpawner>;
409 readonly driver: ProviderDriverKind;
410 readonly capabilities: OrchestrationV2ProviderCapabilities;
411 readonly supportsNativeGoals?: Effect.Effect<boolean>;
412 readonly clientCapabilitiesMeta?: NonNullable<
413 EffectAcpSchema.InitializeRequest["clientCapabilities"]
414 >["_meta"];
415 readonly mcpOverHttp?: boolean;
416 /** The agent has no tool search of its own, so T3 lists optional tools on demand. */
417 readonly deferMcpTools?: boolean;
418 readonly normalizeSessionUpdate?: (
419 notification: EffectAcpSchema.SessionNotification,
420 ) => EffectAcpSchema.SessionNotification;
421 /**
422 * Agent updates that belong to no turn (Kiro's own cloud-config fetch). They
423 * are dropped before anything reads them, so they neither show in the turn
424 * nor count as it starting.
425 */
426 readonly ignoreSessionUpdate?: (notification: EffectAcpSchema.SessionNotification) => boolean;
427 readonly onAvailableCommandsUpdate?: (
428 commands: ReadonlyArray<EffectAcpSchema.AvailableCommand>,
429 ) => Effect.Effect<void>;
430 readonly onSessionConfigurationUpdate?: (
431 configOptions: ReadonlyArray<EffectAcpSchema.SessionConfigOption>,
432 modeState: AcpSessionModeState | undefined,
433 modelState: EffectAcpSchema.SessionModelState | null | undefined,
434 ) => Effect.Effect<void>;
435 readonly onUrlElicitation?: (input: {
436 readonly elicitationId: string;
437 readonly url: string;
438 readonly message: string;
439 }) => Effect.Effect<boolean>;
440 readonly extractElicitationForm?: (request: EffectAcpSchema.CreateElicitationRequest) =>
441 | {
442 readonly questions: ReadonlyArray<OrchestrationV2UserInputQuestion>;
443 readonly respond: (
444 answers: ProviderUserInputAnswers,
445 ) => EffectAcpSchema.CreateElicitationResponse;
446 }
447 | undefined;
448 readonly withRuntimeStartup?: <A, E, R>(effect: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>;
449 readonly makeRuntime: (
450 input: AcpAdapterV2RuntimeInput,
451 ) => Effect.Effect<
452 AcpSessionRuntime.AcpSessionRuntime["Service"],
453 EffectAcpErrors.AcpError,
454 ChildProcessSpawner.ChildProcessSpawner | SecureRandom.SecureRandom | Scope.Scope
455 >;
456 readonly customModels?: ReadonlyArray<string>;
457 /** The agent may run another model than session/new reports, so the model is always written. */
458 readonly alwaysSetModel?: boolean;
459 /** Values the client shows for options a new session's selection leaves unset. */
460 readonly unsetOptionDefaults?: Effect.Effect<NonNullable<ModelSelection["options"]>>;
461 readonly resolveModelId?: (selection: ModelSelection) => string | undefined;
462 /**
463 * The agent advertises its model option only after `session/new` returns
464 * (Kiro sends it in a `config_option_update`), so in-session model switching
465 * is not inferred from the setup result.
466 */
467 readonly modelOptionArrivesLate?: boolean;
468 readonly getModelContextWindow?: (
469 selection: ModelSelection,
470 session: AcpSessionRuntime.AcpSessionRuntimeStartResult,
471 ) => number | undefined;
472 readonly applyModelSelection?: (input: {
473 readonly runtime: AcpSessionRuntime.AcpSessionRuntime["Service"];
474 readonly startResult: AcpSessionRuntime.AcpSessionRuntimeStartResult;
475 readonly modelSelection: ModelSelection;
476 }) => Effect.Effect<string | undefined, EffectAcpErrors.AcpError>;
477 /**
478 * Model-selection option ids `applyModelSelection` sets itself under a
479 * native id, which the generic option loop then skips (Kiro's
480 * `reasoningEffort` is its `effortLevel`).
481 */
482 readonly ownedModelOptionIds?: ReadonlyArray<string>;
483 readonly lockSessionModeToPolicy?: true;
484 readonly sessionModeForPolicy?: (
485 policy: ProviderAdapter.ProviderAdapterV2RuntimePolicy,
486 ) => string | undefined;
487 /**
488 * Native select-option values to apply for a runtime policy (e.g. Kiro's
489 * `autopilot`), set on every session configure. A value the session does
490 * not advertise is skipped; an agent rejecting it fails the session.
491 */
492 readonly sessionConfigForPolicy?: (
493 policy: ProviderAdapter.ProviderAdapterV2RuntimePolicy,
494 ) => ReadonlyArray<{ readonly id: string; readonly value: string }>;
495 /**
496 * The runtime mode a native session mode grants, for flavors whose modes are permission levels.
497 * A picked mode this does not place within the thread's runtime mode is not applied.
498 */
499 readonly runtimeModeForSessionMode?: (modeId: string) => RuntimeMode | undefined;
500 readonly clientFileSystem?: {
501 readonly readTextFile: (
502 request: EffectAcpSchema.ReadTextFileRequest,
503 cwd: string | null,
504 ) => Effect.Effect<EffectAcpSchema.ReadTextFileResponse, EffectAcpErrors.AcpError>;
505 readonly writeTextFile?: (
506 request: EffectAcpSchema.WriteTextFileRequest,
507 cwd: string | null,
508 ) => Effect.Effect<EffectAcpSchema.WriteTextFileResponse, EffectAcpErrors.AcpError>;
509 };
510 readonly extractPermissionQuestion?: (request: EffectAcpSchema.RequestPermissionRequest) =>
511 | {
512 readonly question: OrchestrationV2UserInputQuestion;
513 readonly respond: (
514 answers: ProviderUserInputAnswers,
515 ) => EffectAcpSchema.RequestPermissionResponse | undefined;
516 }
517 | undefined;
518 /** Grok Auto asks only about classifier refusals; T3 policy must not auto-approve them. */
519 readonly permissionDisposition?: (
520 policy: ProviderAdapter.ProviderAdapterV2RuntimePolicy,
521 request: EffectAcpSchema.RequestPermissionRequest,
522 ) => AcpPermissionDisposition;
523 readonly approvalOptions?: (
524 request: EffectAcpSchema.RequestPermissionRequest,
525 ) => ReadonlyArray<ProviderApprovalOption>;
526 /** Options T3 may answer with; the rest (e.g. Devin's bypass-permissions plan exit) are never sent. */
527 readonly answerablePermissionOptions?: (
528 request: EffectAcpSchema.RequestPermissionRequest,
529 ) => ReadonlyArray<EffectAcpSchema.PermissionOption>;
530 readonly onSessionEvent?: (
531 event: AcpSessionRuntime.AcpSessionRuntimeEvent,
532 cwd: string,
533 ) => Effect.Effect<void>;
534 readonly subagentsIdleOnTurnCompletion?: boolean;
535 /**
536 * Subagents the agent goes on running after its prompt, with no update when one ends. Asked
537 * when the prompt ends and when a reply the agent started by itself ends; the native task ids
538 * it returns hold the turn open and the rest become idle.
539 */
540 readonly subagentsOutlivingPrompt?: (input: {
541 readonly sessionId: string;
542 readonly nativeTaskIds: ReadonlyArray<string>;
543 }) => Effect.Effect<ReadonlyArray<string>>;
544 readonly supportsCompaction?: boolean;
545 /** Sends `/compact` as a prompt, only to sessions whose advertised commands include `compact`. */
546 readonly compactViaAdvertisedCommand?: boolean;
547 /**
548 * Native steering: `send` queues a message into the running turn and returns the
549 * agent's id for it, which `injectedSteerId` reads from the update that delivers it.
550 * No id means the running turn reads the message once the agent accepts it.
551 */
552 readonly steering?: {
553 readonly send: (
554 runtime: AcpSessionRuntime.AcpSessionRuntime["Service"],
555 sessionId: string,
556 text: string,
557 images: ReadonlyArray<EffectAcpSchema.ContentBlock>,
558 ) => Effect.Effect<string | undefined, EffectAcpErrors.AcpError>;
559 readonly injectedSteerId?: (
560 notification: EffectAcpSchema.SessionNotification,
561 ) => string | undefined;
562 };
563 /**
564 * Steers with another `session/prompt` while one runs: the agent answers the running prompt
565 * `end_turn` and carries the turn on under the new one, leaving its tools and subagents alone.
566 */
567 readonly steersWithPrompt?: (
568 initializeResult: AcpSessionRuntime.AcpSessionRuntimeStartResult["initializeResult"],
569 ) => boolean;
570 /**
571 * Native fork from an earlier turn. `nativeTurnId` reads the agent's id for a running
572 * turn's prompt, which the turn keeps as its native ref; forking from that turn sends
573 * `forkMeta(id)` as the `session/fork` `_meta`.
574 */
575 readonly forkFromTurn?: {
576 readonly supported: (
577 initializeResult: AcpSessionRuntime.AcpSessionRuntimeStartResult["initializeResult"],
578 ) => boolean;
579 readonly nativeTurnId: (
580 notification: EffectAcpSchema.SessionNotification,
581 ) => string | undefined;
582 readonly forkMeta: (
583 nativeTurnId: string,
584 ) => NonNullable<EffectAcpSchema.ForkSessionRequest["_meta"]>;
585 };
586 /**
587 * Compacts with the agent's own request, for agents that answer a `/compact` prompt as chat.
588 * Compaction is refused when `supported` rejects the running agent's `initialize` result.
589 */
590 readonly compactSession?: {
591 readonly supported: (
592 initializeResult: AcpSessionRuntime.AcpSessionRuntimeStartResult["initializeResult"],
593 ) => boolean;
594 readonly compact: (
595 runtime: AcpSessionRuntime.AcpSessionRuntime["Service"],
596 sessionId: string,
597 ) => Effect.Effect<void, EffectAcpErrors.AcpError>;
598 };
599 readonly runtimeHarness?: string;
600 readonly registerExtensions?: (
601 context: AcpAdapterV2ExtensionContext,
602 ) => Effect.Effect<void, EffectAcpErrors.AcpError>;
603 readonly extractSubagentSessionEvent?: (
604 notification: EffectAcpSchema.SessionNotification,
605 ) => AcpSubagentSessionEvent | undefined;
606 readonly extractSubagentUpdate?: (
607 toolCall: AcpToolCallState,
608 ) => AcpAdapterV2SubagentUpdate | undefined;
609 readonly isProvisionalSubagentTool?: (toolCall: AcpToolCallState) => boolean;
610 readonly normalizeToolCall?: (toolCall: AcpToolCallState) => AcpToolCallState;
611 readonly isCancelledToolCall?: (payload: unknown) => boolean;
612 readonly extractProposedPlanMarkdown?: (toolCall: AcpToolCallState) => string | undefined;
613 readonly extractBackgroundTaskId?: (toolCall: AcpToolCallState) => string | undefined;
614 /** Distinguishes commands from monitors when lifecycle notifications omit their kind. */
615 readonly isBackgroundCommandTool?: (toolCall: AcpToolCallState) => boolean;
616 readonly extractBackgroundToolMutation?: (text: string) => ReadonlyArray<{
617 readonly taskId: string;
618 readonly status: "running" | "completed" | "failed";
619 readonly appendOutput: string;
620 }>;
621 readonly extractSubagentEndNotice?: (text: string) =>
622 | {
623 readonly childSessionId: string;
624 readonly status: "completed" | "failed";
625 }
626 | undefined;
627 readonly extractBackgroundTaskCompletion?: (toolCall: AcpToolCallState) => ReadonlyArray<{
628 readonly taskId: string;
629 readonly status: "running" | "completed" | "failed";
630 readonly appendOutput: string;
631 }>;
632 readonly isPersistentBackgroundTool?: (toolCall: AcpToolCallState) => boolean;
633 /**
634 * A tool the agent goes on running after its prompt ends, and reports on by itself when the
635 * tool ends. With `deferFinalizeForBackgroundWork`, the turn stays open until then.
636 */
637 readonly toolOutlivesPrompt?: (toolCall: AcpToolCallState) => boolean;
638 readonly isProviderWakeNotification?: (
639 notification: EffectAcpSchema.SessionNotification,
640 ) => boolean;
641 readonly deferFinalizeForBackgroundWork?: AcpNegotiatedFlag;
642 /**
643 * Every model reply ends with `usage_update`, also the ones the agent starts with no prompt
644 * open. A turn that ends on the deferred finalize waits for it instead of the short debounce.
645 */
646 readonly replyEndsWithUsageUpdate?: boolean;
647 readonly assertComplete?: Effect.Effect<void, EffectAcpErrors.AcpError>;
648 /** Interrupt the local prompt fiber before `session/cancel` (Grok wedged prompts). */
649 readonly interruptPromptOnCancel?: boolean;
650 /**
651 * Hold `session/cancel` until an update after `session/prompt` matches `isStart`,
652 * or `bound` has passed; skip it if the prompt settles first. Kiro 2.27.1 can
653 * drop a cancel sent just after the prompt and run the turn to completion.
654 */
655 readonly cancelAfterPromptStarts?: {
656 readonly isStart: (update: EffectAcpSchema.SessionUpdate) => boolean;
657 readonly bound: Duration.Input;
658 };
659 /**
660 * The agent's PromptResponse.usage counters read per-turn. The ACP spec
661 * leaves usage semantics open, so this stays unset until proven live.
662 */
663 readonly reportsPerTurnPromptUsage?: boolean;
664 /** Antigravity 1.5+ usage: inputTokens leaves out cachedReadTokens, while outputTokens already includes thoughtTokens. */
665 readonly geminiPromptUsage?: boolean;
666 /**
667 * Fails a dispatched prompt after this long with no update for its session while no
668 * agent request, tool or subagent is open, and replaces the agent before the next turn.
669 */
670 readonly promptInactivityTimeout?: Duration.Input;
671 /** Grok can retain task_already_running until process exit. */
672 readonly restartRuntimeAfterInterrupt?: boolean;
673 /** Prompt failures after which the agent process keeps failing until replaced. */
674 readonly restartRuntimeAfterPromptError?: (error: unknown) => boolean;
675 readonly restartRuntimeOnEveryInterrupt?: boolean;
676 readonly terminateRuntimeProcessGroupOnInterrupt?: boolean;
677 readonly preserveRuntimeOnSettledInterrupt?: boolean;
678 readonly enablePostSettleContinuation?: AcpNegotiatedFlag;
679 /** A native request after prompt settlement starts a continuation before it is handled. */
680 readonly wakeOnDetachedRequest?: boolean;
681 /** Settle on native idle after the accepted user echo, only on negotiated ACP v2. */
682 readonly followAgentWorkState?: boolean;
683 /**
684 * Grok CLI currently accepts and vision-processes image blocks while still
685 * reporting the capability as false; without this override, screenshot turns
686 * fail before `session/prompt`.
687 */
688 readonly supportsImagePrompts?: boolean;
689 /**
690 * True when this session's native system prompt carries T3's PR-linking instructions, so
691 * turns omit them. Must use the same negotiated check that sent them on session setup.
692 */
693 readonly sessionCarriesPullRequestLinking?: (
694 initializeResult: EffectAcpSchema.InitializeResponse,
695 ) => boolean;
696 }
697
698 /**
699 * A flavor flag that is either fixed, or read from the agent's `initialize` result for
700 * agents identified only there, such as one launched through a wrapper command.
701 */
702 type AcpNegotiatedFlag =
703 | boolean
704 | ((initializeResult: EffectAcpSchema.InitializeResponse) => boolean);
705
706 const readNegotiatedFlag = (
707 flag: AcpNegotiatedFlag | undefined,
708 initializeResult: EffectAcpSchema.InitializeResponse,
709 ) => (typeof flag === "function" ? flag(initializeResult) : flag === true);
710
711 function acpSupportsImagePrompts(input: {
712 readonly flavorSupportsImagePrompts?: boolean | undefined;
713 readonly negotiatedImage?: boolean | undefined;
714 }): boolean {
715 return input.flavorSupportsImagePrompts === true || input.negotiatedImage === true;
716 }
717
718 export function acpScopedNativeId(instanceId: ProviderInstanceId, nativeId: string): string {
719 return `provider-instance:${encodeURIComponent(instanceId)}:${nativeId}`;
720 }
721
722 function acpProviderItemNativeId(input: {
723 readonly instanceId: ProviderInstanceId;
724 readonly itemIdentityVersion: 2 | undefined;
725 readonly nativeId: string;
726 }): string {
727 return input.itemIdentityVersion === 2
728 ? acpScopedNativeId(input.instanceId, input.nativeId)
729 : input.nativeId;
730 }
731
732 export type AcpSubagentSessionEvent =
733 | {
734 readonly type: "state";
735 readonly childSessionId: string;
736 readonly parentSessionId: string;
737 readonly status: "running" | "completed" | "failed" | "cancelled";
738 readonly result: string | null;
739 }
740 | {
741 readonly type: "delegation";
742 readonly childSessionId: string;
743 readonly parentSessionId: string | null;
744 readonly delegationId: string;
745 readonly prompt: string;
746 };
747
748 export interface AcpAdapterV2SubagentUpdate {
749 readonly nativeTaskId: string;
750 readonly prompt: string;
751 readonly title: string | null;
752 readonly model: string | null;
753 readonly status:
754 | "pending"
755 | "running"
756 | "idle"
757 | "completed"
758 | "failed"
759 | "interrupted"
760 | "cancelled";
761 readonly childSessionId: string | null;
762 readonly result: string | null;
763 readonly suppressNormalTool?: boolean;
764 }
765
766 export interface AcpAdapterV2Options {
767 readonly instanceId: ProviderInstanceId;
768 readonly flavor: AcpAdapterV2Flavor;
769 readonly selfInvocation: SelfInvocation;
770 readonly clientTerminals?: {
771 readonly environment?: NodeJS.ProcessEnv;
772 readonly shellCommands?: boolean;
773 };
774 readonly nativeLogging?: (threadId: ThreadId) => AcpAdapterV2NativeLogging;
775 readonly continuationRequests?: {
776 readonly offer: (
777 request: ProviderContinuationRequests.ProviderContinuationRequest,
778 ) => Effect.Effect<void>;
779 };
780 readonly testHooks?: {
781 readonly onDeferredFinalizeScheduled?: (debounce: Duration.Input) => Effect.Effect<void>;
782 /** `cancelAfterPromptStarts`: Stop is holding `session/cancel` until the prompt starts. */
783 readonly onCancelHeld?: () => Effect.Effect<void>;
784 readonly afterPromptWireSettled?: () => Effect.Effect<void>;
785 readonly afterPromptSettledWithBackgroundWork?: () => Effect.Effect<void>;
786 readonly afterPromptCallback?: () => Effect.Effect<void>;
787 readonly onNativeResponseLifecycle?: (event: {
788 readonly generation?: number;
789 readonly requestId?: string;
790 readonly type:
791 | "admission_rejected"
792 | "failed"
793 | "late_noop"
794 | "registered"
795 | "removed"
796 | "timer_exited"
797 | "timer_started"
798 | "watcher_exited"
799 | "watcher_started";
800 }) => Effect.Effect<void>;
801 };
802 }
803
804 export const AcpProviderCapabilitiesV2 = {
805 sessions: {
806 supportsMultipleProviderThreadsPerSession: false,
807 supportsModelSwitchInSession: false,
808 supportsProviderSwitchingViaHandoff: true,
809 supportsRuntimeModeSwitchInSession: false,
810 pendingRequestsSurviveRestart: false,
811 },
812 threads: {
813 canCreateEmptyThread: true,
814 canReadThreadSnapshot: false,
815 canRollbackThread: true,
816 canForkThread: false,
817 canForkFromTurn: false,
818 canForkFromSubagentThread: false,
819 exposesNativeThreadId: true,
820 },
821 turns: {
822 exposesNativeTurnId: false,
823 emitsTurnStarted: true,
824 emitsTurnCompleted: true,
825 supportsInterrupt: true,
826 supportsNativeResume: false,
827 supportsActiveSteering: false,
828 supportsSteeringByInterruptRestart: true,
829 supportsQueuedMessages: true,
830 terminalStatusQuality: "strong",
831 },
832 streaming: {
833 streamsAssistantText: true,
834 streamsReasoning: true,
835 streamsToolOutput: true,
836 streamsPlanText: false,
837 emitsMessageCompleted: true,
838 },
839 tools: {
840 exposesToolItemIds: true,
841 emitsToolStarted: true,
842 emitsToolCompleted: true,
843 emitsToolOutput: true,
844 supportsMcpTools: false,
845 supportsDynamicToolCallbacks: false,
846 },
847 approvals: {
848 supportsCommandApproval: true,
849 supportsFileReadApproval: true,
850 supportsFileChangeApproval: true,
851 supportsApplyPatchApproval: false,
852 approvalsHaveNativeRequestIds: false,
853 approvalCallbacksAreLiveOnly: true,
854 approvalsCanOriginateFromSubagents: false,
855 },
856 planning: {
857 emitsPlanUpdated: true,
858 emitsTodoList: true,
859 emitsProposedPlan: false,
860 supportsStructuredQuestions: true,
861 planDeltasHaveItemIds: false,
862 },
863 subagents: {
864 supportsSubagents: false,
865 exposesSubagentThreadIds: false,
866 emitsSubagentLifecycle: false,
867 canWaitForSubagents: false,
868 canCloseSubagents: false,
869 canForkSubagentThread: false,
870 },
871 context: {
872 acceptsSystemContext: false,
873 acceptsDeveloperContext: false,
874 acceptsSyntheticUserContext: true,
875 canGenerateSummaries: true,
876 canConsumeHandoffSummaries: true,
877 supportsDeltaHandoff: true,
878 supportsFullThreadHandoff: true,
879 maxRecommendedHandoffChars: null,
880 },
881 checkpointing: {
882 appCanCheckpointFilesystem: true,
883 supportsNestedCheckpointScopes: true,
884 // ACP lacks truncation; rollback starts a fresh agent session and turn start replays the kept history.
885 providerCanRollbackConversation: false,
886 providerRollbackReturnsSnapshot: true,
887 providerCanReadConversationSnapshot: false,
888 },
889 identity: {
890 nativeThreadIds: "strong",
891 nativeTurnIds: "weak",
892 nativeItemIds: "weak",
893 nativeRequestIds: "weak",
894 },
895 runtimePolicy: {
896 enforcement: "client-boundary",
897 },
898 } satisfies OrchestrationV2ProviderCapabilities;
899
900 function canSwitchModelInSession(
901 configOptions: ReadonlyArray<EffectAcpSchema.SessionConfigOption> | null | undefined,
902 models: EffectAcpSchema.SessionModelState | null | undefined,
903 ): boolean {
904 return findModelConfigOption(configOptions) !== undefined || models != null;
905 }
906
907 const STEER_DELIVERY_BOUND = "2 seconds";
908
909 /**
910 * `session/fork` `_meta` for a fork from `providerTurnId`: none for the session head,
911 * the flavor's meta for a turn the agent named, or `null` when the agent can't fork there.
912 */
913 function forkFromTurnMetaFor(input: {
914 readonly driver: ProviderDriverKind;
915 readonly flavor: Pick<AcpAdapterV2Flavor, "forkFromTurn">;
916 readonly canForkFromTurn: boolean;
917 readonly forkInput: ProviderAdapter.ProviderAdapterV2ForkThreadInput;
918 }): NonNullable<EffectAcpSchema.ForkSessionRequest["_meta"]> | undefined | null {
919 const { forkInput } = input;
920 if (forkInput.providerTurnId === undefined) return undefined;
921 const turns = (forkInput.sourceProviderTurns ?? []).filter(
922 (turn) => turn.providerThreadId === forkInput.sourceProviderThread.id,
923 );
924 const target = turns.find((turn) => turn.id === forkInput.providerTurnId);
925 if (target === undefined) return null;
926 if (turns.every((turn) => turn.ordinal <= target.ordinal)) return undefined;
927 const ref = target.nativeTurnRef;
928 if (
929 input.flavor.forkFromTurn === undefined ||
930 !input.canForkFromTurn ||
931 ref === null ||
932 ref.driver !== input.driver ||
933 ref.strength !== "strong" ||
934 ref.nativeId === null
935 ) {
936 return null;
937 }
938 return input.flavor.forkFromTurn.forkMeta(ref.nativeId);
939 }
940
941 function isCompactionMessage(message: ProviderAdapter.ProviderAdapterV2TurnMessage): boolean {
942 return message.text.trim() === "/compact" && message.attachments.length === 0;
943 }
944
945 /** `/compact`, optionally followed by preservation instructions that some agents accept. */
946 function isCompactCommand(message: ProviderAdapter.ProviderAdapterV2TurnMessage): boolean {
947 return /^\/compact(?:\s|$)/.test(message.text.trim()) && message.attachments.length === 0;
948 }
949
950 function negotiatedCapabilities(
951 base: OrchestrationV2ProviderCapabilities,
952 started: AcpSessionRuntime.AcpSessionRuntimeStartResult,
953 modelOptionArrivesLate: boolean,
954 forksFromTurn: boolean,
955 steersWithPrompt: boolean,
956 ): OrchestrationV2ProviderCapabilities {
957 const agent = started.initializeResult.agentCapabilities ?? {};
958 const session = agent.sessionCapabilities;
959 const setup = started.sessionSetupResult;
960 const canSwitchModel =
961 modelOptionArrivesLate || canSwitchModelInSession(setup.configOptions, setup.models);
962 const canLoad = agent.loadSession === true;
963 const canFork = session?.fork != null;
964 return {
965 ...base,
966 sessions: {
967 ...base.sessions,
968 supportsModelSwitchInSession: canSwitchModel,
969 },
970 threads: {
971 ...base.threads,
972 canReadThreadSnapshot: canLoad,
973 canForkThread: canFork,
974 canForkFromTurn: canFork && forksFromTurn,
975 },
976 turns: {
977 ...base.turns,
978 supportsActiveSteering: base.turns.supportsActiveSteering || steersWithPrompt,
979 },
980 tools: {
981 ...base.tools,
982 supportsMcpTools: true,
983 },
984 checkpointing: {
985 ...base.checkpointing,
986 providerCanReadConversationSnapshot: canLoad,
987 },
988 };
989 }
990
991 interface AcpMcpContext {
992 readonly servers: ReadonlyArray<EffectAcpSchema.McpServer>;
993 readonly acpServers: ReadonlyArray<EffectAcpSchema.McpServer>;
994 readonly httpServers: ReadonlyArray<EffectAcpSchema.McpServer>;
995 readonly processEnvironment?: NodeJS.ProcessEnv;
996 readonly endpoint?: string;
997 readonly authorization?: string;
998 }
999
1000 // A GUI-subsystem executable (packaged Windows desktop) does not hold the console, so PowerShell
1001 // neither waits for it nor captures its output or exit code; cmd.exe running a batch file does.
1002 // cmd.exe decodes batch files with the console code page, so paths come from the (UTF-16) environment.
1003 const ACP_MCP_CALL_LAUNCHER = [
1004 "@echo off",
1005 "setlocal EnableExtensions DisableDelayedExpansion",
1006 'set "ELECTRON_RUN_AS_NODE=1"',
1007 "if not defined T3_ACP_MCP_ENTRYPOINT goto packaged",
1008 '"%T3_ACP_MCP_NODE%" "%T3_ACP_MCP_ENTRYPOINT%" acp-mcp-call %*',
1009 "exit /b %errorlevel%",
1010 ":packaged",
1011 '"%T3_ACP_MCP_NODE%" acp-mcp-call %*',
1012 "",
1013 ].join("\r\n");
1014
1015 const writeAcpMcpCallLauncher = Effect.fn("AcpAdapterV2.writeAcpMcpCallLauncher")(function* (
1016 stateDir: string,
1017 ) {
1018 if (!(yield* HostProcess.isWindows)) return undefined;
1019 const fileSystem = yield* FileSystem.FileSystem;
1020 const dir = `${stateDir}\\acp`;
1021 const launcherPath = `${dir}\\acp-mcp-call.cmd`;
1022 return yield* fileSystem.makeDirectory(dir, { recursive: true }).pipe(
1023 Effect.andThen(fileSystem.writeFileString(launcherPath, ACP_MCP_CALL_LAUNCHER)),
1024 Effect.as(launcherPath),
1025 Effect.catch((error) =>
1026 Effect.logWarning("Could not write the ACP terminal tool launcher.", error).pipe(
1027 Effect.as(undefined),
1028 ),
1029 ),
1030 );
1031 });
1032
1033 function acpMcpContext(
1034 session: McpProviderSession.McpProviderSessionConfig | undefined,
1035 self: SelfInvocation,
1036 mcpOverHttp: boolean | undefined,
1037 deferMcpTools: boolean | undefined,
1038 callLauncher: string | undefined,
1039 ): AcpMcpContext {
1040 if (session === undefined) {
1041 return { servers: [], acpServers: [], httpServers: [] };
1042 }
1043 // codex-acp 1.2.0 and pi-acp drop injected HTTP servers, so HTTP is opt-in per flavor.
1044 return {
1045 servers: [
1046 {
1047 name: "t3-code",
1048 command: self.command,
1049 args: [...selfInvocationArgs(self, ["acp-mcp-bridge"])],
1050 env: [
1051 { name: "ELECTRON_RUN_AS_NODE", value: "1" },
1052 { name: "T3_ACP_MCP_ENDPOINT", value: session.endpoint },
1053 { name: "T3_ACP_MCP_AUTHORIZATION", value: session.authorizationHeader },
1054 ],
1055 },
1056 ],
1057 acpServers: [{ type: "acp", name: "t3-code", serverId: "t3-code" }],
1058 httpServers:
1059 mcpOverHttp === true
1060 ? [
1061 {
1062 type: "http",
1063 name: "t3-code",
1064 url: session.endpoint,
1065 headers: [
1066 { name: "Authorization", value: session.authorizationHeader },
1067 ...(deferMcpTools === true
1068 ? [{ name: McpProviderSession.MCP_TOOL_EXPOSURE_HEADER, value: "deferred" }]
1069 : []),
1070 ],
1071 },
1072 ]
1073 : [],
1074 endpoint: session.endpoint,
1075 authorization: session.authorizationHeader,
1076 processEnvironment: {
1077 // The thread id every process the agent starts inherits, so a tool run
1078 // from its shell can find its T3 thread. Claude and Codex sessions set
1079 // the same variable (PortScanner.AGENT_THREAD_ENV; a string literal here
1080 // because this package cannot reach apps/server).
1081 T3CODE_THREAD_ID: session.threadId,
1082 T3_ACP_MCP_ENDPOINT: session.endpoint,
1083 T3_ACP_MCP_AUTHORIZATION: session.authorizationHeader,
1084 T3_ACP_MCP_NODE: self.command,
1085 ...(self.entrypoint === undefined ? {} : { T3_ACP_MCP_ENTRYPOINT: self.entrypoint }),
1086 ...(callLauncher === undefined ? {} : { T3_ACP_MCP_CALL: callLauncher }),
1087 },
1088 };
1089 }
1090
1091 function acpMcpActivation(context: AcpMcpContext) {
1092 return {
1093 mcpServers: context.servers,
1094 acpMcpServers: context.acpServers,
1095 httpMcpServers: context.httpServers,
1096 };
1097 }
1098
1099 function nativeThreadId(
1100 driver: ProviderDriverKind,
1101 thread: OrchestrationV2ProviderThread,
1102 ): Effect.Effect<string, ProviderAdapter.ProviderAdapterProtocolError> {
1103 const id = thread.nativeThreadRef?.nativeId;
1104 if (id === null || id === undefined || id.trim().length === 0) {
1105 return Effect.fail(
1106 new ProviderAdapter.ProviderAdapterProtocolError({
1107 driver,
1108 detail: `Provider thread ${thread.id} is missing its ACP session id`,
1109 }),
1110 );
1111 }
1112 return Effect.succeed(id);
1113 }
1114
1115 function makeProviderThread(input: {
1116 readonly driver: ProviderDriverKind;
1117 readonly providerInstanceId: ProviderInstanceId;
1118 readonly idAllocator: IdAllocator.IdAllocatorV2["Service"];
1119 readonly appThreadId: OrchestrationV2ProviderThread["appThreadId"];
1120 readonly providerSessionId: OrchestrationV2ProviderThread["providerSessionId"];
1121 readonly nativeThreadId: string;
1122 readonly ownerNodeId?: OrchestrationV2ProviderThread["ownerNodeId"];
1123 readonly forkedFrom?: OrchestrationV2ProviderThread["forkedFrom"];
1124 readonly itemIdentityVersion?: 2;
1125 readonly now: DateTime.Utc;
1126 }): OrchestrationV2ProviderThread {
1127 return {
1128 id: input.idAllocator.derive.providerThread({
1129 driver: input.driver,
1130 providerInstanceId: input.providerInstanceId,
1131 nativeThreadId: input.nativeThreadId,
1132 }),
1133 driver: input.driver,
1134 providerInstanceId: input.providerInstanceId,
1135 providerSessionId: input.providerSessionId,
1136 appThreadId: input.appThreadId,
1137 ownerNodeId: input.ownerNodeId ?? null,
1138 nativeThreadRef: {
1139 driver: input.driver,
1140 nativeId: input.nativeThreadId,
1141 strength: "strong",
1142 },
1143 nativeConversationHeadRef: null,
1144 status: "idle",
1145 firstRunOrdinal: null,
1146 lastRunOrdinal: null,
1147 handoffIds: [],
1148 forkedFrom: input.forkedFrom ?? null,
1149 contextUsage: null,
1150 nativeMetadata:
1151 input.itemIdentityVersion === undefined
1152 ? null
1153 : { itemIdentityVersion: input.itemIdentityVersion },
1154 createdAt: input.now,
1155 updatedAt: input.now,
1156 };
1157 }
1158
1159 /** Stop reasons where the agent ended without finishing. ACP asks clients to show refusals. */
1160 export function acpUnfinishedStopMessage(
1161 stopReason: EffectAcpSchema.StopReason | null | undefined,
1162 ): string | undefined {
1163 switch (stopReason) {
1164 case "refusal":
1165 return "The agent refused this request. The agent's next turn won't include this message or its reply.";
1166 case "max_tokens":
1167 return "The agent stopped because its reply reached the output token limit.";
1168 case "max_turn_requests":
1169 return "The agent stopped because it reached its request limit for this turn.";
1170 default:
1171 return undefined;
1172 }
1173 }
1174
1175 function appendToolContentText(content: unknown, text: string): unknown[] {
1176 const next: unknown[] = Array.isArray(content) ? [...content] : [];
1177 const last = unknownRecord(next.at(-1));
1178 const lastContent = unknownRecord(last?.content);
1179 if (
1180 last?.type === "content" &&
1181 lastContent?.type === "text" &&
1182 typeof lastContent.text === "string"
1183 ) {
1184 next[next.length - 1] = {
1185 ...last,
1186 content: { ...lastContent, text: `${lastContent.text}${text}` },
1187 };
1188 } else {
1189 next.push({ type: "content", content: { type: "text", text } });
1190 }
1191 return next;
1192 }
1193
1194 function acpMcpToolCallOutput(rawOutput: unknown): unknown {
1195 const record = unknownRecord(rawOutput);
1196 if (record === undefined) return rawOutput;
1197 if (!("result" in record) && !("error" in record)) return rawOutput;
1198 const result = unknownRecord(record.result);
1199 const resultOutput = result === undefined ? undefined : mcpToolResultOutput(result);
1200 const errorMessage = unknownRecord(record.error)?.message;
1201 if (typeof errorMessage !== "string") {
1202 return resultOutput ?? rawOutput;
1203 }
1204 return resultOutput === undefined
1205 ? { error: errorMessage }
1206 : { error: errorMessage, result: resultOutput };
1207 }
1208
1209 function nonEmptyText(value: unknown, fallback: string): string {
1210 return typeof value === "string" && value.trim().length > 0 ? value.trim() : fallback;
1211 }
1212
1213 function decodeByteText(value: unknown): string | undefined {
1214 if (!Array.isArray(value) || value.length === 0) return undefined;
1215 if (!value.every((entry) => typeof entry === "number" && Number.isInteger(entry))) {
1216 return undefined;
1217 }
1218 try {
1219 const text = new TextDecoder().decode(Uint8Array.from(value as number[]));
1220 return text.length > 0 ? text : undefined;
1221 } catch {
1222 return undefined;
1223 }
1224 }
1225
1226 function textFromUnknown(value: unknown): string | undefined {
1227 if (typeof value === "string") {
1228 return value;
1229 }
1230 const fromBytes = decodeByteText(value);
1231 if (fromBytes !== undefined) {
1232 return fromBytes;
1233 }
1234 if (Array.isArray(value)) {
1235 const parts = value.flatMap((entry) => {
1236 const text = textFromUnknown(entry);
1237 return text === undefined || text.length === 0 ? [] : [text];
1238 });
1239 return parts.length === 0 ? undefined : parts.join("\n");
1240 }
1241 const record = unknownRecord(value);
1242 if (record === undefined) {
1243 return undefined;
1244 }
1245 for (const key of [
1246 "output_for_prompt",
1247 "stdout",
1248 "stderr",
1249 "output",
1250 "combinedOutput",
1251 "combined_output",
1252 "content",
1253 "text",
1254 "message",
1255 ]) {
1256 const direct = record[key];
1257 if (typeof direct === "string" && direct.length > 0) {
1258 return direct;
1259 }
1260 const decoded = decodeByteText(direct);
1261 if (decoded !== undefined) {
1262 return decoded;
1263 }
1264 const text = textFromUnknown(direct);
1265 if (text !== undefined && text.length > 0) {
1266 return text;
1267 }
1268 }
1269 const result = unknownRecord(record.Result) ?? unknownRecord(record.result);
1270 if (result !== undefined) {
1271 return textFromUnknown(result);
1272 }
1273 return undefined;
1274 }
1275
1276 function commandExitCode(value: unknown): number | undefined {
1277 const record = unknownRecord(value);
1278 for (const key of ["exitCode", "exit_code", "code"]) {
1279 const candidate = record?.[key];
1280 if (typeof candidate === "number" && Number.isInteger(candidate)) {
1281 return candidate;
1282 }
1283 }
1284 return undefined;
1285 }
1286
1287 /**
1288 * Mid-stream Grok Bash re-reports carry exit_code 0 while still in progress;
1289 * interrupted tools must not retain that stale success code.
1290 */
1291 function acpProjectedCommandExitCode(
1292 status: "pending" | "running" | "waiting" | "completed" | "failed" | "interrupted",
1293 rawOutput: unknown,
1294 ): number | undefined {
1295 if (status !== "completed" && status !== "failed") {
1296 return undefined;
1297 }
1298 return commandExitCode(rawOutput);
1299 }
1300
1301 function structuredFileChanges(toolCall: AcpToolCallState) {
1302 const content = toolCall.data.content;
1303 if (!Array.isArray(content)) return [];
1304 return content.flatMap((entry) => {
1305 const diff = unknownRecord(entry);
1306 if (diff?.type !== "diff" || !Array.isArray(diff.changes)) return [];
1307 return diff.changes.flatMap((candidate) => {
1308 const change = unknownRecord(candidate);
1309 const operation = typeof change?.operation === "string" ? change.operation.trim() : "";
1310 const path = typeof change?.path === "string" ? change.path.trim() : "";
1311 if (operation.length === 0 || path.length === 0) return [];
1312 const oldPath = typeof change?.oldPath === "string" ? change.oldPath.trim() : "";
1313 const fileType = typeof change?.fileType === "string" ? change.fileType.trim() : "";
1314 const mimeType = typeof change?.mimeType === "string" ? change.mimeType.trim() : "";
1315 return [
1316 {
1317 operation,
1318 path,
1319 ...(oldPath.length === 0 ? {} : { oldPath }),
1320 ...(fileType.length === 0 ? {} : { fileType }),
1321 ...(mimeType.length === 0 ? {} : { mimeType }),
1322 },
1323 ];
1324 });
1325 });
1326 }
1327
1328 // Bound diff search to protect the event loop; empty-sided diffs need no search.
1329 const ACP_V1_DIFF_MAX_EDITS = 1_000;
1330
1331 /**
1332 * A `snippet` patch has no known location. Keep its recorded text, so no view numbers it
1333 * from line 1.
1334 */
1335 export function acpToolCallSnippetEdit(content: unknown) {
1336 if (!Array.isArray(content)) return undefined;
1337 const diffs = content.flatMap((entry) => {
1338 const diff = unknownRecord(entry);
1339 return diff?.type === "diff" ? [diff] : [];
1340 });
1341 const diff = diffs.length === 1 ? diffs[0] : undefined;
1342 if (diff === undefined || unknownRecord(diff.patch)?.format !== "snippet") return undefined;
1343 return typeof diff.oldText === "string" && typeof diff.newText === "string"
1344 ? { oldStr: diff.oldText, newStr: diff.newText }
1345 : undefined;
1346 }
1347
1348 /**
1349 * No preview when a flavor marked a diff `omitted` (too large) or `snippet` (line unknown);
1350 * the checkpoint diff shows it.
1351 */
1352 function acpToolCallDiffUnpreviewable(content: unknown): boolean {
1353 return (
1354 Array.isArray(content) &&
1355 content.some((entry) => {
1356 const format = unknownRecord(unknownRecord(entry)?.patch)?.format;
1357 return format === "omitted" || format === "snippet";
1358 })
1359 );
1360 }
1361
1362 export function acpToolCallDiffPatch(content: unknown): string | undefined {
1363 if (!Array.isArray(content) || acpToolCallDiffUnpreviewable(content)) {
1364 return undefined;
1365 }
1366 const diffs = content.flatMap((entry) => {
1367 const diff = unknownRecord(entry);
1368 return diff?.type === "diff" ? [diff] : [];
1369 });
1370 const patches = diffs.flatMap((diff): ReadonlyArray<{ text: string; path?: string }> => {
1371 const patch = unknownRecord(diff.patch);
1372 if (typeof patch?.text === "string") {
1373 const change =
1374 Array.isArray(diff.changes) && diff.changes.length === 1
1375 ? unknownRecord(diff.changes[0])
1376 : undefined;
1377 if (
1378 patch.format === "git_patch" &&
1379 patch.text.trimStart().startsWith("@@ ") &&
1380 typeof change?.path === "string"
1381 ) {
1382 const oldPath = typeof change.oldPath === "string" ? change.oldPath : change.path;
1383 const before = change.operation === "add" ? "/dev/null" : JSON.stringify(`a/${oldPath}`);
1384 const after =
1385 change.operation === "delete" ? "/dev/null" : JSON.stringify(`b/${change.path}`);
1386 return [
1387 {
1388 text: `diff --git ${JSON.stringify(`a/${oldPath}`)} ${JSON.stringify(`b/${change.path}`)}\n--- ${before}\n+++ ${after}\n${patch.text.trimStart()}`,
1389 },
1390 ];
1391 }
1392 return [{ text: patch.text }];
1393 }
1394 if (typeof diff.path !== "string" || typeof diff.newText !== "string") return [];
1395 const oldText = typeof diff.oldText === "string" ? diff.oldText : undefined;
1396 const structured = structuredPatch(
1397 oldText === undefined ? "/dev/null" : diff.path,
1398 diff.path,
1399 oldText ?? "",
1400 diff.newText,
1401 undefined,
1402 undefined,
1403 {
1404 context: 3,
1405 maxEditLength: oldText && diff.newText ? ACP_V1_DIFF_MAX_EDITS : Number.POSITIVE_INFINITY,
1406 },
1407 );
1408 return structured === undefined || structured.hunks.length === 0
1409 ? []
1410 : [{ text: formatPatch(structured, FILE_HEADERS_ONLY), path: diff.path }];
1411 });
1412 // Diff parsers split at Git headers once one exists, so every section then needs its own.
1413 const hasGitHeader = patches.some(({ text }) => /^diff --git /m.test(text));
1414 return patches.length === 0
1415 ? undefined
1416 : patches
1417 .map(({ text, path }) =>
1418 hasGitHeader && path !== undefined
1419 ? `diff --git ${JSON.stringify(`a/${path}`)} ${JSON.stringify(`b/${path}`)}\n${text}`
1420 : text,
1421 )
1422 .join("\n");
1423 }
1424
1425 function resolvedPathInfo(
1426 toolCall: AcpToolCallState,
1427 ): { readonly path: string; readonly fromQuery: boolean } | undefined {
1428 const locations = toolCall.data.locations;
1429 if (Array.isArray(locations)) {
1430 for (const location of locations) {
1431 const path = unknownRecord(location)?.path;
1432 if (typeof path === "string" && path.trim().length > 0) {
1433 return { path: path.trim(), fromQuery: false };
1434 }
1435 }
1436 }
1437 const rawInput = unknownRecord(toolCall.data.rawInput);
1438 for (const key of ["path", "filePath", "file_path", "url"]) {
1439 const candidate = rawInput?.[key];
1440 if (typeof candidate === "string" && candidate.trim().length > 0) {
1441 return { path: candidate.trim(), fromQuery: false };
1442 }
1443 }
1444 for (const key of ["query", "pattern"]) {
1445 const candidate = rawInput?.[key];
1446 if (typeof candidate === "string" && candidate.trim().length > 0) {
1447 return { path: candidate.trim(), fromQuery: true };
1448 }
1449 }
1450 return undefined;
1451 }
1452
1453 function pathFromToolCall(toolCall: AcpToolCallState): string | undefined {
1454 return resolvedPathInfo(toolCall)?.path;
1455 }
1456
1457 function acpBackendWebSearch(
1458 rawInput: Record<string, unknown> | undefined,
1459 rawOutput: unknown,
1460 title?: string | null,
1461 ):
1462 | { readonly query: string | undefined; readonly results: OrchestrationV2WebSearchResult[] }
1463 | undefined {
1464 const variant = typeof rawInput?.variant === "string" ? rawInput.variant.toLowerCase() : "";
1465 const rawOutputRecord = unknownRecord(rawOutput);
1466 const action = unknownRecord(rawOutputRecord?.action);
1467 const isWebSearchTitle =
1468 /^\s*(?:web search|search the web|(?:run(?:ning)?\s+)?(?:web_search|search_web)\s*$)/iu.test(
1469 title ?? "",
1470 );
1471 const isWebSearchVariant = [
1472 "xsearch",
1473 "websearch",
1474 "web_search",
1475 "search_web",
1476 "web-search",
1477 ].includes(variant);
1478 if (!isWebSearchVariant && action?.type !== "search" && !isWebSearchTitle) {
1479 return undefined;
1480 }
1481 let args: Record<string, unknown> | undefined;
1482 if (typeof rawOutputRecord?.input === "string") {
1483 try {
1484 args = unknownRecord(JSON.parse(rawOutputRecord.input));
1485 } catch {
1486 args = undefined;
1487 }
1488 }
1489 const argsText = Object.entries(args ?? {})
1490 .filter(([, value]) => typeof value === "string" || typeof value === "number")
1491 .map(([key, value]) => `${key}: ${value}`)
1492 .join(", ");
1493 const query = [
1494 action?.query,
1495 args?.query,
1496 rawInput?.query,
1497 rawInput?.search_query,
1498 rawInput?.q,
1499 argsText,
1500 ]
1501 .find((value): value is string => typeof value === "string" && value.trim().length > 0)
1502 ?.trim();
1503 const urls = new Set<string>();
1504 for (const source of Array.isArray(action?.sources) ? action.sources : []) {
1505 const url = unknownRecord(source)?.url;
1506 if (typeof url === "string" && url.trim().length > 0) urls.add(url.trim());
1507 }
1508 if (urls.size === 0) {
1509 for (const match of textFromUnknown(rawOutput)?.matchAll(/https?:\/\/[^\s<>"]+/gu) ?? []) {
1510 urls.add(trimCitationUrl(match[0]));
1511 }
1512 }
1513 return { query, results: [...urls].map((url) => ({ url })) };
1514 }
1515
1516 // Prose citations end in punctuation or a closing bracket that is not part of the URL.
1517 function trimCitationUrl(raw: string): string {
1518 let url = raw;
1519 for (;;) {
1520 const trimmed = url.replace(/[.,;:]+$/u, "");
1521 const close = trimmed.at(-1);
1522 const open = close === ")" ? "(" : close === "]" ? "[" : undefined;
1523 if (open && close && trimmed.split(open).length < trimmed.split(close).length) {
1524 url = trimmed.slice(0, -1);
1525 } else if (trimmed === url) {
1526 return url;
1527 } else {
1528 url = trimmed;
1529 }
1530 }
1531 }
1532
1533 function providerRequestKind(kind: string | "unknown"): ProviderRequestKind {
1534 switch (kind) {
1535 case "execute":
1536 return "command";
1537 case "read":
1538 case "search":
1539 case "fetch":
1540 return "file-read";
1541 case "edit":
1542 case "delete":
1543 case "move":
1544 return "file-change";
1545 default:
1546 return "command";
1547 }
1548 }
1549
1550 function toolStatus(
1551 status: AcpToolCallState["status"],
1552 ): "pending" | "running" | "waiting" | "completed" | "failed" {
1553 switch (status) {
1554 case "completed":
1555 return "completed";
1556 case "failed":
1557 return "failed";
1558 case "pending":
1559 return "pending";
1560 case "requiresAction":
1561 return "waiting";
1562 default:
1563 return "running";
1564 }
1565 }
1566
1567 type ProjectedToolStatus = ReturnType<typeof toolStatus> | "interrupted";
1568
1569 /**
1570 * Some agents answer Stop's `session/cancel` by failing the tools and subagents
1571 * that were running (Kiro: "Tool execution was cancelled by the user."). After
1572 * Stop, a failure is shown as the interruption it was.
1573 */
1574 function stoppedToolStatus(
1575 turn: Pick<ActiveAcpTurn, "interrupted">,
1576 tool: AcpToolCallState,
1577 ): "interrupted" | undefined {
1578 return turn.interrupted && tool.status === "failed" ? "interrupted" : undefined;
1579 }
1580
1581 function nodeStatus(status: ProjectedToolStatus): OrchestrationV2ExecutionNode["status"] {
1582 return status === "pending" ? "running" : status;
1583 }
1584
1585 function completedAtForStatus(status: ProjectedToolStatus, now: DateTime.Utc): DateTime.Utc | null {
1586 return status === "completed" || status === "failed" || status === "interrupted" ? now : null;
1587 }
1588
1589 // Copilot advertises URL ids such as `https://agentclientprotocol.com/protocol/session-modes#plan`.
1590 function isAcpPlanModeId(id: string): boolean {
1591 const name = id.slice(id.lastIndexOf("#") + 1);
1592 return name === "plan" || name === "architect";
1593 }
1594
1595 function selectPermissionOptionId(
1596 request: EffectAcpSchema.RequestPermissionRequest,
1597 decision: Exclude<ProviderApprovalDecision, "cancel">,
1598 ): string | undefined {
1599 const optionIdOfKind = (kind: EffectAcpSchema.PermissionOption["kind"]) =>
1600 request.options.find((option) => option.kind === kind)?.optionId;
1601 if (decision === "acceptForSession") {
1602 // Agents may offer only allow_once, and answering "cancelled" would stop the turn the user approved.
1603 return optionIdOfKind("allow_always") ?? optionIdOfKind("allow_once");
1604 }
1605 return optionIdOfKind(decision === "accept" ? "allow_once" : "reject_once");
1606 }
1607
1608 // Prefer allow-once; allow-always can persist beyond the session.
1609 function selectAutoApprovedPermissionOption(
1610 request: EffectAcpSchema.RequestPermissionRequest,
1611 ): string | undefined {
1612 return (
1613 selectPermissionOptionId(request, "accept") ??
1614 selectPermissionOptionId(request, "acceptForSession")
1615 );
1616 }
1617
1618 interface ActiveTextSegment {
1619 readonly nativeItemId: string;
1620 readonly startedAt: DateTime.Utc;
1621 sourceMessageId: string | null;
1622 text: string;
1623 // The running node and first text have been emitted.
1624 emitted: boolean;
1625 // Text changed since the last emission; a delayed flush is scheduled.
1626 dirty: boolean;
1627 }
1628
1629 interface ActiveTextStream {
1630 current: ActiveTextSegment | null;
1631 nextSegment: number;
1632 readonly closedNamedSegments: Map<string, ActiveTextSegment>;
1633 }
1634
1635 interface AcpNativeBuildConfiguration {
1636 readonly modeId?: string;
1637 readonly configOptions: ReadonlyArray<{ readonly id: string; readonly value: string }>;
1638 }
1639
1640 interface ActiveAcpTurn {
1641 readonly input: ProviderAdapter.ProviderAdapterV2TurnInput;
1642 readonly providerTurnId: OrchestrationV2ProviderTurn["id"];
1643 readonly nativeThreadId: string;
1644 readonly nativeTurnId: string;
1645 readonly startedAt: DateTime.Utc;
1646 readonly completed: Deferred.Deferred<void, never>;
1647 readonly itemOrdinals: Map<string, number>;
1648 readonly outgoingPrompt?: ReadonlyArray<EffectAcpSchema.ContentBlock> | undefined;
1649 consumedPromptMessageId?: string;
1650 readonly user: ActiveTextStream;
1651 readonly assistant: ActiveTextStream;
1652 readonly reasoning: ActiveTextStream;
1653 providerRetry?:
1654 | {
1655 readonly failure: OrchestrationV2ProviderFailure;
1656 readonly retry: OrchestrationV2ProviderRetry;
1657 readonly startedAt: DateTime.Utc;
1658 readonly itemOrdinal: number;
1659 }
1660 | undefined;
1661 contextUsage: ThreadTokenUsageSnapshot | null;
1662 nativeMetadata: OrchestrationV2ProviderThreadNativeMetadata | null;
1663 readonly tools: Map<string, AcpToolCallState & { readonly backgroundCommandTaskId?: string }>;
1664 /** Tools the agent failed after Stop; later updates keep them interrupted. */
1665 readonly stoppedToolCallIds: Set<string>;
1666 readonly toolUpdatesSkipped: Map<string, number>;
1667 readonly toolStartedAt: Map<string, DateTime.Utc>;
1668 readonly subagents: Map<string, ActiveAcpSubagent>;
1669 readonly subagentsBySessionId: Map<string, ActiveAcpSubagent>;
1670 readonly pendingSubagentNotifications: Map<string, Array<EffectAcpSchema.SessionNotification>>;
1671 readonly toolCallIdsByBackgroundTaskId: Map<string, string>;
1672 /** Command ACKs register null; terminal results wait here for prompt settlement. */
1673 readonly backgroundCommands: Map<
1674 string,
1675 { readonly status: "completed" | "failed"; readonly output?: string } | null
1676 >;
1677 readonly persistentBackgroundTaskIds: Set<string>;
1678 /** Monitor end notices lack output; wait for hydration or the safety timeout. */
1679 readonly awaitingBackgroundHydration: Set<string>;
1680 readonly pendingInjectedReport: Set<string>;
1681 /** Reports can precede monitor end notices; consume their completion marker without re-arming. */
1682 earlyInjectedReportObserved: boolean;
1683 readonly plans: Map<
1684 string,
1685 {
1686 readonly id: OrchestrationV2PlanArtifact["id"];
1687 readonly startedAt: DateTime.Utc;
1688 /** The turn that first reported the plan; later turns update its rows. */
1689 readonly origin: {
1690 readonly runId: ActiveAcpTurn["input"]["runId"];
1691 readonly rootNodeId: ActiveAcpTurn["input"]["rootNodeId"];
1692 readonly providerThreadId: ActiveAcpTurn["input"]["providerThread"]["id"];
1693 readonly providerTurnId: ActiveAcpTurn["providerTurnId"];
1694 readonly nativeItemId: string;
1695 readonly ordinal: number;
1696 };
1697 latest: OrchestrationV2PlanArtifact | null;
1698 }
1699 >;
1700 interrupted: boolean;
1701 finalized: boolean;
1702 finalizedStatus: "completed" | "interrupted" | "failed" | "cancelled" | null;
1703 promptSettled: boolean;
1704 promptSettledStatus: "completed" | "interrupted" | "failed" | "cancelled" | null;
1705 workAccepted: boolean;
1706 /** Settles with the turn's latest prompt; a prompt-steer replaces a settled one. */
1707 promptWireSettled: Deferred.Deferred<void, never>;
1708 /** Completed once `session/prompt` is the runtime's active prompt. */
1709 readonly promptDispatched: Deferred.Deferred<void, never>;
1710 /** Frees the runtime for the next prompt while the agent still holds this one's response. */
1711 foregroundIdle: Deferred.Deferred<void>;
1712 /** Counts the turn's prompts; only the latest one settles the turn. */
1713 promptSequence: number;
1714 /** The turn already resent a prompt after a resumable outcome failure. */
1715 outcomeResumed: boolean;
1716 /** Clock millis just before `session/prompt` was handed to the runtime. */
1717 promptSentAt: number | null;
1718 /** Completed when an update after dispatch matches `cancelAfterPromptStarts.isStart`. */
1719 readonly promptStarted: Deferred.Deferred<void, never>;
1720 promptUsage: EffectAcpSchema.Usage | undefined;
1721 backgroundFinalizeGeneration: number;
1722 /** `replyEndsWithUsageUpdate`: output arrived and its closing `usage_update` has not. */
1723 replyOpen: boolean;
1724 /** The agent's own id for this turn's prompt, from `forkFromTurn.nativeTurnId`. */
1725 nativePromptId: string | undefined;
1726 /** Clock millis of the prompt's last progress, for `promptInactivityTimeout`. */
1727 lastProgressAt: number;
1728 inactivityWatchdog: Fiber.Fiber<void> | undefined;
1729 }
1730
1731 type AcpRuntimeTeardownState =
1732 | { readonly _tag: "Idle" }
1733 | {
1734 readonly _tag: "InProgress";
1735 readonly completed: Deferred.Deferred<void, ProviderAdapter.ProviderAdapterProtocolError>;
1736 }
1737 | { readonly _tag: "Failed"; readonly error: ProviderAdapter.ProviderAdapterProtocolError };
1738
1739 function acpRootSessionUpdateIngestsOutput(
1740 notification: EffectAcpSchema.SessionNotification,
1741 ): boolean {
1742 const update = notification.update;
1743 switch (update.sessionUpdate) {
1744 case "agent_message_chunk":
1745 case "agent_thought_chunk":
1746 return (acpContentBlockDisplayText(update.content)?.length ?? 0) > 0;
1747 case "agent_message":
1748 case "agent_thought":
1749 return (update.content ?? []).some(
1750 (content) => (acpContentBlockDisplayText(content)?.length ?? 0) > 0,
1751 );
1752 case "tool_call":
1753 case "tool_call_update":
1754 case "plan":
1755 case "plan_update":
1756 case "plan_removed":
1757 case "compaction_update":
1758 case "compaction_summary_chunk":
1759 return parseSessionUpdateEvent(notification).events.some(
1760 (event) => event._tag === "ToolCallUpdated" || event._tag === "PlanUpdated",
1761 );
1762 default:
1763 return false;
1764 }
1765 }
1766
1767 /** Monitor wakes arrive as their own chunk led by a tagged `<monitor-event task_id=…>`; bare mentions are content. */
1768 const acpIsMonitorChatter = (text: string) =>
1769 /^\s*(?:<monitor-event\s|Monitor\s+["']?[0-9a-f-]{8,}["']?\s+ended)/i.test(text);
1770
1771 export function acpPostSettleWakeEvidence(
1772 notification: EffectAcpSchema.SessionNotification,
1773 flavor: Pick<AcpAdapterV2Flavor, "extractBackgroundToolMutation"> = {},
1774 ): boolean {
1775 if (!acpRootSessionUpdateIngestsOutput(notification)) return false;
1776 const update = notification.update;
1777 if (
1778 (update.sessionUpdate === "user_message_chunk" ||
1779 update.sessionUpdate === "agent_message_chunk") &&
1780 update.content.type === "text"
1781 ) {
1782 const text = update.content.text;
1783 if ((flavor.extractBackgroundToolMutation?.(text) ?? []).length > 0) return false;
1784 if (update.sessionUpdate === "agent_message_chunk" && text.trim().length === 0) return false;
1785 if (acpIsMonitorChatter(text)) return false;
1786 }
1787 return true;
1788 }
1789
1790 /** Still-running tool updates can outlast the quiet window; they must not offer completion wakes. */
1791 export function acpPostSettleContinuationOfferEvidence(
1792 notification: EffectAcpSchema.SessionNotification,
1793 flavor: Pick<AcpAdapterV2Flavor, "extractBackgroundToolMutation" | "normalizeToolCall"> = {},
1794 ): boolean {
1795 if (!acpPostSettleWakeEvidence(notification, flavor)) {
1796 return false;
1797 }
1798 const update = notification.update;
1799 if (update.sessionUpdate === "agent_message_chunk") {
1800 return (acpContentBlockDisplayText(update.content)?.trim().length ?? 0) > 0;
1801 }
1802 if (update.sessionUpdate === "tool_call" || update.sessionUpdate === "tool_call_update") {
1803 return parseSessionUpdateEvent(notification).events.some((event) => {
1804 if (event._tag !== "ToolCallUpdated") return false;
1805 // Grok monitor start ACKs say completed while the task is still running.
1806 const toolCall = flavor.normalizeToolCall?.(event.toolCall) ?? event.toolCall;
1807 return toolCall.status === "completed" || toolCall.status === "failed";
1808 });
1809 }
1810 return false;
1811 }
1812
1813 function acpPostSettleWakeShouldBuffer(
1814 notification: EffectAcpSchema.SessionNotification,
1815 backgroundWorkRunning: boolean,
1816 ): boolean {
1817 if (!backgroundWorkRunning) return true;
1818 const update = notification.update;
1819 return (
1820 update.sessionUpdate !== "agent_message_chunk" && update.sessionUpdate !== "agent_thought_chunk"
1821 );
1822 }
1823
1824 /**
1825 * An app-owned wake (a delegated child finishing) is injected by the
1826 * orchestrator, not typed by the user. It reports on a sibling child and says
1827 * nothing about this session's own pending wake frames, so it must not discard
1828 * them the way a real user turn does.
1829 */
1830 function acpIsAppOwnedWakeTurn(message: {
1831 readonly createdBy: string;
1832 readonly creationSource: string;
1833 }): boolean {
1834 return message.createdBy === "agent" && message.creationSource === "server";
1835 }
1836
1837 function acpIsProviderContinuationMessage(message: {
1838 readonly createdBy: string;
1839 readonly creationSource: string;
1840 }): boolean {
1841 return message.createdBy === "agent" && message.creationSource === "provider";
1842 }
1843
1844 function acpCarryoverTerminalShouldClearContinuation(input: {
1845 readonly continuationOffered: boolean;
1846 readonly wakeBufferLength: number;
1847 }): boolean {
1848 return !input.continuationOffered && input.wakeBufferLength === 0;
1849 }
1850
1851 function acpTurnStartShouldPreserveContinuation(input: {
1852 readonly continuationRequested: boolean;
1853 readonly isContinuationTurn: boolean;
1854 readonly wakeBufferLength: number;
1855 }): boolean {
1856 return !input.isContinuationTurn && input.continuationRequested && input.wakeBufferLength > 0;
1857 }
1858
1859 function acpPostSettleMonitorPromptShouldSuppress(
1860 mutation:
1861 | {
1862 readonly taskId: string;
1863 readonly status: "running" | "completed" | "failed";
1864 }
1865 | undefined,
1866 ): boolean {
1867 return mutation?.status === "running";
1868 }
1869
1870 export function acpCompletedTurnShouldTerminalizeTool(
1871 tool: AcpToolCallState & { readonly backgroundCommandTaskId?: string },
1872 flavor: Pick<AcpAdapterV2Flavor, "extractBackgroundTaskId" | "extractSubagentUpdate">,
1873 ): boolean {
1874 const status = toolStatus(tool.status);
1875 if (status !== "pending" && status !== "running") return false;
1876 // Progress output replaces the start ACK, so the registered task id outlives it.
1877 if (tool.backgroundCommandTaskId !== undefined) return false;
1878 if (flavor.extractBackgroundTaskId?.(tool) !== undefined) return false;
1879 return flavor.extractSubagentUpdate?.(tool) === undefined;
1880 }
1881
1882 interface ActiveAcpSubagent {
1883 task: OrchestrationV2Subagent;
1884 readonly childThreadId: ThreadId;
1885 readonly childRootNodeId: OrchestrationV2ExecutionNode["id"];
1886 readonly turnItemId: OrchestrationV2TurnItem["id"];
1887 turnItemOrdinal: number;
1888 providerTurnId: OrchestrationV2ProviderTurn["id"];
1889 readonly parentProviderThreadId: ProviderThreadId;
1890 childSessionId: string | null;
1891 assistantText: string;
1892 readonly assistantMessages: Map<string, string>;
1893 // Messages whose latest text waits for a delayed flush.
1894 readonly pendingAssistantMessages: Set<string>;
1895 readonly childItemOrdinals: Map<string, number>;
1896 nextChildOrdinal: number;
1897 terminalStatusProjected: boolean;
1898 readonly toolState: Pick<ActiveAcpTurn, "tools" | "toolUpdatesSkipped" | "toolStartedAt">;
1899 // ACP has no interrupted tool status; keep forced interruption across late updates.
1900 readonly interruptedToolIds: Set<string>;
1901 readonly toolSessionIds: Map<string, string>;
1902 }
1903
1904 interface AcpNativeChildSession {
1905 parentSessionId: string | null;
1906 status: "running" | "completed" | "failed" | "cancelled";
1907 result: string | null;
1908 delegationId: string | null;
1909 prompt: string;
1910 subagent: ActiveAcpSubagent | undefined;
1911 owner: ActiveAcpTurn | undefined;
1912 readonly pending: Array<EffectAcpSchema.SessionNotification>;
1913 }
1914
1915 function acpSubagentStatusIsTerminal(status: OrchestrationV2Subagent["status"]): boolean {
1916 return (
1917 status === "completed" ||
1918 status === "failed" ||
1919 status === "interrupted" ||
1920 status === "cancelled" ||
1921 status === "idle"
1922 );
1923 }
1924
1925 function acpSubagentStatusBlocksTurnSettlement(status: OrchestrationV2Subagent["status"]): boolean {
1926 return status === "running" || status === "pending";
1927 }
1928
1929 function acpSubagentHasPendingBackgroundWork(subagent: ActiveAcpSubagent): boolean {
1930 return (
1931 acpSubagentStatusBlocksTurnSettlement(subagent.task.status) || !subagent.terminalStatusProjected
1932 );
1933 }
1934
1935 type AcpCarryoverSubagents = {
1936 readonly sessionId: string;
1937 /** The root's subscriber keeps ingesting, so late child terminals can still project. */
1938 readonly projectsLateTerminals: boolean;
1939 readonly subagents: ReadonlyArray<ActiveAcpSubagent>;
1940 };
1941
1942 type PendingRuntimeRequest = {
1943 readonly generation: number;
1944 readonly nativeResponseAcknowledgement: Deferred.Deferred<void, EffectAcpErrors.AcpError>;
1945 readonly transportRequestId: string;
1946 readonly requestId: RuntimeRequestId;
1947 readonly runtimeRequest: OrchestrationV2RuntimeRequest;
1948 readonly node: OrchestrationV2ExecutionNode;
1949 readonly turnItem: OrchestrationV2TurnItem;
1950 } & (
1951 | {
1952 readonly type: "approval";
1953 readonly decision: Deferred.Deferred<ProviderApprovalDecision>;
1954 }
1955 | {
1956 readonly type: "user_input";
1957 readonly answers: Deferred.Deferred<ProviderUserInputAnswers | null>;
1958 }
1959 );
1960
1961 /** Writers update `order` and `messages` in place; readers copy them out. */
1962 interface SnapshotMessageState {
1963 readonly order: Array<string>;
1964 readonly messages: Map<string, OrchestrationV2ConversationMessage>;
1965 /** Messages loaded from thought chunks; `messages` stores them as assistant text. */
1966 readonly reasoningIds: ReadonlySet<OrchestrationV2ConversationMessage["id"]>;
1967 loadingRole: "user" | "assistant" | "thought" | null;
1968 loadingMessageId: string | null;
1969 loadingIndex: number;
1970 }
1971
1972 const emptySnapshotState = (): SnapshotMessageState => ({
1973 order: [],
1974 messages: new Map(),
1975 reasoningIds: new Set(),
1976 loadingRole: null,
1977 loadingMessageId: null,
1978 loadingIndex: 0,
1979 });
1980
1981 /** How long a Stop waits for the agent to confirm before the user is offered Force stop. */
1982 const ACP_STOP_CONFIRM_TIMEOUT_MS = 10_000;
1983 const TOOL_UPDATE_PERSIST_EVERY = 10;
1984
1985 // CommandOutputHub reads the last 256 KiB; retain more so its display cut stays unchanged.
1986 const MAX_AGENT_TERMINAL_OUTPUT_CHARS = 320 * 1024;
1987
1988 // Agents can resend whole calls while streaming arguments.
1989 function shouldPersistToolUpdate(
1990 context: Pick<ActiveAcpTurn, "toolUpdatesSkipped">,
1991 key: string,
1992 previous: AcpToolCallState | undefined,
1993 next: AcpToolCallState,
1994 reportedStatus: AcpToolCallState["status"],
1995 ): boolean {
1996 const skipped = context.toolUpdatesSkipped.get(key) ?? 0;
1997 const persist =
1998 reportedStatus === "completed" ||
1999 reportedStatus === "failed" ||
2000 previous === undefined ||
2001 previous.status !== next.status ||
2002 previous.title !== next.title ||
2003 toolCallVisibleOutputChanged(previous, next) ||
2004 skipped + 1 >= TOOL_UPDATE_PERSIST_EVERY;
2005 context.toolUpdatesSkipped.set(key, persist ? 0 : skipped + 1);
2006 return persist;
2007 }
2008
2009 export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
2010 options: AcpAdapterV2Options,
2011 ) {
2012 const random = yield* SecureRandom.SecureRandom;
2013 const fileSystem = yield* FileSystem.FileSystem;
2014 const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
2015 const agentScope = yield* AgentScope;
2016 const idAllocator = yield* IdAllocator.IdAllocatorV2;
2017 const host = yield* ProviderHost.ProviderHost;
2018 const mcpSessions = yield* McpProviderSessions.McpProviderSessions;
2019 const { flavor, selfInvocation: self } = options;
2020 const callLauncher = yield* writeAcpMcpCallLauncher(host.paths.stateDir);
2021 const readMcpContext = (threadId: ThreadId | null) =>
2022 threadId === null
2023 ? Effect.succeed(
2024 acpMcpContext(undefined, self, flavor.mcpOverHttp, flavor.deferMcpTools, callLauncher),
2025 )
2026 : mcpSessions
2027 .read(threadId)
2028 .pipe(
2029 Effect.map((session) =>
2030 acpMcpContext(session, self, flavor.mcpOverHttp, flavor.deferMcpTools, callLauncher),
2031 ),
2032 );
2033 const driver = flavor.driver;
2034 const continuationRequests = options.continuationRequests;
2035
2036 const readCapabilities = Effect.gen(function* () {
2037 if (flavor.supportsNativeGoals === undefined) return flavor.capabilities;
2038 return {
2039 ...flavor.capabilities,
2040 turns: {
2041 ...flavor.capabilities.turns,
2042 supportsNativeGoals: yield* flavor.supportsNativeGoals,
2043 },
2044 };
2045 });
2046
2047 return ProviderAdapter.ProviderAdapterV2.of({
2048 instanceId: options.instanceId,
2049 driver,
2050 checksVersionAtHandshake: flavor.checksVersionAtHandshake === true,
2051 getCapabilities: Effect.fn("AcpAdapter.getCapabilities")(function* () {
2052 return yield* readCapabilities;
2053 }),
2054 planSelectionTransition: Effect.fn("AcpAdapter.planSelectionTransition")(function (input) {
2055 return Effect.succeed(acpSelectionTransition(input));
2056 }),
2057 openSession: Effect.fn("AcpAdapterV2.openSession")(
2058 function* (input: ProviderAdapter.ProviderAdapterV2OpenSessionInput) {
2059 const sessionScope = yield* Effect.scope;
2060 let itemIdentityVersion: 2 | undefined =
2061 input.initialProviderItemIdentityVersion ??
2062 (input.initialNativeThreadId === undefined ? 2 : undefined);
2063 const providerNativeId = (nativeId: string) =>
2064 acpProviderItemNativeId({
2065 instanceId: options.instanceId,
2066 itemIdentityVersion,
2067 nativeId,
2068 });
2069 const providerNodeId = (nativeItemId: string) =>
2070 idAllocator.derive.nodeFromProviderItem({
2071 driver,
2072 nativeItemId: providerNativeId(nativeItemId),
2073 });
2074 const providerMessageId = (nativeItemId: string) =>
2075 idAllocator.derive.messageFromProviderItem({
2076 driver,
2077 nativeItemId: providerNativeId(nativeItemId),
2078 });
2079 const providerTurnItemId = (nativeItemId: string) =>
2080 idAllocator.derive.turnItemFromProviderItem({
2081 driver,
2082 nativeItemId: providerNativeId(nativeItemId),
2083 });
2084 const deriveProviderTurnId = (nativeTurnId: string) =>
2085 idAllocator.derive.providerTurn({
2086 driver,
2087 nativeTurnId: providerNativeId(nativeTurnId),
2088 });
2089 const useProviderThreadIdentity = (thread: OrchestrationV2ProviderThread): void => {
2090 itemIdentityVersion = thread.nativeMetadata?.itemIdentityVersion;
2091 };
2092 const terminalEnvironmentBySessionId = new Map<string, NodeJS.ProcessEnv>();
2093 interface PendingTerminalEnvironment {
2094 readonly environment: NodeJS.ProcessEnv | undefined;
2095 readonly claimUnknownSession: boolean;
2096 readonly sessionId: string | null;
2097 }
2098 let pendingTerminalEnvironment: PendingTerminalEnvironment | null = {
2099 environment: (yield* readMcpContext(input.threadId)).processEnvironment,
2100 claimUnknownSession: input.initialNativeThreadId === undefined,
2101 sessionId: input.initialNativeThreadId ?? null,
2102 };
2103 const prepareTerminalEnvironment = (
2104 mcpContext: AcpMcpContext,
2105 sessionId?: string,
2106 ): void => {
2107 pendingTerminalEnvironment = {
2108 environment: mcpContext.processEnvironment,
2109 claimUnknownSession: false,
2110 sessionId: sessionId ?? null,
2111 };
2112 };
2113 const prepareClaimableTerminalEnvironment = (mcpContext: AcpMcpContext): void => {
2114 pendingTerminalEnvironment = {
2115 environment: mcpContext.processEnvironment,
2116 claimUnknownSession: true,
2117 sessionId: null,
2118 };
2119 };
2120 const rememberTerminalEnvironment = (
2121 sessionId: string,
2122 mcpContext: AcpMcpContext,
2123 ): void => {
2124 const environment = mcpContext.processEnvironment;
2125 pendingTerminalEnvironment = null;
2126 if (environment === undefined) {
2127 terminalEnvironmentBySessionId.delete(sessionId);
2128 } else {
2129 terminalEnvironmentBySessionId.set(sessionId, environment);
2130 }
2131 };
2132 const clientTerminals: AcpClientTerminals | undefined =
2133 options.clientTerminals === undefined
2134 ? undefined
2135 : yield* makeAcpClientTerminals({
2136 defaultCwd: input.runtimePolicy.cwd ?? process.cwd(),
2137 environment: options.clientTerminals.environment,
2138 shellCommands: options.clientTerminals.shellCommands,
2139 environmentForSession: (sessionId) => {
2140 const remembered = terminalEnvironmentBySessionId.get(sessionId);
2141 if (remembered !== undefined) return remembered;
2142 if (pendingTerminalEnvironment === null) return undefined;
2143 if (
2144 pendingTerminalEnvironment.sessionId === null &&
2145 pendingTerminalEnvironment.claimUnknownSession
2146 ) {
2147 pendingTerminalEnvironment = {
2148 ...pendingTerminalEnvironment,
2149 sessionId,
2150 };
2151 }
2152 return pendingTerminalEnvironment.sessionId === sessionId
2153 ? pendingTerminalEnvironment.environment
2154 : undefined;
2155 },
2156 }).pipe(
2157 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, childProcessSpawner),
2158 );
2159 if (clientTerminals !== undefined) {
2160 yield* Scope.addFinalizer(sessionScope, clientTerminals.disposeAll);
2161 }
2162 const sessionScopedId = (sessionId: string, nativeId: string): string =>
2163 JSON.stringify([sessionId, nativeId]);
2164 const embeddedTerminalsByToolCallId = new Map<
2165 string,
2166 {
2167 readonly sessionId: string;
2168 readonly terminalIds: ReadonlyArray<string>;
2169 readonly toolCallId: string;
2170 }
2171 >();
2172 const toolCallIdsByAgentTerminalId = new Map<string, Set<string>>();
2173 const agentTerminalsById = new Map<string, AcpAgentTerminalState>();
2174 const rememberEmbeddedTerminals = (input: {
2175 readonly sessionId: string;
2176 readonly toolCallId: string;
2177 readonly terminalIds: ReadonlyArray<string>;
2178 }): void => {
2179 const toolCallKey = sessionScopedId(input.sessionId, input.toolCallId);
2180 for (const terminalId of embeddedTerminalsByToolCallId.get(toolCallKey)?.terminalIds ??
2181 []) {
2182 const terminalKey = sessionScopedId(input.sessionId, terminalId);
2183 const toolCallIds = toolCallIdsByAgentTerminalId.get(terminalKey);
2184 toolCallIds?.delete(input.toolCallId);
2185 if (toolCallIds?.size === 0) toolCallIdsByAgentTerminalId.delete(terminalKey);
2186 }
2187 embeddedTerminalsByToolCallId.delete(toolCallKey);
2188 embeddedTerminalsByToolCallId.set(toolCallKey, {
2189 sessionId: input.sessionId,
2190 terminalIds: input.terminalIds,
2191 toolCallId: input.toolCallId,
2192 });
2193 for (const terminalId of input.terminalIds) {
2194 const terminalKey = sessionScopedId(input.sessionId, terminalId);
2195 const toolCallIds = toolCallIdsByAgentTerminalId.get(terminalKey) ?? new Set<string>();
2196 toolCallIds.add(input.toolCallId);
2197 toolCallIdsByAgentTerminalId.set(terminalKey, toolCallIds);
2198 }
2199 for (const oldest of embeddedTerminalsByToolCallId.keys()) {
2200 if (embeddedTerminalsByToolCallId.size <= 256) break;
2201 const remembered = embeddedTerminalsByToolCallId.get(oldest);
2202 if (remembered === undefined) continue;
2203 for (const terminalId of remembered.terminalIds) {
2204 const terminalKey = sessionScopedId(remembered.sessionId, terminalId);
2205 const toolCallIds = toolCallIdsByAgentTerminalId.get(terminalKey);
2206 toolCallIds?.delete(remembered.toolCallId);
2207 if (toolCallIds?.size === 0) toolCallIdsByAgentTerminalId.delete(terminalKey);
2208 }
2209 embeddedTerminalsByToolCallId.delete(oldest);
2210 }
2211 };
2212 const embeddedTerminalCommands = (
2213 sessionId: string,
2214 toolCallId: string,
2215 ): ReadonlyArray<string> =>
2216 (
2217 embeddedTerminalsByToolCallId.get(sessionScopedId(sessionId, toolCallId))
2218 ?.terminalIds ?? []
2219 ).flatMap((terminalId) => {
2220 const command =
2221 clientTerminals?.readCommandLine(terminalId) ??
2222 agentTerminalsById.get(sessionScopedId(sessionId, terminalId))?.command;
2223 return command === undefined ? [] : [command];
2224 });
2225 // Client terminals run with server privileges; apply turn policy and prior user approvals.
2226 const clientPolicyGrants = makeAcpClientPolicyGrants();
2227 let latestRuntimePolicy: ProviderAdapter.ProviderAdapterV2RuntimePolicy =
2228 input.runtimePolicy;
2229 const events = yield* Queue.unbounded<ProviderAdapter.ProviderAdapterV2Event>();
2230 const activeTurn = yield* Ref.make<ActiveAcpTurn | null>(null);
2231 // Keyed by the agent's steer id; an injection can arrive before its send returns.
2232 const steerInjections = new Map<string, Deferred.Deferred<void>>();
2233 const steerInjection = (steerId: string) => {
2234 const existing = steerInjections.get(steerId);
2235 if (existing !== undefined) return existing;
2236 const created = Deferred.makeUnsafe<void>();
2237 steerInjections.set(steerId, created);
2238 return created;
2239 };
2240 let pendingStopCloseTurn: ActiveAcpTurn | null = null;
2241 let followsAgentWorkState = false;
2242 let postSettleContinuationEnabled = false;
2243 let defersFinalizeForBackgroundWork = false;
2244 let agentWork: Extract<
2245 EffectAcpSchema.SessionUpdate,
2246 { sessionUpdate: "state_update" }
2247 > | null = null;
2248 // The root's last reportForegroundWork state; undefined until the agent reports one.
2249 let rootForegroundWork: "running" | "idle" | undefined;
2250 const agentRequests = new Set<object>();
2251 const nativeChildren = new Map<string, AcpNativeChildSession>();
2252 const extractSubagentUpdate = (tool: AcpToolCallState) =>
2253 flavor.extractSubagentSessionEvent !== undefined && !followsAgentWorkState
2254 ? undefined
2255 : flavor.extractSubagentUpdate?.(tool);
2256 let turnAttached = yield* Deferred.make<boolean>();
2257 const activeSessionId = yield* Ref.make<string | null>(null);
2258 // session/load replays history before activeSessionId names the loaded session.
2259 const loadingSessionId = yield* Ref.make<string | null>(null);
2260 const contextUsageBySessionId = yield* Ref.make(
2261 new Map<string, ThreadTokenUsageSnapshot>(),
2262 );
2263 const nativeMetadataBySessionId = yield* Ref.make(
2264 new Map<string, OrchestrationV2ProviderThreadNativeMetadata>(),
2265 );
2266 const providerThreadByNativeSessionId = yield* Ref.make(
2267 new Map<string, OrchestrationV2ProviderThread>(),
2268 );
2269 const nativeBuildConfigurationBySessionId = new Map<string, AcpNativeBuildConfiguration>();
2270 const plansBySessionId = new Map<string, ActiveAcpTurn["plans"]>();
2271 const initialSessionActivationFailure = yield* Ref.make<{
2272 readonly sessionId: string;
2273 readonly error: EffectAcpErrors.AcpError;
2274 } | null>(null);
2275 const activeSessionSetup =
2276 yield* Ref.make<AcpSessionRuntime.AcpSessionRuntimeStartResult | null>(null);
2277 const setActiveSessionSetup = Effect.fnUntraced(function* (
2278 setup: AcpSessionRuntime.AcpSessionRuntimeStartResult,
2279 ) {
2280 followsAgentWorkState =
2281 flavor.followAgentWorkState === true &&
2282 continuationRequests !== undefined &&
2283 setup.initializeResult.protocolVersion === 2;
2284 postSettleContinuationEnabled =
2285 continuationRequests !== undefined &&
2286 readNegotiatedFlag(flavor.enablePostSettleContinuation, setup.initializeResult);
2287 defersFinalizeForBackgroundWork = readNegotiatedFlag(
2288 flavor.deferFinalizeForBackgroundWork,
2289 setup.initializeResult,
2290 );
2291 agentWork = null;
2292 rootForegroundWork = undefined;
2293 agentRequests.clear();
2294 nativeChildren.clear();
2295 yield* Ref.set(activeSessionSetup, setup);
2296 });
2297 const activeSelection = yield* Ref.make<ModelSelection | null>(null);
2298 const activeInteractionMode = yield* Ref.make<ProviderInteractionMode | null>(null);
2299 const configuredRuntimeMode = yield* Ref.make<
2300 ProviderAdapter.ProviderAdapterV2RuntimePolicy["runtimeMode"] | null
2301 >(null);
2302 const promptInstructionStates = yield* Ref.make(new Map<string, T3AcpInstructionState>());
2303 const promptRuntimeInstructions = yield* Ref.make(new Map<string, string>());
2304 // Unique markers keep delayed prompt completions from clearing later compactions.
2305 const compactionMarkers = yield* Ref.make(new Map<string, symbol>());
2306 // ACP may patch a completed compaction again; each compaction id marks its session once.
2307 const completedCompactionIds = yield* Ref.make(new Set<string>());
2308 // The next prompt in a compacted session resends T3's instructions and runtime notes.
2309 // Only root sessions get prompts, so a marker on a child session is never read.
2310 const markSessionCompacted = Effect.fn("AcpAdapterV2.markSessionCompacted")(function* (
2311 sessionId: string,
2312 compactionId?: string,
2313 ) {
2314 if (compactionId !== undefined) {
2315 const key = `${sessionId}\u0000${compactionId}`;
2316 const alreadyMarked = yield* Ref.modify(
2317 completedCompactionIds,
2318 (current): [boolean, Set<string>] =>
2319 current.has(key) ? [true, current] : [false, new Set(current).add(key)],
2320 );
2321 if (alreadyMarked) return;
2322 }
2323 yield* Ref.update(compactionMarkers, (current) =>
2324 new Map(current).set(sessionId, Symbol()),
2325 );
2326 });
2327 const advertisedCommandNames = yield* SubscriptionRef.make(
2328 new Map<string, ReadonlySet<string>>(),
2329 );
2330 const compactsContext =
2331 flavor.supportsCompaction === true ||
2332 flavor.compactSession !== undefined ||
2333 flavor.compactViaAdvertisedCommand === true;
2334 const runtimeRestartRequired = yield* Ref.make(false);
2335 const runtimeTeardownState = yield* Ref.make<AcpRuntimeTeardownState>({ _tag: "Idle" });
2336 const runtimeCallbackGeneration = yield* Ref.make(0);
2337 const runtimeCallbackGenerationCounter = yield* Ref.make(0);
2338 const allocateRuntimeCallbackGeneration = Ref.updateAndGet(
2339 runtimeCallbackGenerationCounter,
2340 (generation) => generation + 1,
2341 );
2342 const advanceRuntimeCallbackGeneration = allocateRuntimeCallbackGeneration.pipe(
2343 Effect.tap((generation) => Ref.set(runtimeCallbackGeneration, generation)),
2344 );
2345 const runtimeCallbackPermit = yield* Semaphore.make(1);
2346 const runtimeTransitionPermit = yield* Semaphore.make(1);
2347 const nativeResponseAcknowledgements = yield* Ref.make(
2348 new Map<
2349 string,
2350 {
2351 readonly acknowledgement: Deferred.Deferred<void, EffectAcpErrors.AcpError>;
2352 readonly generation: number;
2353 }
2354 >(),
2355 );
2356 const pendingRuntimeRequests = yield* Ref.make(new Map<string, PendingRuntimeRequest>());
2357 const emitNativeResponseLifecycle =
2358 options.testHooks?.onNativeResponseLifecycle ?? (() => Effect.void);
2359 const nextElicitationOrdinal = yield* Ref.make(0);
2360 const providerTurns = yield* Ref.make(new Map<string, OrchestrationV2ProviderTurn>());
2361 const snapshot = yield* Ref.make(emptySnapshotState());
2362
2363 const awaitRuntimeTeardown = Effect.fnUntraced(function* () {
2364 const state = yield* Ref.get(runtimeTeardownState);
2365 if (state._tag === "InProgress") {
2366 yield* Deferred.await(state.completed);
2367 } else if (state._tag === "Failed") {
2368 return yield* state.error;
2369 }
2370 });
2371 const runRuntimeCallbackAtGeneration = <A, E, R>(
2372 generation: number,
2373 effect: Effect.Effect<A, E, R>,
2374 ) =>
2375 runtimeCallbackPermit.withPermit(
2376 Effect.gen(function* () {
2377 if ((yield* Ref.get(runtimeTeardownState))._tag !== "Idle") {
2378 return Option.none<A>();
2379 }
2380 if ((yield* Ref.get(runtimeCallbackGeneration)) !== generation) {
2381 return Option.none<A>();
2382 }
2383 return Option.some(yield* effect);
2384 }),
2385 );
2386 const registerNativeResponseAcknowledgement =
2387 /* Provider events include streaming deltas; avoid a span for each update. */
2388 Effect.fnUntraced(function* (
2389 generation: number,
2390 transportRequestId: string,
2391 acknowledgement: Deferred.Deferred<void, EffectAcpErrors.AcpError>,
2392 ) {
2393 yield* Ref.update(nativeResponseAcknowledgements, (current) => {
2394 const updated = new Map(current);
2395 updated.set(transportRequestId, { acknowledgement, generation });
2396 return updated;
2397 });
2398 yield* emitNativeResponseLifecycle({
2399 type: "registered",
2400 generation,
2401 requestId: transportRequestId,
2402 });
2403 if (!(yield* Deferred.isDone(acknowledgement))) return;
2404 yield* Ref.update(nativeResponseAcknowledgements, (current) => {
2405 if (current.get(transportRequestId)?.acknowledgement !== acknowledgement) {
2406 return current;
2407 }
2408 const updated = new Map(current);
2409 updated.delete(transportRequestId);
2410 return updated;
2411 });
2412 });
2413 const acknowledgeNativeResponse = (generation: number, transportRequestId: string) =>
2414 runRuntimeCallbackAtGeneration(generation, Effect.void).pipe(
2415 Effect.flatMap((registered) =>
2416 Option.isSome(registered)
2417 ? Effect.void
2418 : emitNativeResponseLifecycle({
2419 type: "admission_rejected",
2420 generation,
2421 requestId: transportRequestId,
2422 }).pipe(
2423 Effect.andThen(
2424 new EffectAcpErrors.AcpTransportError({
2425 detail: "The ACP runtime closed before its response could be admitted",
2426 cause: "Native response registration rejected during teardown",
2427 }),
2428 ),
2429 ),
2430 ),
2431 );
2432 const awaitNativeResponseAcknowledgements = Effect.fnUntraced(function* (
2433 acknowledgements: ReadonlyArray<
2434 readonly [string | undefined, Deferred.Deferred<void, EffectAcpErrors.AcpError>]
2435 >,
2436 ) {
2437 if (acknowledgements.length === 0) return true;
2438 const completed = yield* Deferred.make<"settled" | "timeout">();
2439 yield* emitNativeResponseLifecycle({ type: "watcher_started" });
2440 const acknowledgementFiber = yield* Effect.forEach(
2441 acknowledgements,
2442 ([, acknowledgement]) => Deferred.await(acknowledgement).pipe(Effect.exit),
2443 { concurrency: "unbounded", discard: true },
2444 ).pipe(
2445 Effect.andThen(Deferred.succeed(completed, "settled")),
2446 Effect.interruptible,
2447 Effect.ensuring(emitNativeResponseLifecycle({ type: "watcher_exited" })),
2448 Effect.forkDetach,
2449 );
2450 yield* emitNativeResponseLifecycle({ type: "timer_started" });
2451 const timerFiber = yield* Effect.sleep("2 seconds").pipe(
2452 Effect.andThen(Deferred.succeed(completed, "timeout")),
2453 Effect.interruptible,
2454 Effect.ensuring(emitNativeResponseLifecycle({ type: "timer_exited" })),
2455 Effect.forkDetach,
2456 );
2457 const outcome = yield* Deferred.await(completed);
2458 yield* Fiber.interrupt(acknowledgementFiber);
2459 yield* Fiber.interrupt(timerFiber);
2460 if (outcome === "settled") return true;
2461
2462 yield* Ref.update(nativeResponseAcknowledgements, (current) => {
2463 const updated = new Map(current);
2464 for (const [requestId, acknowledgement] of acknowledgements) {
2465 if (
2466 requestId !== undefined &&
2467 updated.get(requestId)?.acknowledgement === acknowledgement
2468 ) {
2469 updated.delete(requestId);
2470 }
2471 }
2472 return updated;
2473 });
2474 yield* Effect.forEach(
2475 acknowledgements,
2476 ([requestId]) =>
2477 emitNativeResponseLifecycle({
2478 type: "removed",
2479 ...(requestId === undefined ? {} : { requestId }),
2480 }),
2481 { concurrency: "unbounded", discard: true },
2482 );
2483 const timeoutError = new EffectAcpErrors.AcpTransportError({
2484 detail: "Timed out waiting for an admitted ACP response to reach the transport queue",
2485 cause: "Native response acknowledgement timed out",
2486 });
2487 yield* Effect.forEach(
2488 acknowledgements,
2489 ([requestId, acknowledgement]) =>
2490 Deferred.fail(acknowledgement, timeoutError).pipe(
2491 Effect.andThen(
2492 emitNativeResponseLifecycle({
2493 type: "failed",
2494 ...(requestId === undefined ? {} : { requestId }),
2495 }),
2496 ),
2497 ),
2498 { concurrency: "unbounded", discard: true },
2499 );
2500 return false;
2501 });
2502 const awaitAdmittedNativeResponses = Ref.get(nativeResponseAcknowledgements).pipe(
2503 Effect.flatMap((current) =>
2504 awaitNativeResponseAcknowledgements(
2505 [...current.entries()].map(
2506 ([requestId, entry]) => [requestId, entry.acknowledgement] as const,
2507 ),
2508 ),
2509 ),
2510 );
2511 const quarantineNativeTransportAtGeneration = Effect.fnUntraced(function* (
2512 generation: number,
2513 ) {
2514 const quarantined = yield* Ref.modify(nativeResponseAcknowledgements, (current) => {
2515 const updated = new Map(current);
2516 const acknowledgements: Array<Deferred.Deferred<void, EffectAcpErrors.AcpError>> = [];
2517 for (const [requestId, entry] of updated) {
2518 if (entry.generation !== generation) continue;
2519 updated.delete(requestId);
2520 acknowledgements.push(entry.acknowledgement);
2521 }
2522 return [acknowledgements, updated] as const;
2523 });
2524 const error = new EffectAcpErrors.AcpTransportError({
2525 detail: "The ACP runtime was replaced before its response reached the transport queue",
2526 cause: "ACP runtime transport was quarantined during teardown",
2527 });
2528 yield* Effect.forEach(
2529 quarantined,
2530 (acknowledgement) => Deferred.fail(acknowledgement, error),
2531 { concurrency: "unbounded", discard: true },
2532 );
2533 });
2534 const closeNativeTransport = runtimeCallbackPermit.withPermit(
2535 Effect.gen(function* () {
2536 yield* advanceRuntimeCallbackGeneration;
2537 const acknowledgements = yield* Ref.getAndSet(
2538 nativeResponseAcknowledgements,
2539 new Map(),
2540 );
2541 const error = new EffectAcpErrors.AcpTransportError({
2542 detail: "The ACP session closed before its admitted response reached the transport",
2543 cause: "ACP session transport closed",
2544 });
2545 yield* Effect.forEach(
2546 acknowledgements,
2547 ([requestId, entry]) =>
2548 Deferred.fail(entry.acknowledgement, error).pipe(
2549 Effect.andThen(
2550 emitNativeResponseLifecycle({
2551 type: "removed",
2552 generation: entry.generation,
2553 requestId,
2554 }),
2555 ),
2556 Effect.andThen(
2557 emitNativeResponseLifecycle({
2558 type: "failed",
2559 generation: entry.generation,
2560 requestId,
2561 }),
2562 ),
2563 ),
2564 { concurrency: "unbounded", discard: true },
2565 );
2566 return acknowledgements.size > 0;
2567 }),
2568 );
2569 const lastTurnRoute = yield* Ref.make<{
2570 readonly threadId: ThreadId;
2571 readonly providerThreadId: ProviderThreadId;
2572 } | null>(null);
2573 const wakeBuffer = yield* Ref.make<Array<EffectAcpSchema.SessionNotification>>([]);
2574 const noWakeReports = {
2575 reports: new Map<string, BackgroundWorkReport>(),
2576 offered: new Set<string>(),
2577 };
2578 const wakeReports = yield* Ref.make<{
2579 readonly reports: ReadonlyMap<string, BackgroundWorkReport>;
2580 readonly offered: ReadonlySet<string>;
2581 }>(noWakeReports);
2582 const recordWakeReport = Effect.fnUntraced(function* (
2583 key: string,
2584 report: BackgroundWorkReport,
2585 ) {
2586 const context = yield* Ref.get(activeTurn);
2587 if (context !== null && !context.promptSettled && !context.finalized) return;
2588 yield* Ref.update(wakeReports, ({ reports, offered }) => ({
2589 reports: new Map(reports).set(key, report),
2590 offered,
2591 }));
2592 });
2593 const continuationRequested = yield* Ref.make(false);
2594 const continuationGeneration = yield* Ref.make(0);
2595 const continuationPermit = yield* Semaphore.make(1);
2596 const continuationClosed = yield* Ref.make(false);
2597 // Quarantine stopped-run events so they cannot wake or attach to later runs.
2598 const stoppedRunQuarantine = yield* Ref.make(false);
2599 // Native subagents can outlive interrupts; carry lineage forward to finish their original turn items.
2600 const carryoverSubagents = yield* Ref.make<AcpCarryoverSubagents | null>(null);
2601 const handledBackgroundTaskIdsInActiveTurn = yield* Ref.make<ReadonlySet<string>>(
2602 new Set(),
2603 );
2604 const midTurnUnreportedCompletedTaskIds = yield* Ref.make<ReadonlySet<string>>(new Set());
2605 // Grok re-prompts on stale monitor notices; suppress output until a genuine terminal or app turn.
2606 const suppressPostSettleMonitorPrompt = yield* Ref.make(false);
2607 const runningBackgroundTaskIds = yield* Ref.make<ReadonlySet<string>>(new Set());
2608 // Background command task id → the completed turn that owns its row. Ended commands stay,
2609 // bounded, so a later authoritative terminal still corrects the row on its run.
2610 const detachedBackgroundCommands = yield* Ref.make<ReadonlyMap<string, ActiveAcpTurn>>(
2611 new Map(),
2612 );
2613 const endedDetachedBackgroundCommandLimit = 16;
2614 const detachedBackgroundCommandTurn = (taskId: string) =>
2615 Ref.get(detachedBackgroundCommands).pipe(Effect.map((turns) => turns.get(taskId)));
2616 /** The turn a background task's terminal belongs to: its detached turn, else the live one. */
2617 const backgroundCommandTurn = Effect.fnUntraced(function* (taskId: string) {
2618 const detached = yield* detachedBackgroundCommandTurn(taskId);
2619 if (detached !== undefined) return detached;
2620 const active = yield* Ref.get(activeTurn);
2621 return active?.finalized === false ? active : undefined;
2622 });
2623 const detachBackgroundCommands = (context: ActiveAcpTurn) =>
2624 Ref.update(detachedBackgroundCommands, (current) => {
2625 const next = new Map(current);
2626 for (const taskId of context.backgroundCommands.keys()) next.set(taskId, context);
2627 const ended = [...next].filter(([taskId, turn]) => {
2628 const toolCallId = turn.toolCallIdsByBackgroundTaskId.get(taskId);
2629 const tool = toolCallId === undefined ? undefined : turn.tools.get(toolCallId);
2630 const status = tool === undefined ? "completed" : toolStatus(tool.status);
2631 return status !== "pending" && status !== "running";
2632 });
2633 for (const [taskId] of ended.slice(0, -endedDetachedBackgroundCommandLimit)) {
2634 next.delete(taskId);
2635 }
2636 return next;
2637 });
2638 // Tombstones prevent mid-stream exit_code 0 and stale monitor events from resurrecting ended tasks.
2639 const endedBackgroundTaskIds = yield* Ref.make<ReadonlySet<string>>(new Set());
2640 const endedBackgroundTaskIdLimit = 128;
2641
2642 const setBackgroundTaskRunning =
2643 /* Provider events include streaming deltas; avoid a span for each update. */
2644 Effect.fnUntraced(function* (taskId: string, running: boolean) {
2645 if (running && (yield* Ref.get(endedBackgroundTaskIds)).has(taskId)) {
2646 return;
2647 }
2648 yield* Ref.update(runningBackgroundTaskIds, (current) => {
2649 if (current.has(taskId) === running) return current;
2650 const next = new Set(current);
2651 if (running) {
2652 next.add(taskId);
2653 } else {
2654 next.delete(taskId);
2655 }
2656 return next;
2657 });
2658 });
2659
2660 const markBackgroundTaskEnded = (taskId: string) =>
2661 Ref.update(endedBackgroundTaskIds, (current) => {
2662 if (current.has(taskId)) return current;
2663 const next = new Set(current).add(taskId);
2664 for (const oldest of next) {
2665 if (next.size <= endedBackgroundTaskIdLimit) break;
2666 next.delete(oldest);
2667 }
2668 return next;
2669 }).pipe(Effect.andThen(setBackgroundTaskRunning(taskId, false)));
2670
2671 const applyBackgroundTaskMutationRunning = (mutation: {
2672 readonly taskId: string;
2673 readonly status: "running" | "completed" | "failed";
2674 }) =>
2675 mutation.status === "running"
2676 ? setBackgroundTaskRunning(mutation.taskId, true)
2677 : markBackgroundTaskEnded(mutation.taskId);
2678
2679 const trackRunningBackgroundTools =
2680 /* Provider events include streaming deltas; avoid a span for each update. */
2681 Effect.fnUntraced(function* (
2682 notification: EffectAcpSchema.SessionNotification,
2683 ): Effect.fn.Return<void> {
2684 if (flavor.extractBackgroundTaskId === undefined) return;
2685 for (const event of parseSessionUpdateEvent(notification).events) {
2686 if (event._tag !== "ToolCallUpdated") continue;
2687 const toolCall = flavor.normalizeToolCall?.(event.toolCall) ?? event.toolCall;
2688 const taskId = flavor.extractBackgroundTaskId(toolCall);
2689 if (taskId === undefined) continue;
2690 const status = toolStatus(toolCall.status);
2691 yield* setBackgroundTaskRunning(taskId, status === "pending" || status === "running");
2692 }
2693 });
2694
2695 const emitProviderEvent = (event: ProviderAdapter.ProviderAdapterV2Event) =>
2696 Queue.offer(events, event).pipe(Effect.asVoid);
2697 let scheduleDeferredFinalize: (context: ActiveAcpTurn) => Effect.Effect<void> = () =>
2698 Effect.void;
2699 let refreshModelSwitchCapability: Effect.Effect<void> = Effect.void;
2700 // openSession configures the session itself; a late setup that lands
2701 // first waits here and is adopted once that configuration is in place.
2702 const lateSessionSetup: {
2703 openSessionConfigured: boolean;
2704 pending: Effect.Effect<void> | null;
2705 } = { openSessionConfigured: false, pending: null };
2706
2707 const nativeLogging = options.nativeLogging?.(input.threadId);
2708 const promptInactivityTimeoutMillis =
2709 flavor.promptInactivityTimeout === undefined
2710 ? undefined
2711 : Duration.toMillis(flavor.promptInactivityTimeout);
2712 // Each runtime owns its unanswered agent requests, so a dead process's leftovers
2713 // and late callbacks never reach its replacement.
2714 let openAgentRequests = new Set<string>();
2715 const notePromptProgress =
2716 /* Provider events include streaming deltas; avoid a span for each update. */
2717 Effect.fnUntraced(function* (notification?: EffectAcpSchema.SessionNotification) {
2718 if (promptInactivityTimeoutMillis === undefined) return;
2719 if (
2720 notification !== undefined &&
2721 !ACP_PROMPT_ACTIVITY_UPDATES.has(notification.update.sessionUpdate)
2722 ) {
2723 return;
2724 }
2725 const context = yield* Ref.get(activeTurn);
2726 if (
2727 context === null ||
2728 (notification !== undefined &&
2729 notification.sessionId !== context.nativeThreadId &&
2730 !context.subagentsBySessionId.has(notification.sessionId))
2731 ) {
2732 return;
2733 }
2734 context.lastProgressAt = yield* Clock.currentTimeMillis;
2735 });
2736 const closeAgentRequest = (agentRequests: Set<string>, requestId: string) =>
2737 Effect.suspend(() =>
2738 agentRequests.delete(requestId) && agentRequests === openAgentRequests
2739 ? notePromptProgress()
2740 : Effect.void,
2741 );
2742 const handleRuntimeTerminationAtGeneration = (runtimeGeneration: number) =>
2743 runRuntimeCallbackAtGeneration(
2744 runtimeGeneration,
2745 Effect.gen(function* () {
2746 yield* Ref.set(runtimeRestartRequired, true);
2747 if (!followsAgentWorkState) {
2748 // An open prompt fails with its transport. A turn held open for a running tool
2749 // has no prompt, so nothing else ends it.
2750 const held = yield* Ref.get(activeTurn);
2751 if (
2752 flavor.toolOutlivesPrompt === undefined ||
2753 held === null ||
2754 !held.promptSettled ||
2755 held.finalized ||
2756 !hasDeferredBackgroundWork(held)
2757 )
2758 return;
2759 for (const tool of held.tools.values()) {
2760 const status = toolStatus(tool.status);
2761 if (status === "pending" || status === "running" || status === "waiting") {
2762 yield* emitTool(held, tool, "failed");
2763 }
2764 }
2765 yield* finalizeTurn(
2766 held,
2767 "failed",
2768 makeProviderFailure({ class: "transport_error" }),
2769 );
2770 return;
2771 }
2772 agentWork = { sessionUpdate: "state_update", state: "idle", stopReason: "error" };
2773 for (const child of nativeChildren.values()) {
2774 if (child.status !== "running") continue;
2775 child.status = "failed";
2776 child.result = null;
2777 }
2778 for (const child of nativeChildren.values()) {
2779 if (
2780 child.subagent === undefined ||
2781 acpSubagentStatusIsTerminal(child.subagent.task.status)
2782 )
2783 continue;
2784 child.result = null;
2785 yield* publishNativeChildStatus(child, "failed");
2786 }
2787 agentRequests.clear();
2788 yield* Ref.set(wakeBuffer, []);
2789 yield* Ref.set(continuationRequested, false);
2790 yield* cancelPendingRuntimeRequests();
2791 const context = yield* Ref.get(activeTurn);
2792 if (context !== null) {
2793 if (!context.finalized && !context.interrupted) {
2794 yield* terminalizeOpenForegroundTools(context, "failed");
2795 }
2796 yield* finalizeTurn(
2797 context,
2798 "failed",
2799 makeProviderFailure({ class: "transport_error" }),
2800 );
2801 }
2802 }),
2803 ).pipe(Effect.asVoid);
2804 const makeRuntimeInput = (
2805 runtimeGeneration: number,
2806 agentRequests: Set<string>,
2807 mcpContext: AcpMcpContext,
2808 resumeSessionId?: string,
2809 onTermination: AcpAdapterV2RuntimeInput["onTermination"] = () =>
2810 handleRuntimeTerminationAtGeneration(runtimeGeneration),
2811 ): AcpAdapterV2RuntimeInput => {
2812 return {
2813 cwd: input.runtimePolicy.cwd ?? process.cwd(),
2814 runtimePolicy: input.runtimePolicy,
2815 mcpServers: mcpContext.servers,
2816 acpMcpServers: mcpContext.acpServers,
2817 httpMcpServers: mcpContext.httpServers,
2818 ...(mcpContext.processEnvironment === undefined
2819 ? {}
2820 : { processEnvironment: mcpContext.processEnvironment }),
2821 ...(resumeSessionId === undefined ? {} : { resumeSessionId }),
2822 interruptPromptOnCancel: flavor.interruptPromptOnCancel ?? false,
2823 clientCapabilities: {
2824 fs: {
2825 readTextFile: flavor.clientFileSystem !== undefined,
2826 writeTextFile: flavor.clientFileSystem?.writeTextFile !== undefined,
2827 },
2828 terminal: clientTerminals !== undefined,
2829 elicitation: { form: {}, ...(flavor.onUrlElicitation ? { url: {} } : {}) },
2830 ...(flavor.clientCapabilitiesMeta ? { _meta: flavor.clientCapabilitiesMeta } : {}),
2831 },
2832 clientInfo: { name: "t3-code", version: "0.0.0" },
2833 onTermination: (error) =>
2834 Effect.sync(() => agentRequests.clear()).pipe(Effect.andThen(onTermination(error))),
2835 ...(promptInactivityTimeoutMillis === undefined
2836 ? {}
2837 : {
2838 onIncomingRequest: (requestId: string) =>
2839 Effect.sync(() => {
2840 agentRequests.add(requestId);
2841 }),
2842 }),
2843 onOutgoingResponseFailure: (requestId, error) =>
2844 Ref.modify(nativeResponseAcknowledgements, (current) => {
2845 const entry = current.get(requestId);
2846 if (entry === undefined || entry.generation !== runtimeGeneration) {
2847 return [
2848 emitNativeResponseLifecycle({
2849 type: "late_noop",
2850 generation: runtimeGeneration,
2851 requestId,
2852 }),
2853 current,
2854 ] as const;
2855 }
2856 const updated = new Map(current);
2857 updated.delete(requestId);
2858 return [
2859 Deferred.fail(entry.acknowledgement, error).pipe(
2860 Effect.andThen(
2861 emitNativeResponseLifecycle({
2862 type: "removed",
2863 generation: runtimeGeneration,
2864 requestId,
2865 }),
2866 ),
2867 Effect.asVoid,
2868 ),
2869 updated,
2870 ] as const;
2871 }).pipe(Effect.flatten, Effect.andThen(closeAgentRequest(agentRequests, requestId))),
2872 onOutgoingResponse: (requestId) =>
2873 Ref.modify(nativeResponseAcknowledgements, (current) => {
2874 const entry = current.get(requestId);
2875 if (entry === undefined || entry.generation !== runtimeGeneration) {
2876 return [
2877 emitNativeResponseLifecycle({
2878 type: "late_noop",
2879 generation: runtimeGeneration,
2880 requestId,
2881 }),
2882 current,
2883 ] as const;
2884 }
2885 const updated = new Map(current);
2886 updated.delete(requestId);
2887 return [
2888 Deferred.succeed(entry.acknowledgement, undefined).pipe(
2889 Effect.andThen(
2890 emitNativeResponseLifecycle({
2891 type: "removed",
2892 generation: runtimeGeneration,
2893 requestId,
2894 }),
2895 ),
2896 Effect.asVoid,
2897 ),
2898 updated,
2899 ] as const;
2900 }).pipe(Effect.flatten, Effect.andThen(closeAgentRequest(agentRequests, requestId))),
2901 ...(nativeLogging?.requestLogger === undefined
2902 ? {}
2903 : { requestLogger: nativeLogging.requestLogger }),
2904 protocolLogging: nativeLogging?.protocolLogging ?? {
2905 logIncoming: false,
2906 logOutgoing: false,
2907 logger: () => Effect.void,
2908 },
2909 };
2910 };
2911 let runtimeScope: Scope.Closeable | undefined;
2912 let runtime!: AcpSessionRuntime.AcpSessionRuntime["Service"];
2913 let runtimeMcpBridge: AcpMcpOverAcpBridge | undefined;
2914 yield* Effect.addFinalizer(() =>
2915 runtimeScope === undefined
2916 ? Effect.void
2917 : Scope.close(runtimeScope, Exit.void).pipe(Effect.ignore),
2918 );
2919
2920 const resolveItemOrdinal = (context: ActiveAcpTurn, nativeItemId: string) =>
2921 Effect.sync(() => {
2922 const existing = context.itemOrdinals.get(nativeItemId);
2923 if (existing !== undefined) return existing;
2924 const ordinal = context.input.providerTurnOrdinal * 100 + context.itemOrdinals.size + 1;
2925 context.itemOrdinals.set(nativeItemId, ordinal);
2926 return ordinal;
2927 });
2928
2929 const resolveSubagentChildOrdinal = (subagent: ActiveAcpSubagent, nativeItemId: string) => {
2930 const existing = subagent.childItemOrdinals.get(nativeItemId);
2931 if (existing !== undefined) return existing;
2932 const ordinal = subagent.nextChildOrdinal++;
2933 subagent.childItemOrdinals.set(nativeItemId, ordinal);
2934 return ordinal;
2935 };
2936
2937 const emitProviderRetry = Effect.fnUntraced(function* (
2938 context: ActiveAcpTurn,
2939 status: "running" | "completed" | "interrupted" | "cancelled",
2940 ) {
2941 const state = context.providerRetry;
2942 if (state === undefined) return;
2943 yield* emitProviderEvent({
2944 type: "turn_item.updated",
2945 driver,
2946 turnItem: makeProviderRetryTurnItem({
2947 driver,
2948 threadId: context.input.threadId,
2949 runId: context.input.runId,
2950 nodeId: context.input.rootNodeId,
2951 providerThreadId: context.input.providerThread.id,
2952 providerTurnId: context.providerTurnId,
2953 ...state,
2954 status,
2955 updatedAt: yield* DateTime.now,
2956 }),
2957 });
2958 if (status !== "running") context.providerRetry = undefined;
2959 });
2960
2961 const reportProviderRetry = Effect.fnUntraced(function* (notice: {
2962 readonly sessionId: string;
2963 readonly failure: OrchestrationV2ProviderFailure;
2964 }) {
2965 const context = yield* Ref.get(activeTurn);
2966 if (
2967 context === null ||
2968 context.finalized ||
2969 context.interrupted ||
2970 context.nativeThreadId !== notice.sessionId ||
2971 (yield* Ref.get(stoppedRunQuarantine))
2972 )
2973 return;
2974 const previous = context.providerRetry;
2975 context.providerRetry = {
2976 failure: notice.failure,
2977 retry: {
2978 attempt: (previous?.retry.attempt ?? 0) + 1,
2979 maxAttempts: null,
2980 retryDelayMs: null,
2981 },
2982 startedAt: previous?.startedAt ?? (yield* DateTime.now),
2983 itemOrdinal:
2984 previous?.itemOrdinal ??
2985 (yield* resolveItemOrdinal(context, `terminal-failure:${context.providerTurnId}`)),
2986 };
2987 yield* emitProviderRetry(context, "running");
2988 });
2989
2990 const lastCapturedProposedPlan = yield* Ref.make<{
2991 readonly nativeTurnId: string;
2992 readonly markdown: string;
2993 readonly planId: OrchestrationV2PlanArtifact["id"];
2994 } | null>(null);
2995 const captureProposedPlan = Effect.fnUntraced(function* (input: {
2996 readonly planMarkdown: string;
2997 }) {
2998 const context = yield* Ref.get(activeTurn);
2999 if (context === null) return;
3000 const markdown = input.planMarkdown.trim();
3001 if (markdown.length === 0) return;
3002 const previous = yield* Ref.get(lastCapturedProposedPlan);
3003 if (
3004 previous !== null &&
3005 previous.nativeTurnId === context.nativeTurnId &&
3006 previous.markdown === markdown
3007 ) {
3008 return;
3009 }
3010 const nativeItemId = `${context.nativeTurnId}:proposed-plan`;
3011 const planId =
3012 previous !== null && previous.nativeTurnId === context.nativeTurnId
3013 ? previous.planId
3014 : yield* idAllocator.allocate
3015 .plan({
3016 threadId: context.input.threadId,
3017 runId: context.input.runId,
3018 driver,
3019 })
3020 .pipe(Effect.orDie);
3021 yield* Ref.set(lastCapturedProposedPlan, {
3022 nativeTurnId: context.nativeTurnId,
3023 markdown,
3024 planId,
3025 });
3026 const now = yield* DateTime.now;
3027 const nodeId = idAllocator.derive.nodeFromProviderItem({ driver, nativeItemId });
3028 const turnItemId = idAllocator.derive.turnItemFromProviderItem({ driver, nativeItemId });
3029 const ordinal = yield* resolveItemOrdinal(context, nativeItemId);
3030 const nativeItemRef = { driver, nativeId: nativeItemId, strength: "weak" as const };
3031 yield* emitProviderEvent({
3032 type: "node.updated",
3033 driver,
3034 node: {
3035 id: nodeId,
3036 threadId: context.input.threadId,
3037 runId: context.input.runId,
3038 parentNodeId: context.input.rootNodeId,
3039 rootNodeId: context.input.rootNodeId,
3040 kind: "plan",
3041 status: "completed",
3042 countsForRun: false,
3043 providerThreadId: context.input.providerThread.id,
3044 providerTurnId: context.providerTurnId,
3045 nativeItemRef,
3046 runtimeRequestId: null,
3047 checkpointScopeId: null,
3048 startedAt: context.startedAt,
3049 completedAt: now,
3050 },
3051 });
3052 yield* emitProviderEvent({
3053 type: "plan.updated",
3054 driver,
3055 plan: {
3056 id: planId,
3057 threadId: context.input.threadId,
3058 runId: context.input.runId,
3059 nodeId,
3060 kind: "proposed_plan",
3061 status: "completed",
3062 markdown,
3063 },
3064 });
3065 yield* emitProviderEvent({
3066 type: "turn_item.updated",
3067 driver,
3068 turnItem: {
3069 id: turnItemId,
3070 threadId: context.input.threadId,
3071 runId: context.input.runId,
3072 nodeId,
3073 providerThreadId: context.input.providerThread.id,
3074 providerTurnId: context.providerTurnId,
3075 nativeItemRef,
3076 parentItemId: null,
3077 ordinal,
3078 status: "completed",
3079 title: null,
3080 startedAt: context.startedAt,
3081 completedAt: now,
3082 updatedAt: now,
3083 type: "proposed_plan",
3084 planId,
3085 markdown,
3086 streaming: false,
3087 },
3088 });
3089 });
3090 const lastProposedPlanMarkdown = Effect.gen(function* () {
3091 const context = yield* Ref.get(activeTurn);
3092 const previous = yield* Ref.get(lastCapturedProposedPlan);
3093 return context !== null && previous?.nativeTurnId === context.nativeTurnId
3094 ? previous.markdown
3095 : undefined;
3096 });
3097
3098 const rememberSnapshotMessage = (message: OrchestrationV2ConversationMessage) =>
3099 Ref.update(snapshot, (current) => {
3100 const key = String(message.id);
3101 if (!current.messages.has(key)) current.order.push(key);
3102 current.messages.set(key, message);
3103 return current;
3104 });
3105
3106 const textStreamFor = (
3107 context: ActiveAcpTurn,
3108 kind: "user" | "assistant" | "reasoning",
3109 ): ActiveTextStream =>
3110 kind === "user"
3111 ? context.user
3112 : kind === "assistant"
3113 ? context.assistant
3114 : context.reasoning;
3115
3116 const textEmissionPermit = yield* Semaphore.make(1);
3117 /**
3118 * Emits the stream's current segment. A `flushOf` call is a delayed
3119 * flush: it emits only while that segment is still current and has
3120 * unsent text. The permit keeps a flush from landing after the
3121 * segment's completed snapshot.
3122 */
3123 const emitTextSegment = Effect.fnUntraced(function* (
3124 context: ActiveAcpTurn,
3125 kind: "user" | "assistant" | "reasoning",
3126 completed: boolean,
3127 flushOf?: ActiveTextSegment,
3128 ) {
3129 const stream = textStreamFor(context, kind);
3130 const segment = stream.current;
3131 if (segment === null) return;
3132 if (flushOf !== undefined && (segment !== flushOf || !segment.dirty)) return;
3133 // The node carries no text, so it changes only when the segment
3134 // opens and when it completes.
3135 const emitsNode = completed || !segment.emitted;
3136 segment.emitted = true;
3137 segment.dirty = false;
3138 // Read the text in the same step that clears `dirty`. Chunks keep
3139 // appending while this emission yields; each one marks the segment
3140 // dirty again and reaches the next flush or the close.
3141 const text = segment.text;
3142 const now = yield* DateTime.now;
3143 const ordinal = yield* resolveItemOrdinal(context, segment.nativeItemId);
3144 const nodeId = providerNodeId(segment.nativeItemId);
3145 const turnItemId = providerTurnItemId(segment.nativeItemId);
3146 const nativeItemRef = {
3147 driver,
3148 nativeId: segment.nativeItemId,
3149 strength: "weak" as const,
3150 };
3151 if (kind !== "user" && emitsNode) {
3152 yield* emitProviderEvent({
3153 type: "node.updated",
3154 driver,
3155 node: {
3156 id: nodeId,
3157 threadId: context.input.threadId,
3158 runId: context.input.runId,
3159 parentNodeId: context.input.rootNodeId,
3160 rootNodeId: context.input.rootNodeId,
3161 kind: kind === "assistant" ? "assistant_message" : "reasoning",
3162 status: completed ? "completed" : "running",
3163 countsForRun: false,
3164 providerThreadId: context.input.providerThread.id,
3165 providerTurnId: context.providerTurnId,
3166 nativeItemRef,
3167 runtimeRequestId: null,
3168 checkpointScopeId: null,
3169 startedAt: segment.startedAt,
3170 completedAt: completed ? now : null,
3171 },
3172 });
3173 }
3174 if (kind !== "reasoning") {
3175 const messageId = providerMessageId(segment.nativeItemId);
3176 const messageNodeId = kind === "user" ? context.input.rootNodeId : nodeId;
3177 const message: OrchestrationV2ConversationMessage = {
3178 createdBy: kind === "user" ? "user" : "agent",
3179 creationSource: "provider",
3180 id: messageId,
3181 threadId: context.input.threadId,
3182 runId: context.input.runId,
3183 nodeId: messageNodeId,
3184 role: kind,
3185 text,
3186 attachments: [],
3187 streaming: !completed,
3188 createdAt: segment.startedAt,
3189 updatedAt: now,
3190 };
3191 yield* emitProviderEvent({ type: "message.updated", driver, message });
3192 yield* emitProviderEvent(
3193 kind === "user"
3194 ? {
3195 type: "turn_item.updated",
3196 driver,
3197 turnItem: {
3198 createdBy: "user",
3199 creationSource: "provider",
3200 id: turnItemId,
3201 threadId: context.input.threadId,
3202 runId: context.input.runId,
3203 nodeId: messageNodeId,
3204 providerThreadId: context.input.providerThread.id,
3205 providerTurnId: context.providerTurnId,
3206 nativeItemRef,
3207 parentItemId: null,
3208 ordinal,
3209 status: completed ? "completed" : "running",
3210 title: null,
3211 startedAt: segment.startedAt,
3212 completedAt: completed ? now : null,
3213 updatedAt: now,
3214 type: "user_message",
3215 messageId,
3216 inputIntent: "turn_start",
3217 text,
3218 attachments: [],
3219 },
3220 }
3221 : {
3222 type: "turn_item.updated",
3223 driver,
3224 turnItem: {
3225 id: turnItemId,
3226 threadId: context.input.threadId,
3227 runId: context.input.runId,
3228 nodeId,
3229 providerThreadId: context.input.providerThread.id,
3230 providerTurnId: context.providerTurnId,
3231 nativeItemRef,
3232 parentItemId: null,
3233 ordinal,
3234 status: completed ? "completed" : "running",
3235 title: null,
3236 startedAt: segment.startedAt,
3237 completedAt: completed ? now : null,
3238 updatedAt: now,
3239 type: "assistant_message",
3240 messageId,
3241 text,
3242 streaming: !completed,
3243 },
3244 },
3245 );
3246 if (completed) yield* rememberSnapshotMessage(message);
3247 return;
3248 }
3249 yield* emitProviderEvent({
3250 type: "turn_item.updated",
3251 driver,
3252 turnItem: {
3253 id: turnItemId,
3254 threadId: context.input.threadId,
3255 runId: context.input.runId,
3256 nodeId,
3257 providerThreadId: context.input.providerThread.id,
3258 providerTurnId: context.providerTurnId,
3259 nativeItemRef,
3260 parentItemId: null,
3261 ordinal,
3262 status: completed ? "completed" : "running",
3263 title: null,
3264 startedAt: segment.startedAt,
3265 completedAt: completed ? now : null,
3266 updatedAt: now,
3267 type: "reasoning",
3268 text,
3269 streaming: !completed,
3270 },
3271 });
3272 }, textEmissionPermit.withPermit);
3273
3274 /**
3275 * Publishes a text change. A segment's first text emits at once so
3276 * live output starts immediately; later changes coalesce into one
3277 * snapshot per ACP_TEXT_FLUSH_INTERVAL. Closing the segment emits its
3278 * final text and makes a pending flush a no-op.
3279 */
3280 const publishTextSegment = Effect.fnUntraced(function* (
3281 context: ActiveAcpTurn,
3282 kind: "user" | "assistant" | "reasoning",
3283 ) {
3284 const segment = textStreamFor(context, kind).current;
3285 if (segment === null) return;
3286 if (!segment.emitted) return yield* emitTextSegment(context, kind, false);
3287 if (segment.dirty) return;
3288 segment.dirty = true;
3289 yield* emitTextSegment(context, kind, false, segment).pipe(
3290 Effect.delay(ACP_TEXT_FLUSH_INTERVAL),
3291 Effect.forkIn(sessionScope),
3292 );
3293 });
3294
3295 const closeTextStream = Effect.fnUntraced(function* (
3296 context: ActiveAcpTurn,
3297 kind: "user" | "assistant" | "reasoning",
3298 ) {
3299 const stream = textStreamFor(context, kind);
3300 const segment = stream.current;
3301 if (segment === null) return;
3302 yield* emitTextSegment(context, kind, true);
3303 if (segment.sourceMessageId !== null) {
3304 stream.closedNamedSegments.set(segment.sourceMessageId, segment);
3305 }
3306 stream.current = null;
3307 });
3308
3309 const closeTextStreams = Effect.fnUntraced(function* (context: ActiveAcpTurn) {
3310 yield* closeTextStream(context, "user");
3311 yield* closeTextStream(context, "reasoning");
3312 yield* closeTextStream(context, "assistant");
3313 });
3314
3315 const openTextSegment = Effect.fnUntraced(function* (
3316 context: ActiveAcpTurn,
3317 kind: "user" | "assistant" | "reasoning",
3318 sourceMessageId: string | null,
3319 ) {
3320 const stream = textStreamFor(context, kind);
3321 const closed =
3322 sourceMessageId === null ? undefined : stream.closedNamedSegments.get(sourceMessageId);
3323 // A new object, so a flush scheduled before the close stays a no-op.
3324 const segment: ActiveTextSegment =
3325 closed === undefined
3326 ? {
3327 nativeItemId:
3328 sourceMessageId === null
3329 ? `${context.nativeTurnId}:${kind}:${stream.nextSegment}`
3330 : `${context.nativeTurnId}:${kind}:message:${sourceMessageId}`,
3331 startedAt: yield* DateTime.now,
3332 sourceMessageId,
3333 text: "",
3334 emitted: false,
3335 dirty: false,
3336 }
3337 : { ...closed, emitted: false, dirty: false };
3338 if (closed === undefined) stream.nextSegment += 1;
3339 stream.current = segment;
3340 return segment;
3341 });
3342
3343 const appendText = Effect.fnUntraced(function* (
3344 context: ActiveAcpTurn,
3345 kind: "user" | "assistant" | "reasoning",
3346 text: string,
3347 messageId?: string | null,
3348 ) {
3349 if (text.length === 0) return;
3350 for (const other of ["user", "reasoning", "assistant"] as const) {
3351 if (other !== kind) yield* closeTextStream(context, other);
3352 }
3353 const stream = textStreamFor(context, kind);
3354 const sourceMessageId = messageId || null;
3355 if (
3356 stream.current !== null &&
3357 sourceMessageId !== null &&
3358 stream.current.sourceMessageId !== null &&
3359 stream.current.sourceMessageId !== sourceMessageId
3360 ) {
3361 yield* closeTextStream(context, kind);
3362 }
3363 let segment = stream.current;
3364 if (segment === null) {
3365 segment = yield* openTextSegment(context, kind, sourceMessageId);
3366 } else if (segment.sourceMessageId === null && sourceMessageId !== null) {
3367 // Agents may omit the first messageId; retain projected identity until the first later id.
3368 segment.sourceMessageId = sourceMessageId;
3369 }
3370 segment.text += text;
3371 yield* publishTextSegment(context, kind);
3372 });
3373
3374 const replaceText = Effect.fnUntraced(function* (
3375 context: ActiveAcpTurn,
3376 kind: "user" | "assistant" | "reasoning",
3377 text: string,
3378 messageId: string,
3379 ) {
3380 for (const other of ["user", "reasoning", "assistant"] as const) {
3381 if (other !== kind) yield* closeTextStream(context, other);
3382 }
3383 let segment = textStreamFor(context, kind).current;
3384 if (segment?.sourceMessageId !== messageId) {
3385 yield* closeTextStream(context, kind);
3386 segment = yield* openTextSegment(context, kind, messageId);
3387 }
3388 segment.text = text;
3389 yield* publishTextSegment(context, kind);
3390 });
3391
3392 const emitSubagentAssistant = Effect.fnUntraced(function* (
3393 subagent: ActiveAcpSubagent,
3394 text: string,
3395 mode: "append" | "replace" = "append",
3396 messageId?: string | null,
3397 ) {
3398 if (text.length === 0 && mode === "append") return;
3399 const nativeItemId = `${subagent.task.nativeTaskRef?.nativeId ?? subagent.task.id}:message:${messageId ?? "result"}`;
3400 const previous = subagent.assistantMessages.get(nativeItemId);
3401 const messageText = mode === "replace" ? text : `${previous ?? ""}${text}`;
3402 subagent.assistantMessages.set(nativeItemId, messageText);
3403 subagent.assistantText = messageText;
3404 if (mode === "append" && previous !== undefined) {
3405 if (subagent.pendingAssistantMessages.has(nativeItemId)) return;
3406 subagent.pendingAssistantMessages.add(nativeItemId);
3407 yield* writeSubagentAssistant(subagent, nativeItemId, true).pipe(
3408 Effect.delay(ACP_SUBAGENT_TEXT_FLUSH_INTERVAL),
3409 Effect.forkIn(sessionScope),
3410 );
3411 return;
3412 }
3413 subagent.pendingAssistantMessages.delete(nativeItemId);
3414 yield* writeSubagentAssistant(subagent, nativeItemId, false);
3415 });
3416
3417 // Reads the pending set under the permit, so it also waits for a write in progress.
3418 const flushPendingSubagentAssistant = (subagent: ActiveAcpSubagent) =>
3419 Effect.suspend(() =>
3420 Effect.forEach(
3421 [...subagent.pendingAssistantMessages],
3422 (nativeItemId) => writeSubagentAssistantUnlocked(subagent, nativeItemId, true),
3423 { discard: true },
3424 ),
3425 );
3426
3427 const flushSubagentAssistant = (subagent: ActiveAcpSubagent) =>
3428 textEmissionPermit.withPermit(flushPendingSubagentAssistant(subagent));
3429
3430 const writeSubagentAssistant = (
3431 subagent: ActiveAcpSubagent,
3432 nativeItemId: string,
3433 onlyIfPending: boolean,
3434 ) =>
3435 textEmissionPermit.withPermit(
3436 writeSubagentAssistantUnlocked(subagent, nativeItemId, onlyIfPending),
3437 );
3438
3439 const writeSubagentAssistantUnlocked = Effect.fnUntraced(function* (
3440 subagent: ActiveAcpSubagent,
3441 nativeItemId: string,
3442 onlyIfPending: boolean,
3443 ) {
3444 if (onlyIfPending && !subagent.pendingAssistantMessages.delete(nativeItemId)) return;
3445 const text = subagent.assistantMessages.get(nativeItemId);
3446 if (text === undefined) return;
3447 const now = yield* DateTime.now;
3448 const ordinal = resolveSubagentChildOrdinal(subagent, nativeItemId);
3449 const artifacts = makeSubagentConversationArtifacts({
3450 messageId: providerMessageId(nativeItemId),
3451 turnItemId: providerTurnItemId(nativeItemId),
3452 threadId: subagent.childThreadId,
3453 rootNodeId: subagent.childRootNodeId,
3454 providerThreadId: subagent.task.providerThreadId,
3455 providerTurnId: null,
3456 nativeItemRef: { driver, nativeId: nativeItemId, strength: "weak" },
3457 role: "assistant",
3458 text,
3459 ordinal,
3460 now,
3461 });
3462 yield* emitProviderEvent({ type: "message.updated", driver, message: artifacts.message });
3463 yield* emitProviderEvent({
3464 type: "turn_item.updated",
3465 driver,
3466 turnItem: artifacts.turnItem,
3467 });
3468 });
3469
3470 const projectSubagentNotification = Effect.fnUntraced(function* (
3471 subagent: ActiveAcpSubagent,
3472 notification: EffectAcpSchema.SessionNotification,
3473 owner: ActiveAcpTurn,
3474 ) {
3475 const update = notification.update;
3476 if (update.sessionUpdate === "agent_message_chunk") {
3477 const text = acpContentBlockDisplayText(update.content);
3478 if (text !== undefined) {
3479 yield* emitSubagentAssistant(subagent, text, "append", update.messageId);
3480 }
3481 } else if (update.sessionUpdate === "tool_call_content_chunk") {
3482 yield* projectSubagentTool(subagent, notification.sessionId, update, undefined, owner);
3483 } else if (update.sessionUpdate === "agent_message") {
3484 if (update.content === undefined) return;
3485 const text = (update.content ?? [])
3486 .flatMap((content) => {
3487 const display = acpContentBlockDisplayText(content);
3488 return display === undefined ? [] : [display];
3489 })
3490 .join("\n");
3491 yield* emitSubagentAssistant(subagent, text, "replace", update.messageId);
3492 }
3493 });
3494
3495 const projectSubagentTool = Effect.fnUntraced(function* (
3496 subagent: ActiveAcpSubagent,
3497 sessionId: string,
3498 toolCall:
3499 | AcpToolCallState
3500 | Extract<EffectAcpSchema.SessionUpdate, { sessionUpdate: "tool_call_content_chunk" }>,
3501 projectedStatus?: ProjectedToolStatus,
3502 owner?: ActiveAcpTurn,
3503 ) {
3504 const nativeTaskId = subagent.task.nativeTaskRef?.nativeId ?? String(subagent.task.id);
3505 const key =
3506 sessionId === subagent.childSessionId
3507 ? `${nativeTaskId}:tool:${toolCall.toolCallId}`
3508 : `${nativeTaskId}:session:${sessionId}:tool:${toolCall.toolCallId}`;
3509 const context = subagent.toolState;
3510 const rootSessionId = yield* Ref.get(activeSessionId);
3511 subagent.toolSessionIds.set(key, sessionId);
3512 const previous = context.tools.get(key);
3513 if ("sessionUpdate" in toolCall) {
3514 if (toolCall.content.type !== "content") return;
3515 const text = acpContentBlockDisplayText(toolCall.content.content);
3516 if (text === undefined || text.length === 0) return;
3517 toolCall = {
3518 toolCallId: toolCall.toolCallId,
3519 data: { content: appendToolContentText(previous?.data.content, text) },
3520 };
3521 }
3522 const merged = mergeToolCallState(previous, toolCall);
3523 projectedStatus ??= owner === undefined ? undefined : stoppedToolStatus(owner, merged);
3524 if (merged.status !== "failed") subagent.interruptedToolIds.delete(key);
3525 if (projectedStatus === "interrupted") subagent.interruptedToolIds.add(key);
3526 if (merged.status === "failed" && subagent.interruptedToolIds.has(key))
3527 projectedStatus = "interrupted";
3528 context.tools.set(key, merged);
3529 if (
3530 projectedStatus === undefined &&
3531 !shouldPersistToolUpdate(context, key, previous, merged, merged.status)
3532 )
3533 return;
3534 const mcpIdentity = extractMcpToolCallIdentity(merged, {
3535 embeddedTerminalCommands: [
3536 ...embeddedTerminalCommands(sessionId, toolCall.toolCallId),
3537 ...(rootSessionId === null
3538 ? []
3539 : embeddedTerminalCommands(rootSessionId, toolCall.toolCallId)),
3540 ],
3541 });
3542 const now = yield* DateTime.now;
3543 const status = projectedStatus ?? toolStatus(merged.status);
3544 const startedAt = context.toolStartedAt.get(key) ?? now;
3545 context.toolStartedAt.set(key, startedAt);
3546 const ordinal = resolveSubagentChildOrdinal(subagent, key);
3547 yield* emitProviderEvent({
3548 type: "turn_item.updated",
3549 driver,
3550 turnItem: {
3551 id: providerTurnItemId(key),
3552 threadId: subagent.childThreadId,
3553 runId: null,
3554 nodeId: subagent.childRootNodeId,
3555 providerThreadId: subagent.task.providerThreadId,
3556 providerTurnId: null,
3557 nativeItemRef: { driver, nativeId: key, strength: "strong" },
3558 parentItemId: null,
3559 ordinal,
3560 status,
3561 title: merged.title ?? merged.kind ?? "Tool",
3562 startedAt,
3563 completedAt: completedAtForStatus(status, now),
3564 updatedAt: now,
3565 type: "dynamic_tool",
3566 ...(mcpIdentity === undefined
3567 ? {}
3568 : mcpToolPresentation({
3569 serverName: mcpIdentity.server,
3570 toolName: mcpIdentity.tool,
3571 source: unknownRecord(
3572 (
3573 unknownRecord(unknownRecord(merged.data.rawOutput)?.result) ??
3574 unknownRecord(merged.data.rawOutput)
3575 )?._meta,
3576 )?.source,
3577 })),
3578 toolName:
3579 mcpIdentity === undefined
3580 ? (merged.title ?? merged.kind ?? "Tool")
3581 : `${mcpIdentity.server}.${mcpIdentity.tool}`,
3582 input: merged.data.rawInput ?? null,
3583 output: merged.data.rawOutput ?? merged.data.content ?? null,
3584 },
3585 });
3586 });
3587
3588 const terminalizeSubagentTools = Effect.fnUntraced(function* (subagent: ActiveAcpSubagent) {
3589 for (const [key, tool] of subagent.toolState.tools) {
3590 if (
3591 toolStatus(tool.status) !== "running" &&
3592 toolStatus(tool.status) !== "pending" &&
3593 toolStatus(tool.status) !== "waiting"
3594 )
3595 continue;
3596 const sessionId = subagent.toolSessionIds.get(key);
3597 if (sessionId !== undefined)
3598 yield* projectSubagentTool(
3599 subagent,
3600 sessionId,
3601 { ...tool, status: "failed" },
3602 "interrupted",
3603 );
3604 }
3605 });
3606
3607 const emitSubagent = Effect.fnUntraced(function* (
3608 context: ActiveAcpTurn,
3609 reported: AcpAdapterV2SubagentUpdate,
3610 ) {
3611 // Providers with cancellation detection already classify their subagent failures.
3612 const update: AcpAdapterV2SubagentUpdate =
3613 flavor.isCancelledToolCall === undefined &&
3614 context.interrupted &&
3615 reported.status === "failed"
3616 ? { ...reported, status: "interrupted" }
3617 : reported;
3618 // Hydration uses a new toolCallId but references the original child by subagent_id or task id.
3619 const existing =
3620 context.subagents.get(update.nativeTaskId) ??
3621 (update.childSessionId !== null
3622 ? context.subagentsBySessionId.get(update.childSessionId)
3623 : undefined);
3624 const updateIsTerminal = acpSubagentStatusIsTerminal(update.status);
3625 if (
3626 existing !== undefined &&
3627 acpSubagentStatusIsTerminal(existing.task.status) &&
3628 !updateIsTerminal
3629 ) {
3630 return;
3631 }
3632 if (
3633 existing !== undefined &&
3634 existing.task.status === update.status &&
3635 updateIsTerminal &&
3636 existing.terminalStatusProjected
3637 ) {
3638 return;
3639 }
3640 // Empty-prompt hydration must match existing lineage; only spawn ACKs can create it.
3641 if (existing === undefined) {
3642 const isHydrationOnly = update.prompt === "" && update.title === null;
3643 if (isHydrationOnly || update.suppressNormalTool === false) {
3644 return;
3645 }
3646 }
3647 const now = yield* DateTime.now;
3648 const nativeTaskId = existing?.task.nativeTaskRef?.nativeId ?? update.nativeTaskId;
3649 const nativeItemRef = {
3650 driver,
3651 nativeId: nativeTaskId,
3652 strength: "strong" as const,
3653 };
3654 const nodeId = existing?.task.id ?? providerNodeId(nativeTaskId);
3655 const childThreadId =
3656 existing?.childThreadId ??
3657 idAllocator.derive.subagentThread({
3658 driver,
3659 providerInstanceId: context.input.modelSelection.instanceId,
3660 nativeThreadId: `${context.nativeThreadId}:task:${nativeTaskId}`,
3661 });
3662 const childRootNodeId =
3663 existing?.childRootNodeId ?? providerNodeId(`${nativeTaskId}:child-root`);
3664 const turnItemId = existing?.turnItemId ?? providerTurnItemId(nativeTaskId);
3665 const turnItemOrdinal =
3666 existing?.turnItemOrdinal ?? (yield* resolveItemOrdinal(context, nativeTaskId));
3667 const taskStatus = update.status;
3668 const task: OrchestrationV2Subagent = {
3669 ...(existing?.task ?? {
3670 id: nodeId,
3671 threadId: context.input.threadId,
3672 runId: context.input.runId,
3673 parentNodeId: context.input.rootNodeId,
3674 origin: "provider_native" as const,
3675 createdBy: "agent" as const,
3676 driver,
3677 providerInstanceId: context.input.modelSelection.instanceId,
3678 providerThreadId: null,
3679 childThreadId,
3680 nativeTaskRef: nativeItemRef,
3681 prompt: update.prompt,
3682 title: update.title,
3683 result: null,
3684 startedAt: now,
3685 }),
3686 model: update.model?.trim() || existing?.task.model || null,
3687 status: taskStatus,
3688 result: update.result ?? existing?.task.result ?? null,
3689 completedAt: acpSubagentStatusIsTerminal(taskStatus) ? now : null,
3690 updatedAt: now,
3691 };
3692 const subagent: ActiveAcpSubagent = existing ?? {
3693 task,
3694 childThreadId,
3695 childRootNodeId,
3696 turnItemId,
3697 turnItemOrdinal,
3698 providerTurnId: context.providerTurnId,
3699 parentProviderThreadId: context.input.providerThread.id,
3700 childSessionId: null,
3701 assistantText: "",
3702 assistantMessages: new Map(),
3703 pendingAssistantMessages: new Set(),
3704 childItemOrdinals: new Map(),
3705 nextChildOrdinal: 101,
3706 terminalStatusProjected: false,
3707 toolState: {
3708 tools: new Map(),
3709 toolUpdatesSkipped: new Map(),
3710 toolStartedAt: new Map(),
3711 },
3712 interruptedToolIds: new Set(),
3713 toolSessionIds: new Map(),
3714 };
3715 subagent.task = task;
3716 context.subagents.set(nativeTaskId, subagent);
3717
3718 if (existing === undefined) {
3719 yield* emitProviderEvent({
3720 type: "app_thread.created",
3721 driver,
3722 appThread: makeSubagentChildThread({
3723 parentThread: context.input.appThread,
3724 childThreadId,
3725 parentNodeId: nodeId,
3726 activeProviderThreadId: null,
3727 providerInstanceId: context.input.modelSelection.instanceId,
3728 modelSelection: {
3729 ...context.input.modelSelection,
3730 model: task.model ?? context.input.modelSelection.model,
3731 },
3732 title: subagentThreadTitle({
3733 parentTitle: context.input.appThread.title,
3734 title: update.title,
3735 prompt: update.prompt,
3736 ordinal: context.subagents.size,
3737 }),
3738 now,
3739 createdBy: "agent",
3740 creationSource: "provider",
3741 }),
3742 });
3743 const promptNativeItemId = `${nativeTaskId}:prompt`;
3744 const promptArtifacts = makeSubagentConversationArtifacts({
3745 senderThreadId: context.input.threadId,
3746 messageId: providerMessageId(promptNativeItemId),
3747 turnItemId: providerTurnItemId(promptNativeItemId),
3748 threadId: childThreadId,
3749 rootNodeId: childRootNodeId,
3750 providerThreadId: null,
3751 providerTurnId: null,
3752 nativeItemRef: { driver, nativeId: promptNativeItemId, strength: "weak" },
3753 role: "user",
3754 text: update.prompt,
3755 ordinal: 100,
3756 now,
3757 });
3758 yield* emitProviderEvent({
3759 type: "message.updated",
3760 driver,
3761 message: promptArtifacts.message,
3762 });
3763 yield* emitProviderEvent({
3764 type: "turn_item.updated",
3765 driver,
3766 turnItem: promptArtifacts.turnItem,
3767 });
3768 }
3769
3770 const childSessionId = update.childSessionId;
3771 if (childSessionId !== null && subagent.childSessionId === null) {
3772 subagent.childSessionId = childSessionId;
3773 context.subagentsBySessionId.set(childSessionId, subagent);
3774 const providerThread = makeProviderThread({
3775 driver,
3776 providerInstanceId: context.input.modelSelection.instanceId,
3777 idAllocator,
3778 appThreadId: childThreadId,
3779 providerSessionId: input.providerSessionId,
3780 nativeThreadId: childSessionId,
3781 ...(itemIdentityVersion === undefined ? {} : { itemIdentityVersion }),
3782 forkedFrom: {
3783 providerThreadId: context.input.providerThread.id,
3784 providerTurnId: context.providerTurnId,
3785 },
3786 now,
3787 });
3788 subagent.task = { ...subagent.task, providerThreadId: providerThread.id };
3789 yield* Ref.update(providerThreadByNativeSessionId, (current) =>
3790 new Map(current).set(childSessionId, providerThread),
3791 );
3792 yield* emitProviderEvent({
3793 type: "provider_thread.updated",
3794 driver,
3795 providerThread: { ...providerThread, status: "idle" },
3796 });
3797 const buffered = context.pendingSubagentNotifications.get(childSessionId) ?? [];
3798 context.pendingSubagentNotifications.delete(childSessionId);
3799 yield* Effect.forEach(
3800 buffered,
3801 (notification) => projectSubagentNotification(subagent, notification, context),
3802 { concurrency: 1, discard: true },
3803 );
3804 }
3805
3806 yield* flushSubagentAssistant(subagent);
3807 // A failed child's result explains the failure; it is not the child's reply.
3808 if (
3809 taskStatus !== "running" &&
3810 reported.status !== "failed" &&
3811 subagent.assistantText.length === 0 &&
3812 update.result !== null
3813 ) {
3814 yield* emitSubagentAssistant(subagent, update.result);
3815 }
3816 const result = update.result ?? subagent.task.result ?? (subagent.assistantText || null);
3817 subagent.task = {
3818 ...subagent.task,
3819 status: taskStatus,
3820 result,
3821 completedAt: acpSubagentStatusIsTerminal(taskStatus) ? now : null,
3822 updatedAt: now,
3823 };
3824 const providerThreadId = subagent.task.providerThreadId;
3825 yield* emitProviderEvent({
3826 type: "node.updated",
3827 driver,
3828 node: {
3829 id: nodeId,
3830 threadId: context.input.threadId,
3831 runId: subagent.task.runId,
3832 parentNodeId: subagent.task.parentNodeId,
3833 rootNodeId: subagent.task.parentNodeId,
3834 kind: "subagent",
3835 status: taskStatus,
3836 countsForRun: false,
3837 providerThreadId: context.input.providerThread.id,
3838 providerTurnId: subagent.providerTurnId,
3839 nativeItemRef,
3840 runtimeRequestId: null,
3841 checkpointScopeId: null,
3842 startedAt: subagent.task.startedAt,
3843 completedAt: subagent.task.completedAt,
3844 },
3845 });
3846 yield* emitProviderEvent({
3847 type: "node.updated",
3848 driver,
3849 node: {
3850 id: childRootNodeId,
3851 threadId: childThreadId,
3852 runId: null,
3853 parentNodeId: null,
3854 rootNodeId: childRootNodeId,
3855 kind: "root_turn",
3856 status: taskStatus,
3857 countsForRun: false,
3858 providerThreadId,
3859 providerTurnId: null,
3860 nativeItemRef,
3861 runtimeRequestId: null,
3862 checkpointScopeId: null,
3863 startedAt: subagent.task.startedAt,
3864 completedAt: subagent.task.completedAt,
3865 },
3866 });
3867 yield* emitProviderEvent({ type: "subagent.updated", driver, subagent: subagent.task });
3868 yield* emitProviderEvent({
3869 type: "turn_item.updated",
3870 driver,
3871 turnItem: {
3872 id: turnItemId,
3873 threadId: context.input.threadId,
3874 runId: subagent.task.runId,
3875 nodeId,
3876 providerThreadId: context.input.providerThread.id,
3877 providerTurnId: subagent.providerTurnId,
3878 nativeItemRef,
3879 parentItemId: null,
3880 ordinal: turnItemOrdinal,
3881 status: taskStatus,
3882 title: subagent.task.title,
3883 startedAt: subagent.task.startedAt,
3884 completedAt: subagent.task.completedAt,
3885 updatedAt: now,
3886 type: "subagent",
3887 subagentId: subagent.task.id,
3888 origin: "provider_native",
3889 driver,
3890 providerInstanceId: context.input.modelSelection.instanceId,
3891 childThreadId,
3892 prompt: subagent.task.prompt,
3893 result,
3894 },
3895 });
3896 if (acpSubagentStatusIsTerminal(taskStatus)) {
3897 subagent.terminalStatusProjected = true;
3898 }
3899 });
3900
3901 const nativeChild = (sessionId: string) => {
3902 let child = nativeChildren.get(sessionId);
3903 if (child === undefined) {
3904 child = {
3905 parentSessionId: null,
3906 status: "running",
3907 result: null,
3908 delegationId: null,
3909 prompt: "",
3910 subagent: undefined,
3911 owner: undefined,
3912 pending: [],
3913 };
3914 nativeChildren.set(sessionId, child);
3915 }
3916 return child;
3917 };
3918
3919 const setNativeChildState = Effect.fnUntraced(function* (
3920 child: AcpNativeChildSession,
3921 status: AcpNativeChildSession["status"],
3922 result: string | null,
3923 ) {
3924 if (child.status !== "running" && status === "running" && child.subagent !== undefined) {
3925 yield* flushSubagentAssistant(child.subagent);
3926 // A new execution replaces its result; live ownership transfers keep their progress.
3927 child.subagent.task = { ...child.subagent.task, result: null };
3928 child.subagent.assistantText = "";
3929 child.subagent.assistantMessages.clear();
3930 child.subagent.pendingAssistantMessages.clear();
3931 }
3932 child.status = status;
3933 child.result = result;
3934 });
3935
3936 const nativeChildOwner = (sessionId: string): AcpNativeChildSession | undefined => {
3937 const visited = new Set<string>();
3938 let child = nativeChildren.get(sessionId);
3939 while (child !== undefined && !visited.has(sessionId)) {
3940 if (child.subagent !== undefined) return child;
3941 visited.add(sessionId);
3942 if (child.parentSessionId === null) return;
3943 sessionId = child.parentSessionId;
3944 child = nativeChildren.get(sessionId);
3945 }
3946 };
3947
3948 const hasWorkingDescendant = (sessionId: string) => {
3949 for (const [id, child] of nativeChildren) {
3950 if (id === sessionId || child.status !== "running") continue;
3951 const visited = new Set<string>();
3952 let parent = child.parentSessionId;
3953 while (parent !== null && !visited.has(parent)) {
3954 if (parent === sessionId) return true;
3955 visited.add(parent);
3956 parent = nativeChildren.get(parent)?.parentSessionId ?? null;
3957 }
3958 }
3959 return false;
3960 };
3961
3962 const publishNativeChildStatus = Effect.fnUntraced(function* (
3963 child: AcpNativeChildSession,
3964 status: AcpAdapterV2SubagentUpdate["status"],
3965 ) {
3966 const { subagent, owner } = child;
3967 if (subagent === undefined || owner === undefined) return;
3968 if (acpSubagentStatusIsTerminal(status)) yield* terminalizeSubagentTools(subagent);
3969 yield* emitSubagent(owner, {
3970 nativeTaskId: subagent.task.nativeTaskRef?.nativeId ?? subagent.task.id,
3971 childSessionId: subagent.childSessionId,
3972 prompt: subagent.task.prompt,
3973 title: subagent.task.title,
3974 model: subagent.task.model,
3975 status,
3976 result: child.result,
3977 });
3978 });
3979
3980 const syncNativeChildren = Effect.fnUntraced(function* (
3981 context: ActiveAcpTurn,
3982 ): Effect.fn.Return<void> {
3983 const rootSessionId = yield* Ref.get(activeSessionId);
3984 for (const [sessionId, child] of nativeChildren) {
3985 if (child.parentSessionId !== rootSessionId) continue;
3986 if (child.subagent === undefined && child.delegationId !== null) {
3987 const subagent = context.subagents.get(child.delegationId);
3988 if (subagent !== undefined) {
3989 child.subagent = subagent;
3990 child.owner = context;
3991 yield* emitSubagent(context, {
3992 nativeTaskId: child.delegationId,
3993 childSessionId: sessionId,
3994 prompt: subagent.task.prompt,
3995 title: subagent.task.title,
3996 model: subagent.task.model,
3997 status: "running",
3998 result: child.result,
3999 });
4000 }
4001 }
4002 const subagent = child.subagent;
4003 if (subagent === undefined) continue;
4004 const newDelegation =
4005 child.delegationId !== null &&
4006 child.delegationId !== subagent.task.nativeTaskRef?.nativeId &&
4007 !subagent.childItemOrdinals.has(`${sessionId}:prompt:${child.delegationId}`);
4008 if (newDelegation && child.status !== "running")
4009 yield* setNativeChildState(child, "running", null);
4010 const hasNativeWork = child.status === "running" || hasWorkingDescendant(sessionId);
4011 if (
4012 (hasNativeWork && acpSubagentStatusIsTerminal(subagent.task.status)) ||
4013 (child.owner !== context &&
4014 (child.owner?.finalizedStatus !== "completed" || newDelegation) &&
4015 (hasNativeWork || child.pending.length > 0))
4016 ) {
4017 // The ownership event precedes child tools so the old run can detach first.
4018 child.owner = context;
4019 subagent.task = {
4020 ...subagent.task,
4021 runId: context.input.runId,
4022 parentNodeId: context.input.rootNodeId,
4023 status: "running",
4024 completedAt: null,
4025 };
4026 subagent.providerTurnId = context.providerTurnId;
4027 subagent.turnItemOrdinal = yield* resolveItemOrdinal(
4028 context,
4029 subagent.task.nativeTaskRef?.nativeId ?? subagent.task.id,
4030 );
4031 subagent.terminalStatusProjected = false;
4032 context.subagents.set(
4033 subagent.task.nativeTaskRef?.nativeId ?? subagent.task.id,
4034 subagent,
4035 );
4036 context.subagentsBySessionId.set(sessionId, subagent);
4037 yield* publishNativeChildStatus(child, "running");
4038 for (const [key, tool] of subagent.toolState.tools) {
4039 const toolSessionId = subagent.toolSessionIds.get(key);
4040 if (
4041 toolSessionId === undefined ||
4042 (toolStatus(tool.status) !== "running" && toolStatus(tool.status) !== "pending")
4043 )
4044 continue;
4045 subagent.toolState.toolUpdatesSkipped.delete(key);
4046 yield* projectSubagentTool(
4047 subagent,
4048 toolSessionId,
4049 tool,
4050 toolStatus(tool.status),
4051 context,
4052 );
4053 }
4054 }
4055 if (
4056 child.delegationId !== null &&
4057 child.delegationId !== subagent.task.nativeTaskRef?.nativeId
4058 ) {
4059 const nativeItemId = `${sessionId}:prompt:${child.delegationId}`;
4060 if (!subagent.childItemOrdinals.has(nativeItemId)) {
4061 const now = yield* DateTime.now;
4062 const artifacts = makeSubagentConversationArtifacts({
4063 senderThreadId: subagent.task.threadId,
4064 messageId: providerMessageId(nativeItemId),
4065 turnItemId: providerTurnItemId(nativeItemId),
4066 threadId: subagent.childThreadId,
4067 rootNodeId: subagent.childRootNodeId,
4068 providerThreadId: subagent.task.providerThreadId,
4069 providerTurnId: null,
4070 nativeItemRef: { driver, nativeId: nativeItemId, strength: "weak" },
4071 role: "user",
4072 text: child.prompt,
4073 ordinal: resolveSubagentChildOrdinal(subagent, nativeItemId),
4074 now,
4075 });
4076 yield* emitProviderEvent({
4077 type: "message.updated",
4078 driver,
4079 message: artifacts.message,
4080 });
4081 yield* emitProviderEvent({
4082 type: "turn_item.updated",
4083 driver,
4084 turnItem: artifacts.turnItem,
4085 });
4086 }
4087 }
4088 }
4089 for (const [sessionId, child] of nativeChildren) {
4090 const owner = nativeChildOwner(sessionId);
4091 if (owner?.owner !== context && owner?.owner?.finalizedStatus !== "completed") continue;
4092 for (const notification of child.pending.splice(0))
4093 yield* projectNativeChildFrame(notification);
4094 if (
4095 child.subagent?.childSessionId != null &&
4096 child.status !== "running" &&
4097 !hasWorkingDescendant(child.subagent.childSessionId)
4098 ) {
4099 yield* publishNativeChildStatus(child, child.status);
4100 }
4101 }
4102 });
4103
4104 const projectNativeChildFrame = Effect.fnUntraced(function* (
4105 notification: EffectAcpSchema.SessionNotification,
4106 ): Effect.fn.Return<void> {
4107 const child = nativeChild(notification.sessionId);
4108 const owner = nativeChildOwner(notification.sessionId);
4109 const subagent = owner?.subagent;
4110 if (
4111 subagent === undefined ||
4112 owner?.owner === undefined ||
4113 (owner.owner.finalized && owner.owner.finalizedStatus !== "completed") ||
4114 (acpSubagentStatusIsTerminal(subagent.task.status) && child.status === "running")
4115 ) {
4116 if (child.pending.length < 256) child.pending.push(notification);
4117 if (subagent !== undefined) {
4118 const root = yield* Ref.get(activeSessionId);
4119 if (root !== null) yield* offerContinuationRun(root);
4120 }
4121 return;
4122 }
4123 const update = notification.update;
4124 if (update.sessionUpdate === "tool_call" || update.sessionUpdate === "tool_call_update") {
4125 for (const event of parseSessionUpdateEvent(notification).events) {
4126 if (event._tag === "ToolCallUpdated") {
4127 const tool = flavor.normalizeToolCall?.(event.toolCall) ?? event.toolCall;
4128 yield* projectSubagentTool(
4129 subagent,
4130 notification.sessionId,
4131 tool,
4132 undefined,
4133 owner.owner,
4134 );
4135 }
4136 }
4137 } else {
4138 yield* projectSubagentNotification(subagent, notification, owner.owner);
4139 }
4140 });
4141
4142 const followNativeChild = Effect.fnUntraced(function* (
4143 notification: EffectAcpSchema.SessionNotification,
4144 context: ActiveAcpTurn | null,
4145 ): Effect.fn.Return<boolean> {
4146 if (!followsAgentWorkState || flavor.extractSubagentSessionEvent === undefined)
4147 return false;
4148 const root = yield* Ref.get(activeSessionId);
4149 const event = flavor.extractSubagentSessionEvent(notification);
4150 if (event !== undefined) {
4151 if (yield* Ref.get(stoppedRunQuarantine)) return true;
4152 const child = nativeChild(event.childSessionId);
4153 child.parentSessionId = event.parentSessionId ?? child.parentSessionId;
4154 if (event.type === "state") {
4155 yield* setNativeChildState(child, event.status, event.result);
4156 } else {
4157 child.delegationId = event.delegationId;
4158 child.prompt = event.prompt;
4159 }
4160 if (context !== null) yield* syncNativeChildren(context);
4161 const owner = nativeChildOwner(event.childSessionId);
4162 if (owner?.subagent !== undefined && owner.owner !== undefined) {
4163 const sessionId = owner.subagent.childSessionId;
4164 if (
4165 owner.status !== "running" &&
4166 sessionId !== null &&
4167 !hasWorkingDescendant(sessionId)
4168 ) {
4169 yield* publishNativeChildStatus(owner, owner.status);
4170 } else if (acpSubagentStatusIsTerminal(owner.subagent.task.status)) {
4171 if (context !== null) yield* syncNativeChildren(context);
4172 else if (root !== null) yield* offerContinuationRun(root);
4173 }
4174 }
4175 return true;
4176 }
4177 if (
4178 notification.sessionId === root ||
4179 notification.sessionId === (yield* Ref.get(loadingSessionId))
4180 )
4181 return false;
4182 if (yield* Ref.get(stoppedRunQuarantine)) return true;
4183 const update = notification.update;
4184 if (update.sessionUpdate === "state_update") {
4185 const child = nativeChild(notification.sessionId);
4186 const unfinishedMessage =
4187 update.state === "idle" ? acpUnfinishedStopMessage(update.stopReason) : undefined;
4188 yield* setNativeChildState(
4189 child,
4190 update.state !== "idle"
4191 ? "running"
4192 : update.stopReason === "error" || unfinishedMessage !== undefined
4193 ? "failed"
4194 : update.stopReason === "cancelled"
4195 ? "cancelled"
4196 : "completed",
4197 update.state === "idle" ? (update.error?.message ?? unfinishedMessage ?? null) : null,
4198 );
4199 }
4200 if (context !== null) yield* syncNativeChildren(context);
4201 yield* projectNativeChildFrame(notification);
4202 const owner = nativeChildOwner(notification.sessionId);
4203 if (
4204 owner?.subagent?.childSessionId != null &&
4205 owner.status !== "running" &&
4206 !hasWorkingDescendant(owner.subagent.childSessionId)
4207 ) {
4208 yield* publishNativeChildStatus(owner, owner.status);
4209 }
4210 return true;
4211 });
4212
4213 const toolOutputText = (toolCall: AcpToolCallState): string => {
4214 if (typeof toolCall.data.rawOutput === "string") {
4215 return toolCall.data.rawOutput;
4216 }
4217 if (
4218 typeof (toolCall.data.rawOutput as { text?: unknown } | undefined)?.text === "string"
4219 ) {
4220 return String((toolCall.data.rawOutput as { text: string }).text);
4221 }
4222 return textFromUnknown(toolCall.data.rawOutput) ?? "";
4223 };
4224
4225 const setToolOutputText = (toolCall: AcpToolCallState, text: string): AcpToolCallState => ({
4226 ...toolCall,
4227 data: {
4228 ...toolCall.data,
4229 rawOutput: {
4230 type: "Text",
4231 text,
4232 },
4233 },
4234 });
4235
4236 const appendToolOutputText = (
4237 toolCall: AcpToolCallState,
4238 appendOutput: string,
4239 ): AcpToolCallState => {
4240 if (appendOutput.length === 0) return toolCall;
4241 return setToolOutputText(toolCall, `${toolOutputText(toolCall)}${appendOutput}`);
4242 };
4243
4244 const isMonitorEndNoticeText = (text: string): boolean =>
4245 /Monitor\s+["']?[0-9a-f-]{8,}/i.test(text) && /ended/i.test(text);
4246
4247 const hasDeferredBackgroundWork = (context: ActiveAcpTurn): boolean => {
4248 if (flavor.wakeOnDetachedRequest && agentRequests.size > 0) return true;
4249 if (flavor.toolOutlivesPrompt !== undefined) {
4250 // A tool that never started has nothing to report later.
4251 for (const tool of context.tools.values()) {
4252 if (toolStatus(tool.status) === "running" && flavor.toolOutlivesPrompt(tool))
4253 return true;
4254 }
4255 }
4256 if (context.awaitingBackgroundHydration.size > 0) return true;
4257 if (context.pendingInjectedReport.size > 0) return true;
4258 for (const [taskId, toolCallId] of context.toolCallIdsByBackgroundTaskId) {
4259 if (context.persistentBackgroundTaskIds.has(taskId)) continue;
4260 // Commands are as often a dev server as a wait; only their wake follows up.
4261 if (context.backgroundCommands.has(taskId)) continue;
4262 const tool = context.tools.get(toolCallId);
4263 if (tool === undefined) continue;
4264 const status = toolStatus(tool.status);
4265 if (status === "pending" || status === "running") return true;
4266 }
4267 // finalizeTurn idles these subagents, so waiting on them would never settle.
4268 if (
4269 flavor.subagentsIdleOnTurnCompletion === true &&
4270 flavor.subagentsOutlivingPrompt === undefined
4271 )
4272 return false;
4273 for (const subagent of context.subagents.values()) {
4274 if (acpSubagentStatusBlocksTurnSettlement(subagent.task.status)) {
4275 return true;
4276 }
4277 }
4278 return false;
4279 };
4280
4281 const idleReportedSubagents = Effect.fn("AcpAdapterV2.idleReportedSubagents")(function* (
4282 context: ActiveAcpTurn,
4283 ) {
4284 if (flavor.subagentsOutlivingPrompt === undefined) return;
4285 const nativeTaskId = (subagent: ActiveAcpSubagent) =>
4286 subagent.task.nativeTaskRef?.nativeId ?? String(subagent.task.id);
4287 const running = [...context.subagents.values()].filter((subagent) =>
4288 acpSubagentStatusBlocksTurnSettlement(subagent.task.status),
4289 );
4290 if (running.length === 0) return;
4291 const atWork = yield* flavor.subagentsOutlivingPrompt({
4292 sessionId: context.nativeThreadId,
4293 nativeTaskIds: running.map(nativeTaskId),
4294 });
4295 if (context.finalized) return;
4296 for (const subagent of running) {
4297 if (
4298 atWork.includes(nativeTaskId(subagent)) ||
4299 !acpSubagentStatusBlocksTurnSettlement(subagent.task.status)
4300 )
4301 continue;
4302 yield* emitSubagent(context, {
4303 nativeTaskId: nativeTaskId(subagent),
4304 prompt: subagent.task.prompt,
4305 title: subagent.task.title,
4306 model: subagent.task.model,
4307 status: "idle",
4308 childSessionId: subagent.childSessionId,
4309 result: null,
4310 });
4311 }
4312 });
4313
4314 const hasSurvivingBackgroundWork = (context: ActiveAcpTurn): boolean =>
4315 [...context.toolCallIdsByBackgroundTaskId.values()].some((toolCallId) => {
4316 const tool = context.tools.get(toolCallId);
4317 const status = tool === undefined ? undefined : toolStatus(tool.status);
4318 return status === "pending" || status === "running";
4319 }) ||
4320 [...context.subagents.values()].some((subagent) =>
4321 acpSubagentStatusBlocksTurnSettlement(subagent.task.status),
4322 );
4323
4324 const rearmDeferredFinalize =
4325 /* Provider events include streaming deltas; avoid a span for each update. */
4326 Effect.fnUntraced(function* (context: ActiveAcpTurn) {
4327 if (!defersFinalizeForBackgroundWork) return;
4328 if (!context.promptSettled || context.finalized) return;
4329 if (hasDeferredBackgroundWork(context)) return;
4330 yield* scheduleDeferredFinalize(context);
4331 });
4332
4333 // let breaks circular inference from monitor hydration re-entry.
4334 let emitTool: (
4335 context: ActiveAcpTurn,
4336 incoming: AcpToolCallState,
4337 projectedStatus?: ProjectedToolStatus,
4338 rawPayload?: unknown,
4339 ) => Effect.Effect<void> = () => Effect.void;
4340
4341 const markAwaitingBackgroundHydration =
4342 /* Provider events include streaming deltas; avoid a span for each update. */
4343 Effect.fnUntraced(function* (context: ActiveAcpTurn, taskId: string) {
4344 if (context.awaitingBackgroundHydration.has(taskId)) return;
4345 context.awaitingBackgroundHydration.add(taskId);
4346 yield* Effect.gen(function* () {
4347 yield* Effect.sleep("60000 millis");
4348 if (context.finalized || !context.awaitingBackgroundHydration.has(taskId)) return;
4349 context.awaitingBackgroundHydration.delete(taskId);
4350 const toolCallId = context.toolCallIdsByBackgroundTaskId.get(taskId);
4351 const tool = toolCallId !== undefined ? context.tools.get(toolCallId) : undefined;
4352 if (tool !== undefined) {
4353 const status = toolStatus(tool.status);
4354 if (status === "pending" || status === "running") {
4355 yield* emitTool(context, { ...tool, status: "completed" });
4356 }
4357 }
4358 yield* rearmDeferredFinalize(context);
4359 }).pipe(Effect.forkIn(sessionScope), Effect.asVoid);
4360 });
4361
4362 const markPendingInjectedReport =
4363 /* Provider events include streaming deltas; avoid a span for each update. */
4364 Effect.fnUntraced(function* (context: ActiveAcpTurn, taskId: string) {
4365 if (!context.promptSettled) return;
4366 if (context.pendingInjectedReport.has(taskId)) return;
4367 context.pendingInjectedReport.add(taskId);
4368 yield* Effect.gen(function* () {
4369 yield* Effect.sleep("25000 millis");
4370 if (context.finalized || !context.pendingInjectedReport.has(taskId)) return;
4371 context.pendingInjectedReport.delete(taskId);
4372 yield* rearmDeferredFinalize(context);
4373 }).pipe(Effect.forkIn(sessionScope), Effect.asVoid);
4374 });
4375
4376 const clearMidTurnUnreportedTaskIds = (taskIds: ReadonlyArray<string>) =>
4377 Ref.update(midTurnUnreportedCompletedTaskIds, (current) => {
4378 let next: Set<string> | null = null;
4379 for (const taskId of taskIds) {
4380 if (!current.has(taskId)) continue;
4381 if (next === null) next = new Set(current);
4382 next.delete(taskId);
4383 }
4384 return next ?? current;
4385 });
4386
4387 emitTool = Effect.fnUntraced(function* (
4388 context: ActiveAcpTurn,
4389 incoming: AcpToolCallState,
4390 projectedStatus?: ProjectedToolStatus,
4391 rawPayload?: unknown,
4392 ) {
4393 if (context.assistant.current?.sourceMessageId == null)
4394 yield* closeTextStream(context, "assistant");
4395 if (context.reasoning.current?.sourceMessageId == null)
4396 yield* closeTextStream(context, "reasoning");
4397 yield* closeTextStream(context, "user");
4398 const previous = context.tools.get(incoming.toolCallId);
4399 const merged = mergeToolCallState(previous, incoming);
4400 const normalized = flavor.normalizeToolCall?.(merged) ?? merged;
4401 const backgroundTaskId = flavor.extractBackgroundTaskId?.(normalized);
4402 const backgroundCommandTaskId =
4403 flavor.isBackgroundCommandTool?.(normalized) === true
4404 ? backgroundTaskId
4405 : previous?.backgroundCommandTaskId;
4406 if (
4407 backgroundCommandTaskId !== undefined &&
4408 !context.backgroundCommands.has(backgroundCommandTaskId)
4409 ) {
4410 context.backgroundCommands.set(backgroundCommandTaskId, null);
4411 }
4412 const completion =
4413 context.promptSettled && backgroundCommandTaskId !== undefined
4414 ? (context.backgroundCommands.get(backgroundCommandTaskId) ?? undefined)
4415 : undefined;
4416 // Preserve hydrated output; only a replayed start ACK needs its output restored.
4417 const toolCall =
4418 completion === undefined
4419 ? normalized
4420 : {
4421 ...(backgroundTaskId === undefined || completion.output === undefined
4422 ? normalized
4423 : setToolOutputText(normalized, completion.output)),
4424 status: completion.status,
4425 };
4426 context.tools.set(
4427 toolCall.toolCallId,
4428 backgroundCommandTaskId === undefined
4429 ? toolCall
4430 : { ...toolCall, backgroundCommandTaskId },
4431 );
4432 // A failure racing Stop needs the provider's cancellation signal before relabeling it.
4433 const previousStatus = previous === undefined ? undefined : toolStatus(previous.status);
4434 if (
4435 context.interrupted &&
4436 toolCall.status === "failed" &&
4437 flavor.isCancelledToolCall?.(rawPayload) === true &&
4438 (previousStatus === undefined ||
4439 previousStatus === "pending" ||
4440 previousStatus === "running" ||
4441 previousStatus === "waiting")
4442 ) {
4443 context.stoppedToolCallIds.add(toolCall.toolCallId);
4444 }
4445 const stoppedStatus =
4446 projectedStatus ??
4447 (toolCall.status === "failed" && context.stoppedToolCallIds.has(toolCall.toolCallId)
4448 ? "interrupted"
4449 : undefined);
4450 if (
4451 followsAgentWorkState &&
4452 projectedStatus === undefined &&
4453 flavor.isProvisionalSubagentTool?.(toolCall)
4454 ) {
4455 yield* rearmDeferredFinalize(context);
4456 return;
4457 }
4458 if (backgroundTaskId !== undefined) {
4459 context.toolCallIdsByBackgroundTaskId.set(backgroundTaskId, toolCall.toolCallId);
4460 if (flavor.isPersistentBackgroundTool?.(toolCall) === true) {
4461 context.persistentBackgroundTaskIds.add(backgroundTaskId);
4462 }
4463 const backgroundStatus = projectedStatus ?? toolStatus(toolCall.status);
4464 yield* setBackgroundTaskRunning(
4465 backgroundTaskId,
4466 backgroundStatus === "pending" || backgroundStatus === "running",
4467 );
4468 if (
4469 !context.promptSettled &&
4470 backgroundStatus !== "pending" &&
4471 backgroundStatus !== "running"
4472 ) {
4473 yield* Ref.update(handledBackgroundTaskIdsInActiveTurn, (current) =>
4474 new Set(current).add(backgroundTaskId),
4475 );
4476 yield* Ref.update(midTurnUnreportedCompletedTaskIds, (current) => {
4477 if (!current.has(backgroundTaskId)) return current;
4478 const next = new Set(current);
4479 next.delete(backgroundTaskId);
4480 return next;
4481 });
4482 }
4483 }
4484
4485 const backgroundCompletions =
4486 projectedStatus === undefined
4487 ? (flavor.extractBackgroundTaskCompletion?.(toolCall) ?? [])
4488 : [];
4489 let hydratedRegisteredMonitor = false;
4490 for (const backgroundCompletion of backgroundCompletions) {
4491 yield* applyBackgroundTaskMutationRunning(backgroundCompletion);
4492 if (backgroundCompletion.status !== "running") {
4493 yield* Ref.update(handledBackgroundTaskIdsInActiveTurn, (current) =>
4494 new Set(current).add(backgroundCompletion.taskId),
4495 );
4496 yield* Ref.update(midTurnUnreportedCompletedTaskIds, (current) => {
4497 if (!current.has(backgroundCompletion.taskId)) return current;
4498 const next = new Set(current);
4499 next.delete(backgroundCompletion.taskId);
4500 return next;
4501 });
4502 }
4503 if (backgroundCompletion.status !== "running") {
4504 context.awaitingBackgroundHydration.delete(backgroundCompletion.taskId);
4505 }
4506 const owner = context.toolCallIdsByBackgroundTaskId.has(backgroundCompletion.taskId)
4507 ? context
4508 : ((yield* detachedBackgroundCommandTurn(backgroundCompletion.taskId)) ?? context);
4509 const targetToolCallId = owner.toolCallIdsByBackgroundTaskId.get(
4510 backgroundCompletion.taskId,
4511 );
4512 if (targetToolCallId !== undefined) {
4513 hydratedRegisteredMonitor = true;
4514 }
4515 const target =
4516 targetToolCallId !== undefined ? owner.tools.get(targetToolCallId) : undefined;
4517 if (target !== undefined && target.toolCallId !== toolCall.toolCallId) {
4518 const nextStatus =
4519 backgroundCompletion.status === "running"
4520 ? ("inProgress" as const)
4521 : backgroundCompletion.status === "failed"
4522 ? ("failed" as const)
4523 : ("completed" as const);
4524 const hydrated =
4525 backgroundCompletion.appendOutput.length > 0
4526 ? isMonitorEndNoticeText(toolOutputText(target)) ||
4527 toolOutputText(target).trim().length === 0
4528 ? setToolOutputText(
4529 { ...target, status: nextStatus },
4530 backgroundCompletion.appendOutput,
4531 )
4532 : appendToolOutputText(
4533 { ...target, status: nextStatus },
4534 backgroundCompletion.appendOutput,
4535 )
4536 : { ...target, status: nextStatus };
4537 // BackgroundTaskStarted normalization can reopen this row, so keep the
4538 // completion for settlement when no task_completed recorded one.
4539 if (
4540 backgroundCompletion.status !== "running" &&
4541 owner.backgroundCommands.get(backgroundCompletion.taskId) === null
4542 ) {
4543 owner.backgroundCommands.set(backgroundCompletion.taskId, {
4544 status: backgroundCompletion.status,
4545 output: toolOutputText(hydrated),
4546 });
4547 }
4548 yield* emitTool(owner, hydrated);
4549 }
4550 }
4551
4552 // Monitor TaskOutput resembles subagent hydration; do not invent a subagent.
4553 const subagentUpdate = hydratedRegisteredMonitor
4554 ? undefined
4555 : extractSubagentUpdate(toolCall);
4556 if (subagentUpdate !== undefined) {
4557 yield* emitSubagent(
4558 context,
4559 stoppedStatus === "interrupted" && subagentUpdate.status === "failed"
4560 ? { ...subagentUpdate, status: "interrupted" }
4561 : subagentUpdate,
4562 );
4563 if (followsAgentWorkState) yield* syncNativeChildren(context);
4564 if (subagentUpdate.suppressNormalTool !== false) {
4565 yield* rearmDeferredFinalize(context);
4566 return;
4567 }
4568 }
4569 if (
4570 stoppedStatus === undefined &&
4571 !shouldPersistToolUpdate(
4572 context,
4573 toolCall.toolCallId,
4574 previous,
4575 toolCall,
4576 merged.status,
4577 )
4578 ) {
4579 yield* rearmDeferredFinalize(context);
4580 return;
4581 }
4582 const status =
4583 stoppedStatus ??
4584 (flavor.isCancelledToolCall === undefined
4585 ? stoppedToolStatus(context, toolCall)
4586 : undefined) ??
4587 toolStatus(toolCall.status);
4588 const now = yield* DateTime.now;
4589 const nativeItemId = `${context.nativeThreadId}:tool:${toolCall.toolCallId}`;
4590 const ordinal = yield* resolveItemOrdinal(context, nativeItemId);
4591 const nodeId = providerNodeId(nativeItemId);
4592 const turnItemId = providerTurnItemId(nativeItemId);
4593 const nativeItemRef = {
4594 driver,
4595 nativeId: toolCall.toolCallId,
4596 strength: "strong" as const,
4597 };
4598 const startedAt = context.toolStartedAt.get(toolCall.toolCallId) ?? now;
4599 context.toolStartedAt.set(toolCall.toolCallId, startedAt);
4600 const completedAt = completedAtForStatus(status, now);
4601 const title = toolCall.title ?? null;
4602 yield* emitProviderEvent({
4603 type: "node.updated",
4604 driver,
4605 node: {
4606 id: nodeId,
4607 threadId: context.input.threadId,
4608 runId: context.input.runId,
4609 parentNodeId: context.input.rootNodeId,
4610 rootNodeId: context.input.rootNodeId,
4611 kind: "tool_call",
4612 status: nodeStatus(status),
4613 countsForRun: true,
4614 providerThreadId: context.input.providerThread.id,
4615 providerTurnId: context.providerTurnId,
4616 nativeItemRef,
4617 runtimeRequestId: null,
4618 checkpointScopeId: null,
4619 startedAt,
4620 completedAt,
4621 },
4622 });
4623
4624 const base = {
4625 id: turnItemId,
4626 threadId: context.input.threadId,
4627 runId: context.input.runId,
4628 nodeId,
4629 providerThreadId: context.input.providerThread.id,
4630 providerTurnId: context.providerTurnId,
4631 nativeItemRef,
4632 parentItemId: null,
4633 ordinal,
4634 status,
4635 title,
4636 startedAt,
4637 completedAt,
4638 updatedAt: now,
4639 } as const;
4640 const rawInput = toolCall.data.rawInput;
4641 const rawOutput = toolCall.data.rawOutput ?? toolCall.data.content;
4642 const changes = structuredFileChanges(toolCall);
4643 const path = changes[0]?.path ?? pathFromToolCall(toolCall);
4644 const diffText =
4645 acpToolCallDiffPatch(toolCall.data.content) ?? textFromUnknown(rawOutput);
4646 const rawInputRecord = unknownRecord(rawInput);
4647 const inputVariant =
4648 typeof rawInputRecord?.variant === "string"
4649 ? rawInputRecord.variant.trim().toLowerCase()
4650 : "";
4651 const rawOutputRecord = unknownRecord(rawOutput);
4652 const outputCommand =
4653 typeof rawOutputRecord?.command === "string" &&
4654 rawOutputRecord.command.trim().length > 0
4655 ? rawOutputRecord.command.trim()
4656 : undefined;
4657 const monitorCommand =
4658 (typeof rawInputRecord?.command === "string" && rawInputRecord.command.trim().length > 0
4659 ? rawInputRecord.command.trim()
4660 : undefined) ?? outputCommand;
4661 const outputIsBashResult =
4662 typeof rawOutputRecord?.type === "string" &&
4663 rawOutputRecord.type.trim().toLowerCase() === "bash" &&
4664 commandExitCode(rawOutput) !== undefined;
4665 const projectAsCommandExecution = inputVariant === "monitor" || outputIsBashResult;
4666 const mcpIdentity = extractMcpToolCallIdentity(toolCall, {
4667 embeddedTerminalCommands: embeddedTerminalCommands(
4668 context.nativeThreadId,
4669 toolCall.toolCallId,
4670 ),
4671 });
4672 let turnItem: OrchestrationV2TurnItem;
4673 if (toolCall.toolCallId.startsWith("acp-compaction:")) {
4674 const summary =
4675 (status === "failed" ? textFromUnknown(toolCall.data.compactionError) : undefined) ||
4676 textFromUnknown(rawOutput);
4677 turnItem = {
4678 ...base,
4679 type: "compaction",
4680 driver,
4681 ...(summary === undefined ? {} : { summary }),
4682 ...(context.contextUsage?.usedTokens === undefined
4683 ? {}
4684 : { beforeTokenCount: context.contextUsage.usedTokens }),
4685 };
4686 if (status === "completed") {
4687 context.contextUsage = null;
4688 yield* Ref.update(contextUsageBySessionId, (current) => {
4689 const updated = new Map(current);
4690 updated.delete(context.nativeThreadId);
4691 return updated;
4692 });
4693 // A completion projected at turn end must not swallow the agent's later real one.
4694 yield* markSessionCompacted(
4695 context.nativeThreadId,
4696 projectedStatus === undefined
4697 ? toolCall.toolCallId.slice("acp-compaction:".length)
4698 : undefined,
4699 );
4700 }
4701 } else if (mcpIdentity !== undefined) {
4702 const toolName = `${mcpIdentity.server}.${mcpIdentity.tool}`;
4703 const input =
4704 mcpIdentity.input ?? unknownRecord(rawInputRecord?.arguments) ?? rawInputRecord ?? {};
4705 let output = rawOutput === undefined ? undefined : acpMcpToolCallOutput(rawOutput);
4706 const isHtmlRender = resolveT3McpToolId(toolName) === HTML_RENDER_TOOL_NAME;
4707 const isError =
4708 compactDynamicToolOutput(output)?.isError === true ||
4709 compactDynamicToolOutput(rawOutputRecord?.result)?.isError === true;
4710 if (
4711 isHtmlRender &&
4712 (status === "failed" || (status === "completed" && isError)) &&
4713 previous?.status !== "failed" &&
4714 previous?.status !== "completed"
4715 ) {
4716 // A failed call may have published before the provider lost its result.
4717 yield* mcpSessions.takeHtmlRender(
4718 context.input.threadId,
4719 input,
4720 htmlRenderFromToolItem({ toolName, output }),
4721 );
4722 }
4723 if (status === "completed" && isHtmlRender && !isError) {
4724 const reportedPage = htmlRenderFromToolItem({ toolName, output });
4725 // Antigravity replaces MCP results with summaries, including on repeated completions.
4726 const previousPage = htmlRenderFromToolItem({
4727 toolName,
4728 output: acpMcpToolCallOutput(previous?.data.rawOutput ?? previous?.data.content),
4729 });
4730 const page = reportedPage
4731 ? yield* mcpSessions.takeHtmlRender(context.input.threadId, input, reportedPage)
4732 : (previousPage ??
4733 (yield* mcpSessions.takeHtmlRender(context.input.threadId, input)));
4734 if (reportedPage === undefined && page !== undefined) {
4735 output = { htmlRender: page };
4736 context.tools.set(toolCall.toolCallId, {
4737 ...toolCall,
4738 data: { ...toolCall.data, rawOutput: output },
4739 });
4740 }
4741 }
4742 turnItem = {
4743 ...base,
4744 title: null,
4745 ...mcpToolPresentation({
4746 serverName: mcpIdentity.server,
4747 toolName: mcpIdentity.tool,
4748 source: unknownRecord(
4749 (unknownRecord(rawOutputRecord?.result) ?? rawOutputRecord)?._meta,
4750 )?.source,
4751 }),
4752 type: "dynamic_tool",
4753 toolName,
4754 input,
4755 ...(output === undefined ? {} : { output }),
4756 };
4757 yield* emitProviderEvent({ type: "turn_item.updated", driver, turnItem });
4758 yield* rearmDeferredFinalize(context);
4759 return;
4760 } else if (changes.length > 0) {
4761 turnItem = {
4762 ...base,
4763 type: "file_change",
4764 fileName: changes[0]!.path,
4765 changes,
4766 ...(diffText === undefined ? {} : { diffStr: diffText }),
4767 };
4768 } else {
4769 switch (toolCall.kind) {
4770 case "read":
4771 turnItem = {
4772 ...base,
4773 title: path ? formatReadToolLabel(path) : (title ?? "Read file"),
4774 type: "dynamic_tool",
4775 toolName: "Read",
4776 ...(path !== undefined &&
4777 path.length <= 4096 &&
4778 !/[\r\n]/.test(path) &&
4779 isWorkspaceImagePreviewPath(path)
4780 ? { viewedImagePath: path }
4781 : {}),
4782 input:
4783 path === undefined ||
4784 ["path", "filePath", "file_path"].some((key) => rawInputRecord?.[key] === path)
4785 ? (rawInputRecord ?? {})
4786 : { ...rawInputRecord, path },
4787 ...(rawOutput === undefined ? {} : { output: rawOutput }),
4788 };
4789 break;
4790 case "search": {
4791 const backendSearch = acpBackendWebSearch(
4792 rawInputRecord,
4793 rawOutput,
4794 typeof toolCall.data.title === "string" ? toolCall.data.title : title,
4795 );
4796 if (backendSearch !== undefined) {
4797 const label = nonEmptyText(toolCall.data.title, title ?? "Web search")
4798 .replace(/:\s*$/u, "")
4799 // Antigravity titles the call "Running search_web".
4800 .replace(
4801 /^\s*(?:run(?:ning)?\s+)?(?:web_search|search_web)\s*$/iu,
4802 "Web search",
4803 );
4804 turnItem = {
4805 ...base,
4806 title:
4807 backendSearch.query === undefined
4808 ? label
4809 : `${label}: ${backendSearch.query}`,
4810 type: "web_search",
4811 ...(backendSearch.query === undefined
4812 ? {}
4813 : { patterns: [backendSearch.query] }),
4814 ...(backendSearch.results.length === 0
4815 ? {}
4816 : { results: backendSearch.results }),
4817 };
4818 break;
4819 }
4820 const pathIsQuery = resolvedPathInfo(toolCall)?.fromQuery === true;
4821 turnItem = {
4822 ...base,
4823 title:
4824 formatSearchToolLabel({
4825 rawInput: rawInputRecord,
4826 input: rawInputRecord,
4827 ...(path === undefined ? {} : { pattern: path }),
4828 }) ?? title,
4829 type: "file_search",
4830 ...(path === undefined ? {} : { pattern: path }),
4831 ...(path === undefined ||
4832 (pathIsQuery && textFromUnknown(rawOutput) === undefined)
4833 ? {}
4834 : {
4835 results: [
4836 {
4837 fileName: path,
4838 ...(textFromUnknown(rawOutput) === undefined
4839 ? {}
4840 : { preview: textFromUnknown(rawOutput) }),
4841 },
4842 ],
4843 }),
4844 };
4845 break;
4846 }
4847 case "execute": {
4848 const exitCode = acpProjectedCommandExitCode(status, rawOutput);
4849 turnItem = {
4850 ...base,
4851 type: "command_execution",
4852 input: toolCall.command ?? monitorCommand ?? "",
4853 ...(textFromUnknown(rawOutput) === undefined
4854 ? {}
4855 : { output: textFromUnknown(rawOutput) }),
4856 ...(exitCode === undefined ? {} : { exitCode }),
4857 };
4858 break;
4859 }
4860 case "edit":
4861 case "delete":
4862 case "move": {
4863 const snippet = acpToolCallSnippetEdit(toolCall.data.content);
4864 const unpreviewable = acpToolCallDiffUnpreviewable(toolCall.data.content);
4865 turnItem = {
4866 ...base,
4867 type: "file_change",
4868 fileName: path ?? toolCall.title ?? "File change",
4869 ...(snippet ??
4870 (unpreviewable || diffText === undefined ? {} : { diffStr: diffText })),
4871 };
4872 break;
4873 }
4874 case "fetch": {
4875 // Grok rawOutput.Content is unreadable by textFromUnknown; bounded content blocks duplicate it.
4876 const snippet =
4877 textFromUnknown(toolCall.data.content) ?? textFromUnknown(rawOutput);
4878 turnItem = {
4879 ...base,
4880 type: "web_search",
4881 ...(path === undefined ? {} : { patterns: [path] }),
4882 ...(path === undefined
4883 ? {}
4884 : {
4885 results: [
4886 {
4887 url: path,
4888 ...(snippet === undefined ? {} : { snippet }),
4889 },
4890 ],
4891 }),
4892 };
4893 break;
4894 }
4895 default:
4896 if (projectAsCommandExecution) {
4897 const exitCode = acpProjectedCommandExitCode(status, rawOutput);
4898 turnItem = {
4899 ...base,
4900 type: "command_execution",
4901 input: toolCall.command ?? monitorCommand ?? "",
4902 ...(textFromUnknown(rawOutput) === undefined
4903 ? {}
4904 : { output: textFromUnknown(rawOutput) }),
4905 ...(exitCode === undefined ? {} : { exitCode }),
4906 ...(inputVariant === "monitor" ? { monitor: true } : {}),
4907 };
4908 } else {
4909 turnItem = {
4910 ...base,
4911 type: "dynamic_tool",
4912 toolName: toolCall.title ?? toolCall.kind ?? null,
4913 input: rawInput ?? {},
4914 ...(rawOutput === undefined ? {} : { output: rawOutput }),
4915 };
4916 }
4917 }
4918 }
4919 yield* emitProviderEvent({ type: "turn_item.updated", driver, turnItem });
4920 yield* rearmDeferredFinalize(context);
4921 });
4922
4923 /**
4924 * Notices have no id; each is its own item, numbered by the turn's item count.
4925 * A notice is not conversation content, so an open message keeps streaming across it.
4926 */
4927 const emitNotice = Effect.fnUntraced(function* (
4928 context: ActiveAcpTurn,
4929 notice: { readonly title: string; readonly description?: string },
4930 ) {
4931 const nativeItemId = `${context.nativeTurnId}:notice:${context.itemOrdinals.size}`;
4932 const now = yield* DateTime.now;
4933 yield* emitProviderEvent({
4934 type: "turn_item.updated",
4935 driver,
4936 turnItem: {
4937 id: providerTurnItemId(nativeItemId),
4938 threadId: context.input.threadId,
4939 runId: context.input.runId,
4940 nodeId: context.input.rootNodeId,
4941 providerThreadId: context.input.providerThread.id,
4942 providerTurnId: context.providerTurnId,
4943 nativeItemRef: { driver, nativeId: nativeItemId, strength: "weak" },
4944 parentItemId: null,
4945 ordinal: yield* resolveItemOrdinal(context, nativeItemId),
4946 type: "system_notice",
4947 status: "completed",
4948 title: notice.title,
4949 message:
4950 notice.description === undefined
4951 ? notice.title
4952 : `${notice.title}\n\n${notice.description}`,
4953 startedAt: now,
4954 completedAt: now,
4955 updatedAt: now,
4956 },
4957 });
4958 });
4959
4960 const emitPlan = Effect.fnUntraced(function* (
4961 context: ActiveAcpTurn,
4962 update: AcpPlanUpdate,
4963 sessionScoped: boolean,
4964 ) {
4965 yield* closeTextStreams(context);
4966 let plans = sessionScoped ? plansBySessionId.get(context.nativeThreadId) : context.plans;
4967 if (plans === undefined) {
4968 plans = new Map();
4969 plansBySessionId.set(context.nativeThreadId, plans);
4970 }
4971 const existing = plans.get(update.nativePlanId);
4972 if (update.kind === "removed" && existing === undefined) return;
4973 const now = yield* DateTime.now;
4974 let planState = existing;
4975 if (planState === undefined) {
4976 const nativeItemId = `${context.nativeTurnId}:plan:${encodeURIComponent(update.nativePlanId)}`;
4977 planState = {
4978 id: yield* idAllocator.allocate.plan({
4979 threadId: context.input.threadId,
4980 runId: context.input.runId,
4981 driver,
4982 }),
4983 startedAt: now,
4984 origin: {
4985 runId: context.input.runId,
4986 rootNodeId: context.input.rootNodeId,
4987 providerThreadId: context.input.providerThread.id,
4988 providerTurnId: context.providerTurnId,
4989 nativeItemId,
4990 ordinal: yield* resolveItemOrdinal(context, nativeItemId),
4991 },
4992 latest: null,
4993 };
4994 }
4995 const { origin } = planState;
4996 const nodeId = providerNodeId(origin.nativeItemId);
4997 const turnItemId = providerTurnItemId(origin.nativeItemId);
4998 const planId = planState.id;
4999 const nativeItemRef = {
5000 driver,
Showing first 5,000 of 10,698 lines. View raw