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

AcpRuntimeModel.ts

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