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

main
ts 1,700 lines 56.4 KB
Raw
1 import * as Clock from "effect/Clock";
2 import * as Duration from "effect/Duration";
3 import * as Effect from "effect/Effect";
4 import * as Option from "effect/Option";
5 import * as Ref from "effect/Ref";
6 import * as Schema from "effect/Schema";
7 import * as EffectAcpSchema from "effect-acp/compat";
8 import * as EffectAcpSchemaV1 from "effect-acp/schema-v1";
9 import {
10 deriveToolActivityPresentation,
11 mergeToolActivityData,
12 } from "@t3tools/shared/toolActivity";
13 import { T3_MCP_TOOL_NAMES } from "@t3tools/shared/t3McpToolPresentation";
14 import type {
15 OrchestrationV2ProviderThreadNativeMetadata,
16 ThreadTokenUsageSnapshot,
17 ToolLifecycleItemType,
18 } from "@t3tools/contracts";
19
20 function isRecord(value: unknown): value is Record<string, unknown> {
21 return typeof value === "object" && value !== null && !Array.isArray(value);
22 }
23
24 // Modes were removed from ACP v2, so the v1 wire schema is the source of truth.
25 const isSessionModelState = Schema.is(EffectAcpSchema.SessionModelState);
26 const isSessionModeState = Schema.is(EffectAcpSchemaV1.SessionModeState);
27
28 export interface AcpSessionMode {
29 readonly id: string;
30 readonly name: string;
31 readonly description?: string;
32 }
33
34 export interface AcpSessionModeState {
35 readonly currentModeId: string;
36 readonly availableModes: ReadonlyArray<AcpSessionMode>;
37 }
38
39 export interface AcpToolCallState {
40 readonly toolCallId: string;
41 readonly kind?: string;
42 readonly title?: string;
43 readonly status?: "pending" | "inProgress" | "requiresAction" | "completed" | "failed";
44 readonly command?: string;
45 readonly detail?: string;
46 readonly data: Record<string, unknown>;
47 }
48
49 export interface AcpAgentTerminalState {
50 readonly command?: string;
51 readonly cwd?: string;
52 readonly output: string;
53 /** UTF-8 byte length of `output`, so appending a chunk never re-encodes the buffer. */
54 readonly outputBytes: number;
55 readonly exitStatus?: EffectAcpSchema.TerminalExitStatus;
56 readonly pendingOutputBytes?: Uint8Array;
57 }
58
59 type AcpAgentTerminalUpdate = Extract<
60 EffectAcpSchema.SessionUpdate,
61 { readonly sessionUpdate: "terminal_update" | "terminal_output_chunk" }
62 >;
63
64 const MAX_ACP_TERMINAL_OUTPUT_BYTES = 16 * 1024 * 1024;
65 const ACP_TERMINAL_OUTPUT_TRIM_BYTES = 1024 * 1024;
66 const MAX_ACP_TERMINAL_FRAME_BYTES = MAX_ACP_TERMINAL_OUTPUT_BYTES;
67
68 function isBase64DataCode(code: number): boolean {
69 return (
70 (code >= 65 && code <= 90) ||
71 (code >= 97 && code <= 122) ||
72 (code >= 48 && code <= 57) ||
73 code === 43 ||
74 code === 47
75 );
76 }
77
78 function decodeBase64TerminalFrame(encoded: string): Uint8Array | undefined {
79 if (encoded.length > Math.ceil(MAX_ACP_TERMINAL_FRAME_BYTES / 3) * 4) {
80 return undefined;
81 }
82 const padding = encoded.endsWith("==") ? 2 : encoded.endsWith("=") ? 1 : 0;
83 const dataLength = encoded.length - padding;
84 if (
85 encoded.length % 4 === 1 ||
86 (padding > 0 && encoded.length % 4 !== 0) ||
87 (padding === 1 && dataLength % 4 !== 3) ||
88 (padding === 2 && dataLength % 4 !== 2)
89 ) {
90 return undefined;
91 }
92 for (let index = 0; index < dataLength; index += 1) {
93 if (!isBase64DataCode(encoded.charCodeAt(index))) return undefined;
94 }
95 const decoded = Buffer.from(encoded, "base64");
96 return decoded.byteLength <= MAX_ACP_TERMINAL_FRAME_BYTES ? decoded : undefined;
97 }
98
99 function trailingIncompleteUtf8Start(bytes: Uint8Array): number {
100 if (bytes.length === 0) return bytes.length;
101 let leadIndex = bytes.length - 1;
102 while (leadIndex >= 0 && (bytes[leadIndex]! & 0xc0) === 0x80) {
103 leadIndex -= 1;
104 }
105 if (leadIndex < 0) return bytes.length;
106 const lead = bytes[leadIndex]!;
107 const expectedLength =
108 lead >= 0xc2 && lead <= 0xdf
109 ? 2
110 : lead >= 0xe0 && lead <= 0xef
111 ? 3
112 : lead >= 0xf0 && lead <= 0xf4
113 ? 4
114 : 1;
115 return bytes.length - leadIndex < expectedLength ? leadIndex : bytes.length;
116 }
117
118 function decodeTerminalOutputChunk(
119 pending: Uint8Array | undefined,
120 encoded: string,
121 ): { readonly text: string; readonly pendingOutputBytes?: Uint8Array } | undefined {
122 const frame = decodeBase64TerminalFrame(encoded);
123 if (frame === undefined) return undefined;
124 const bytes = Buffer.concat([...(pending === undefined ? [] : [Buffer.from(pending)]), frame]);
125 const completeEnd = trailingIncompleteUtf8Start(bytes);
126 const text = bytes.subarray(0, completeEnd).toString("utf8");
127 return completeEnd === bytes.length
128 ? { text }
129 : { text, pendingOutputBytes: Uint8Array.from(bytes.subarray(completeEnd)) };
130 }
131
132 // Drop an extra batch at UTF-8 boundaries so flattening the retained string is amortized.
133 function appendTerminalOutput(
134 output: string,
135 outputBytes: number,
136 text: string,
137 ): Pick<AcpAgentTerminalState, "output" | "outputBytes"> {
138 const combined = `${output}${text}`;
139 const combinedBytes = outputBytes + Buffer.byteLength(text, "utf8");
140 const excess = combinedBytes - MAX_ACP_TERMINAL_OUTPUT_BYTES;
141 if (excess <= 0) return { output: combined, outputBytes: combinedBytes };
142 let start = 0;
143 let dropped = 0;
144 while (dropped < excess + ACP_TERMINAL_OUTPUT_TRIM_BYTES) {
145 const codePoint = combined.codePointAt(start)!;
146 dropped += codePoint < 0x80 ? 1 : codePoint < 0x800 ? 2 : codePoint < 0x10000 ? 3 : 4;
147 start += codePoint < 0x10000 ? 1 : 2;
148 }
149 return { output: combined.slice(start), outputBytes: combinedBytes - dropped };
150 }
151
152 export function applyAcpAgentTerminalUpdate(
153 previous: AcpAgentTerminalState | undefined,
154 update: AcpAgentTerminalUpdate,
155 ): AcpAgentTerminalState {
156 const current = previous ?? { output: "", outputBytes: 0 };
157 if (update.sessionUpdate === "terminal_output_chunk") {
158 const decoded = decodeTerminalOutputChunk(current.pendingOutputBytes, update.data);
159 if (decoded === undefined) return current;
160 const { pendingOutputBytes: _pendingOutputBytes, ...withoutPendingOutputBytes } = current;
161 return {
162 ...withoutPendingOutputBytes,
163 ...appendTerminalOutput(current.output, current.outputBytes, decoded.text),
164 ...(decoded.pendingOutputBytes === undefined
165 ? {}
166 : { pendingOutputBytes: decoded.pendingOutputBytes }),
167 };
168 }
169 let next: AcpAgentTerminalState = current;
170 if (update.command === null) {
171 const { command: _command, ...withoutCommand } = next;
172 next = withoutCommand;
173 } else if (update.command !== undefined) {
174 next = { ...next, command: update.command };
175 }
176 if (update.cwd === null) {
177 const { cwd: _cwd, ...withoutCwd } = next;
178 next = withoutCwd;
179 } else if (update.cwd !== undefined) {
180 next = { ...next, cwd: update.cwd };
181 }
182 if (update.output !== undefined) {
183 const decoded =
184 update.output === null
185 ? { text: "" }
186 : decodeTerminalOutputChunk(undefined, update.output.data);
187 if (decoded !== undefined) {
188 const { pendingOutputBytes: _pendingOutputBytes, ...withoutPendingOutputBytes } = next;
189 next = {
190 ...withoutPendingOutputBytes,
191 ...appendTerminalOutput("", 0, decoded.text),
192 ...(decoded.pendingOutputBytes === undefined
193 ? {}
194 : { pendingOutputBytes: decoded.pendingOutputBytes }),
195 };
196 }
197 }
198 if (update.exitStatus === null) {
199 const { exitStatus: _exitStatus, ...withoutExitStatus } = next;
200 next = withoutExitStatus;
201 } else if (update.exitStatus !== undefined) {
202 const pendingText =
203 next.pendingOutputBytes === undefined
204 ? ""
205 : Buffer.from(next.pendingOutputBytes).toString("utf8");
206 const { pendingOutputBytes: _pendingOutputBytes, ...withoutPendingOutputBytes } = next;
207 next = {
208 ...withoutPendingOutputBytes,
209 ...appendTerminalOutput(next.output, next.outputBytes, pendingText),
210 exitStatus: update.exitStatus,
211 };
212 }
213 return next;
214 }
215
216 export type AcpPlanUpdate =
217 | {
218 readonly nativePlanId: string;
219 readonly kind: "items";
220 readonly explanation?: string | null;
221 readonly plan: ReadonlyArray<{
222 readonly step: string;
223 readonly status: "pending" | "inProgress" | "completed" | "cancelled";
224 }>;
225 }
226 | { readonly nativePlanId: string; readonly kind: "markdown"; readonly markdown: string }
227 | { readonly nativePlanId: string; readonly kind: "file"; readonly uri: string }
228 | { readonly nativePlanId: string; readonly kind: "unknown"; readonly contentType: string }
229 | { readonly nativePlanId: string; readonly kind: "removed" };
230
231 export interface AcpPermissionRequest {
232 readonly kind: string | "unknown";
233 readonly detail?: string;
234 readonly toolCall?: AcpToolCallState;
235 }
236
237 export type AcpParsedSessionEvent =
238 | {
239 readonly _tag: "ModeChanged";
240 readonly modeId: string;
241 }
242 | {
243 readonly _tag: "AvailableCommandsUpdated";
244 readonly availableCommands: ReadonlyArray<EffectAcpSchema.AvailableCommand>;
245 readonly rawPayload: unknown;
246 }
247 | {
248 readonly _tag: "ConfigOptionsUpdated";
249 readonly configOptions: ReadonlyArray<EffectAcpSchema.SessionConfigOption>;
250 readonly rawPayload: unknown;
251 }
252 | {
253 readonly _tag: "AssistantItemStarted";
254 readonly itemId: string;
255 }
256 | {
257 readonly _tag: "AssistantItemCompleted";
258 readonly itemId: string;
259 }
260 | {
261 readonly _tag: "PlanUpdated";
262 readonly payload: AcpPlanUpdate;
263 readonly rawPayload: unknown;
264 }
265 | {
266 readonly _tag: "ToolCallUpdated";
267 readonly toolCall: AcpToolCallState;
268 readonly rawPayload: unknown;
269 }
270 | {
271 readonly _tag: "ContentDelta";
272 readonly itemId?: string;
273 readonly messageId?: string;
274 readonly text: string;
275 readonly rawPayload: unknown;
276 }
277 | {
278 readonly _tag: "ThoughtDelta";
279 readonly text: string;
280 readonly rawPayload: unknown;
281 }
282 | {
283 readonly _tag: "UsageUpdated";
284 readonly usage: ThreadTokenUsageSnapshot;
285 readonly rawPayload: unknown;
286 }
287 | {
288 readonly _tag: "SessionInfoUpdated";
289 readonly metadata: OrchestrationV2ProviderThreadNativeMetadata;
290 readonly rawPayload: unknown;
291 }
292 | {
293 readonly _tag: "NoticeReceived";
294 readonly severity: string;
295 readonly title: string;
296 readonly description?: string;
297 readonly rawPayload: unknown;
298 }
299 | {
300 readonly _tag: "UnknownUpdate";
301 readonly updateType: string;
302 readonly rawPayload: unknown;
303 };
304
305 const boundedContentMetadata = (value: string | null | undefined, maximumLength: number): string =>
306 value?.trim().slice(0, maximumLength) ?? "";
307
308 const MAX_ACP_CONTENT_TEXT_LENGTH = 65_536;
309
310 const boundedContentText = (value: string): string => value.slice(0, MAX_ACP_CONTENT_TEXT_LENGTH);
311
312 const boundedContentUri = (value: string | null | undefined): string => {
313 const uri = boundedContentMetadata(value, 4_096);
314 return uri.toLowerCase().startsWith("data:") ? "" : uri;
315 };
316
317 export function acpContentBlockDisplayText(
318 content: EffectAcpSchema.ContentBlock,
319 ): string | undefined {
320 switch (content.type) {
321 case "text":
322 return boundedContentText(content.text);
323 case "resource_link": {
324 const label =
325 boundedContentMetadata(content.title, 512) ||
326 boundedContentMetadata(content.name, 512) ||
327 "resource";
328 const description = boundedContentMetadata(content.description, 2_048);
329 const uri = boundedContentUri(content.uri);
330 return `${description ? `${label}: ${description}` : label}${uri ? `\n${uri}` : ""}`;
331 }
332 case "resource": {
333 if ("text" in content.resource) {
334 return boundedContentText(content.resource.text);
335 }
336 const mimeType = boundedContentMetadata(content.resource.mimeType, 256);
337 const uri = boundedContentUri(content.resource.uri);
338 return `[ACP binary resource${mimeType ? ` (${mimeType})` : ""}${uri ? `: ${uri}` : ""}]`;
339 }
340 case "image": {
341 const mimeType = boundedContentMetadata(content.mimeType, 256) || "unknown type";
342 const uri = boundedContentUri(content.uri);
343 return `[ACP image (${mimeType})${uri ? `: ${uri}` : ""}]`;
344 }
345 case "audio": {
346 const mimeType = boundedContentMetadata(content.mimeType, 256) || "unknown type";
347 return `[ACP audio (${mimeType})]`;
348 }
349 case "_t3_unknown":
350 return `[Unsupported ACP content: ${boundedContentMetadata(content.originalType, 128) || "unknown"}]`;
351 }
352 }
353
354 function sanitizeAcpToolCallContent(
355 content: ReadonlyArray<EffectAcpSchema.ToolCallContent>,
356 ): ReadonlyArray<EffectAcpSchema.ToolCallContent> {
357 return content.map((entry) => {
358 switch (entry.type) {
359 case "content":
360 return {
361 type: "content",
362 content: {
363 type: "text",
364 text: acpContentBlockDisplayText(entry.content) ?? "",
365 },
366 };
367 case "diff":
368 if ("changes" in entry) {
369 return {
370 type: "diff",
371 changes: entry.changes,
372 ...(entry.patch === undefined ? {} : { patch: entry.patch }),
373 };
374 }
375 return {
376 type: "diff",
377 path: entry.path,
378 ...(entry.oldText !== undefined ? { oldText: entry.oldText } : {}),
379 newText: entry.newText,
380 };
381 case "terminal":
382 return { type: "terminal", terminalId: entry.terminalId };
383 case "_t3_unknown":
384 return {
385 type: "_t3_unknown",
386 originalType: boundedContentMetadata(entry.originalType, 128) || "unknown",
387 raw: null,
388 };
389 }
390 });
391 }
392
393 type AcpSessionSetupResponse =
394 | EffectAcpSchema.ForkSessionResponse
395 | EffectAcpSchema.LoadSessionResponse
396 | EffectAcpSchema.NewSessionResponse
397 | EffectAcpSchema.ResumeSessionResponse;
398
399 type AcpToolCallUpdate = Extract<
400 EffectAcpSchema.SessionNotification["update"],
401 { readonly sessionUpdate: "tool_call" | "tool_call_update" }
402 >;
403
404 type AcpSelectConfigOption = Extract<
405 EffectAcpSchema.SessionConfigOption,
406 { readonly type: "select" }
407 >;
408
409 // ACP resolves options in the same category by array order.
410 export function findModelConfigOption(
411 configOptions: ReadonlyArray<EffectAcpSchema.SessionConfigOption> | null | undefined,
412 ): AcpSelectConfigOption | undefined {
413 return configOptions?.find(
414 (option): option is AcpSelectConfigOption =>
415 option.category === "model" && option.type === "select" && option.id.trim().length > 0,
416 );
417 }
418
419 export function extractModelConfigId(sessionResponse: AcpSessionSetupResponse): string | undefined {
420 return findModelConfigOption(sessionResponse.configOptions)?.id.trim();
421 }
422
423 export function findSessionConfigOption(
424 configOptions: ReadonlyArray<EffectAcpSchema.SessionConfigOption> | null | undefined,
425 configId: string,
426 ): EffectAcpSchema.SessionConfigOption | undefined {
427 if (!configOptions) {
428 return undefined;
429 }
430 const normalizedConfigId = configId.trim();
431 if (!normalizedConfigId) {
432 return undefined;
433 }
434 return configOptions.find((option) => option.id.trim() === normalizedConfigId);
435 }
436
437 export function collectSessionConfigOptionValues(
438 configOption: EffectAcpSchema.SessionConfigOption,
439 ): ReadonlyArray<string> {
440 if (configOption.type !== "select") {
441 return [];
442 }
443 return configOption.options.flatMap((entry) =>
444 "value" in entry ? [entry.value] : entry.options.map((option) => option.value),
445 );
446 }
447
448 export function parseSessionModeState(
449 sessionResponse: AcpSessionSetupResponse,
450 ): AcpSessionModeState | undefined {
451 const modeConfig = sessionResponse.configOptions?.find(
452 (option) => option.category === "mode" && option.type === "select",
453 );
454 const modes =
455 sessionResponse.modes ??
456 (modeConfig?.type === "select"
457 ? {
458 currentModeId: modeConfig.currentValue,
459 availableModes: modeConfig.options
460 .flatMap((option) => ("options" in option ? option.options : [option]))
461 .map((option) => ({
462 id: option.value,
463 name: option.name,
464 description: option.description,
465 })),
466 }
467 : undefined);
468 if (!modes) return undefined;
469 const currentModeId = modes.currentModeId.trim();
470 if (!currentModeId) {
471 return undefined;
472 }
473 const availableModes: Array<AcpSessionMode> = [];
474 for (const mode of modes.availableModes) {
475 const id = mode.id.trim();
476 const name = mode.name.trim();
477 if (!id || !name) {
478 continue;
479 }
480 const description = mode.description?.trim() || undefined;
481 availableModes.push(
482 description !== undefined
483 ? ({ id, name, description } satisfies AcpSessionMode)
484 : ({ id, name } satisfies AcpSessionMode),
485 );
486 }
487 if (availableModes.length === 0) {
488 return undefined;
489 }
490 return {
491 currentModeId,
492 availableModes,
493 };
494 }
495
496 function normalizePlanStepStatus(
497 raw: unknown,
498 ): "pending" | "inProgress" | "completed" | "cancelled" {
499 switch (raw) {
500 case "completed":
501 return "completed";
502 case "cancelled":
503 return "cancelled";
504 case "in_progress":
505 case "inProgress":
506 return "inProgress";
507 default:
508 return "pending";
509 }
510 }
511
512 function normalizeToolCallStatus(
513 raw: unknown,
514 fallback?: "pending" | "inProgress" | "completed" | "failed",
515 ): "pending" | "inProgress" | "completed" | "failed" | undefined {
516 switch (raw) {
517 case "pending":
518 return "pending";
519 case "in_progress":
520 case "inProgress":
521 return "inProgress";
522 case "completed":
523 return "completed";
524 case "failed":
525 case "cancelled":
526 return "failed";
527 default:
528 return fallback;
529 }
530 }
531
532 function normalizeCommandValue(value: unknown): string | undefined {
533 if (typeof value === "string" && value.trim().length > 0) {
534 return value.trim();
535 }
536 if (!Array.isArray(value)) {
537 return undefined;
538 }
539 const parts: Array<string> = [];
540 for (const entry of value) {
541 if (typeof entry === "string") {
542 const part = entry.trim();
543 if (part.length > 0) {
544 parts.push(part);
545 }
546 }
547 }
548 return parts.length > 0 ? parts.join(" ") : undefined;
549 }
550
551 function extractCommandFromTitle(title: string | undefined): string | undefined {
552 if (!title) {
553 return undefined;
554 }
555 const match = /`([^`]+)`/.exec(title);
556 return match?.[1]?.trim() || undefined;
557 }
558
559 function extractToolCallCommand(
560 rawInput: unknown,
561 title: string | undefined,
562 kind: string | undefined,
563 ): string | undefined {
564 if (isRecord(rawInput)) {
565 const directCommand = normalizeCommandValue(rawInput.command);
566 if (directCommand) {
567 return directCommand;
568 }
569 const executable = typeof rawInput.executable === "string" ? rawInput.executable.trim() : "";
570 const args = normalizeCommandValue(rawInput.args);
571 if (executable && args) {
572 return `${executable} ${args}`;
573 }
574 if (executable) {
575 return executable;
576 }
577 }
578 // Only execute tools may treat titles as commands.
579 if (kind !== "execute") {
580 return undefined;
581 }
582 return extractCommandFromTitle(title);
583 }
584
585 function filePathFromToolValue(value: unknown): string | undefined {
586 if (typeof value !== "string") {
587 return undefined;
588 }
589 const trimmed = value.trim();
590 return trimmed.length > 0 ? trimmed : undefined;
591 }
592
593 function locationsFromToolCallInput(input: {
594 readonly locations?: ReadonlyArray<EffectAcpSchema.ToolCallLocation> | null | undefined;
595 readonly content?: ReadonlyArray<EffectAcpSchema.ToolCallContent> | null | undefined;
596 readonly rawInput?: unknown;
597 readonly rawOutput?: unknown;
598 }): ReadonlyArray<EffectAcpSchema.ToolCallLocation> | undefined {
599 if (input.locations === null || input.locations?.length === 0) {
600 return [];
601 }
602 const locations: EffectAcpSchema.ToolCallLocation[] = [];
603 const seen = new Set<string>();
604 const pushLocation = (location: EffectAcpSchema.ToolCallLocation) => {
605 const path = filePathFromToolValue(location.path);
606 if (!path || seen.has(path)) {
607 return;
608 }
609 seen.add(path);
610 locations.push({ ...location, path });
611 };
612 const pushPath = (value: unknown) => {
613 const path = filePathFromToolValue(value);
614 if (!path || seen.has(path)) {
615 return;
616 }
617 seen.add(path);
618 locations.push({ path });
619 };
620
621 if (input.locations) {
622 for (const location of input.locations) {
623 pushLocation(location);
624 }
625 }
626 if (input.content) {
627 for (const entry of input.content) {
628 if (entry.type === "diff" && "path" in entry) {
629 pushPath(entry.path);
630 }
631 }
632 }
633 if (isRecord(input.rawInput)) {
634 pushPath(input.rawInput.path);
635 pushPath(input.rawInput.filePath);
636 pushPath(input.rawInput.file_path);
637 }
638 if (isRecord(input.rawOutput)) {
639 pushPath(input.rawOutput.path);
640 pushPath(input.rawOutput.filePath);
641 pushPath(input.rawOutput.file_path);
642 }
643
644 return locations.length > 0 ? locations : undefined;
645 }
646
647 // Agents resend cumulative output; bound it to avoid flooding event ingestion.
648 const TOOL_CALL_CONTENT_MAX_CHARS = 8_000;
649 const TOOL_CALL_CONTENT_TRUNCATION_MARKER = "[Earlier output truncated]\n\n";
650
651 /** The tail to keep, or undefined when the text fits or an adapter already bounded it. */
652 function retainedToolCallOutputTail(text: string): string | undefined {
653 if (
654 text.length <= TOOL_CALL_CONTENT_MAX_CHARS ||
655 (text.startsWith(TOOL_CALL_CONTENT_TRUNCATION_MARKER) &&
656 text.length <= TOOL_CALL_CONTENT_MAX_CHARS + TOOL_CALL_CONTENT_TRUNCATION_MARKER.length)
657 ) {
658 return undefined;
659 }
660 // A tail starting inside a surrogate pair is invalid Unicode.
661 return text.slice(-TOOL_CALL_CONTENT_MAX_CHARS).replace(/^[\uDC00-\uDFFF]/u, "");
662 }
663
664 function boundToolCallOutputText(text: string): string {
665 const tail = retainedToolCallOutputTail(text);
666 return tail === undefined ? text : `${TOOL_CALL_CONTENT_TRUNCATION_MARKER}${tail}`;
667 }
668
669 const RAW_OUTPUT_TEXT_FIELDS = ["content", "stdout", "stderr", "output"] as const;
670
671 // rawOutput can duplicate cumulative output and bypass content limits.
672 function boundToolCallRawOutput(rawOutput: unknown): unknown {
673 if (!isRecord(rawOutput)) {
674 return rawOutput;
675 }
676 let changed = false;
677 const bounded: Record<string, unknown> = { ...rawOutput };
678 for (const field of RAW_OUTPUT_TEXT_FIELDS) {
679 const value = rawOutput[field];
680 if (typeof value === "string" && value.length > TOOL_CALL_CONTENT_MAX_CHARS) {
681 bounded[field] = boundToolCallOutputText(value);
682 changed = true;
683 }
684 }
685 return changed ? bounded : rawOutput;
686 }
687
688 interface ExtractedToolCallContent {
689 readonly text: string | undefined;
690 readonly content: ReadonlyArray<EffectAcpSchema.ToolCallContent> | undefined;
691 }
692
693 function toolCallContentText(entry: EffectAcpSchema.ToolCallContent): string | undefined {
694 if (entry.type !== "content" || entry.content.type !== "text") {
695 return undefined;
696 }
697 return entry.content.text;
698 }
699
700 function boundToolCallContentEntries(
701 content: ReadonlyArray<EffectAcpSchema.ToolCallContent>,
702 ): ReadonlyArray<EffectAcpSchema.ToolCallContent> {
703 let changed = false;
704 const bounded = content.map((entry) => {
705 const text = toolCallContentText(entry);
706 if (text === undefined || text.length <= TOOL_CALL_CONTENT_MAX_CHARS) {
707 return entry;
708 }
709 changed = true;
710 const trimmed = text.trim();
711 return {
712 type: "content",
713 content: {
714 type: "text",
715 text: boundToolCallOutputText(trimmed.length > 0 ? trimmed : text),
716 },
717 } as const;
718 });
719 return changed ? bounded : content;
720 }
721
722 function extractTextContentFromToolCallContent(
723 content: ReadonlyArray<EffectAcpSchema.ToolCallContent> | null | undefined,
724 ): ExtractedToolCallContent {
725 if (!content) {
726 return { text: undefined, content: undefined };
727 }
728 const chunks: Array<string> = [];
729 for (const entry of content) {
730 const text = toolCallContentText(entry)?.trim();
731 if (text) {
732 chunks.push(text);
733 }
734 }
735 if (chunks.length === 0) {
736 return { text: undefined, content: boundToolCallContentEntries(content) };
737 }
738 const joined = chunks.join("\n");
739 const tail = retainedToolCallOutputTail(joined);
740 if (tail === undefined) {
741 return { text: joined, content: boundToolCallContentEntries(content) };
742 }
743 return {
744 text: `${TOOL_CALL_CONTENT_TRUNCATION_MARKER}${tail}`,
745 content: distributeRetainedTailAcrossContent(content, tail),
746 };
747 }
748
749 function distributeRetainedTailAcrossContent(
750 content: ReadonlyArray<EffectAcpSchema.ToolCallContent>,
751 tail: string,
752 ): ReadonlyArray<EffectAcpSchema.ToolCallContent> {
753 const textRanges: Array<
754 | {
755 readonly start: number;
756 readonly end: number;
757 readonly text: string;
758 }
759 | undefined
760 > = Array.from({ length: content.length });
761 let offset = 0;
762 let seenText = false;
763 for (const [index, entry] of content.entries()) {
764 const text = toolCallContentText(entry)?.trim();
765 if (!text) {
766 continue;
767 }
768 if (seenText) {
769 offset += 1;
770 }
771 seenText = true;
772 const start = offset;
773 const end = offset + text.length;
774 textRanges[index] = { start, end, text };
775 offset = end;
776 }
777 const tailStart = Math.max(0, offset - tail.length);
778 let markerPending = true;
779 return content.flatMap((entry, index) => {
780 if (toolCallContentText(entry) === undefined) {
781 return [entry];
782 }
783 const range = textRanges[index];
784 if (range === undefined) {
785 return [];
786 }
787 const overlapStart = Math.max(range.start, tailStart);
788 const overlapEnd = Math.min(range.end, offset);
789 if (overlapEnd <= overlapStart) {
790 return [];
791 }
792 let piece = range.text.slice(overlapStart - range.start, overlapEnd - range.start);
793 if (markerPending) {
794 piece = `${TOOL_CALL_CONTENT_TRUNCATION_MARKER}${piece}`;
795 markerPending = false;
796 }
797 return [{ type: "content", content: { type: "text", text: piece } } as const];
798 });
799 }
800
801 function normalizeToolKind(kind: unknown): string | undefined {
802 return typeof kind === "string" && kind.trim().length > 0 ? kind.trim() : undefined;
803 }
804
805 function canonicalItemTypeFromAcpToolKind(kind: string | undefined): ToolLifecycleItemType {
806 switch (kind) {
807 case "read":
808 return "dynamic_tool_call";
809 case "execute":
810 return "command_execution";
811 case "edit":
812 case "delete":
813 case "move":
814 return "file_change";
815 case "search":
816 case "fetch":
817 return "web_search";
818 default:
819 return "dynamic_tool_call";
820 }
821 }
822
823 const TOOL_FALLBACK_SUMMARY = "Tool";
824
825 function makeToolCallState(
826 input: {
827 readonly toolCallId: string;
828 readonly name?: string | null | undefined;
829 readonly title?: string | null | undefined;
830 readonly kind?: EffectAcpSchema.ToolKind | null | undefined;
831 readonly status?: EffectAcpSchema.ToolCallStatus | null | undefined;
832 readonly rawInput?: unknown;
833 readonly rawOutput?: unknown;
834 readonly content?: ReadonlyArray<EffectAcpSchema.ToolCallContent> | null | undefined;
835 readonly locations?: ReadonlyArray<EffectAcpSchema.ToolCallLocation> | null | undefined;
836 readonly _meta?: unknown;
837 },
838 options?: {
839 readonly fallbackStatus?: "pending" | "inProgress" | "completed" | "failed";
840 },
841 ): AcpToolCallState | undefined {
842 const toolCallId = input.toolCallId.trim();
843 if (!toolCallId) {
844 return undefined;
845 }
846 const title = input.title?.trim() || undefined;
847 const kind = normalizeToolKind(input.kind);
848 const command = extractToolCallCommand(input.rawInput, title, kind);
849 const extractedContent = extractTextContentFromToolCallContent(input.content);
850 const textContent = extractedContent.text;
851 const normalizedTitle =
852 title && title.toLowerCase() !== "terminal" && title.toLowerCase() !== "tool call"
853 ? title
854 : undefined;
855 const data: Record<string, unknown> = { toolCallId };
856 // ACP v2 clears a field set to null; mergeToolCallState consumes these markers.
857 const clearable = {
858 name: input.name,
859 title: input.title,
860 kind: input.kind,
861 status: input.status,
862 content: input.content,
863 rawInput: input.rawInput,
864 meta: input._meta,
865 };
866 for (const [key, value] of Object.entries(clearable)) {
867 if (value === null) data[key] = null;
868 }
869 if (input.name != null) data.name = input.name;
870 if (kind) {
871 data.kind = kind;
872 }
873 if (title) {
874 // Identity checks need the verbatim title; presentation summarizes the state title.
875 data.title = title;
876 }
877 if (command) {
878 data.command = command;
879 }
880 if (input.rawInput !== undefined) {
881 data.rawInput = input.rawInput;
882 }
883 if (isRecord(input._meta)) {
884 // goose, qwen, and claude-acp may identify MCP calls only in metadata.
885 data.meta = input._meta;
886 }
887 if (input.rawOutput !== undefined) {
888 data.rawOutput = boundToolCallRawOutput(input.rawOutput);
889 }
890 if (input.content != null) {
891 data.content = sanitizeAcpToolCallContent(extractedContent.content ?? input.content);
892 }
893 const locations = locationsFromToolCallInput(input);
894 if (locations !== undefined) {
895 data.locations = locations;
896 }
897 if (isRecord(input._meta)) {
898 data.meta = input._meta;
899 }
900 const fallbackDetail = command ?? normalizedTitle ?? textContent;
901 const hasPresentationSeed =
902 title !== undefined ||
903 kind !== undefined ||
904 command !== undefined ||
905 normalizedTitle !== undefined ||
906 textContent !== undefined;
907 const presentation = hasPresentationSeed
908 ? deriveToolActivityPresentation({
909 itemType: canonicalItemTypeFromAcpToolKind(kind),
910 title,
911 detail: fallbackDetail,
912 data,
913 fallbackSummary: title ?? TOOL_FALLBACK_SUMMARY,
914 })
915 : undefined;
916 // A titleless update omits an unchanged title; the generic fallback must not replace it.
917 const presentationTitle =
918 title === undefined && presentation?.summary === TOOL_FALLBACK_SUMMARY
919 ? undefined
920 : presentation?.summary;
921 const status = normalizeToolCallStatus(input.status, options?.fallbackStatus);
922 return {
923 toolCallId,
924 ...(kind ? { kind } : {}),
925 ...(presentationTitle ? { title: presentationTitle } : {}),
926 ...(status ? { status } : {}),
927 ...(command ? { command } : {}),
928 ...(presentation?.detail ? { detail: presentation.detail } : {}),
929 data,
930 };
931 }
932
933 function parseTypedToolCallState(
934 event: AcpToolCallUpdate,
935 options?: {
936 readonly fallbackStatus?: "pending" | "inProgress" | "completed" | "failed";
937 },
938 ): AcpToolCallState | undefined {
939 return makeToolCallState(
940 {
941 toolCallId: event.toolCallId,
942 name: event.name,
943 title: event.title,
944 kind: event.kind,
945 status: event.status,
946 rawInput: event.rawInput,
947 rawOutput: event.rawOutput,
948 content: event.content,
949 locations: event.locations,
950 _meta: event._meta,
951 },
952 options,
953 );
954 }
955
956 export function mergeToolCallState(
957 previous: AcpToolCallState | undefined,
958 next: AcpToolCallState,
959 ): AcpToolCallState {
960 const nextKind = next.kind ?? (typeof next.data.kind === "string" ? next.data.kind : undefined);
961 const kind = next.data.kind === null ? nextKind : (nextKind ?? previous?.kind);
962 const title = next.data.title === null ? next.title : (next.title ?? previous?.title);
963 const status = next.data.status === null ? next.status : (next.status ?? previous?.status);
964 const command = next.command ?? previous?.command;
965 const detail = next.detail ?? previous?.detail;
966 const data = mergeToolActivityData(previous?.data, next.data) ?? next.data;
967 return {
968 toolCallId: next.toolCallId,
969 ...(kind ? { kind } : {}),
970 ...(title ? { title } : {}),
971 ...(status ? { status } : {}),
972 ...(command ? { command } : {}),
973 ...(detail ? { detail } : {}),
974 data,
975 };
976 }
977
978 // Bounded terminal tails still shift on each redraw; coalesce those updates.
979 const TOOL_CALL_UPDATE_MIN_DETAIL_GROWTH_CHARS = 256;
980 const TOOL_CALL_UPDATE_COALESCE_LIMIT = 10;
981
982 export interface AcpToolCallEmitDecisionInput {
983 readonly previous: AcpToolCallState | undefined;
984 readonly next: AcpToolCallState;
985 readonly lastEmittedDetailLength: number | undefined;
986 readonly skippedSinceEmit: number;
987 }
988
989 export interface AcpToolCallEmitDecision {
990 readonly emit: boolean;
991 readonly skippedSinceEmit: number;
992 }
993
994 function toolCallOutputUnchanged(previous: AcpToolCallState, next: AcpToolCallState): boolean {
995 return (
996 previous.data.content === next.data.content && previous.data.rawOutput === next.data.rawOutput
997 );
998 }
999
1000 // Command detail is static; measure stdout in content/rawOutput to detect progress.
1001 export function toolCallProgressLength(state: AcpToolCallState): number {
1002 let contentChars = 0;
1003 const content = state.data.content;
1004 if (Array.isArray(content)) {
1005 for (const entry of content) {
1006 if (!isRecord(entry)) {
1007 continue;
1008 }
1009 const text = toolCallContentText(entry as EffectAcpSchema.ToolCallContent);
1010 if (text) {
1011 contentChars += text.length;
1012 }
1013 }
1014 }
1015 let rawOutputChars = 0;
1016 const rawOutput = state.data.rawOutput;
1017 if (isRecord(rawOutput)) {
1018 for (const field of RAW_OUTPUT_TEXT_FIELDS) {
1019 const value = rawOutput[field];
1020 if (typeof value === "string") {
1021 rawOutputChars += value.length;
1022 }
1023 }
1024 }
1025 return Math.max(state.detail?.length ?? 0, contentChars, rawOutputChars);
1026 }
1027
1028 function toolCallContentTexts(state: AcpToolCallState): string {
1029 const content = state.data.content;
1030 if (!Array.isArray(content)) return "";
1031 return content
1032 .map((entry) =>
1033 isRecord(entry) ? (toolCallContentText(entry as EffectAcpSchema.ToolCallContent) ?? "") : "",
1034 )
1035 .join("\u0000");
1036 }
1037
1038 function toolCallLocationsChanged(previous: AcpToolCallState, next: AcpToolCallState): boolean {
1039 const before = previous.data.locations;
1040 const after = next.data.locations;
1041 return before !== after && JSON.stringify(before) !== JSON.stringify(after);
1042 }
1043
1044 export function toolCallVisibleOutputChanged(
1045 previous: AcpToolCallState,
1046 next: AcpToolCallState,
1047 ): boolean {
1048 return (
1049 previous.detail !== next.detail ||
1050 toolCallLocationsChanged(previous, next) ||
1051 toolCallContentTexts(previous) !== toolCallContentTexts(next) ||
1052 JSON.stringify(previous.data.rawOutput) !== JSON.stringify(next.data.rawOutput)
1053 );
1054 }
1055
1056 export function decideToolCallUpdateEmission(
1057 input: AcpToolCallEmitDecisionInput,
1058 ): AcpToolCallEmitDecision {
1059 const { previous, next, lastEmittedDetailLength, skippedSinceEmit } = input;
1060 if (next.status === "completed" || next.status === "failed") {
1061 return { emit: true, skippedSinceEmit: 0 };
1062 }
1063 if (
1064 previous === undefined ||
1065 previous.title !== next.title ||
1066 previous.status !== next.status ||
1067 toolCallLocationsChanged(previous, next)
1068 ) {
1069 return { emit: true, skippedSinceEmit: 0 };
1070 }
1071 if (previous.detail === next.detail && toolCallOutputUnchanged(previous, next)) {
1072 return { emit: false, skippedSinceEmit };
1073 }
1074 const progressLength = toolCallProgressLength(next);
1075 const grewMeaningfully =
1076 lastEmittedDetailLength === undefined ||
1077 Math.abs(progressLength - lastEmittedDetailLength) >= TOOL_CALL_UPDATE_MIN_DETAIL_GROWTH_CHARS;
1078 if (grewMeaningfully || skippedSinceEmit + 1 >= TOOL_CALL_UPDATE_COALESCE_LIMIT) {
1079 return { emit: true, skippedSinceEmit: 0 };
1080 }
1081 return { emit: false, skippedSinceEmit: skippedSinceEmit + 1 };
1082 }
1083
1084 export interface AcpMcpToolCallIdentity {
1085 readonly server: string;
1086 readonly tool: string;
1087 readonly input?: Record<string, unknown>;
1088 }
1089
1090 const ACP_MCP_FALLBACK_CALL = /(?:^|[\s"'=])acp-mcp-call[\s"']+([A-Za-z0-9_.-]+)(?:\s+(.+?))?\s*$/u;
1091
1092 function acpMcpFallbackInput(value: string | undefined): Record<string, unknown> | undefined {
1093 if (value === undefined) return undefined;
1094 const trimmed = value.trim();
1095 const candidates = [
1096 trimmed,
1097 ...(trimmed.startsWith("'") && trimmed.endsWith("'") ? [trimmed.slice(1, -1)] : []),
1098 ];
1099 for (const candidate of candidates) {
1100 try {
1101 const parsed: unknown = JSON.parse(candidate);
1102 const unwrapped = typeof parsed === "string" ? JSON.parse(parsed) : parsed;
1103 if (isRecord(unwrapped)) return unwrapped;
1104 } catch {
1105 // Unknown shell quoting retains MCP identity but omits unparseable input.
1106 }
1107 }
1108 return undefined;
1109 }
1110
1111 // Known T3 inventory gates matches, so server-name separators can stay loose. Kiro titles "@t3-code/<tool>".
1112 const T3_MCP_TITLE_CALL =
1113 /^(?:@|mcp[-_]{1,2})?t3[-_ ]?code[-_.:/ ]{1,3}(?<tool>[A-Za-z0-9][A-Za-z0-9_.-]*)(?::.*)?$/i;
1114
1115 const T3_MCP_TITLE_SUFFIX_CALL =
1116 /^(?<tool>[A-Za-z0-9][A-Za-z0-9_.-]*?)(?: \(t3[-_ ]?code MCP Server\)(?::|$)|[-_.]t3[-_ ]?code$)/i;
1117
1118 /**
1119 * glm and Kimi use bare names. Kimi appends streamed JSON arguments. Require a
1120 * name or JSON opening brace so built-ins titled "<tool>: <description>" cannot
1121 * impersonate an inventory entry.
1122 */
1123 const T3_MCP_BARE_TITLE_CALL = /^(?<tool>[A-Za-z0-9_]+)(?::\s*\{|$)/;
1124
1125 // Antigravity titles calls "Running <tool>" or, from agy 1.5.8, "Run mcp_<server>_<tool>"; prompts end in "?".
1126 const ANTIGRAVITY_TOOL_TITLE = /^Run(?:ning)? (?<name>[^\s?]+)\??$/;
1127
1128 /** ACP lacks typed MCP calls; recognize provider metadata and terminal fallback commands. */
1129 export function extractMcpToolCallIdentity(
1130 toolCall: AcpToolCallState,
1131 options?: {
1132 readonly embeddedTerminalCommands?: ReadonlyArray<string>;
1133 },
1134 ): AcpMcpToolCallIdentity | undefined {
1135 const rawInput = isRecord(toolCall.data.rawInput) ? toolCall.data.rawInput : undefined;
1136 const meta = isRecord(toolCall.data.meta) ? toolCall.data.meta : undefined;
1137 const server = typeof rawInput?.server === "string" ? rawInput.server.trim() : "";
1138 const tool = typeof rawInput?.tool === "string" ? rawInput.tool.trim() : "";
1139 if (meta?.is_mcp_tool_call === true && server.length > 0 && tool.length > 0) {
1140 return { server, tool };
1141 }
1142 // Antigravity reaches MCP tools its context budget left out through call_mcp_tool, an execute
1143 // call titled "MCP Tool <tool>" whose rawInput names the server, tool, and arguments.
1144 const proxiedServer = typeof rawInput?.ServerName === "string" ? rawInput.ServerName.trim() : "";
1145 const proxiedTool = typeof rawInput?.ToolName === "string" ? rawInput.ToolName.trim() : "";
1146 if (proxiedServer.length > 0 && proxiedTool.length > 0) {
1147 const input = isRecord(rawInput?.Arguments) ? rawInput.Arguments : undefined;
1148 return { server: proxiedServer, tool: proxiedTool, ...(input === undefined ? {} : { input }) };
1149 }
1150 // Kiro names the server in `_meta.kiro.serverName` and the call in `rawInput.tool_id`
1151 // ("<server>::<tool>"), with the tool's own input under `rawInput.arguments`.
1152 const kiroServer = isRecord(meta?.kiro) ? meta.kiro.serverName : undefined;
1153 const kiroToolId = typeof rawInput?.tool_id === "string" ? rawInput.tool_id.trim() : "";
1154 if (
1155 typeof kiroServer === "string" &&
1156 kiroServer.length > 0 &&
1157 kiroToolId.startsWith(`${kiroServer}::`) &&
1158 kiroToolId.length > kiroServer.length + 2
1159 ) {
1160 return { server: kiroServer, tool: kiroToolId.slice(kiroServer.length + 2) };
1161 }
1162 const claudeCode = isRecord(meta?.claudeCode) ? meta.claudeCode : undefined;
1163 const gooseToolCall = isRecord(meta?.goose)
1164 ? isRecord(meta.goose.toolCall)
1165 ? meta.goose.toolCall
1166 : undefined
1167 : undefined;
1168 const metaServerId = typeof meta?.serverId === "string" ? meta.serverId.trim() : "";
1169 const metaToolName = typeof meta?.toolName === "string" ? meta.toolName.trim() : "";
1170 if (/^t3[-_ ]?code$/i.test(metaServerId) && metaToolName.length > 0) {
1171 for (const knownTool of T3_MCP_TOOL_NAMES) {
1172 const boundary = metaToolName.length - knownTool.length - 1;
1173 if (
1174 metaToolName === knownTool ||
1175 (metaToolName.endsWith(knownTool) &&
1176 boundary >= 0 &&
1177 !/[A-Za-z0-9]/.test(metaToolName.charAt(boundary)))
1178 ) {
1179 return { server: "t3-code", tool: knownTool };
1180 }
1181 }
1182 }
1183 const gooseExtension =
1184 typeof gooseToolCall?.extensionName === "string" ? gooseToolCall.extensionName.trim() : "";
1185 const assertsForeignOrigin =
1186 (metaServerId.length > 0 && !/^t3[-_ ]?code$/i.test(metaServerId)) ||
1187 (gooseExtension.length > 0 && !/^t3[-_ ]?code$/i.test(gooseExtension));
1188 // goose metadata also tags built-ins; retain their command/file projections instead of classifying as MCP.
1189 if (assertsForeignOrigin) {
1190 if (metaServerId.length === 0 || metaToolName.length === 0) return undefined;
1191 const prefix = [`mcp__${metaServerId}__`, `mcp::${metaServerId}::`].find((prefix) =>
1192 metaToolName.startsWith(prefix),
1193 );
1194 const tool = prefix === undefined ? metaToolName : metaToolName.slice(prefix.length);
1195 return tool ? { server: metaServerId, tool } : undefined;
1196 }
1197 // OMP mounts MCP tools as xd://mcp__<server>_<tool> devices and calls them by writing JSON
1198 // args; a read of the same path only fetches the tool's docs.
1199 const devicePath = typeof rawInput?.path === "string" ? rawInput.path : "";
1200 if (devicePath.startsWith("xd://") && typeof rawInput?.content === "string") {
1201 const deviceTool = T3_MCP_TITLE_CALL.exec(devicePath.slice("xd://".length))?.groups?.tool;
1202 if (deviceTool !== undefined && T3_MCP_TOOL_NAMES.has(deviceTool)) {
1203 const input = acpMcpFallbackInput(rawInput.content);
1204 return { server: "t3-code", tool: deviceTool, ...(input === undefined ? {} : { input }) };
1205 }
1206 }
1207 const candidates = [
1208 meta?.toolName,
1209 claudeCode?.toolName,
1210 gooseToolCall?.toolName,
1211 toolCall.data.title,
1212 ].filter((value): value is string => typeof value === "string");
1213 for (const candidate of candidates) {
1214 const trimmed = candidate.trim();
1215 const qualified = /^mcp__(.+?)__(.+)$/i.exec(trimmed);
1216 // Hermes renames client MCP servers to editor_<sanitized name>_<8 hex of a per-session hash>.
1217 if (
1218 qualified?.[1] &&
1219 qualified[2] &&
1220 /^editor_t3_?code_[0-9a-f]{8}$/.test(qualified[1]) &&
1221 T3_MCP_TOOL_NAMES.has(qualified[2])
1222 ) {
1223 return { server: "t3-code", tool: qualified[2] };
1224 }
1225 if (qualified?.[1] && qualified[2] && !/^t3[-_ ]?code$/i.test(qualified[1]))
1226 return { server: qualified[1], tool: qualified[2] };
1227 const name = ANTIGRAVITY_TOOL_TITLE.exec(trimmed)?.groups?.name ?? trimmed;
1228 const match =
1229 T3_MCP_TITLE_CALL.exec(name) ??
1230 T3_MCP_TITLE_SUFFIX_CALL.exec(name) ??
1231 T3_MCP_BARE_TITLE_CALL.exec(name);
1232 const candidateTool = match?.groups?.tool;
1233 if (candidateTool !== undefined && T3_MCP_TOOL_NAMES.has(candidateTool)) {
1234 return { server: "t3-code", tool: candidateTool };
1235 }
1236 }
1237 const commands = [
1238 ...(toolCall.command === undefined ? [] : [toolCall.command]),
1239 // pi-acp reports the exec command line only as the verbatim title.
1240 ...(typeof toolCall.data.title === "string" ? [toolCall.data.title] : []),
1241 ...(options?.embeddedTerminalCommands ?? []),
1242 ];
1243 for (const command of commands) {
1244 const match = ACP_MCP_FALLBACK_CALL.exec(command);
1245 if (match?.[1] !== undefined) {
1246 const input = acpMcpFallbackInput(match[2]);
1247 return { server: "t3-code", tool: match[1], ...(input === undefined ? {} : { input }) };
1248 }
1249 }
1250 return undefined;
1251 }
1252
1253 /** Capture IDs before resolveEmbeddedTerminalContent replaces them with text, to recover commands later. */
1254 export function embeddedTerminalIdsFromSessionUpdate(
1255 notification: EffectAcpSchema.SessionNotification,
1256 ): { readonly toolCallId: string; readonly terminalIds: ReadonlyArray<string> } | undefined {
1257 const update = notification.update;
1258 if (update.sessionUpdate !== "tool_call" && update.sessionUpdate !== "tool_call_update") {
1259 return undefined;
1260 }
1261 const terminalIds = (update.content ?? [])
1262 .filter((entry) => entry.type === "terminal")
1263 .map((entry) => entry.terminalId);
1264 return terminalIds.length === 0 ? undefined : { toolCallId: update.toolCallId, terminalIds };
1265 }
1266
1267 /** ACP lets a permission request name its tool call by ID only; omitted (not null) fields come from the tracked call. */
1268 export function withTrackedPermissionToolCall(
1269 params: EffectAcpSchema.RequestPermissionRequest,
1270 tracked: AcpToolCallState | undefined,
1271 ): EffectAcpSchema.RequestPermissionRequest {
1272 if (tracked === undefined) return params;
1273 const { title, kind, rawInput } = params.toolCall;
1274 return {
1275 ...params,
1276 toolCall: {
1277 ...params.toolCall,
1278 ...(title === undefined && typeof tracked.data.title === "string"
1279 ? { title: tracked.data.title }
1280 : {}),
1281 // Unrecognised kinds map to command approvals, so only a tracked execute kind may grant execution.
1282 ...(kind === undefined && tracked.kind === "execute" ? { kind: "execute" as const } : {}),
1283 ...(rawInput === undefined && tracked.data.rawInput !== undefined
1284 ? { rawInput: tracked.data.rawInput }
1285 : {}),
1286 },
1287 };
1288 }
1289
1290 export function parsePermissionRequest(
1291 params: EffectAcpSchema.RequestPermissionRequest,
1292 ): AcpPermissionRequest {
1293 const toolCall = makeToolCallState(
1294 {
1295 toolCallId: params.toolCall.toolCallId,
1296 title: params.toolCall.title,
1297 kind: params.toolCall.kind,
1298 status: params.toolCall.status,
1299 rawInput: params.toolCall.rawInput,
1300 rawOutput: params.toolCall.rawOutput,
1301 content: params.toolCall.content,
1302 locations: params.toolCall.locations,
1303 },
1304 { fallbackStatus: "pending" },
1305 );
1306 const kind = normalizeToolKind(params.toolCall.kind) ?? "unknown";
1307 const detail =
1308 toolCall?.command ??
1309 toolCall?.title ??
1310 toolCall?.detail ??
1311 (typeof params.sessionId === "string" ? `Session ${params.sessionId}` : undefined);
1312 return {
1313 kind,
1314 ...(detail ? { detail } : {}),
1315 ...(toolCall ? { toolCall } : {}),
1316 };
1317 }
1318
1319 export function sessionUpdateIsReplay(params: EffectAcpSchema.SessionNotification): boolean {
1320 const meta = params._meta;
1321 return isRecord(meta) && meta.isReplay === true;
1322 }
1323
1324 export function sessionUpdateCountsAsLoadReplayActivity(
1325 params: EffectAcpSchema.SessionNotification,
1326 gatedSessionId?: string,
1327 ): boolean {
1328 if (gatedSessionId !== undefined && params.sessionId !== gatedSessionId) {
1329 return false;
1330 }
1331 if (sessionUpdateIsReplay(params)) return true;
1332 const update = params.update;
1333 switch (update.sessionUpdate) {
1334 case "agent_message_chunk":
1335 case "agent_thought_chunk":
1336 return (acpContentBlockDisplayText(update.content)?.length ?? 0) > 0;
1337 case "agent_message":
1338 case "agent_thought":
1339 return (update.content ?? []).some(
1340 (content) => (acpContentBlockDisplayText(content)?.length ?? 0) > 0,
1341 );
1342 case "tool_call":
1343 case "tool_call_update":
1344 case "plan":
1345 case "plan_update":
1346 case "plan_removed":
1347 case "available_commands_update":
1348 case "current_mode_update":
1349 case "config_option_update":
1350 case "session_info_update":
1351 case "usage_update":
1352 case "compaction_update":
1353 case "compaction_summary_chunk":
1354 return true;
1355 default:
1356 return false;
1357 }
1358 }
1359
1360 export interface SessionLoadGate {
1361 readonly active: boolean;
1362 readonly sessionId: string;
1363 readonly lastActivityAtMillis: number | undefined;
1364 readonly idleGap: Duration.Duration;
1365 readonly initializeResult: EffectAcpSchema.InitializeResponse;
1366 readonly candidateConfigOptions?: ReadonlyArray<EffectAcpSchema.SessionConfigOption>;
1367 }
1368
1369 export const waitForSessionLoadReplayIdle = Effect.fn(
1370 "AcpRuntimeModel.waitForSessionLoadReplayIdle",
1371 )(function* (input: {
1372 readonly gateRef: Ref.Ref<Option.Option<SessionLoadGate>>;
1373 }): Effect.fn.Return<EffectAcpSchema.LoadSessionResponse, never> {
1374 const pollInterval = Duration.millis(25);
1375 while (true) {
1376 const gate = yield* Ref.get(input.gateRef);
1377 if (Option.isSome(gate) && gate.value.active && gate.value.lastActivityAtMillis !== undefined) {
1378 const idleGapMillis = Duration.toMillis(gate.value.idleGap);
1379 const nowMillis = yield* Clock.currentTimeMillis;
1380 if (nowMillis - gate.value.lastActivityAtMillis >= idleGapMillis) {
1381 return syntheticLoadSessionResponseFromInitialize(gate.value.initializeResult);
1382 }
1383 }
1384 yield* Effect.sleep(pollInterval);
1385 }
1386 });
1387
1388 export function sessionModelStateFromInitialize(
1389 initializeResult: EffectAcpSchema.InitializeResponse,
1390 ): EffectAcpSchema.SessionModelState | undefined {
1391 const meta = initializeResult._meta;
1392 const modelState = isRecord(meta) ? meta.modelState : undefined;
1393 return isSessionModelState(modelState) ? modelState : undefined;
1394 }
1395
1396 export function syntheticLoadSessionResponseFromInitialize(
1397 initializeResult: EffectAcpSchema.InitializeResponse,
1398 ): EffectAcpSchema.LoadSessionResponse {
1399 const meta = initializeResult._meta;
1400 const modeState = isRecord(meta) ? meta.modeState : undefined;
1401
1402 const modes = isSessionModeState(modeState) ? modeState : undefined;
1403
1404 return {
1405 ...(modes ? { modes } : {}),
1406 _meta: {
1407 t3SessionLoadReady: "replay_idle",
1408 },
1409 };
1410 }
1411
1412 // Persisted rawPayload must not bypass cumulative output limits.
1413 function boundToolCallRawPayload(
1414 params: EffectAcpSchema.SessionNotification,
1415 update: AcpToolCallUpdate,
1416 toolCall: AcpToolCallState,
1417 ): unknown {
1418 const boundedContent = toolCall.data.content;
1419 const boundedRawOutput = toolCall.data.rawOutput;
1420 const contentBounded = update.content !== undefined && boundedContent !== update.content;
1421 const rawOutputBounded = update.rawOutput !== undefined && boundedRawOutput !== update.rawOutput;
1422 if (!contentBounded && !rawOutputBounded) {
1423 return params;
1424 }
1425 return {
1426 ...params,
1427 update: {
1428 ...update,
1429 ...(contentBounded ? { content: boundedContent } : {}),
1430 ...(rawOutputBounded ? { rawOutput: boundedRawOutput } : {}),
1431 },
1432 };
1433 }
1434
1435 export function parseSessionUpdateEvent(params: EffectAcpSchema.SessionNotification): {
1436 readonly modeId?: string;
1437 readonly events: ReadonlyArray<AcpParsedSessionEvent>;
1438 } {
1439 const upd = params.update;
1440 const events: Array<AcpParsedSessionEvent> = [];
1441 let modeId: string | undefined;
1442
1443 switch (upd.sessionUpdate) {
1444 case "config_option_update": {
1445 const modes = parseSessionModeState({ configOptions: upd.configOptions });
1446 if (modes !== undefined) {
1447 modeId = modes.currentModeId;
1448 events.push({ _tag: "ModeChanged", modeId });
1449 }
1450 events.push({
1451 _tag: "ConfigOptionsUpdated",
1452 configOptions: upd.configOptions,
1453 rawPayload: params,
1454 });
1455 break;
1456 }
1457 case "available_commands_update": {
1458 events.push({
1459 _tag: "AvailableCommandsUpdated",
1460 availableCommands: upd.availableCommands,
1461 rawPayload: params,
1462 });
1463 break;
1464 }
1465 case "current_mode_update": {
1466 modeId = upd.currentModeId.trim();
1467 if (modeId) {
1468 events.push({
1469 _tag: "ModeChanged",
1470 modeId,
1471 });
1472 }
1473 break;
1474 }
1475 case "plan": {
1476 const plan = upd.entries.map((entry, index) => ({
1477 step: entry.content.trim().length > 0 ? entry.content.trim() : `Step ${index + 1}`,
1478 status: normalizePlanStepStatus(entry.status),
1479 }));
1480 events.push({
1481 _tag: "PlanUpdated",
1482 payload: {
1483 nativePlanId: "legacy",
1484 kind: "items",
1485 plan,
1486 },
1487 rawPayload: params,
1488 });
1489 break;
1490 }
1491 case "plan_update": {
1492 const nativePlanId = upd.plan.planId.trim();
1493 if (nativePlanId.length === 0) {
1494 break;
1495 }
1496 if (upd.plan.type === "items" && "entries" in upd.plan && Array.isArray(upd.plan.entries)) {
1497 const entries: ReadonlyArray<unknown> = upd.plan.entries;
1498 const plan = entries.flatMap((entry, index) => {
1499 if (!isRecord(entry) || typeof entry.content !== "string") return [];
1500 const status = typeof entry.status === "string" ? entry.status : "pending";
1501 return [
1502 {
1503 step: entry.content.trim().length > 0 ? entry.content.trim() : `Step ${index + 1}`,
1504 status: normalizePlanStepStatus(status),
1505 },
1506 ];
1507 });
1508 events.push({
1509 _tag: "PlanUpdated",
1510 payload: { nativePlanId, kind: "items", plan },
1511 rawPayload: params,
1512 });
1513 } else if (
1514 upd.plan.type === "markdown" &&
1515 "content" in upd.plan &&
1516 typeof upd.plan.content === "string"
1517 ) {
1518 events.push({
1519 _tag: "PlanUpdated",
1520 payload: { nativePlanId, kind: "markdown", markdown: upd.plan.content },
1521 rawPayload: params,
1522 });
1523 } else if (
1524 upd.plan.type === "file" &&
1525 "uri" in upd.plan &&
1526 typeof upd.plan.uri === "string"
1527 ) {
1528 events.push({
1529 _tag: "PlanUpdated",
1530 payload: { nativePlanId, kind: "file", uri: upd.plan.uri },
1531 rawPayload: params,
1532 });
1533 } else {
1534 events.push({
1535 _tag: "PlanUpdated",
1536 payload: { nativePlanId, kind: "unknown", contentType: upd.plan.type },
1537 rawPayload: params,
1538 });
1539 }
1540 break;
1541 }
1542 case "plan_removed": {
1543 const nativePlanId = upd.planId.trim();
1544 if (nativePlanId.length > 0) {
1545 events.push({
1546 _tag: "PlanUpdated",
1547 payload: { nativePlanId, kind: "removed" },
1548 rawPayload: params,
1549 });
1550 }
1551 break;
1552 }
1553 case "tool_call": {
1554 const toolCall = parseTypedToolCallState(upd, {
1555 fallbackStatus: "pending",
1556 });
1557 if (toolCall) {
1558 events.push({
1559 _tag: "ToolCallUpdated",
1560 toolCall,
1561 rawPayload: boundToolCallRawPayload(params, upd, toolCall),
1562 });
1563 }
1564 break;
1565 }
1566 case "tool_call_update": {
1567 const toolCall = parseTypedToolCallState(upd);
1568 if (toolCall) {
1569 events.push({
1570 _tag: "ToolCallUpdated",
1571 toolCall,
1572 rawPayload: boundToolCallRawPayload(params, upd, toolCall),
1573 });
1574 }
1575 break;
1576 }
1577 case "agent_message_chunk": {
1578 const text = acpContentBlockDisplayText(upd.content);
1579 if (text !== undefined && text.length > 0) {
1580 events.push({
1581 _tag: "ContentDelta",
1582 ...(upd.messageId ? { messageId: upd.messageId } : {}),
1583 text,
1584 rawPayload: params,
1585 });
1586 }
1587 break;
1588 }
1589 case "agent_thought_chunk": {
1590 if (upd.content.type === "text" && upd.content.text.length > 0) {
1591 events.push({
1592 _tag: "ThoughtDelta",
1593 text: upd.content.text,
1594 rawPayload: params,
1595 });
1596 }
1597 break;
1598 }
1599 case "compaction_update": {
1600 const summary = (upd.summary ?? [])
1601 .flatMap((content) => {
1602 const text = acpContentBlockDisplayText(content);
1603 return text === undefined || text.length === 0 ? [] : [text];
1604 })
1605 .join("\n");
1606 const status =
1607 upd.status === "completed"
1608 ? ("completed" as const)
1609 : upd.status === "failed" || upd.status === "cancelled"
1610 ? ("failed" as const)
1611 : ("inProgress" as const);
1612 const toolCall = makeToolCallState({
1613 toolCallId: `acp-compaction:${upd.compactionId}`,
1614 title: "Compact context",
1615 kind: "think",
1616 status,
1617 rawOutput: upd.summary === undefined ? undefined : summary || null,
1618 _meta: upd._meta,
1619 });
1620 if (toolCall !== undefined) {
1621 // Summary and error are independent patches; null clears only its own field.
1622 events.push({
1623 _tag: "ToolCallUpdated",
1624 toolCall:
1625 upd.error === undefined
1626 ? toolCall
1627 : { ...toolCall, data: { ...toolCall.data, compactionError: upd.error } },
1628 rawPayload: params,
1629 });
1630 }
1631 break;
1632 }
1633 case "compaction_summary_chunk": {
1634 const text = acpContentBlockDisplayText(upd.content);
1635 const toolCall = makeToolCallState({
1636 toolCallId: `acp-compaction:${upd.compactionId}`,
1637 title: "Compact context",
1638 kind: "think",
1639 status: "inProgress",
1640 ...(text === undefined ? {} : { rawOutput: text }),
1641 _meta: upd._meta,
1642 });
1643 if (toolCall !== undefined) {
1644 events.push({ _tag: "ToolCallUpdated", toolCall, rawPayload: params });
1645 }
1646 break;
1647 }
1648 case "usage_update": {
1649 const currency = upd.cost?.currency.trim().slice(0, 32);
1650 events.push({
1651 _tag: "UsageUpdated",
1652 usage: {
1653 usedTokens: upd.used,
1654 ...(upd.size > 0 ? { maxTokens: upd.size } : {}),
1655 ...(upd.cost && currency ? { cost: { amount: upd.cost.amount, currency } } : {}),
1656 },
1657 rawPayload: params,
1658 });
1659 break;
1660 }
1661 case "session_info_update": {
1662 const title = upd.title?.trim().slice(0, 1_024);
1663 const updatedAt = upd.updatedAt?.trim().slice(0, 128);
1664 events.push({
1665 _tag: "SessionInfoUpdated",
1666 metadata: {
1667 ...(upd.title === null ? { title: null } : title ? { title } : {}),
1668 ...(upd.updatedAt === null ? { updatedAt: null } : updatedAt ? { updatedAt } : {}),
1669 },
1670 rawPayload: params,
1671 });
1672 break;
1673 }
1674 case "notice": {
1675 const title = upd.title.trim().slice(0, 1_024);
1676 const description = upd.description?.trim().slice(0, 4_096);
1677 if (title.length === 0) break;
1678 events.push({
1679 _tag: "NoticeReceived",
1680 severity: boundedContentMetadata(upd.severity, 64) || "info",
1681 title,
1682 ...(description ? { description } : {}),
1683 rawPayload: params,
1684 });
1685 break;
1686 }
1687 case "_t3_unknown": {
1688 events.push({
1689 _tag: "UnknownUpdate",
1690 updateType: boundedContentMetadata(upd.originalSessionUpdate, 128) || "unknown",
1691 rawPayload: params,
1692 });
1693 break;
1694 }
1695 default:
1696 break;
1697 }
1698
1699 return { ...(modeId !== undefined ? { modeId } : {}), events };
1700 }