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

AcpRuntimeModel.ts

729 lines22.8 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: "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;
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);
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 );
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 };
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 }
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 }
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;
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;
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);
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}`;
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;
306​
307interface ExtractedToolCallContent {
308 readonly text: string | undefined;
309 readonly content: ReadonlyArray<EffectAcpSchema.ToolCallContent> | undefined;
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;
318​
319function extractTextContentFromToolCallContent(
320 content: ReadonlyArray<EffectAcpSchema.ToolCallContent> | null | undefined,
321): ExtractedToolCallContent {
322 if (!content) {
323 return { text: undefined, content: undefined };
324 }
325 const chunks: Array<string> = [];
326 for (const entry of content) {
327 const text = toolCallContentText(entry)?.trim();
328 if (text) {
329 chunks.push(text);
330 }
331 }
332 if (chunks.length === 0) {
333 return { text: undefined, content };
334 }
335 const joined = chunks.join("\n");
336 if (joined.length <= TOOL_CALL_CONTENT_MAX_CHARS) {
337 return { text: joined, content };
338 }
339 const bounded = boundToolCallOutputText(joined);
340 // Collapse the text entries into a single bounded one at the final contributing text entry,
341 // and leave every other entry kind (diffs, images, resource links) in its original relative
342 // order. The retained tail came from that text entry, so placing it there also preserves its
343 // ordering relative to interleaved non-text content and ignores later blank text entries.
344 const lastContributingTextIndex = content.reduce(
345 (lastIndex, entry, index) => (toolCallContentText(entry)?.trim() ? index : lastIndex),
346 -1,
347 );
348 const boundedContent = content.flatMap((entry, index) => {
349 if (toolCallContentText(entry) === undefined) {
350 return [entry];
351 }
352 if (index !== lastContributingTextIndex) {
353 return [];
354 }
355 return [{ type: "content", content: { type: "text", text: bounded } } as const];
356 });
357 return { text: bounded, content: boundedContent };
359​
360function normalizeToolKind(kind: unknown): string | undefined {
361 return typeof kind === "string" && kind.trim().length > 0 ? kind.trim() : undefined;
363​
364function canonicalItemTypeFromAcpToolKind(kind: string | undefined): ToolLifecycleItemType {
365 switch (kind) {
366 case "execute":
367 return "command_execution";
368 case "edit":
369 case "delete":
370 case "move":
371 return "file_change";
372 case "search":
373 case "fetch":
374 return "web_search";
375 default:
376 return "dynamic_tool_call";
377 }
379​
380function makeToolCallState(
381 input: {
382 readonly toolCallId: string;
383 readonly title?: string | null | undefined;
384 readonly kind?: EffectAcpSchema.ToolKind | null | undefined;
385 readonly status?: EffectAcpSchema.ToolCallStatus | null | undefined;
386 readonly rawInput?: unknown;
387 readonly rawOutput?: unknown;
388 readonly content?: ReadonlyArray<EffectAcpSchema.ToolCallContent> | null | undefined;
389 readonly locations?: ReadonlyArray<EffectAcpSchema.ToolCallLocation> | null | undefined;
390 },
391 options?: {
392 readonly fallbackStatus?: "pending" | "inProgress" | "completed" | "failed";
393 },
394): AcpToolCallState | undefined {
395 const toolCallId = input.toolCallId.trim();
396 if (!toolCallId) {
397 return undefined;
398 }
399 const title = input.title?.trim() || undefined;
400 const command = extractToolCallCommand(input.rawInput, title);
401 const extractedContent = extractTextContentFromToolCallContent(input.content);
402 const textContent = extractedContent.text;
403 const normalizedTitle =
404 title && title.toLowerCase() !== "terminal" && title.toLowerCase() !== "tool call"
405 ? title
406 : undefined;
407 const data: Record<string, unknown> = { toolCallId };
408 const kind = normalizeToolKind(input.kind);
409 if (kind) {
410 data.kind = kind;
411 }
412 if (command) {
413 data.command = command;
414 }
415 if (input.rawInput !== undefined) {
416 data.rawInput = input.rawInput;
417 }
418 if (input.rawOutput !== undefined) {
419 data.rawOutput = boundToolCallRawOutput(input.rawOutput);
420 }
421 if (input.content !== undefined) {
422 data.content = extractedContent.content ?? input.content;
423 }
424 if (input.locations !== undefined) {
425 data.locations = input.locations;
426 }
427 const fallbackDetail = command ?? normalizedTitle ?? textContent;
428 const hasPresentationSeed =
429 title !== undefined ||
430 kind !== undefined ||
431 command !== undefined ||
432 normalizedTitle !== undefined ||
433 textContent !== undefined;
434 const presentation = hasPresentationSeed
435 ? deriveToolActivityPresentation({
436 itemType: canonicalItemTypeFromAcpToolKind(kind),
437 title,
438 detail: fallbackDetail,
439 data,
440 fallbackSummary: title ?? "Tool",
441 })
442 : undefined;
443 const status = normalizeToolCallStatus(input.status, options?.fallbackStatus);
444 return {
445 toolCallId,
446 ...(kind ? { kind } : {}),
447 ...(presentation?.summary ? { title: presentation.summary } : {}),
448 ...(status ? { status } : {}),
449 ...(command ? { command } : {}),
450 ...(presentation?.detail ? { detail: presentation.detail } : {}),
451 data,
452 };
454​
455function parseTypedToolCallState(
456 event: AcpToolCallUpdate,
457 options?: {
458 readonly fallbackStatus?: "pending" | "inProgress" | "completed" | "failed";
459 },
460): AcpToolCallState | undefined {
461 return makeToolCallState(
462 {
463 toolCallId: event.toolCallId,
464 title: event.title,
465 kind: event.kind,
466 status: event.status,
467 rawInput: event.rawInput,
468 rawOutput: event.rawOutput,
469 content: event.content,
470 locations: event.locations,
471 },
472 options,
473 );
475​
476export function mergeToolCallState(
477 previous: AcpToolCallState | undefined,
478 next: AcpToolCallState,
479): AcpToolCallState {
480 const nextKind = typeof next.data.kind === "string" ? next.data.kind : undefined;
481 const kind = nextKind ?? previous?.kind;
482 const title = next.title ?? previous?.title;
483 const status = next.status ?? previous?.status;
484 const command = next.command ?? previous?.command;
485 const detail = next.detail ?? previous?.detail;
486 return {
487 toolCallId: next.toolCallId,
488 ...(kind ? { kind } : {}),
489 ...(title ? { title } : {}),
490 ...(status ? { status } : {}),
491 ...(command ? { command } : {}),
492 ...(detail ? { detail } : {}),
493 data: {
494 ...previous?.data,
495 ...next.data,
496 },
497 };
499​
500// Even with bounded content (see TOOL_CALL_CONTENT_MAX_CHARS above), a redrawing terminal
501// can still shift its bounded tail window on nearly every notification, which would emit
502// a runtime event per redraw. Coalesce those: only emit early when the tool call's detail
503// has grown meaningfully since the last emission, otherwise batch up to a small number of
504// skipped updates before emitting anyway, so the UI still gets periodic progress and the
505// final (completed/failed) state is always emitted immediately.
506const TOOL_CALL_UPDATE_MIN_DETAIL_GROWTH_CHARS = 256;
507const TOOL_CALL_UPDATE_COALESCE_LIMIT = 10;
508​
509export interface AcpToolCallEmitDecisionInput {
510 readonly previous: AcpToolCallState | undefined;
511 readonly next: AcpToolCallState;
512 readonly lastEmittedDetailLength: number | undefined;
513 readonly skippedSinceEmit: number;
515​
516export interface AcpToolCallEmitDecision {
517 readonly emit: boolean;
518 readonly skippedSinceEmit: number;
520​
521export function decideToolCallUpdateEmission(
522 input: AcpToolCallEmitDecisionInput,
523): AcpToolCallEmitDecision {
524 const { previous, next, lastEmittedDetailLength, skippedSinceEmit } = input;
525 if (next.status === "completed" || next.status === "failed") {
526 return { emit: true, skippedSinceEmit: 0 };
527 }
528 if (!next.detail) {
529 return { emit: false, skippedSinceEmit };
530 }
531 if (previous === undefined || previous.title !== next.title) {
532 return { emit: true, skippedSinceEmit: 0 };
533 }
534 if (previous.detail === next.detail) {
535 return { emit: false, skippedSinceEmit };
536 }
537 const grewMeaningfully =
538 lastEmittedDetailLength === undefined ||
539 Math.abs(next.detail.length - lastEmittedDetailLength) >=
540 TOOL_CALL_UPDATE_MIN_DETAIL_GROWTH_CHARS;
541 if (grewMeaningfully || skippedSinceEmit + 1 >= TOOL_CALL_UPDATE_COALESCE_LIMIT) {
542 return { emit: true, skippedSinceEmit: 0 };
543 }
544 return { emit: false, skippedSinceEmit: skippedSinceEmit + 1 };
546​
547export function parsePermissionRequest(
548 params: EffectAcpSchema.RequestPermissionRequest,
549): AcpPermissionRequest {
550 const toolCall = makeToolCallState(
551 {
552 toolCallId: params.toolCall.toolCallId,
553 title: params.toolCall.title,
554 kind: params.toolCall.kind,
555 status: params.toolCall.status,
556 rawInput: params.toolCall.rawInput,
557 rawOutput: params.toolCall.rawOutput,
558 content: params.toolCall.content,
559 locations: params.toolCall.locations,
560 },
561 { fallbackStatus: "pending" },
562 );
563 const kind = normalizeToolKind(params.toolCall.kind) ?? "unknown";
564 const detail =
565 toolCall?.command ??
566 toolCall?.title ??
567 toolCall?.detail ??
568 (typeof params.sessionId === "string" ? `Session ${params.sessionId}` : undefined);
569 return {
570 kind,
571 ...(detail ? { detail } : {}),
572 ...(toolCall ? { toolCall } : {}),
573 };
575​
576export function sessionUpdateIsReplay(params: EffectAcpSchema.SessionNotification): boolean {
577 const meta = params._meta;
578 return isRecord(meta) && meta.isReplay === true;
580​
581export interface SessionLoadGate {
582 readonly active: boolean;
583 readonly lastActivityAtMillis: number | undefined;
584 readonly idleGap: Duration.Duration;
585 readonly initializeResult: EffectAcpSchema.InitializeResponse;
587​
588export const waitForSessionLoadReplayIdle = (input: {
589 readonly gateRef: Ref.Ref<Option.Option<SessionLoadGate>>;
590}): Effect.Effect<EffectAcpSchema.LoadSessionResponse, never> =>
591 Effect.gen(function* () {
592 const pollInterval = Duration.millis(25);
593 while (true) {
594 const gate = yield* Ref.get(input.gateRef);
595 if (
596 Option.isSome(gate) &&
597 gate.value.active &&
598 gate.value.lastActivityAtMillis !== undefined
599 ) {
600 const idleGapMillis = Duration.toMillis(gate.value.idleGap);
601 const nowMillis = yield* Clock.currentTimeMillis;
602 if (nowMillis - gate.value.lastActivityAtMillis >= idleGapMillis) {
603 return syntheticLoadSessionResponseFromInitialize(gate.value.initializeResult);
604 }
605 }
606 yield* Effect.sleep(pollInterval);
607 }
608 });
609​
610export function syntheticLoadSessionResponseFromInitialize(
611 initializeResult: EffectAcpSchema.InitializeResponse,
612): EffectAcpSchema.LoadSessionResponse {
613 const meta = initializeResult._meta;
614 const modelState = isRecord(meta) ? meta.modelState : undefined;
615 const modeState = isRecord(meta) ? meta.modeState : undefined;
616 const models = isSessionModelState(modelState) ? modelState : undefined;
617 const modes = isSessionModeState(modeState) ? modeState : undefined;
618​
619 return {
620 ...(models ? { models } : {}),
621 ...(modes ? { modes } : {}),
622 _meta: {
623 t3SessionLoadReady: "replay_idle",
624 },
625 };
627​
628// The parsed AcpToolCallState already carries bounded content (see makeToolCallState /
629// extractTextContentFromToolCallContent above), but the raw JSON-RPC notification is also
630// threaded through as `rawPayload` for logging/debugging and ends up persisted on the
631// runtime event. Substitute the same bounded `content`/`rawOutput` there so an oversized
632// cumulative update cannot smuggle the unbounded buffer back in through the raw payload.
633function boundToolCallRawPayload(
634 params: EffectAcpSchema.SessionNotification,
635 update: AcpToolCallUpdate,
636 toolCall: AcpToolCallState,
637): unknown {
638 const boundedContent = toolCall.data.content;
639 const boundedRawOutput = toolCall.data.rawOutput;
640 const contentBounded = update.content !== undefined && boundedContent !== update.content;
641 const rawOutputBounded = update.rawOutput !== undefined && boundedRawOutput !== update.rawOutput;
642 if (!contentBounded && !rawOutputBounded) {
643 return params;
644 }
645 return {
646 ...params,
647 update: {
648 ...update,
649 ...(contentBounded ? { content: boundedContent } : {}),
650 ...(rawOutputBounded ? { rawOutput: boundedRawOutput } : {}),
651 },
652 };
654​
655export function parseSessionUpdateEvent(params: EffectAcpSchema.SessionNotification): {
656 readonly modeId?: string;
657 readonly events: ReadonlyArray<AcpParsedSessionEvent>;
658} {
659 const upd = params.update;
660 const events: Array<AcpParsedSessionEvent> = [];
661 let modeId: string | undefined;
662​
663 switch (upd.sessionUpdate) {
664 case "current_mode_update": {
665 modeId = upd.currentModeId.trim();
666 if (modeId) {
667 events.push({
668 _tag: "ModeChanged",
669 modeId,
670 });
671 }
672 break;
673 }
674 case "plan": {
675 const plan = upd.entries.map((entry, index) => ({
676 step: entry.content.trim().length > 0 ? entry.content.trim() : `Step ${index + 1}`,
677 status: normalizePlanStepStatus(entry.status),
678 }));
679 if (plan.length > 0) {
680 events.push({
681 _tag: "PlanUpdated",
682 payload: {
683 plan,
684 },
685 rawPayload: params,
686 });
687 }
688 break;
689 }
690 case "tool_call": {
691 const toolCall = parseTypedToolCallState(upd, {
692 fallbackStatus: "pending",
693 });
694 if (toolCall) {
695 events.push({
696 _tag: "ToolCallUpdated",
697 toolCall,
698 rawPayload: boundToolCallRawPayload(params, upd, toolCall),
699 });
700 }
701 break;
702 }
703 case "tool_call_update": {
704 const toolCall = parseTypedToolCallState(upd);
705 if (toolCall) {
706 events.push({
707 _tag: "ToolCallUpdated",
708 toolCall,
709 rawPayload: boundToolCallRawPayload(params, upd, toolCall),
710 });
711 }
712 break;
713 }
714 case "agent_message_chunk": {
715 if (upd.content.type === "text" && upd.content.text.length > 0) {
716 events.push({
717 _tag: "ContentDelta",
718 text: upd.content.text,
719 rawPayload: params,
720 });
721 }
722 break;
723 }
724 default:
725 break;
726 }
727​
728 return { ...(modeId !== undefined ? { modeId } : {}), events };