Open History to see the last commit
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);
12}
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 );
30}
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 );
46}
47
48export interface AcpSessionMode {
49 readonly id: string;
50 readonly name: string;
51 readonly description?: string;
52}
53
54export interface AcpSessionModeState {
55 readonly currentModeId: string;
56 readonly availableModes: ReadonlyArray<AcpSessionMode>;
57}
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>;
67}
68
69export interface AcpPlanUpdate {
70 readonly explanation?: string | null;
71 readonly plan: ReadonlyArray<{
72 readonly step: string;
73 readonly status: "pending" | "inProgress" | "completed";
74 }>;
75}
76
77export interface AcpPermissionRequest {
78 readonly kind: string | "unknown";
79 readonly detail?: string;
80 readonly toolCall?: AcpToolCallState;
81}
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;
132}
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);
146}
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 );
157}
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 };
189}
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 }
201}
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 }
220}
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;
239}
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;
247}
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);
265}
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}`;
283}
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;
305}
306
307interface ExtractedToolCallContent {
308 readonly text: string | undefined;
309 readonly content: ReadonlyArray<EffectAcpSchema.ToolCallContent> | undefined;
310}
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;
317}
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;
343}
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 };
371}
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 });
427}
428
429function normalizeToolKind(kind: unknown): string | undefined {
430 return typeof kind === "string" && kind.trim().length > 0 ? kind.trim() : undefined;
431}
432
433/**
434 * Map an ACP tool kind onto the canonical runtime item type used by the
435 * thread activity model. Unknown kinds fall back to a generic tool call.
436 */
437export function canonicalItemTypeFromAcpToolKind(kind: string | undefined): ToolLifecycleItemType {
438 switch (kind) {
439 case "execute":
440 return "command_execution";
441 case "edit":
442 case "delete":
443 case "move":
444 return "file_change";
445 case "search":
446 case "fetch":
447 return "web_search";
448 default:
449 return "dynamic_tool_call";
450 }
451}
452
453function makeToolCallState(
454 input: {
455 readonly toolCallId: string;
456 readonly title?: string | null | undefined;
457 readonly kind?: EffectAcpSchema.ToolKind | null | undefined;
458 readonly status?: EffectAcpSchema.ToolCallStatus | null | undefined;
459 readonly rawInput?: unknown;
460 readonly rawOutput?: unknown;
461 readonly content?: ReadonlyArray<EffectAcpSchema.ToolCallContent> | null | undefined;
462 readonly locations?: ReadonlyArray<EffectAcpSchema.ToolCallLocation> | null | undefined;
463 },
464 options?: {
465 readonly fallbackStatus?: "pending" | "inProgress" | "completed" | "failed";
466 },
467): AcpToolCallState | undefined {
468 const toolCallId = input.toolCallId.trim();
469 if (!toolCallId) {
470 return undefined;
471 }
472 const title = input.title?.trim() || undefined;
473 const command = extractToolCallCommand(input.rawInput, title);
474 const extractedContent = extractTextContentFromToolCallContent(input.content);
475 const textContent = extractedContent.text;
476 const normalizedTitle =
477 title && title.toLowerCase() !== "terminal" && title.toLowerCase() !== "tool call"
478 ? title
479 : undefined;
480 const data: Record<string, unknown> = { toolCallId };
481 const kind = normalizeToolKind(input.kind);
482 if (kind) {
483 data.kind = kind;
484 }
485 if (command) {
486 data.command = command;
487 }
488 if (input.rawInput !== undefined) {
489 data.rawInput = input.rawInput;
490 }
491 if (input.rawOutput !== undefined) {
492 data.rawOutput = boundToolCallRawOutput(input.rawOutput);
493 }
494 if (input.content !== undefined) {
495 data.content = extractedContent.content ?? input.content;
496 }
497 if (input.locations !== undefined) {
498 data.locations = input.locations;
499 }
500 const fallbackDetail = command ?? normalizedTitle ?? textContent;
501 const hasPresentationSeed =
502 title !== undefined ||
503 kind !== undefined ||
504 command !== undefined ||
505 normalizedTitle !== undefined ||
506 textContent !== undefined;
507 const presentation = hasPresentationSeed
508 ? deriveToolActivityPresentation({
509 itemType: canonicalItemTypeFromAcpToolKind(kind),
510 title,
511 detail: fallbackDetail,
512 data,
513 fallbackSummary: title ?? "Tool",
514 })
515 : undefined;
516 const status = normalizeToolCallStatus(input.status, options?.fallbackStatus);
517 return {
518 toolCallId,
519 ...(kind ? { kind } : {}),
520 ...(presentation?.summary ? { title: presentation.summary } : {}),
521 ...(status ? { status } : {}),
522 ...(command ? { command } : {}),
523 ...(presentation?.detail ? { detail: presentation.detail } : {}),
524 data,
525 };
526}
527
528function parseTypedToolCallState(
529 event: AcpToolCallUpdate,
530 options?: {
531 readonly fallbackStatus?: "pending" | "inProgress" | "completed" | "failed";
532 },
533): AcpToolCallState | undefined {
534 return makeToolCallState(
535 {
536 toolCallId: event.toolCallId,
537 title: event.title,
538 kind: event.kind,
539 status: event.status,
540 rawInput: event.rawInput,
541 rawOutput: event.rawOutput,
542 content: event.content,
543 locations: event.locations,
544 },
545 options,
546 );
547}
548
549export function mergeToolCallState(
550 previous: AcpToolCallState | undefined,
551 next: AcpToolCallState,
552): AcpToolCallState {
553 const nextKind = typeof next.data.kind === "string" ? next.data.kind : undefined;
554 const kind = nextKind ?? previous?.kind;
555 const title = next.title ?? previous?.title;
556 const status = next.status ?? previous?.status;
557 const command = next.command ?? previous?.command;
558 const detail = next.detail ?? previous?.detail;
559 return {
560 toolCallId: next.toolCallId,
561 ...(kind ? { kind } : {}),
562 ...(title ? { title } : {}),
563 ...(status ? { status } : {}),
564 ...(command ? { command } : {}),
565 ...(detail ? { detail } : {}),
566 data: {
567 ...previous?.data,
568 ...next.data,
569 },
570 };
571}
572
573// Even with bounded content (see TOOL_CALL_CONTENT_MAX_CHARS above), a redrawing terminal
574// can still shift its bounded tail window on nearly every notification, which would emit
575// a runtime event per redraw. Coalesce those: only emit early when the tool call's detail
576// has grown meaningfully since the last emission, otherwise batch up to a small number of
577// skipped updates before emitting anyway, so the UI still gets periodic progress and the
578// final (completed/failed) state is always emitted immediately.
579const TOOL_CALL_UPDATE_MIN_DETAIL_GROWTH_CHARS = 256;
580const TOOL_CALL_UPDATE_COALESCE_LIMIT = 10;
581
582export interface AcpToolCallEmitDecisionInput {
583 readonly previous: AcpToolCallState | undefined;
584 readonly next: AcpToolCallState;
585 readonly lastEmittedDetailLength: number | undefined;
586 readonly skippedSinceEmit: number;
587}
588
589export interface AcpToolCallEmitDecision {
590 readonly emit: boolean;
591 readonly skippedSinceEmit: number;
592}
593
594function toolCallOutputUnchanged(previous: AcpToolCallState, next: AcpToolCallState): boolean {
595 return (
596 previous.data.content === next.data.content && previous.data.rawOutput === next.data.rawOutput
597 );
598}
599
600// Command tools keep `detail` equal to the command, so live stdout lives on
601// `data.content` / `data.rawOutput`. Measure that too, otherwise coalescing never
602// sees growth and in-progress output is held until completed/failed.
603export function toolCallProgressLength(state: AcpToolCallState): number {
604 let contentChars = 0;
605 const content = state.data.content;
606 if (Array.isArray(content)) {
607 for (const entry of content) {
608 if (!isRecord(entry)) {
609 continue;
610 }
611 const text = toolCallContentText(entry as EffectAcpSchema.ToolCallContent);
612 if (text) {
613 contentChars += text.length;
614 }
615 }
616 }
617 let rawOutputChars = 0;
618 const rawOutput = state.data.rawOutput;
619 if (isRecord(rawOutput)) {
620 for (const field of RAW_OUTPUT_TEXT_FIELDS) {
621 const value = rawOutput[field];
622 if (typeof value === "string") {
623 rawOutputChars += value.length;
624 }
625 }
626 }
627 return Math.max(state.detail?.length ?? 0, contentChars, rawOutputChars);
628}
629
630export function decideToolCallUpdateEmission(
631 input: AcpToolCallEmitDecisionInput,
632): AcpToolCallEmitDecision {
633 const { previous, next, lastEmittedDetailLength, skippedSinceEmit } = input;
634 if (next.status === "completed" || next.status === "failed") {
635 return { emit: true, skippedSinceEmit: 0 };
636 }
637 if (previous === undefined || previous.title !== next.title || previous.status !== next.status) {
638 return { emit: true, skippedSinceEmit: 0 };
639 }
640 if (previous.detail === next.detail && toolCallOutputUnchanged(previous, next)) {
641 return { emit: false, skippedSinceEmit };
642 }
643 const progressLength = toolCallProgressLength(next);
644 const grewMeaningfully =
645 lastEmittedDetailLength === undefined ||
646 Math.abs(progressLength - lastEmittedDetailLength) >= TOOL_CALL_UPDATE_MIN_DETAIL_GROWTH_CHARS;
647 if (grewMeaningfully || skippedSinceEmit + 1 >= TOOL_CALL_UPDATE_COALESCE_LIMIT) {
648 return { emit: true, skippedSinceEmit: 0 };
649 }
650 return { emit: false, skippedSinceEmit: skippedSinceEmit + 1 };
651}
652
653export function parsePermissionRequest(
654 params: EffectAcpSchema.RequestPermissionRequest,
655): AcpPermissionRequest {
656 const toolCall = makeToolCallState(
657 {
658 toolCallId: params.toolCall.toolCallId,
659 title: params.toolCall.title,
660 kind: params.toolCall.kind,
661 status: params.toolCall.status,
662 rawInput: params.toolCall.rawInput,
663 rawOutput: params.toolCall.rawOutput,
664 content: params.toolCall.content,
665 locations: params.toolCall.locations,
666 },
667 { fallbackStatus: "pending" },
668 );
669 const kind = normalizeToolKind(params.toolCall.kind) ?? "unknown";
670 const detail =
671 toolCall?.command ??
672 toolCall?.title ??
673 toolCall?.detail ??
674 (typeof params.sessionId === "string" ? `Session ${params.sessionId}` : undefined);
675 return {
676 kind,
677 ...(detail ? { detail } : {}),
678 ...(toolCall ? { toolCall } : {}),
679 };
680}
681
682export function sessionUpdateIsReplay(params: EffectAcpSchema.SessionNotification): boolean {
683 const meta = params._meta;
684 return isRecord(meta) && meta.isReplay === true;
685}
686
687export interface SessionLoadGate {
688 readonly active: boolean;
689 readonly lastActivityAtMillis: number | undefined;
690 readonly idleGap: Duration.Duration;
691 readonly initializeResult: EffectAcpSchema.InitializeResponse;
692}
693
694export const waitForSessionLoadReplayIdle = (input: {
695 readonly gateRef: Ref.Ref<Option.Option<SessionLoadGate>>;
696}): Effect.Effect<EffectAcpSchema.LoadSessionResponse, never> =>
697 Effect.gen(function* () {
698 const pollInterval = Duration.millis(25);
699 while (true) {
700 const gate = yield* Ref.get(input.gateRef);
701 if (
702 Option.isSome(gate) &&
703 gate.value.active &&
704 gate.value.lastActivityAtMillis !== undefined
705 ) {
706 const idleGapMillis = Duration.toMillis(gate.value.idleGap);
707 const nowMillis = yield* Clock.currentTimeMillis;
708 if (nowMillis - gate.value.lastActivityAtMillis >= idleGapMillis) {
709 return syntheticLoadSessionResponseFromInitialize(gate.value.initializeResult);
710 }
711 }
712 yield* Effect.sleep(pollInterval);
713 }
714 });
715
716/**
717 * Model state some agents (Grok) advertise in `initialize._meta.modelState`, before any
718 * session exists. Undefined when the agent does not advertise it or the shape is unknown.
719 */
720export function sessionModelStateFromInitialize(
721 initializeResult: EffectAcpSchema.InitializeResponse,
722): EffectAcpSchema.SessionModelState | undefined {
723 const meta = initializeResult._meta;
724 const modelState = isRecord(meta) ? meta.modelState : undefined;
725 return isSessionModelState(modelState) ? modelState : undefined;
726}
727
728export function syntheticLoadSessionResponseFromInitialize(
729 initializeResult: EffectAcpSchema.InitializeResponse,
730): EffectAcpSchema.LoadSessionResponse {
731 const meta = initializeResult._meta;
732 const modeState = isRecord(meta) ? meta.modeState : undefined;
733 const models = sessionModelStateFromInitialize(initializeResult);
734 const modes = isSessionModeState(modeState) ? modeState : undefined;
735
736 return {
737 ...(models ? { models } : {}),
738 ...(modes ? { modes } : {}),
739 _meta: {
740 t3SessionLoadReady: "replay_idle",
741 },
742 };
743}
744
745// The parsed AcpToolCallState already carries bounded content (see makeToolCallState /
746// extractTextContentFromToolCallContent above), but the raw JSON-RPC notification is also
747// threaded through as `rawPayload` for logging/debugging and ends up persisted on the
748// runtime event. Substitute the same bounded `content`/`rawOutput` there so an oversized
749// cumulative update cannot smuggle the unbounded buffer back in through the raw payload.
750function boundToolCallRawPayload(
751 params: EffectAcpSchema.SessionNotification,
752 update: AcpToolCallUpdate,
753 toolCall: AcpToolCallState,
754): unknown {
755 const boundedContent = toolCall.data.content;
756 const boundedRawOutput = toolCall.data.rawOutput;
757 const contentBounded = update.content !== undefined && boundedContent !== update.content;
758 const rawOutputBounded = update.rawOutput !== undefined && boundedRawOutput !== update.rawOutput;
759 if (!contentBounded && !rawOutputBounded) {
760 return params;
761 }
762 return {
763 ...params,
764 update: {
765 ...update,
766 ...(contentBounded ? { content: boundedContent } : {}),
767 ...(rawOutputBounded ? { rawOutput: boundedRawOutput } : {}),
768 },
769 };
770}
771
772export function parseSessionUpdateEvent(params: EffectAcpSchema.SessionNotification): {
773 readonly modeId?: string;
774 readonly events: ReadonlyArray<AcpParsedSessionEvent>;
775} {
776 const upd = params.update;
777 const events: Array<AcpParsedSessionEvent> = [];
778 let modeId: string | undefined;
779
780 switch (upd.sessionUpdate) {
781 case "current_mode_update": {
782 modeId = upd.currentModeId.trim();
783 if (modeId) {
784 events.push({
785 _tag: "ModeChanged",
786 modeId,
787 });
788 }
789 break;
790 }
791 case "plan": {
792 const plan = upd.entries.map((entry, index) => ({
793 step: entry.content.trim().length > 0 ? entry.content.trim() : `Step ${index + 1}`,
794 status: normalizePlanStepStatus(entry.status),
795 }));
796 if (plan.length > 0) {
797 events.push({
798 _tag: "PlanUpdated",
799 payload: {
800 plan,
801 },
802 rawPayload: params,
803 });
804 }
805 break;
806 }
807 case "tool_call": {
808 const toolCall = parseTypedToolCallState(upd, {
809 fallbackStatus: "pending",
810 });
811 if (toolCall) {
812 events.push({
813 _tag: "ToolCallUpdated",
814 toolCall,
815 rawPayload: boundToolCallRawPayload(params, upd, toolCall),
816 });
817 }
818 break;
819 }
820 case "tool_call_update": {
821 const toolCall = parseTypedToolCallState(upd);
822 if (toolCall) {
823 events.push({
824 _tag: "ToolCallUpdated",
825 toolCall,
826 rawPayload: boundToolCallRawPayload(params, upd, toolCall),
827 });
828 }
829 break;
830 }
831 case "agent_message_chunk": {
832 if (upd.content.type === "text" && upd.content.text.length > 0) {
833 events.push({
834 _tag: "ContentDelta",
835 text: upd.content.text,
836 rawPayload: params,
837 });
838 }
839 break;
840 }
841 default:
842 break;
843 }
844
845 return { ...(modeId !== undefined ? { modeId } : {}), events };
846}