@tangle-network/agent-app 4.0.3 → 4.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -3,7 +3,7 @@ import {
3
3
  ResizeHandle,
4
4
  chatToolCallPart,
5
5
  resolveToolPresentation
6
- } from "../chunk-EYPYU4PZ.js";
6
+ } from "../chunk-QXPOBDPU.js";
7
7
  import "../chunk-UHSUY6H6.js";
8
8
  import "../chunk-3HUFJ5LO.js";
9
9
  import "../chunk-7PULOECS.js";
@@ -99,10 +99,13 @@ export interface DraftPersistenceTuning {
99
99
  * interval. Default 262144 (256 KiB) -> interval x 2.5; ten times that ->
100
100
  * interval x 5. The final write is never throttled. */
101
101
  backoffBytes?: number;
102
- /** Per-tool-part output cap applied to DRAFTS ONLY (bytes). A tool returning
103
- * a large blob would otherwise be rewritten in full on every draft. The
104
- * final write always carries the untruncated value. Default 32768 (32 KiB);
105
- * 0 disables truncation. */
102
+ /** Per-tool-part output cap applied to DRAFTS ONLY, in serialized UTF-8
103
+ * bytes (including JSON escaping and the preview marker). A tool returning
104
+ * a large blob would otherwise be rewritten in full on every draft.
105
+ * `draftTruncated` marks a clipped preview even if the cap cannot fit its
106
+ * text marker; below 2 bytes the draft omits the output value. The final
107
+ * write always carries the untruncated value. Default 32768 (32 KiB);
108
+ * 0 disables truncation. This is not a bound on the whole parts array. */
106
109
  maxDraftToolOutputBytes?: number;
107
110
  }
108
111
  /** Define the inputs required to construct an assistant draft writer */
@@ -40,7 +40,7 @@ import {
40
40
  observeNativeCompletion,
41
41
  readCompletedSandboxTurn,
42
42
  recoverSandboxAssistantMessage
43
- } from "../chunk-JKYCXQFI.js";
43
+ } from "../chunk-W2DIPVHW.js";
44
44
  import {
45
45
  runProtectedRouterTurn
46
46
  } from "../chunk-GWATTXFR.js";
@@ -88,7 +88,7 @@ import {
88
88
  turnPromptText,
89
89
  valueRedactor,
90
90
  withProducerStream
91
- } from "../chunk-W5YQZEE4.js";
91
+ } from "../chunk-ROTSZSYZ.js";
92
92
  import "../chunk-SBHFMDR7.js";
93
93
  import "../chunk-H6BRJU5M.js";
94
94
  import "../chunk-4DBHC63F.js";
@@ -109,7 +109,7 @@ import {
109
109
  rowIdOf,
110
110
  storeSupportsDraftPersistence,
111
111
  transformVisibleTextParts
112
- } from "../chunk-SJKQUTGU.js";
112
+ } from "../chunk-K4YIDNX5.js";
113
113
  import "../chunk-2PCNHHN2.js";
114
114
  import "../chunk-YG66IHDU.js";
