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