@tangle-network/agent-app 4.0.2 → 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.
- package/dist/assistant/index.js +1 -1
- package/dist/chat-routes/draft-persistence.d.ts +7 -4
- package/dist/chat-routes/index.js +3 -3
- package/dist/{chunk-EI27JMS6.js → chunk-565M7QOK.js} +1 -1
- package/dist/chunk-565M7QOK.js.map +1 -0
- package/dist/{chunk-LBMFQLBS.js → chunk-DKEIQRKT.js} +4 -2
- package/dist/chunk-DKEIQRKT.js.map +1 -0
- package/dist/{chunk-XOHE6SKU.js → chunk-EK2Y55K4.js} +2 -137
- package/dist/chunk-EK2Y55K4.js.map +1 -0
- package/dist/{chunk-QVGDVY5U.js → chunk-I4MPG5T6.js} +2 -2
- package/dist/chunk-IJ6B5ZPU.js +141 -0
- package/dist/chunk-IJ6B5ZPU.js.map +1 -0
- package/dist/{chunk-SJKQUTGU.js → chunk-K4YIDNX5.js} +28 -6
- package/dist/chunk-K4YIDNX5.js.map +1 -0
- package/dist/{chunk-U2PTQCQ3.js → chunk-NKANJSKB.js} +2 -2
- package/dist/{chunk-EYPYU4PZ.js → chunk-QXPOBDPU.js} +7 -9
- package/dist/{chunk-EYPYU4PZ.js.map → chunk-QXPOBDPU.js.map} +1 -1
- package/dist/{chunk-W5YQZEE4.js → chunk-ROTSZSYZ.js} +2 -2
- package/dist/{chunk-JKYCXQFI.js → chunk-W2DIPVHW.js} +2 -2
- package/dist/conformance/cli.js +2 -2
- package/dist/conformance/index.js +2 -2
- package/dist/launch-invariants/cli.js +4 -3
- package/dist/launch-invariants/cli.js.map +1 -1
- package/dist/launch-invariants/index.js +3 -2
- package/dist/launch-invariants/index.js.map +1 -1
- package/dist/launch-invariants/testing.js +4 -3
- package/dist/operator/contract.d.ts +6 -0
- package/dist/operator/index.js +6 -1
- package/dist/operator/index.js.map +1 -1
- package/dist/preset-cloudflare/index.js +2 -2
- package/dist/public-consultation/index.js +2 -2
- package/dist/turn-health/index.js +5 -3
- package/dist/turn-health/index.js.map +1 -1
- package/dist/web-react/chat-message-body.d.ts +2 -2
- package/dist/web-react/index.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-EI27JMS6.js.map +0 -1
- package/dist/chunk-LBMFQLBS.js.map +0 -1
- package/dist/chunk-SJKQUTGU.js.map +0 -1
- package/dist/chunk-XOHE6SKU.js.map +0 -1
- /package/dist/{chunk-QVGDVY5U.js.map → chunk-I4MPG5T6.js.map} +0 -0
- /package/dist/{chunk-U2PTQCQ3.js.map → chunk-NKANJSKB.js.map} +0 -0
- /package/dist/{chunk-W5YQZEE4.js.map → chunk-ROTSZSYZ.js.map} +0 -0
- /package/dist/{chunk-JKYCXQFI.js.map → chunk-W2DIPVHW.js.map} +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/turn-health/sink.ts"],"sourcesContent":["/**\n * Where a silent-failure verdict GOES.\n *\n * The detection half is worthless without this half. Every failure this module\n * finds was already visible in the database the whole time — 255 unanswered\n * messages sat in a table for 17 days. What was missing was not the data, it\n * was delivery to a human who had not thought to look.\n *\n * So the sink is a seam, not a channel: the product supplies the transport,\n * and agent-app ships the two shapes the fleet already has credentials for\n * (an ops webhook, and stderr). No new channel is invented here.\n */\n\nimport { postSlackAlert } from '../alerting/slack.js'\nimport { describeReason, type TurnHealthReason, type TurnHealthSeverity } from './classify.js'\n\n/** One deliverable alert. */\nexport interface TurnHealthAlert {\n /** Which product raised it (`projectId`). Alerts from four products land in\n * one channel, so this is what makes the message actionable. */\n product: string\n severity: TurnHealthSeverity\n /** Stable grouping key. Throttling is keyed on this, so it must NOT contain\n * a turn id or a timestamp or every alert is unique and nothing dedupes. */\n key: string\n title: string\n /** Human-readable lines. */\n details: string[]\n /** Structured payload for a machine consumer. */\n data?: Record<string, unknown>\n at: number\n}\n\n/** Deliver an alert. Implementations MUST NOT throw — see\n * {@link createGuardedAlertSink}. */\nexport interface AlertSink {\n deliver(alert: TurnHealthAlert): Promise<void>\n}\n\n/** Build the alert for a set of reasons found on one turn. */\nexport function turnAlert(input: {\n product: string\n severity: TurnHealthSeverity\n reasons: TurnHealthReason[]\n threadId?: string\n turnId?: string\n model?: string\n at?: number\n}): TurnHealthAlert {\n const kinds = [...new Set(input.reasons.map((r) => r.kind))].sort()\n return {\n product: input.product,\n severity: input.severity,\n // Keyed by product + reason kinds ONLY. A blank-completion storm across\n // 200 turns is one incident, not 200 pages.\n key: `turn:${input.product}:${kinds.join('+')}`,\n title: `${input.product}: turn completed but delivered nothing (${kinds.join(', ')})`,\n details: input.reasons.map(describeReason),\n data: {\n kinds,\n ...(input.threadId ? { threadId: input.threadId } : {}),\n ...(input.turnId ? { turnId: input.turnId } : {}),\n ...(input.model ? { model: input.model } : {}),\n },\n at: input.at ?? Date.now(),\n }\n}\n\n// ── transports ────────────────────────────────────────────────────────────\n\n/** Minimal structural fetch, so this module has no lib-dom dependency and can\n * be driven by a fake in tests. */\ntype FetchLike = (\n url: string,\n init: { method: string; headers: Record<string, string>; body: string },\n) => Promise<{ ok: boolean; status: number; text?(): Promise<string> }>\n\n/**\n * POST to an incoming webhook in the Slack message format.\n *\n * Chosen because the org already runs one (`SLACK_OPS_WEBHOOK_URL`) and\n * gtm-agent's outbound webhook code already speaks this exact shape — the\n * instruction was to route somewhere humans already look, not to stand up a\n * new channel. Discord and most log drains accept the same `{text}` body.\n */\nexport function createWebhookAlertSink(options: {\n webhookUrl: string\n fetchImpl?: FetchLike\n}): AlertSink {\n const fetchImpl = options.fetchImpl ?? (globalThis.fetch as unknown as FetchLike)\n return {\n async deliver(alert) {\n const text = slackAlertText(alert)\n const response = await fetchImpl(options.webhookUrl, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ text: text }),\n })\n if (!response.ok) {\n // A dropped alert is a silent failure of the silent-failure detector.\n // It must be loud in the one place that is still working: the log.\n throw new Error(`alert webhook responded ${response.status}`)\n }\n },\n }\n}\n\n/**\n * POST to Slack `chat.postMessage` with a bot token.\n *\n * This is the transport the org actually has. A survey of the four product\n * repos found NO ops alert path of any kind — no incoming webhook, no pager, no\n * notifier — which is the mechanical reason a 17-day outage never reached a\n * human. What does exist is a Slack bot token in the shared secrets store, and\n * `@tangle-network/agent-integrations` already speaks this exact API, so this\n * routes alerts through the channel the org runs rather than standing up a new\n * one.\n *\n * Slack answers `200 OK` with `{\"ok\": false, \"error\": \"...\"}` for an invalid\n * token or channel, so the body is checked and not just the status — a\n * transport that reports success on a rejected post would make the alerter\n * itself a silent failure.\n */\nexport function createSlackBotAlertSink(options: {\n botToken: string\n channel: string\n fetchImpl?: FetchLike\n}): AlertSink {\n const fetchImpl = options.fetchImpl ?? (globalThis.fetch as unknown as FetchLike)\n return {\n async deliver(alert) {\n const text = slackAlertText(alert)\n const outcome = await postSlackAlert({\n token: options.botToken, channel: options.channel, text: text, attempts: 1,\n // Preserve the public minimal-fetch seam without owning a second Slack\n // request builder or response parser. Real callers use native fetch.\n fetchImpl: options.fetchImpl ? (async (url, init) => {\n const response = await fetchImpl(String(url), {\n method: init?.method ?? 'POST',\n headers: Object.fromEntries(new Headers(init?.headers)),\n body: String(init?.body ?? ''),\n })\n return new Response(await response.text?.() ?? '', { status: response.status })\n }) : undefined,\n })\n if (!outcome.delivered) throw new Error(`Slack alert failed (${outcome.reason}): ${outcome.detail}`)\n },\n }\n}\n\n/** stderr sink. The zero-config fallback so a product that has not yet been\n * given a webhook still emits something a log search can find. */\nexport function createConsoleAlertSink(log: (message: string) => void = console.error): AlertSink {\n return {\n async deliver(alert) {\n log(\n `[turn-health] ${alert.severity.toUpperCase()} ${alert.title} :: ${alert.details.join(' | ')}`,\n )\n },\n }\n}\n\n/** Fan out to several sinks. One failing transport must not stop the others. */\nexport function createMultiAlertSink(sinks: readonly AlertSink[]): AlertSink {\n return {\n async deliver(alert) {\n const settled = await Promise.allSettled(sinks.map((s) => s.deliver(alert)))\n const failures = settled.filter((r) => r.status === 'rejected')\n if (failures.length === sinks.length && sinks.length > 0) {\n throw new Error('every alert sink failed')\n }\n },\n }\n}\n\n// ── throttling ────────────────────────────────────────────────────────────\n\n/** Records the last time a key was alerted on. A product backs this with KV,\n * D1, or a Durable Object; the in-memory default is correct for a sweep that\n * runs as a single cron invocation. */\nexport interface AlertThrottleStore {\n lastSentAt(key: string): Promise<number | null>\n markSent(key: string, at: number): Promise<void>\n}\n\n/** Process-local throttle store. */\nexport function createMemoryThrottleStore(): AlertThrottleStore {\n const seen = new Map<string, number>()\n return {\n async lastSentAt(key) {\n return seen.get(key) ?? null\n },\n async markSent(key, at) {\n seen.set(key, at)\n },\n }\n}\n\n/**\n * Collapse repeats of the same `key` inside `windowMs`.\n *\n * Deliberately re-alerts once per window rather than going silent after the\n * first: an incident that is still burning must keep saying so. Going quiet\n * after one message is how a 17-day outage stays invisible after someone\n * dismisses the first notification.\n */\nexport function createThrottledAlertSink(\n inner: AlertSink,\n options: { windowMs: number; store?: AlertThrottleStore },\n): AlertSink {\n const store = options.store ?? createMemoryThrottleStore()\n return {\n async deliver(alert) {\n const last = await store.lastSentAt(alert.key)\n if (last !== null && alert.at - last < options.windowMs) return\n await inner.deliver(alert)\n await store.markSent(alert.key, alert.at)\n },\n }\n}\n\n/**\n * Swallow transport errors so telemetry can never fail the turn it measures.\n *\n * Use this at the LIVE lifecycle call site only. A sweep should let the error\n * surface, because a sweep that cannot deliver has done nothing at all and its\n * cron run should go red.\n */\nexport function createGuardedAlertSink(\n inner: AlertSink,\n onError: (error: unknown) => void = (e) => console.error('[turn-health] alert delivery failed', e),\n): AlertSink {\n return {\n async deliver(alert) {\n try {\n await inner.deliver(alert)\n } catch (error) {\n onError(error)\n }\n },\n }\n}\n\n\nfunction slackAlertText(alert: TurnHealthAlert): string {\n const icon = alert.severity === 'critical' ? ':rotating_light:' : ':warning:'\n return [\n `${icon} *${alert.title}*`,\n ...alert.details.map((detail) => `• ${detail}`),\n `_${new Date(alert.at).toISOString()}_`,\n ].join('\\n')\n}\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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
|
|
81
|
-
const
|
|
82
|
-
|
|
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:
|
|
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 ?
|
|
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-
|
|
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 assistantRowIdForTurn(turnKey: string): string {\n return `assistant:${turnKey}`\n}\n"],"mappings":";;;;;;;;AAIO,IAAM,kBAAkB;AAAA,EAC7B;AAAA,EAAe;AAAA,EAA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AAS,QAAQ,UAAkC;AACxD,QAAM,KAAM,UAAkD;AAC9D,SAAO,OAAO,OAAO,YAAY,KAAK,KAAK;AAC7C;AAKO,SAAS,sBAAsB,SAAyB;AAC7D,SAAO,aAAa,OAAO;AAC7B;","names":[]}
|
|
@@ -3,7 +3,7 @@ import {
|
|
|
3
3
|
PASTED_CODE_SAMPLES,
|
|
4
4
|
isEdgeBlock,
|
|
5
5
|
parseWranglerCrons
|
|
6
|
-
} from "./chunk-
|
|
6
|
+
} from "./chunk-I4MPG5T6.js";
|
|
7
7
|
import {
|
|
8
8
|
LAUNCH_BUDGETS,
|
|
9
9
|
LAUNCH_INVARIANTS,
|
|
@@ -547,4 +547,4 @@ export {
|
|
|
547
547
|
PLATFORM_LIMITS,
|
|
548
548
|
checkLimitAlarms
|
|
549
549
|
};
|
|
550
|
-
//# sourceMappingURL=chunk-
|
|
550
|
+
//# sourceMappingURL=chunk-NKANJSKB.js.map
|
|
@@ -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 (
|
|
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__ */
|
|
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-
|
|
8833
|
+
//# sourceMappingURL=chunk-QXPOBDPU.js.map
|