115
115
  import {
@@ -67,6 +67,7 @@ var CONTENT_EVENT_TYPES = /* @__PURE__ */ new Set([
67
67
  var DEFAULT_INTERVAL_MS = 2e3;
68
68
  var DEFAULT_BACKOFF_BYTES = 262144;
69
69
  var DEFAULT_MAX_DRAFT_TOOL_OUTPUT_BYTES = 32768;
70
+ var encoder = new TextEncoder();
70
71
  function isDraftContentEvent(event) {
71
72
  return typeof event?.type === "string" && CONTENT_EVENT_TYPES.has(event.type);
72
73
  }
@@ -77,19 +78,40 @@ function capDraftToolOutput(part, maxBytes) {
77
78
  if (!state || typeof state !== "object") return part;
78
79
  const record = state;
79
80
  const output = record.output;
80
- if (output === void 0 || output === null) return part;
81
- const serialized = typeof output === "string" ? output : safeStringify(output);
82
- if (serialized.length <= maxBytes) return part;
81
+ if (output === void 0) return part;
82
+ const text = typeof output === "string" ? output : safeStringify(output);
83
+ const serialized = typeof output === "string" && text.length <= maxBytes ? safeStringify(text) : text;
84
+ if (serialized.length <= maxBytes && encoder.encode(serialized).byteLength <= maxBytes) return part;
83
85
  const metadata = record.metadata && typeof record.metadata === "object" ? record.metadata : {};
84
86
  return {
85
87
  ...part,
86
88
  state: {
87
89
  ...record,
88
- output: `${serialized.slice(0, maxBytes)}\u2026[draft-truncated ${serialized.length - maxBytes} chars]`,
90
+ output: draftOutputPreview(text, maxBytes),
89
91
  metadata: { ...metadata, draftTruncated: true }
90
92
  }
91
93
  };
92
94
  }
95
+ function draftOutputPreview(text, maxBytes) {
96
+ if (maxBytes < 2) return void 0;
97
+ const marker = "\u2026[draft-truncated]";
98
+ const suffix = serializedBytes(marker) <= maxBytes ? marker : "";
99
+ const prefix = (end) => {
100
+ if (end > 0 && (text.codePointAt(end - 1) ?? 0) > 65535) end -= 1;
101
+ return text.slice(0, end);
102
+ };
103
+ let low = 0;
104
+ let high = Math.min(text.length, Math.floor(maxBytes));
105
+ while (low < high) {
106
+ const middle = Math.ceil((low + high) / 2);
107
+ if (serializedBytes(prefix(middle) + suffix) <= maxBytes) low = middle;
108
+ else high = middle - 1;
109
+ }
110
+ return prefix(low) + suffix;
111
+ }
112
+ function serializedBytes(value) {
113
+ return encoder.encode(safeStringify(value)).byteLength;
114
+ }
93
115
  function safeStringify(value) {
94
116
  try {
95
117
  return JSON.stringify(value) ?? "";
@@ -169,7 +191,7 @@ function createAssistantDraftWriter(options) {
169
191
  inFlight = (async () => {
170
192
  try {
171
193
  const values = await projectValues(snapshot);
172
- lastBlobBytes = values.parts ? safeStringify(values.parts).length : 0;
194
+ lastBlobBytes = values.parts ? serializedBytes(values.parts) : 0;
173
195
  await writeOnce(values);
174
196
  } catch (err) {
175
197
  log("[chat-routes] incremental assistant persistence failed", {
@@ -238,4 +260,4 @@ export {
238
260
  rowIdOf,
239
261
  assistantRowIdForTurn
240
262
  };
241
- //# sourceMappingURL=chunk-SJKQUTGU.js.map
263
+ //# sourceMappingURL=chunk-K4YIDNX5.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/chat-routes/sandbox-turn-usage.ts","../src/chat-routes/visible-text.ts","../src/chat-routes/draft-persistence.ts"],"sourcesContent":["import { asRecord, type JsonRecord } from '../stream/index'\nimport type { ChatTurnUsage } from './turn-routes'\n\n/** Every usage field a turn can record, in column order. */\nexport const TURN_USAGE_KEYS = [\n 'inputTokens', 'outputTokens', 'reasoningTokens', 'cacheReadTokens', 'cacheWriteTokens', 'costUsd', 'harnessCostUsd',\n] as const\n\n/** The usage fields a turn measured; unknown ones stay absent, never zero. */\nexport function measuredUsage(usage: ChatTurnUsage | undefined): ChatTurnUsage {\n const measured: ChatTurnUsage = {}\n for (const key of TURN_USAGE_KEYS) if (usage?.[key] !== undefined) measured[key] = usage[key]\n return measured\n}\n\n/** Add one canonical Sandbox `step-finish` receipt to a turn total. */\nexport function addStepFinishUsage(part: JsonRecord, usage: ChatTurnUsage): void {\n const tokens = asRecord(part.tokens)\n if (tokens) {\n const cache = asRecord(tokens.cache)\n const add = (current: number | undefined, value: unknown): number | undefined => {\n const n = Number(value)\n if (!Number.isFinite(n)) return current\n return (current ?? 0) + n\n }\n usage.inputTokens = add(usage.inputTokens, tokens.input)\n usage.outputTokens = add(usage.outputTokens, tokens.output)\n usage.reasoningTokens = add(usage.reasoningTokens, tokens.reasoning)\n if (cache) {\n usage.cacheReadTokens = add(usage.cacheReadTokens, cache.read)\n usage.cacheWriteTokens = add(usage.cacheWriteTokens, cache.write)\n }\n }\n const cost = Number(part.cost)\n if (Number.isFinite(cost)) usage.harnessCostUsd = (usage.harnessCostUsd ?? 0) + cost\n}\n","/**\n * Apply a product's final-text transform (a PII redactor, for example) to every\n * stored part a reader sees as words: the answer's text parts and the reasoning\n * parts, which also hold a Router turn's pre-tool narration. One rule for the\n * final row, the draft row and the detached-turn row.\n */\nexport function transformVisibleTextParts<T>(\n parts: readonly T[],\n transform: (text: string) => string | Promise<string>,\n): Promise<T[]> {\n return Promise.all(parts.map(async (part) => {\n const type = String((part as { type?: unknown }).type ?? '')\n return type === 'text' || type === 'reasoning'\n ? { ...part, text: await transform(String((part as { text?: unknown }).text ?? '')) }\n : part\n }))\n}\n","/**\n * Incremental (\"draft\") persistence of the assistant row WHILE a turn streams.\n *\n * Why this exists — the scale argument, not a convenience:\n *\n * A live turn is readable from two places. The hot path is the session\n * gateway's in-memory/Redis event buffer, which exists so a viewer survives a\n * network blip: it is keyed one sorted set per session, refreshed on every\n * push, and expires on a TTL. Its memory cost is `arrival_rate x TTL x\n * bytes_per_session` — strictly LINEAR in the TTL. Stretching that TTL to\n * cover \"a viewer who opens the tab later\" is a category error: it buys memory\n * proportional to the increase and still serves nothing to a viewer who\n * arrives past the new horizon.\n *\n * So the hot buffer must stay SHORT (live delivery + reconnect only), and\n * durable storage must serve history. That only works if durable storage\n * actually HAS the in-flight turn — which, before this module, it did not: the\n * assistant row was written once, after the stream drained. A viewer arriving\n * mid-turn past the hot window read an empty transcript.\n *\n * This module closes that gap: the assistant row is inserted early and patched\n * on a coalesced cadence, so the durable transcript is at most one interval\n * (default 2 s) behind the live stream and the hot buffer never has to be the\n * history tier.\n *\n * Mechanism only. It owns no vocabulary: the caller supplies the snapshot\n * function, the store, and the deterministic row id.\n *\n * Four properties the cadence guarantees:\n * - **Time-floored.** At most one write per `intervalMs`, never one per token.\n * - **Dirty-gated.** Only content-bearing events arm a write; heartbeats,\n * status pings, and lifecycle envelopes never do.\n * - **Single-flight.** A write already in flight suppresses the next trigger\n * instead of queueing; the final write is authoritative regardless of how\n * many drafts landed.\n * - **Best-effort.** A store failure is logged and swallowed — a durability\n * optimization must never kill a healthy stream (the same rule\n * `withDurableChatProjection` already states).\n */\n\nimport type { ChatMessageValues } from '../chat-store/core'\nimport { toChatMessageParts, type ChatMessagePart } from '../chat-store/parts'\nimport type { ChatTurnUsage } from './turn-routes'\nimport { measuredUsage } from './sandbox-turn-usage'\nimport { transformVisibleTextParts } from './visible-text'\n\n/** Message row shape the writer reads back when re-entering a turn. */\nexport interface DraftStoredMessage extends Pick<AssistantRowValues, keyof ChatTurnUsage> {\n id: string\n role: 'user' | 'assistant' | 'system' | 'tool'\n content: string\n parts?: ChatMessagePart[] | null\n model?: string | null\n requestedModel?: string | null\n servedModel?: string | null\n servedProvider?: string | null\n servedSource?: string | null\n}\n\n/** Values written to the assistant row — the intersection of the append and\n * patch shapes, so one snapshot serves both. */\nexport interface AssistantRowValues extends ChatMessageValues {}\n\n/** The store capability incremental persistence needs on top of\n * `appendMessage`. A store without `updateMessage` cannot patch a row, so it\n * cannot draft at all — the caller keeps today's single-write behavior. */\nexport interface AssistantDraftStore {\n listMessages(threadId: string): Promise<DraftStoredMessage[]>\n appendMessage(input: AssistantRowValues & {\n id?: string\n threadId: string\n role: 'user' | 'assistant'\n }): Promise<unknown>\n updateMessage?(id: string, patch: AssistantRowValues): Promise<unknown>\n deleteMessage?(id: string): Promise<unknown>\n}\n\n/** Live snapshot of the assistant body, taken from the producer's own\n * accumulators. `parts` is the DRAFT projection (`draftParts()`), never the\n * finalized one — see `draftAssistantParts`. */\nexport interface AssistantDraftSnapshot {\n content: string\n parts?: Array<Record<string, unknown>>\n usage?: ChatTurnUsage\n model?: string\n}\n\n/** Product-tunable cadence. Defaults are stated on each field; a product with\n * a chattier or heavier workload moves them without forking the writer. */\nexport interface DraftPersistenceTuning {\n /** Minimum wall-clock gap between draft writes, in ms. Default 2000.\n *\n * Justification for 2 s, from a measured tool-heavy production run (517\n * stream events over ~90 s wall = ~5.7 events/s): a 2 s floor with the\n * dirty gate turns 517 candidate writes into <= 45, while leaving the\n * durable row at most 2 s stale — an order of magnitude below the time it\n * takes a viewer to open a tab and render, so a late viewer never perceives\n * the lag. Fleet arithmetic at 10k concurrent 60 s runs: <= 30 updates per\n * run x 167 run-starts/s = ~334 row-updates/s spread over per-tenant\n * shards. Lower it and write amplification grows with no perceptible\n * freshness gain; raise it past ~5 s and a late viewer starts seeing a\n * visibly truncated answer. */\n intervalMs?: number\n /** Serialized-parts size (bytes) past which the interval backs off, so a\n * turn accumulating a megabyte-scale `parts` blob does not rewrite it every\n * interval. Default 262144 (256 KiB) -> interval x 2.5; ten times that ->\n * interval x 5. The final write is never throttled. */\n backoffBytes?: number\n /** Per-tool-part output cap applied to DRAFTS ONLY, in serialized UTF-8\n * bytes (including JSON escaping and the preview marker). A tool returning\n * a large blob would otherwise be rewritten in full on every draft.\n * `draftTruncated` marks a clipped preview even if the cap cannot fit its\n * text marker; below 2 bytes the draft omits the output value. The final\n * write always carries the untruncated value. Default 32768 (32 KiB);\n * 0 disables truncation. This is not a bound on the whole parts array. */\n maxDraftToolOutputBytes?: number\n}\n\n/** Define the inputs required to construct an assistant draft writer */\nexport interface AssistantDraftWriterOptions extends DraftPersistenceTuning {\n store: AssistantDraftStore\n threadId: string\n /** DETERMINISTIC row id for this turn's assistant message — the whole\n * idempotency mechanism. Derived from the turn's existing identity\n * (`deriveExecutionId` in the interactive lane, the turn id in the detached\n * lane), so a re-entered turn addresses the SAME row: the writer looks the\n * id up before its first insert and patches what it finds. */\n messageId: string\n /** Read the producer's live accumulators. Returns null before the producer\n * is resolved (the assembly defers box resolution into the first pull). */\n snapshot(): AssistantDraftSnapshot | null\n /** Pre-persist text transform (`/redact`'s `redactPII`). Applied to the\n * draft's scalar content AND every draft text part — parity with the final\n * write, or incremental persistence would re-open the at-rest PII leak that\n * transform closed, just seconds earlier and on every turn. */\n transformText?(text: string): string | Promise<string>\n log?: (message: string, meta?: Record<string, unknown>) => void\n}\n\n/** Coalescing writer that keeps one durable assistant row in step with a\n * streaming turn. Created per turn; not reusable. */\nexport interface AssistantDraftWriter {\n /** Arm/trigger a draft write from one engine event. Synchronous by design —\n * the write itself is fire-and-forget so the stream is never blocked on\n * store latency. */\n notify(event: { type?: unknown }): void\n /** Stop drafting and settle any in-flight write. Called before the final\n * write so a late draft can never clobber the authoritative row. */\n close(): Promise<void>\n /** Write the AUTHORITATIVE completion values onto this turn's row —\n * insert-or-patch under the same deterministic id, un-throttled and\n * un-truncated. Errors propagate: the final write is the one that must not\n * fail silently. Implies {@link close}. */\n finalize(values: AssistantRowValues): Promise<void>\n /** The durable row this turn is writing, once one exists. */\n rowId(): string | undefined\n /** Retract the row for a turn that produced nothing (mirrors the final\n * write's empty-turn skip, which leaves no row at all today). Also retracts\n * a row a PREVIOUS attempt left behind, so a re-entered turn that ends\n * empty converges on \"no row\" rather than a stale partial. */\n discard(): Promise<void>\n /** Diagnostics: how many draft writes actually reached the store. */\n writeCount(): number\n}\n\n/** Event types that carry assistant content and therefore arm a draft write.\n * An allowlist on purpose: an unknown type (a product heartbeat, a bespoke\n * passthrough) must NEVER arm a write, or a silent producer would rewrite the\n * same row forever. */\nconst CONTENT_EVENT_TYPES: ReadonlySet<string> = new Set([\n 'text',\n 'reasoning',\n 'tool_call',\n 'tool_result',\n 'usage',\n 'notice',\n 'error',\n 'file',\n 'interaction',\n 'interaction.cancel',\n 'plan.submitted',\n 'message.part.updated',\n])\n\nconst DEFAULT_INTERVAL_MS = 2000\nconst DEFAULT_BACKOFF_BYTES = 262144\nconst DEFAULT_MAX_DRAFT_TOOL_OUTPUT_BYTES = 32768\nconst encoder = new TextEncoder()\n\n/** True when this event should arm a draft write. */\nexport function isDraftContentEvent(event: { type?: unknown }): boolean {\n return typeof event?.type === 'string' && CONTENT_EVENT_TYPES.has(event.type)\n}\n\n/** Caps one tool part's `output` for a DRAFT write. Metadata marks every\n * clipped preview, with a text marker when it fits. Finalization restores the\n * untruncated value. */\nfunction capDraftToolOutput(part: Record<string, unknown>, maxBytes: number): Record<string, unknown> {\n if (maxBytes <= 0) return part\n if (String(part.type ?? '') !== 'tool') return part\n const state = part.state\n if (!state || typeof state !== 'object') return part\n const record = state as Record<string, unknown>\n const output = record.output\n if (output === undefined) return part\n const text = typeof output === 'string' ? output : safeStringify(output)\n // A longer string cannot fit even before escaping. Avoid serializing and\n // encoding the entire large tool body just to establish that lower bound.\n const serialized = typeof output === 'string' && text.length <= maxBytes ? safeStringify(text) : text\n if (serialized.length <= maxBytes && encoder.encode(serialized).byteLength <= maxBytes) return part\n const metadata = (record.metadata && typeof record.metadata === 'object' ? record.metadata : {}) as Record<string, unknown>\n return {\n ...part,\n state: {\n ...record,\n output: draftOutputPreview(text, maxBytes),\n metadata: { ...metadata, draftTruncated: true },\n },\n }\n}\n\n/** A preview is a string even when the retained output is structured. Bound\n * that stored string, whose JSON escaping may expand the source a second\n * time. Never cut a valid surrogate pair while finding the fitting prefix. */\nfunction draftOutputPreview(text: string, maxBytes: number): string | undefined {\n if (maxBytes < 2) return undefined\n const marker = '…[draft-truncated]'\n const suffix = serializedBytes(marker) <= maxBytes ? marker : ''\n const prefix = (end: number): string => {\n if (end > 0 && (text.codePointAt(end - 1) ?? 0) > 0xffff) end -= 1\n return text.slice(0, end)\n }\n let low = 0\n let high = Math.min(text.length, Math.floor(maxBytes))\n while (low < high) {\n const middle = Math.ceil((low + high) / 2)\n if (serializedBytes(prefix(middle) + suffix) <= maxBytes) low = middle\n else high = middle - 1\n }\n return prefix(low) + suffix\n}\n\nfunction serializedBytes(value: unknown): number {\n return encoder.encode(safeStringify(value)).byteLength\n}\n\nfunction safeStringify(value: unknown): string {\n try {\n return JSON.stringify(value) ?? ''\n } catch {\n return String(value)\n }\n}\n\n/** Build the coalescing draft writer for one turn. */\nexport function createAssistantDraftWriter(options: AssistantDraftWriterOptions): AssistantDraftWriter {\n const log = options.log ?? (() => {})\n const baseIntervalMs = options.intervalMs ?? DEFAULT_INTERVAL_MS\n const backoffBytes = options.backoffBytes ?? DEFAULT_BACKOFF_BYTES\n const maxToolOutput = options.maxDraftToolOutputBytes ?? DEFAULT_MAX_DRAFT_TOOL_OUTPUT_BYTES\n\n let dirty = false\n let closed = false\n let inFlight: Promise<void> | undefined\n let lastWriteAt = 0\n let lastBlobBytes = 0\n let rowId: string | undefined\n let writes = 0\n\n /** Interval for the NEXT write, backed off by the size of the last blob\n * written — a turn accumulating a huge parts array rewrites it less often. */\n function currentIntervalMs(): number {\n if (lastBlobBytes >= backoffBytes * 10) return baseIntervalMs * 5\n if (lastBlobBytes >= backoffBytes) return Math.round(baseIntervalMs * 2.5)\n return baseIntervalMs\n }\n\n async function projectValues(snapshot: AssistantDraftSnapshot): Promise<AssistantRowValues> {\n const transform = options.transformText\n const content = transform ? await transform(snapshot.content) : snapshot.content\n let parts: ChatMessagePart[] | undefined\n if (snapshot.parts) {\n const capped = snapshot.parts.map((part) => capDraftToolOutput(part, maxToolOutput))\n const redacted = transform ? await transformVisibleTextParts(capped, transform) : capped\n parts = toChatMessageParts(redacted)\n }\n const usage = snapshot.usage ?? {}\n return {\n content,\n ...(parts && parts.length > 0 ? { parts } : {}),\n ...(snapshot.model ? { model: snapshot.model } : {}),\n ...measuredUsage(usage),\n }\n }\n\n /** Adopt the row a PREVIOUS attempt at this turn already inserted, if any.\n * This lookup — by the deterministic id, through the store's ordinary read\n * — is the whole crash-safety mechanism: no new state, no extra column, no\n * second index. */\n async function adoptRow(): Promise<string | undefined> {\n if (rowId) return rowId\n const existing = (await options.store.listMessages(options.threadId)).find(\n (message) => message.id === options.messageId,\n )\n if (existing) rowId = existing.id\n return rowId\n }\n\n /** Insert-or-patch one set of values onto this turn's single row. */\n async function writeOnce(values: AssistantRowValues): Promise<void> {\n if (await adoptRow()) {\n await options.store.updateMessage!(rowId!, values)\n writes += 1\n return\n }\n const inserted = await options.store.appendMessage({\n id: options.messageId,\n threadId: options.threadId,\n role: 'assistant',\n ...values,\n })\n // The `?? options.messageId` tail is valid HERE and only here: this writer\n // supplied the id, so a store that returns nothing still wrote that row.\n // A caller that did not assign an id has no such fallback — which is why\n // `rowIdOf` deliberately stops at the honest read.\n rowId = rowIdOf(inserted) ?? options.messageId\n writes += 1\n }\n\n function trigger(): void {\n if (closed) return\n if (!dirty) return\n // Single-flight: a write already in flight SUPPRESSES this trigger rather\n // than queueing behind it. `dirty` stays armed, so the next event after it\n // lands writes the newer snapshot — one write is never spent on state a\n // later one supersedes.\n if (inFlight) return\n const now = Date.now()\n // The first content event writes immediately (a late viewer sees a row at\n // once); the time floor governs every write after it.\n if (lastWriteAt !== 0 && now - lastWriteAt < currentIntervalMs()) return\n const snapshot = options.snapshot()\n if (!snapshot) return\n // Nothing to persist yet: an armed-but-empty snapshot (first event is a\n // tool call with no text and no parts) would insert a blank row.\n if (!snapshot.content && (!snapshot.parts || snapshot.parts.length === 0)) return\n dirty = false\n lastWriteAt = now\n inFlight = (async () => {\n try {\n const values = await projectValues(snapshot)\n lastBlobBytes = values.parts ? serializedBytes(values.parts) : 0\n await writeOnce(values)\n } catch (err) {\n // Best-effort by contract: a store outage degrades freshness for late\n // viewers, it does not fail a healthy turn.\n log('[chat-routes] incremental assistant persistence failed', {\n messageId: options.messageId,\n error: err instanceof Error ? err.message : String(err),\n })\n } finally {\n inFlight = undefined\n // A trigger that arrived while this write was in flight left `dirty`\n // armed with a NEWER snapshot. Re-run it here or that state would sit\n // unwritten until the next content event — and if this was the last\n // event of a quiet stretch, until the final write.\n if (dirty && !closed) trigger()\n }\n })()\n }\n\n return {\n notify(event) {\n if (closed) return\n if (isDraftContentEvent(event)) dirty = true\n trigger()\n },\n async close() {\n closed = true\n if (inFlight) await inFlight\n },\n async finalize(values) {\n closed = true\n if (inFlight) await inFlight\n await writeOnce(values)\n },\n rowId: () => rowId,\n async discard() {\n closed = true\n if (inFlight) await inFlight\n if (!options.store.deleteMessage) return\n try {\n if (!(await adoptRow())) return\n await options.store.deleteMessage(rowId!)\n rowId = undefined\n } catch (err) {\n log('[chat-routes] draft assistant row discard failed', {\n messageId: options.messageId,\n error: err instanceof Error ? err.message : String(err),\n })\n }\n },\n writeCount: () => writes,\n }\n}\n\n/** True when a store can support incremental persistence at all. Without\n * `updateMessage` a draft row could never be patched, so the caller keeps\n * today's exact single-write behavior. */\nexport function storeSupportsDraftPersistence(store: AssistantDraftStore): boolean {\n return typeof store.updateMessage === 'function'\n}\n\n/** The row id an `appendMessage` actually returned, or `null` when the store\n * returned nothing usable. `ChatTurnMessageStore.appendMessage` is typed\n * `Promise<unknown>` so a product adapter is free to resolve `void`; every\n * caller that wants to NAME the row it just wrote has to read defensively.\n *\n * Deliberately no fallback to a caller-assigned id — see `writeOnce`, which\n * adds its own. A caller that let the store mint the id has nothing to fall\n * back TO, and guessing one would report a row that may not exist. */\nexport function rowIdOf(inserted: unknown): string | null {\n const id = (inserted as { id?: unknown } | null | undefined)?.id\n return typeof id === 'string' && id ? id : null\n}\n\n/** The default deterministic assistant-row id for a turn. Readable on purpose\n * (an operator grepping a transcript row id finds the run), and stable across\n * re-entries because every input already is. */\nexport function assistantR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IACF;AAAA,IACA,YAAY,MAAM;AAAA,EACpB;AACF;AAKO,SAAS,8BAA8B,OAAqC;AACjF,SAAO,OAAO,MAAM,kBAAkB;AACxC;AAUO,SAAS,QAAQ,UAAkC;AACxD,QAAM,KAAM,UAAkD;AAC9D,SAAO,OAAO,OAAO,YAAY,KAAK,KAAK;AAC7C;AAKO,SAAS,sBAAsB,SAAyB;AAC7D,SAAO,aAAa,OAAO;AAC7B;","names":[]}
@@ -7827,8 +7827,8 @@ function SegmentText({
7827
7827
  );
7828
7828
  }
7829
7829
  var COLLAPSE_TOOL_RUN_AT = 3;
7830
- function isImportantTool(call) {
7831
- return call.status === "running" || toolCallFailed(call) || pendingApprovalOf(call) !== null;
7830
+ function isImportantTool(call, streaming) {
7831
+ return !streaming && call.status === "running" || toolCallFailed(call) || pendingApprovalOf(call) !== null;
7832
7832
  }
7833
7833
  function SegmentedBody({
7834
7834
  segments,
@@ -7896,14 +7896,12 @@ function SegmentedBody({
7896
7896
  );
7897
7897
  continue;
7898
7898
  }
7899
- if (!streaming && g.calls.length >= COLLAPSE_TOOL_RUN_AT && !g.calls.some(isImportantTool)) {
7899
+ if (g.calls.length >= COLLAPSE_TOOL_RUN_AT && !g.calls.some((call) => isImportantTool(call, streaming))) {
7900
+ const running = g.calls.filter((call) => call.status === "running");
7901
+ const summary = running.length > 1 ? `Working \xB7 ${running.length} active steps` : running.length === 1 ? `Working \xB7 step ${g.calls.indexOf(running[0]) + 1}` : `Worked through ${g.calls.length} steps`;
7900
7902
  children.push(
7901
7903
  /* @__PURE__ */ jsxs26("details", { children: [
7902
- /* @__PURE__ */ jsxs26("summary", { className: "cursor-pointer select-none rounded-md py-0.5 text-xs font-medium text-muted-foreground [transition:color_var(--motion-control)] hover:text-foreground", children: [
7903
- "Worked through ",
7904
- g.calls.length,
7905
- " steps"
7906
- ] }),
7904
+ /* @__PURE__ */ jsx28("summary", { className: "cursor-pointer select-none rounded-md py-0.5 text-xs font-medium text-muted-foreground [transition:color_var(--motion-control)] hover:text-foreground", children: /* @__PURE__ */ jsx28("span", { "aria-live": "polite", children: summary }) }),
7907
7905
  /* @__PURE__ */ jsx28("div", { className: "mt-1.5 flex flex-col gap-1.5", children: g.calls.map(renderToolCard) })
7908
7906
  ] }, `tools-fold-${g.index}`)
7909
7907
  );
@@ -8832,4 +8830,4 @@ export {
8832
8830
  AgentProfileChoices,
8833
8831
  ComposerProfilePill
8834
8832
  };
8835
- //# sourceMappingURL=chunk-EYPYU4PZ.js.map
8833
+ //# sourceMappingURL=chunk-QXPOBDPU.js.map