@tangle-network/agent-app 4.0.1 → 4.0.3
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/agent-profiles/d1.js +1 -1
- package/dist/agent-profiles/index.d.ts +2 -1
- package/dist/agent-profiles/index.js +1 -1
- package/dist/chat-routes/index.js +12 -17
- package/dist/chat-routes/index.js.map +1 -1
- package/dist/chat-routes/visible-text.d.ts +7 -0
- 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-AFMLLZWU.js → chunk-GWATTXFR.js} +3 -3
- package/dist/{chunk-AFMLLZWU.js.map → chunk-GWATTXFR.js.map} +1 -1
- 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-HES3IABJ.js → chunk-JKYCXQFI.js} +2 -2
- package/dist/{chunk-U2PTQCQ3.js → chunk-NKANJSKB.js} +2 -2
- package/dist/{chunk-5DAEU3CP.js → chunk-SJKQUTGU.js} +11 -6
- package/dist/chunk-SJKQUTGU.js.map +1 -0
- package/dist/{chunk-JSWBJBPM.js → chunk-W5YQZEE4.js} +15 -10
- package/dist/chunk-W5YQZEE4.js.map +1 -0
- package/dist/{chunk-PISTUUEZ.js → chunk-XCUT2I52.js} +25 -12
- package/dist/{chunk-PISTUUEZ.js.map → chunk-XCUT2I52.js.map} +1 -1
- package/dist/{chunk-BRQ2SC6V.js → chunk-XKVJQVOT.js} +2 -1
- package/dist/chunk-XKVJQVOT.js.map +1 -0
- 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.d.ts +1 -1
- package/dist/public-consultation/index.js +5 -3
- package/dist/public-consultation/index.js.map +1 -1
- package/dist/runtime/index.js +4 -2
- package/dist/runtime/index.js.map +1 -1
- package/dist/runtime/router-turn.d.ts +15 -0
- package/dist/runtime/router-turn.js +3 -1
- package/dist/turn-health/index.js +5 -3
- package/dist/turn-health/index.js.map +1 -1
- package/package.json +1 -1
- package/dist/chunk-5DAEU3CP.js.map +0 -1
- package/dist/chunk-BRQ2SC6V.js.map +0 -1
- package/dist/chunk-EI27JMS6.js.map +0 -1
- package/dist/chunk-JSWBJBPM.js.map +0 -1
- package/dist/chunk-LBMFQLBS.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-HES3IABJ.js.map → chunk-JKYCXQFI.js.map} +0 -0
- /package/dist/{chunk-U2PTQCQ3.js.map → chunk-NKANJSKB.js.map} +0 -0
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
import {
|
|
2
|
+
describeReason
|
|
3
|
+
} from "./chunk-EK2Y55K4.js";
|
|
4
|
+
import {
|
|
5
|
+
postSlackAlert
|
|
6
|
+
} from "./chunk-JRCZHDRG.js";
|
|
7
|
+
|
|
8
|
+
// src/turn-health/sink.ts
|
|
9
|
+
function turnAlert(input) {
|
|
10
|
+
const kinds = [...new Set(input.reasons.map((r) => r.kind))].sort();
|
|
11
|
+
return {
|
|
12
|
+
product: input.product,
|
|
13
|
+
severity: input.severity,
|
|
14
|
+
// Keyed by product + reason kinds ONLY. A blank-completion storm across
|
|
15
|
+
// 200 turns is one incident, not 200 pages.
|
|
16
|
+
key: `turn:${input.product}:${kinds.join("+")}`,
|
|
17
|
+
title: `${input.product}: turn completed but delivered nothing (${kinds.join(", ")})`,
|
|
18
|
+
details: input.reasons.map(describeReason),
|
|
19
|
+
data: {
|
|
20
|
+
kinds,
|
|
21
|
+
...input.threadId ? { threadId: input.threadId } : {},
|
|
22
|
+
...input.turnId ? { turnId: input.turnId } : {},
|
|
23
|
+
...input.model ? { model: input.model } : {}
|
|
24
|
+
},
|
|
25
|
+
at: input.at ?? Date.now()
|
|
26
|
+
};
|
|
27
|
+
}
|
|
28
|
+
function createWebhookAlertSink(options) {
|
|
29
|
+
const fetchImpl = options.fetchImpl ?? globalThis.fetch;
|
|
30
|
+
return {
|
|
31
|
+
async deliver(alert) {
|
|
32
|
+
const text = slackAlertText(alert);
|
|
33
|
+
const response = await fetchImpl(options.webhookUrl, {
|
|
34
|
+
method: "POST",
|
|
35
|
+
headers: { "Content-Type": "application/json" },
|
|
36
|
+
body: JSON.stringify({ text })
|
|
37
|
+
});
|
|
38
|
+
if (!response.ok) {
|
|
39
|
+
throw new Error(`alert webhook responded ${response.status}`);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
function createSlackBotAlertSink(options) {
|
|
45
|
+
const fetchImpl = options.fetchImpl ?? globalThis.fetch;
|
|
46
|
+
return {
|
|
47
|
+
async deliver(alert) {
|
|
48
|
+
const text = slackAlertText(alert);
|
|
49
|
+
const outcome = await postSlackAlert({
|
|
50
|
+
token: options.botToken,
|
|
51
|
+
channel: options.channel,
|
|
52
|
+
text,
|
|
53
|
+
attempts: 1,
|
|
54
|
+
// Preserve the public minimal-fetch seam without owning a second Slack
|
|
55
|
+
// request builder or response parser. Real callers use native fetch.
|
|
56
|
+
fetchImpl: options.fetchImpl ? (async (url, init) => {
|
|
57
|
+
const response = await fetchImpl(String(url), {
|
|
58
|
+
method: init?.method ?? "POST",
|
|
59
|
+
headers: Object.fromEntries(new Headers(init?.headers)),
|
|
60
|
+
body: String(init?.body ?? "")
|
|
61
|
+
});
|
|
62
|
+
return new Response(await response.text?.() ?? "", { status: response.status });
|
|
63
|
+
}) : void 0
|
|
64
|
+
});
|
|
65
|
+
if (!outcome.delivered) throw new Error(`Slack alert failed (${outcome.reason}): ${outcome.detail}`);
|
|
66
|
+
}
|
|
67
|
+
};
|
|
68
|
+
}
|
|
69
|
+
function createConsoleAlertSink(log = console.error) {
|
|
70
|
+
return {
|
|
71
|
+
async deliver(alert) {
|
|
72
|
+
log(
|
|
73
|
+
`[turn-health] ${alert.severity.toUpperCase()} ${alert.title} :: ${alert.details.join(" | ")}`
|
|
74
|
+
);
|
|
75
|
+
}
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
function createMultiAlertSink(sinks) {
|
|
79
|
+
return {
|
|
80
|
+
async deliver(alert) {
|
|
81
|
+
const settled = await Promise.allSettled(sinks.map((s) => s.deliver(alert)));
|
|
82
|
+
const failures = settled.filter((r) => r.status === "rejected");
|
|
83
|
+
if (failures.length === sinks.length && sinks.length > 0) {
|
|
84
|
+
throw new Error("every alert sink failed");
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
function createMemoryThrottleStore() {
|
|
90
|
+
const seen = /* @__PURE__ */ new Map();
|
|
91
|
+
return {
|
|
92
|
+
async lastSentAt(key) {
|
|
93
|
+
return seen.get(key) ?? null;
|
|
94
|
+
},
|
|
95
|
+
async markSent(key, at) {
|
|
96
|
+
seen.set(key, at);
|
|
97
|
+
}
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
function createThrottledAlertSink(inner, options) {
|
|
101
|
+
const store = options.store ?? createMemoryThrottleStore();
|
|
102
|
+
return {
|
|
103
|
+
async deliver(alert) {
|
|
104
|
+
const last = await store.lastSentAt(alert.key);
|
|
105
|
+
if (last !== null && alert.at - last < options.windowMs) return;
|
|
106
|
+
await inner.deliver(alert);
|
|
107
|
+
await store.markSent(alert.key, alert.at);
|
|
108
|
+
}
|
|
109
|
+
};
|
|
110
|
+
}
|
|
111
|
+
function createGuardedAlertSink(inner, onError = (e) => console.error("[turn-health] alert delivery failed", e)) {
|
|
112
|
+
return {
|
|
113
|
+
async deliver(alert) {
|
|
114
|
+
try {
|
|
115
|
+
await inner.deliver(alert);
|
|
116
|
+
} catch (error) {
|
|
117
|
+
onError(error);
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
};
|
|
121
|
+
}
|
|
122
|
+
function slackAlertText(alert) {
|
|
123
|
+
const icon = alert.severity === "critical" ? ":rotating_light:" : ":warning:";
|
|
124
|
+
return [
|
|
125
|
+
`${icon} *${alert.title}*`,
|
|
126
|
+
...alert.details.map((detail) => `\u2022 ${detail}`),
|
|
127
|
+
`_${new Date(alert.at).toISOString()}_`
|
|
128
|
+
].join("\n");
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
export {
|
|
132
|
+
turnAlert,
|
|
133
|
+
createWebhookAlertSink,
|
|
134
|
+
createSlackBotAlertSink,
|
|
135
|
+
createConsoleAlertSink,
|
|
136
|
+
createMultiAlertSink,
|
|
137
|
+
createMemoryThrottleStore,
|
|
138
|
+
createThrottledAlertSink,
|
|
139
|
+
createGuardedAlertSink
|
|
140
|
+
};
|
|
141
|
+
//# sourceMappingURL=chunk-IJ6B5ZPU.js.map
|
|
@@ -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}\n"],"mappings":";;;;;;;;AAwCO,SAAS,UAAU,OAQN;AAClB,QAAM,QAAQ,CAAC,GAAG,IAAI,IAAI,MAAM,QAAQ,IAAI,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC,EAAE,KAAK;AAClE,SAAO;AAAA,IACL,SAAS,MAAM;AAAA,IACf,UAAU,MAAM;AAAA;AAAA;AAAA,IAGhB,KAAK,QAAQ,MAAM,OAAO,IAAI,MAAM,KAAK,GAAG,CAAC;AAAA,IAC7C,OAAO,GAAG,MAAM,OAAO,2CAA2C,MAAM,KAAK,IAAI,CAAC;AAAA,IAClF,SAAS,MAAM,QAAQ,IAAI,cAAc;AAAA,IACzC,MAAM;AAAA,MACJ;AAAA,MACA,GAAI,MAAM,WAAW,EAAE,UAAU,MAAM,SAAS,IAAI,CAAC;AAAA,MACrD,GAAI,MAAM,SAAS,EAAE,QAAQ,MAAM,OAAO,IAAI,CAAC;AAAA,MAC/C,GAAI,MAAM,QAAQ,EAAE,OAAO,MAAM,MAAM,IAAI,CAAC;AAAA,IAC9C;AAAA,IACA,IAAI,MAAM,MAAM,KAAK,IAAI;AAAA,EAC3B;AACF;AAmBO,SAAS,uBAAuB,SAGzB;AACZ,QAAM,YAAY,QAAQ,aAAc,WAAW;AAC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;AAAA,MACf;AAAA,IACF;AAAA,EACF;AACF;AAGA,SAAS,eAAe,OAAgC;AACtD,QAAM,OAAO,MAAM,aAAa,aAAa,qBAAqB;AAClE,SAAO;AAAA,IACL,GAAG,IAAI,KAAK,MAAM,KAAK;AAAA,IACvB,GAAG,MAAM,QAAQ,IAAI,CAAC,WAAW,UAAK,MAAM,EAAE;AAAA,IAC9C,IAAI,IAAI,KAAK,MAAM,EAAE,EAAE,YAAY,CAAC;AAAA,EACtC,EAAE,KAAK,IAAI;AACb;","names":[]}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import {
|
|
2
2
|
TURN_USAGE_KEYS,
|
|
3
3
|
addStepFinishUsage
|
|
4
|
-
} from "./chunk-
|
|
4
|
+
} from "./chunk-SJKQUTGU.js";
|
|
5
5
|
import {
|
|
6
6
|
asRecord,
|
|
7
7
|
asString,
|
|
@@ -446,4 +446,4 @@ export {
|
|
|
446
446
|
TOOL_ABORTED_ERROR,
|
|
447
447
|
observeNativeCompletion
|
|
448
448
|
};
|
|
449
|
-
//# sourceMappingURL=chunk-
|
|
449
|
+
//# sourceMappingURL=chunk-JKYCXQFI.js.map
|
|
@@ -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
|
|
@@ -41,6 +41,14 @@ function addStepFinishUsage(part, usage) {
|
|
|
41
41
|
if (Number.isFinite(cost)) usage.harnessCostUsd = (usage.harnessCostUsd ?? 0) + cost;
|
|
42
42
|
}
|
|
43
43
|
|
|
44
|
+
// src/chat-routes/visible-text.ts
|
|
45
|
+
function transformVisibleTextParts(parts, transform) {
|
|
46
|
+
return Promise.all(parts.map(async (part) => {
|
|
47
|
+
const type = String(part.type ?? "");
|
|
48
|
+
return type === "text" || type === "reasoning" ? { ...part, text: await transform(String(part.text ?? "")) } : part;
|
|
49
|
+
}));
|
|
50
|
+
}
|
|
51
|
+
|
|
44
52
|
// src/chat-routes/draft-persistence.ts
|
|
45
53
|
var CONTENT_EVENT_TYPES = /* @__PURE__ */ new Set([
|
|
46
54
|
"text",
|
|
@@ -113,11 +121,7 @@ function createAssistantDraftWriter(options) {
|
|
|
113
121
|
let parts;
|
|
114
122
|
if (snapshot.parts) {
|
|
115
123
|
const capped = snapshot.parts.map((part) => capDraftToolOutput(part, maxToolOutput));
|
|
116
|
-
const redacted = transform ? await
|
|
117
|
-
capped.map(
|
|
118
|
-
async (part) => String(part.type ?? "") === "text" ? { ...part, text: await transform(String(part.text ?? "")) } : part
|
|
119
|
-
)
|
|
120
|
-
) : capped;
|
|
124
|
+
const redacted = transform ? await transformVisibleTextParts(capped, transform) : capped;
|
|
121
125
|
parts = toChatMessageParts(redacted);
|
|
122
126
|
}
|
|
123
127
|
const usage = snapshot.usage ?? {};
|
|
@@ -227,10 +231,11 @@ export {
|
|
|
227
231
|
TURN_USAGE_KEYS,
|
|
228
232
|
measuredUsage,
|
|
229
233
|
addStepFinishUsage,
|
|
234
|
+
transformVisibleTextParts,
|
|
230
235
|
isDraftContentEvent,
|
|
231
236
|
createAssistantDraftWriter,
|
|
232
237
|
storeSupportsDraftPersistence,
|
|
233
238
|
rowIdOf,
|
|
234
239
|
assistantRowIdForTurn
|
|
235
240
|
};
|
|
236
|
-
//# sourceMappingURL=chunk-
|
|
241
|
+
//# sourceMappingURL=chunk-SJKQUTGU.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 (bytes). A tool returning\n * a large blob would otherwise be rewritten in full on every draft. The\n * final write always carries the untruncated value. Default 32768 (32 KiB);\n * 0 disables truncation. */\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\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. The value is replaced by a\n * truncated string plus a marker, so a reader can tell a clipped draft from a\n * real short output; the final write restores the 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 || output === null) return part\n const serialized = typeof output === 'string' ? output : safeStringify(output)\n if (serialized.length <= 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: `${serialized.slice(0, maxBytes)}…[draft-truncated ${serialized.length - maxBytes} chars]`,\n metadata: { ...metadata, draftTruncated: true },\n },\n }\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 ? safeStringify(values.parts).length : 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,EAAgB;AAAA,EAAmB;AAAA,EAAmB;AAAA,EAAoB;AAAA,EAAW;AACtG;AAGO,SAAS,cAAc,OAAiD;AAC7E,QAAM,WAA0B,CAAC;AACjC,aAAW,OAAO,gBAAiB,KAAI,QAAQ,GAAG,MAAM,OAAW,UAAS,GAAG,IAAI,MAAM,GAAG;AAC5F,SAAO;AACT;AAGO,SAAS,mBAAmB,MAAkB,OAA4B;AAC/E,QAAM,SAAS,SAAS,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A,UACnB,OAAO,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;AAAA,QACxD,CAAC;AAAA,MACH;AAAA,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":[]}
|
|
@@ -41,8 +41,9 @@ import {
|
|
|
41
41
|
createAssistantDraftWriter,
|
|
42
42
|
measuredUsage,
|
|
43
43
|
rowIdOf,
|
|
44
|
-
storeSupportsDraftPersistence
|
|
45
|
-
|
|
44
|
+
storeSupportsDraftPersistence,
|
|
45
|
+
transformVisibleTextParts
|
|
46
|
+
} from "./chunk-SJKQUTGU.js";
|
|
46
47
|
import {
|
|
47
48
|
normalizeClientTurnId,
|
|
48
49
|
resolveChatTurn
|
|
@@ -117,8 +118,9 @@ import {
|
|
|
117
118
|
} from "./chunk-XELWWXJJ.js";
|
|
118
119
|
import {
|
|
119
120
|
composeRouterTurnPromptSections,
|
|
121
|
+
narratesBefore,
|
|
120
122
|
runRouterTurn
|
|
121
|
-
} from "./chunk-
|
|
123
|
+
} from "./chunk-XCUT2I52.js";
|
|
122
124
|
import {
|
|
123
125
|
createIntelligenceTurnTraceSink,
|
|
124
126
|
createTurnTrace,
|
|
@@ -577,6 +579,7 @@ function createRouterTurnProducer(options) {
|
|
|
577
579
|
const parts = [];
|
|
578
580
|
const toolParts = /* @__PURE__ */ new Map();
|
|
579
581
|
let textPart = null;
|
|
582
|
+
const narration = /* @__PURE__ */ new Set();
|
|
580
583
|
let textSegment = 0;
|
|
581
584
|
let reasoningPart = null;
|
|
582
585
|
const reasoningClock = createReasoningClock();
|
|
@@ -621,6 +624,8 @@ function createRouterTurnProducer(options) {
|
|
|
621
624
|
reasoningPart = null;
|
|
622
625
|
reasoningClock.settle(event.startedAt);
|
|
623
626
|
if (event.status === "running") {
|
|
627
|
+
if (textPart && narratesBefore(options.tools?.find((tool) => tool.name === event.toolName))) narration.add(textPart);
|
|
628
|
+
textPart = null;
|
|
624
629
|
const part = {
|
|
625
630
|
type: "tool",
|
|
626
631
|
id: event.callId,
|
|
@@ -673,9 +678,13 @@ function createRouterTurnProducer(options) {
|
|
|
673
678
|
result.failure = { code: "turn_deadline", message: "The reply was stopped before it finished." };
|
|
674
679
|
}
|
|
675
680
|
outcome = result;
|
|
681
|
+
if (parts.some((part) => part.type === "text" && !narration.has(part) && String(part.text).trim())) {
|
|
682
|
+
for (const part of narration) part.type = "reasoning";
|
|
683
|
+
}
|
|
676
684
|
const final = await options.onOutcome?.(result);
|
|
677
685
|
if (final && final.trailingText) {
|
|
678
686
|
result.text += final.trailingText;
|
|
687
|
+
result.answer += final.trailingText;
|
|
679
688
|
parts.push({ type: "text", text: final.trailingText });
|
|
680
689
|
push({ type: "text", text: final.trailingText });
|
|
681
690
|
}
|
|
@@ -742,7 +751,7 @@ function createRouterTurnProducer(options) {
|
|
|
742
751
|
stream: events,
|
|
743
752
|
// The route tracks this continuation even when failure is visible before a pending key arrives.
|
|
744
753
|
cleanup: run.then(retire, retire),
|
|
745
|
-
finalText: () => outcome?.
|
|
754
|
+
finalText: () => outcome?.answer ?? "",
|
|
746
755
|
assistantParts: snapshot,
|
|
747
756
|
draftParts: snapshot,
|
|
748
757
|
usage,
|
|
@@ -3419,11 +3428,7 @@ function createTurnEngine(identity, ctx, log, state, dispatched, produceArgs, tr
|
|
|
3419
3428
|
return;
|
|
3420
3429
|
}
|
|
3421
3430
|
const rawParts = state.producer?.assistantParts ? state.producer.assistantParts() : void 0;
|
|
3422
|
-
const projected = rawParts && options.transformFinalText ? await
|
|
3423
|
-
rawParts.map(
|
|
3424
|
-
async (part) => String(part.type ?? "") === "text" ? { ...part, text: await options.transformFinalText(String(part.text ?? "")) } : part
|
|
3425
|
-
)
|
|
3426
|
-
) : rawParts;
|
|
3431
|
+
const projected = rawParts && options.transformFinalText ? await transformVisibleTextParts(rawParts, options.transformFinalText) : rawParts;
|
|
3427
3432
|
const parts = projected ? toChatMessageParts(projected) : void 0;
|
|
3428
3433
|
if (!finalText.trim() && (!parts || parts.length === 0)) {
|
|
3429
3434
|
await state.draft?.discard();
|
|
@@ -4227,4 +4232,4 @@ export {
|
|
|
4227
4232
|
createChatTurnRoutes,
|
|
4228
4233
|
streamChatRouteAsSandboxEvents
|
|
4229
4234
|
};
|
|
4230
|
-
//# sourceMappingURL=chunk-
|
|
4235
|
+
//# sourceMappingURL=chunk-W5YQZEE4.js.map
|