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