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

AcpRuntimeModel.ts

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