Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

AcpRuntimeModel.ts

831 lines26.2 KB

1import * as Clock from "effect/Clock";
2import * as Duration from "effect/Duration";
3import * as Effect from "effect/Effect";
4import * as Option from "effect/Option";
5import * as Ref from "effect/Ref";
6import type * as EffectAcpSchema from "effect-acp/schema";
7import { deriveToolActivityPresentation } from "@t3tools/shared/toolActivity";
8import type { ToolLifecycleItemType } from "@t3tools/contracts";
9​
10function isRecord(value: unknown): value is Record<string, unknown> {
11 return typeof value === "object" && value !== null && !Array.isArray(value);
13​
14function isSessionModelState(value: unknown): value is EffectAcpSchema.SessionModelState {
15 if (!isRecord(value) || typeof value.currentModelId !== "string") {
16 return false;
17 }
18 if (!Array.isArray(value.availableModels)) {
19 return false;
20 }
21 return value.availableModels.every(
22 (model) =>
23 isRecord(model) &&
24 typeof model.modelId === "string" &&
25 typeof model.name === "string" &&
26 (model.description === undefined ||
27 model.description === null ||
28 typeof model.description === "string"),
29 );
31​
32function isSessionModeState(value: unknown): value is EffectAcpSchema.SessionModeState {
33 if (!isRecord(value) || typeof value.currentModeId !== "string") {
34 return false;
35 }
36 if (!Array.isArray(value.availableModes)) {
37 return false;
38 }
39 return value.availableModes.every(
40 (mode) =>
41 isRecord(mode) &&
42 typeof mode.id === "string" &&
43 typeof mode.name === "string" &&
44 (mode.description === undefined || typeof mode.description === "string"),
45 );
47​
48export interface AcpSessionMode {
49 readonly id: string;
50 readonly name: string;
51 readonly description?: string;
53​
54export interface AcpSessionModeState {
55 readonly currentModeId: string;
56 readonly availableModes: ReadonlyArray<AcpSessionMode>;
58​
59export interface AcpToolCallState {
60 readonly toolCallId: string;
61 readonly kind?: string;
62 readonly title?: string;
63 readonly status?: "pending" | "inProgress" | "completed" | "failed";
64 readonly command?: string;
65 readonly detail?: string;
66 readonly data: Record<string, unknown>;
68​
69export interface AcpPlanUpdate {
70 readonly explanation?: string | null;
71 readonly plan: ReadonlyArray<{
72 readonly step: string;
73 readonly status: "pending" | "inProgress" | "completed";
74 }>;
76​
77export interface AcpPermissionRequest {
78 readonly kind: string | "unknown";
79 readonly detail?: string;
80 readonly toolCall?: AcpToolCallState;
82​
83export type AcpParsedSessionEvent =
84 | {
85 readonly _tag: "ModeChanged";
86 readonly modeId: string;
87 }
88 | {
89 readonly _tag: "AssistantItemStarted";
90 readonly itemId: string;
91 }
92 | {
93 readonly _tag: "AssistantItemCompleted";
94 readonly itemId: string;
95 }
96 | {
97 readonly _tag: "PlanUpdated";
98 readonly payload: AcpPlanUpdate;
99 readonly rawPayload: unknown;
100 }
101 | {
102 readonly _tag: "ToolCallUpdated";
103 readonly toolCall: AcpToolCallState;
104 readonly rawPayload: unknown;
105 }
106 | {
107 readonly _tag: "ContentDelta";
108 readonly itemId?: string;
109 readonly text: string;
110 readonly rawPayload: unknown;
111 };
112​
113type AcpSessionSetupResponse =
114 | EffectAcpSchema.LoadSessionResponse
115 | EffectAcpSchema.NewSessionResponse
116 | EffectAcpSchema.ResumeSessionResponse;
117​
118type AcpToolCallUpdate = Extract<
119 EffectAcpSchema.SessionNotification["update"],
120 { readonly sessionUpdate: "tool_call" | "tool_call_update" }
121>;
122​
123export function extractModelConfigId(sessionResponse: AcpSessionSetupResponse): string | undefined {
124 const configOptions = sessionResponse.configOptions;
125 if (!configOptions) return undefined;
126 for (const opt of configOptions) {
127 if (opt.category === "model" && opt.id.trim().length > 0) {
128 return opt.id.trim();
129 }
130 }
131 return undefined;
133​
134export function findSessionConfigOption(
135 configOptions: ReadonlyArray<EffectAcpSchema.SessionConfigOption> | null | undefined,
136 configId: string,
137): EffectAcpSchema.SessionConfigOption | undefined {
138 if (!configOptions) {
139 return undefined;
140 }
141 const normalizedConfigId = configId.trim();
142 if (!normalizedConfigId) {
143 return undefined;
144 }
145 return configOptions.find((option) => option.id.trim() === normalizedConfigId);
147​
148export function collectSessionConfigOptionValues(
149 configOption: EffectAcpSchema.SessionConfigOption,
150): ReadonlyArray<string> {
151 if (configOption.type !== "select") {
152 return [];
153 }
154 return configOption.options.flatMap((entry) =>
155 "value" in entry ? [entry.value] : entry.options.map((option) => option.value),
156 );
158​
159export function parseSessionModeState(
160 sessionResponse: AcpSessionSetupResponse,
161): AcpSessionModeState | undefined {
162 const modes = sessionResponse.modes;
163 if (!modes) return undefined;
164 const currentModeId = modes.currentModeId.trim();
165 if (!currentModeId) {
166 return undefined;
167 }
168 const availableModes: Array<AcpSessionMode> = [];
169 for (const mode of modes.availableModes) {
170 const id = mode.id.trim();
171 const name = mode.name.trim();
172 if (!id || !name) {
173 continue;
174 }
175 const description = mode.description?.trim() || undefined;
176 availableModes.push(
177 description !== undefined
178 ? ({ id, name, description } satisfies AcpSessionMode)
179 : ({ id, name } satisfies AcpSessionMode),
180 );
181 }
182 if (availableModes.length === 0) {
183 return undefined;
184 }
185 return {
186 currentModeId,
187 availableModes,
188 };
190​
191function normalizePlanStepStatus(raw: unknown): "pending" | "inProgress" | "completed" {
192 switch (raw) {
193 case "completed":
194 return "completed";
195 case "in_progress":
196 case "inProgress":
197 return "inProgress";
198 default:
199 return "pending";
200 }
202​
203function normalizeToolCallStatus(
204 raw: unknown,
205 fallback?: "pending" | "inProgress" | "completed" | "failed",
206): "pending" | "inProgress" | "completed" | "failed" | undefined {
207 switch (raw) {
208 case "pending":
209 return "pending";
210 case "in_progress":
211 case "inProgress":
212 return "inProgress";
213 case "completed":
214 return "completed";
215 case "failed":
216 return "failed";
217 default:
218 return fallback;
219 }
221​
222function normalizeCommandValue(value: unknown): string | undefined {
223 if (typeof value === "string" && value.trim().length > 0) {
224 return value.trim();
225 }
226 if (!Array.isArray(value)) {
227 return undefined;
228 }
229 const parts: Array<string> = [];
230 for (const entry of value) {
231 if (typeof entry === "string") {
232 const part = entry.trim();
233 if (part.length > 0) {
234 parts.push(part);
235 }
236 }
237 }
238 return parts.length > 0 ? parts.join(" ") : undefined;
240​
241function extractCommandFromTitle(title: string | undefined): string | undefined {
242 if (!title) {
243 return undefined;
244 }
245 const match = /`([^`]+)`/.exec(title);
246 return match?.[1]?.trim() || undefined;
248​
249function extractToolCallCommand(rawInput: unknown, title: string | undefined): string | undefined {
250 if (isRecord(rawInput)) {
251 const directCommand = normalizeCommandValue(rawInput.command);
252 if (directCommand) {
253 return directCommand;
254 }
255 const executable = typeof rawInput.executable === "string" ? rawInput.executable.trim() : "";
256 const args = normalizeCommandValue(rawInput.args);
257 if (executable && args) {
258 return `${executable} ${args}`;
259 }
260 if (executable) {
261 return executable;
262 }
263 }
264 return extractCommandFromTitle(title);
266​
267// Some ACP agents (observed with Grok's CLI) resend the ENTIRE accumulated tool-call
268// output on every `tool_call_update` notification instead of a delta, so a redrawing
269// terminal progress bar can balloon a single tool call to hundreds of KB per update at
270// several updates per second. Cap what we retain/emit to a bounded tail so one busy tool
271// call cannot flood runtime event ingestion. We always keep the tail: `tool_call_update`
272// deltas routinely omit `kind`, so there is no reliable way to tell a redrawing terminal
273// from another tool here, and the end is the useful part of any live-growing output.
274const TOOL_CALL_CONTENT_MAX_CHARS = 8_000;
275const TOOL_CALL_CONTENT_TRUNCATION_MARKER = "[Earlier output truncated]\n\n";
276​
277function boundToolCallOutputText(text: string): string {
278 if (text.length <= TOOL_CALL_CONTENT_MAX_CHARS) {
279 return text;
280 }
281 const tail = text.slice(text.length - TOOL_CALL_CONTENT_MAX_CHARS);
282 return `${TOOL_CALL_CONTENT_TRUNCATION_MARKER}${tail}`;
284​
285const RAW_OUTPUT_TEXT_FIELDS = ["content", "stdout", "stderr", "output"] as const;
286​
287// `rawOutput` is provider-defined and, for terminal-shaped tools, mirrors the same
288// cumulative text-growth problem as `content` (see the comment above). Bound its known
289// text-bearing fields the same way so a chatty provider cannot smuggle unbounded output
290// through this field instead.
291function boundToolCallRawOutput(rawOutput: unknown): unknown {
292 if (!isRecord(rawOutput)) {
293 return rawOutput;
294 }
295 let changed = false;
296 const bounded: Record<string, unknown> = { ...rawOutput };
297 for (const field of RAW_OUTPUT_TEXT_FIELDS) {
298 const value = rawOutput[field];
299 if (typeof value === "string" && value.length > TOOL_CALL_CONTENT_MAX_CHARS) {
300 bounded[field] = boundToolCallOutputText(value);
301 changed = true;
302 }
303 }
304 return changed ? bounded : rawOutput;
306​
307interface ExtractedToolCallContent {
308 readonly text: string | undefined;
309 readonly content: ReadonlyArray<EffectAcpSchema.ToolCallContent> | undefined;
311​
312function toolCallContentText(entry: EffectAcpSchema.ToolCallContent): string | undefined {
313 if (entry.type !== "content" || entry.content.type !== "text") {
314 return undefined;
315 }
316 return entry.content.text;
318​
319// Trim is used for display `text`, so whitespace-only (or whitespace-padded) entries never
320// contribute to `chunks` and used to take the early returns with the original array. Bound
321// each text entry independently so those paths cannot persist an unbounded terminal buffer
322// on `toolCall.data.content` / `rawPayload`.
323function boundToolCallContentEntries(
324 content: ReadonlyArray<EffectAcpSchema.ToolCallContent>,
325): ReadonlyArray<EffectAcpSchema.ToolCallContent> {
326 let changed = false;
327 const bounded = content.map((entry) => {
328 const text = toolCallContentText(entry);
329 if (text === undefined || text.length <= TOOL_CALL_CONTENT_MAX_CHARS) {
330 return entry;
331 }
332 changed = true;
333 const trimmed = text.trim();
334 return {
335 type: "content",
336 content: {
337 type: "text",
338 text: boundToolCallOutputText(trimmed.length > 0 ? trimmed : text),
339 },
340 } as const;
341 });
342 return changed ? bounded : content;
344​
345function extractTextContentFromToolCallContent(
346 content: ReadonlyArray<EffectAcpSchema.ToolCallContent> | null | undefined,
347): ExtractedToolCallContent {
348 if (!content) {
349 return { text: undefined, content: undefined };
350 }
351 const chunks: Array<string> = [];
352 for (const entry of content) {
353 const text = toolCallContentText(entry)?.trim();
354 if (text) {
355 chunks.push(text);
356 }
357 }
358 if (chunks.length === 0) {
359 return { text: undefined, content: boundToolCallContentEntries(content) };
360 }
361 const joined = chunks.join("\n");
362 if (joined.length <= TOOL_CALL_CONTENT_MAX_CHARS) {
363 return { text: joined, content: boundToolCallContentEntries(content) };
364 }
365 const bounded = boundToolCallOutputText(joined);
366 const tail = joined.slice(joined.length - TOOL_CALL_CONTENT_MAX_CHARS);
367 return {
368 text: bounded,
369 content: distributeRetainedTailAcrossContent(content, tail),
370 };
372​
373// Walk the original text entries from the joined tail window so a retained slice that
374// spans entries around an image/diff stays on those entries. Non-text kinds keep their
375// relative order; blank text entries are dropped; the truncation marker is prepended to
376// the first remaining text entry.
377function distributeRetainedTailAcrossContent(
378 content: ReadonlyArray<EffectAcpSchema.ToolCallContent>,
379 tail: string,
380): ReadonlyArray<EffectAcpSchema.ToolCallContent> {
381 const textRanges: Array<
382 | {
383 readonly start: number;
384 readonly end: number;
385 readonly text: string;
386 }
387 | undefined
388 > = Array.from({ length: content.length });
389 let offset = 0;
390 let seenText = false;
391 for (const [index, entry] of content.entries()) {
392 const text = toolCallContentText(entry)?.trim();
393 if (!text) {
394 continue;
395 }
396 if (seenText) {
397 offset += 1;
398 }
399 seenText = true;
400 const start = offset;
401 const end = offset + text.length;
402 textRanges[index] = { start, end, text };
403 offset = end;
404 }
405 const tailStart = Math.max(0, offset - tail.length);
406 let markerPending = true;
407 return content.flatMap((entry, index) => {
408 if (toolCallContentText(entry) === undefined) {
409 return [entry];
410 }
411 const range = textRanges[index];
412 if (range === undefined) {
413 return [];
414 }
415 const overlapStart = Math.max(range.start, tailStart);
416 const overlapEnd = Math.min(range.end, offset);
417 if (overlapEnd <= overlapStart) {
418 return [];
419 }
420 let piece = range.text.slice(overlapStart - range.start, overlapEnd - range.start);
421 if (markerPending) {
422 piece = `${TOOL_CALL_CONTENT_TRUNCATION_MARKER}${piece}`;
423 markerPending = false;
424 }
425 return [{ type: "content", content: { type: "text", text: piece } } as const];
426 });
428​
429function normalizeToolKind(kind: unknown): string | undefined {
430 return typeof kind === "string" && kind.trim().length > 0 ? kind.trim() : undefined;
432​
433function canonicalItemTypeFromAcpToolKind(kind: string | undefined): ToolLifecycleItemType {
434 switch (kind) {
435 case "execute":
436 return "command_execution";
437 case "edit":
438 case "delete":
439 case "move":
440 return "file_change";
441 case "search":
442 case "fetch":
443 return "web_search";
444 default:
445 return "dynamic_tool_call";
446 }
448​
449function makeToolCallState(
450 input: {
451 readonly toolCallId: string;
452 readonly title?: string | null | undefined;
453 readonly kind?: EffectAcpSchema.ToolKind | null | undefined;
454 readonly status?: EffectAcpSchema.ToolCallStatus | null | undefined;
455 readonly rawInput?: unknown;
456 readonly rawOutput?: unknown;
457 readonly content?: ReadonlyArray<EffectAcpSchema.ToolCallContent> | null | undefined;
458 readonly locations?: ReadonlyArray<EffectAcpSchema.ToolCallLocation> | null | undefined;
459 },
460 options?: {
461 readonly fallbackStatus?: "pending" | "inProgress" | "completed" | "failed";
462 },
463): AcpToolCallState | undefined {
464 const toolCallId = input.toolCallId.trim();
465 if (!toolCallId) {
466 return undefined;
467 }
468 const title = input.title?.trim() || undefined;
469 const command = extractToolCallCommand(input.rawInput, title);
470 const extractedContent = extractTextContentFromToolCallContent(input.content);
471 const textContent = extractedContent.text;
472 const normalizedTitle =
473 title && title.toLowerCase() !== "terminal" && title.toLowerCase() !== "tool call"
474 ? title
475 : undefined;
476 const data: Record<string, unknown> = { toolCallId };
477 const kind = normalizeToolKind(input.kind);
478 if (kind) {
479 data.kind = kind;
480 }
481 if (command) {
482 data.command = command;
483 }
484 if (input.rawInput !== undefined) {
485 data.rawInput = input.rawInput;
486 }
487 if (input.rawOutput !== undefined) {
488 data.rawOutput = boundToolCallRawOutput(input.rawOutput);
489 }
490 if (input.content !== undefined) {
491 data.content = extractedContent.content ?? input.content;
492 }
493 if (input.locations !== undefined) {
494 data.locations = input.locations;
495 }
496 const fallbackDetail = command ?? normalizedTitle ?? textContent;
497 const hasPresentationSeed =
498 title !== undefined ||
499 kind !== undefined ||
500 command !== undefined ||
501 normalizedTitle !== undefined ||
502 textContent !== undefined;
503 const presentation = hasPresentationSeed
504 ? deriveToolActivityPresentation({
505 itemType: canonicalItemTypeFromAcpToolKind(kind),
506 title,
507 detail: fallbackDetail,
508 data,
509 fallbackSummary: title ?? "Tool",
510 })
511 : undefined;
512 const status = normalizeToolCallStatus(input.status, options?.fallbackStatus);
513 return {
514 toolCallId,
515 ...(kind ? { kind } : {}),
516 ...(presentation?.summary ? { title: presentation.summary } : {}),
517 ...(status ? { status } : {}),
518 ...(command ? { command } : {}),
519 ...(presentation?.detail ? { detail: presentation.detail } : {}),
520 data,
521 };
523​
524function parseTypedToolCallState(
525 event: AcpToolCallUpdate,
526 options?: {
527 readonly fallbackStatus?: "pending" | "inProgress" | "completed" | "failed";
528 },
529): AcpToolCallState | undefined {
530 return makeToolCallState(
531 {
532 toolCallId: event.toolCallId,
533 title: event.title,
534 kind: event.kind,
535 status: event.status,
536 rawInput: event.rawInput,
537 rawOutput: event.rawOutput,
538 content: event.content,
539 locations: event.locations,
540 },
541 options,
542 );
544​
545export function mergeToolCallState(
546 previous: AcpToolCallState | undefined,
547 next: AcpToolCallState,
548): AcpToolCallState {
549 const nextKind = typeof next.data.kind === "string" ? next.data.kind : undefined;
550 const kind = nextKind ?? previous?.kind;
551 const title = next.title ?? previous?.title;
552 const status = next.status ?? previous?.status;
553 const command = next.command ?? previous?.command;
554 const detail = next.detail ?? previous?.detail;
555 return {
556 toolCallId: next.toolCallId,
557 ...(kind ? { kind } : {}),
558 ...(title ? { title } : {}),
559 ...(status ? { status } : {}),
560 ...(command ? { command } : {}),
561 ...(detail ? { detail } : {}),
562 data: {
563 ...previous?.data,
564 ...next.data,
565 },
566 };
568​
569// Even with bounded content (see TOOL_CALL_CONTENT_MAX_CHARS above), a redrawing terminal
570// can still shift its bounded tail window on nearly every notification, which would emit
571// a runtime event per redraw. Coalesce those: only emit early when the tool call's detail
572// has grown meaningfully since the last emission, otherwise batch up to a small number of
573// skipped updates before emitting anyway, so the UI still gets periodic progress and the
574// final (completed/failed) state is always emitted immediately.
575const TOOL_CALL_UPDATE_MIN_DETAIL_GROWTH_CHARS = 256;
576const TOOL_CALL_UPDATE_COALESCE_LIMIT = 10;
577​
578export interface AcpToolCallEmitDecisionInput {
579 readonly previous: AcpToolCallState | undefined;
580 readonly next: AcpToolCallState;
581 readonly lastEmittedDetailLength: number | undefined;
582 readonly skippedSinceEmit: number;
584​
585export interface AcpToolCallEmitDecision {
586 readonly emit: boolean;
587 readonly skippedSinceEmit: number;
589​
590function toolCallOutputUnchanged(previous: AcpToolCallState, next: AcpToolCallState): boolean {
591 return (
592 previous.data.content === next.data.content && previous.data.rawOutput === next.data.rawOutput
593 );
595​
596// Command tools keep `detail` equal to the command, so live stdout lives on
597// `data.content` / `data.rawOutput`. Measure that too, otherwise coalescing never
598// sees growth and in-progress output is held until completed/failed.
599export function toolCallProgressLength(state: AcpToolCallState): number {
600 let contentChars = 0;
601 const content = state.data.content;
602 if (Array.isArray(content)) {
603 for (const entry of content) {
604 if (!isRecord(entry)) {
605 continue;
606 }
607 const text = toolCallContentText(entry as EffectAcpSchema.ToolCallContent);
608 if (text) {
609 contentChars += text.length;
610 }
611 }
612 }
613 let rawOutputChars = 0;
614 const rawOutput = state.data.rawOutput;
615 if (isRecord(rawOutput)) {
616 for (const field of RAW_OUTPUT_TEXT_FIELDS) {
617 const value = rawOutput[field];
618 if (typeof value === "string") {
619 rawOutputChars += value.length;
620 }
621 }
622 }
623 return Math.max(state.detail?.length ?? 0, contentChars, rawOutputChars);
625​
626export function decideToolCallUpdateEmission(
627 input: AcpToolCallEmitDecisionInput,
628): AcpToolCallEmitDecision {
629 const { previous, next, lastEmittedDetailLength, skippedSinceEmit } = input;
630 if (next.status === "completed" || next.status === "failed") {
631 return { emit: true, skippedSinceEmit: 0 };
632 }
633 if (previous === undefined || previous.title !== next.title || previous.status !== next.status) {
634 return { emit: true, skippedSinceEmit: 0 };
635 }
636 if (previous.detail === next.detail && toolCallOutputUnchanged(previous, next)) {
637 return { emit: false, skippedSinceEmit };
638 }
639 const progressLength = toolCallProgressLength(next);
640 const grewMeaningfully =
641 lastEmittedDetailLength === undefined ||
642 Math.abs(progressLength - lastEmittedDetailLength) >= TOOL_CALL_UPDATE_MIN_DETAIL_GROWTH_CHARS;
643 if (grewMeaningfully || skippedSinceEmit + 1 >= TOOL_CALL_UPDATE_COALESCE_LIMIT) {
644 return { emit: true, skippedSinceEmit: 0 };
645 }
646 return { emit: false, skippedSinceEmit: skippedSinceEmit + 1 };
648​
649export function parsePermissionRequest(
650 params: EffectAcpSchema.RequestPermissionRequest,
651): AcpPermissionRequest {
652 const toolCall = makeToolCallState(
653 {
654 toolCallId: params.toolCall.toolCallId,
655 title: params.toolCall.title,
656 kind: params.toolCall.kind,
657 status: params.toolCall.status,
658 rawInput: params.toolCall.rawInput,
659 rawOutput: params.toolCall.rawOutput,
660 content: params.toolCall.content,
661 locations: params.toolCall.locations,
662 },
663 { fallbackStatus: "pending" },
664 );
665 const kind = normalizeToolKind(params.toolCall.kind) ?? "unknown";
666 const detail =
667 toolCall?.command ??
668 toolCall?.title ??
669 toolCall?.detail ??
670 (typeof params.sessionId === "string" ? `Session ${params.sessionId}` : undefined);
671 return {
672 kind,
673 ...(detail ? { detail } : {}),
674 ...(toolCall ? { toolCall } : {}),
675 };
677​
678export function sessionUpdateIsReplay(params: EffectAcpSchema.SessionNotification): boolean {
679 const meta = params._meta;
680 return isRecord(meta) && meta.isReplay === true;
682​
683export interface SessionLoadGate {
684 readonly active: boolean;
685 readonly lastActivityAtMillis: number | undefined;
686 readonly idleGap: Duration.Duration;
687 readonly initializeResult: EffectAcpSchema.InitializeResponse;
689​
690export const waitForSessionLoadReplayIdle = (input: {
691 readonly gateRef: Ref.Ref<Option.Option<SessionLoadGate>>;
692}): Effect.Effect<EffectAcpSchema.LoadSessionResponse, never> =>
693 Effect.gen(function* () {
694 const pollInterval = Duration.millis(25);
695 while (true) {
696 const gate = yield* Ref.get(input.gateRef);
697 if (
698 Option.isSome(gate) &&
699 gate.value.active &&
700 gate.value.lastActivityAtMillis !== undefined
701 ) {
702 const idleGapMillis = Duration.toMillis(gate.value.idleGap);
703 const nowMillis = yield* Clock.currentTimeMillis;
704 if (nowMillis - gate.value.lastActivityAtMillis >= idleGapMillis) {
705 return syntheticLoadSessionResponseFromInitialize(gate.value.initializeResult);
706 }
707 }
708 yield* Effect.sleep(pollInterval);
709 }
710 });
711​
712export function syntheticLoadSessionResponseFromInitialize(
713 initializeResult: EffectAcpSchema.InitializeResponse,
714): EffectAcpSchema.LoadSessionResponse {
715 const meta = initializeResult._meta;
716 const modelState = isRecord(meta) ? meta.modelState : undefined;
717 const modeState = isRecord(meta) ? meta.modeState : undefined;
718 const models = isSessionModelState(modelState) ? modelState : undefined;
719 const modes = isSessionModeState(modeState) ? modeState : undefined;
720​
721 return {
722 ...(models ? { models } : {}),
723 ...(modes ? { modes } : {}),
724 _meta: {
725 t3SessionLoadReady: "replay_idle",
726 },
727 };
729​
730// The parsed AcpToolCallState already carries bounded content (see makeToolCallState /
731// extractTextContentFromToolCallContent above), but the raw JSON-RPC notification is also
732// threaded through as `rawPayload` for logging/debugging and ends up persisted on the
733// runtime event. Substitute the same bounded `content`/`rawOutput` there so an oversized
734// cumulative update cannot smuggle the unbounded buffer back in through the raw payload.
735function boundToolCallRawPayload(
736 params: EffectAcpSchema.SessionNotification,
737 update: AcpToolCallUpdate,
738 toolCall: AcpToolCallState,
739): unknown {
740 const boundedContent = toolCall.data.content;
741 const boundedRawOutput = toolCall.data.rawOutput;
742 const contentBounded = update.content !== undefined && boundedContent !== update.content;
743 const rawOutputBounded = update.rawOutput !== undefined && boundedRawOutput !== update.rawOutput;
744 if (!contentBounded && !rawOutputBounded) {
745 return params;
746 }
747 return {
748 ...params,
749 update: {
750 ...update,
751 ...(contentBounded ? { content: boundedContent } : {}),
752 ...(rawOutputBounded ? { rawOutput: boundedRawOutput } : {}),
753 },
754 };
756​
757export function parseSessionUpdateEvent(params: EffectAcpSchema.SessionNotification): {
758 readonly modeId?: string;
759 readonly events: ReadonlyArray<AcpParsedSessionEvent>;
760} {
761 const upd = params.update;
762 const events: Array<AcpParsedSessionEvent> = [];
763 let modeId: string | undefined;
764​
765 switch (upd.sessionUpdate) {
766 case "current_mode_update": {
767 modeId = upd.currentModeId.trim();
768 if (modeId) {
769 events.push({
770 _tag: "ModeChanged",
771 modeId,
772 });
773 }
774 break;
775 }
776 case "plan": {
777 const plan = upd.entries.map((entry, index) => ({
778 step: entry.content.trim().length > 0 ? entry.content.trim() : `Step ${index + 1}`,
779 status: normalizePlanStepStatus(entry.status),
780 }));
781 if (plan.length > 0) {
782 events.push({
783 _tag: "PlanUpdated",
784 payload: {
785 plan,
786 },
787 rawPayload: params,
788 });
789 }
790 break;
791 }
792 case "tool_call": {
793 const toolCall = parseTypedToolCallState(upd, {
794 fallbackStatus: "pending",
795 });
796 if (toolCall) {
797 events.push({
798 _tag: "ToolCallUpdated",
799 toolCall,
800 rawPayload: boundToolCallRawPayload(params, upd, toolCall),
801 });
802 }
803 break;
804 }
805 case "tool_call_update": {
806 const toolCall = parseTypedToolCallState(upd);
807 if (toolCall) {
808 events.push({
809 _tag: "ToolCallUpdated",
810 toolCall,
811 rawPayload: boundToolCallRawPayload(params, upd, toolCall),
812 });
813 }
814 break;
815 }
816 case "agent_message_chunk": {
817 if (upd.content.type === "text" && upd.content.text.length > 0) {
818 events.push({
819 _tag: "ContentDelta",
820 text: upd.content.text,
821 rawPayload: params,
822 });
823 }
824 break;
825 }
826 default:
827 break;
828 }
829​
830 return { ...(modeId !== undefined ? { modeId } : {}), events };