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

AcpRuntimeModel.ts

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