@tangle-network/agent-app 0.62.3 → 0.63.0

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.
Files changed (136) hide show
  1. package/README.md +1 -1
  2. package/dist/agent-profiles/d1.js +1 -1
  3. package/dist/agent-profiles/index.d.ts +4 -1
  4. package/dist/agent-profiles/index.js +1 -1
  5. package/dist/app-auth/index.js +2 -2
  6. package/dist/assistant/index.js +7 -7
  7. package/dist/chat-react/index.js +3 -3
  8. package/dist/chat-routes/cancellation.d.ts +61 -0
  9. package/dist/chat-routes/dispatch-first.d.ts +14 -25
  10. package/dist/chat-routes/early-turn-work.d.ts +10 -0
  11. package/dist/chat-routes/hybrid-producer.d.ts +4 -3
  12. package/dist/chat-routes/index.d.ts +2 -1
  13. package/dist/chat-routes/index.js +86 -1874
  14. package/dist/chat-routes/index.js.map +1 -1
  15. package/dist/chat-routes/native-turn-timing.d.ts +15 -0
  16. package/dist/chat-routes/producer-stream.d.ts +5 -0
  17. package/dist/chat-routes/route-producer.d.ts +3 -0
  18. package/dist/chat-routes/route-storage.d.ts +7 -0
  19. package/dist/chat-routes/router-producer.d.ts +31 -5
  20. package/dist/chat-routes/turn-admission.d.ts +2 -1
  21. package/dist/chat-routes/turn-execution.d.ts +6 -11
  22. package/dist/chat-routes/turn-ownership.d.ts +22 -0
  23. package/dist/chat-routes/turn-route-contracts.d.ts +112 -105
  24. package/dist/chat-routes/turn-routes.d.ts +4 -4
  25. package/dist/chat-routes/wire.d.ts +0 -7
  26. package/dist/chat-store/index.d.ts +1 -1
  27. package/dist/chat-store/index.js +21 -3
  28. package/dist/chat-store/index.js.map +1 -1
  29. package/dist/chat-store/schema.d.ts +3 -2
  30. package/dist/chat-store/store.d.ts +8 -0
  31. package/dist/{chunk-GIEUZBQQ.js → chunk-4CALWPN5.js} +3 -7
  32. package/dist/chunk-4CALWPN5.js.map +1 -0
  33. package/dist/chunk-4DBHC63F.js +54 -0
  34. package/dist/chunk-4DBHC63F.js.map +1 -0
  35. package/dist/{chunk-G7M2C72Q.js → chunk-5TSRFF5W.js} +1 -1
  36. package/dist/chunk-5TSRFF5W.js.map +1 -0
  37. package/dist/chunk-A2NQMVMF.js +485 -0
  38. package/dist/chunk-A2NQMVMF.js.map +1 -0
  39. package/dist/{chunk-PCAY23GS.js → chunk-AVBNS64P.js} +172 -2
  40. package/dist/chunk-AVBNS64P.js.map +1 -0
  41. package/dist/{chunk-4P5NFBWX.js → chunk-BI5AZAOO.js} +4 -4
  42. package/dist/chunk-BV3VZEKB.js +483 -0
  43. package/dist/chunk-BV3VZEKB.js.map +1 -0
  44. package/dist/{chunk-UW2DKTEM.js → chunk-IDG2XR5O.js} +20 -10
  45. package/dist/chunk-IDG2XR5O.js.map +1 -0
  46. package/dist/{chunk-KS4I7KVC.js → chunk-JRTWTADT.js} +184 -123
  47. package/dist/chunk-JRTWTADT.js.map +1 -0
  48. package/dist/chunk-KG2Y44XT.js +1 -0
  49. package/dist/chunk-KG2Y44XT.js.map +1 -0
  50. package/dist/chunk-MM3GOLHO.js +3365 -0
  51. package/dist/chunk-MM3GOLHO.js.map +1 -0
  52. package/dist/chunk-N6URQ6DM.js +225 -0
  53. package/dist/chunk-N6URQ6DM.js.map +1 -0
  54. package/dist/{chunk-ISRPOPMM.js → chunk-ND5XWLRU.js} +21 -18
  55. package/dist/chunk-ND5XWLRU.js.map +1 -0
  56. package/dist/{chunk-IUVDR3KJ.js → chunk-NHVSO47Q.js} +2 -2
  57. package/dist/{chunk-FAXSYC2C.js → chunk-RZLCBWGG.js} +2 -2
  58. package/dist/{chunk-MRZP65DZ.js → chunk-SRWQCWLR.js} +14 -3
  59. package/dist/chunk-SRWQCWLR.js.map +1 -0
  60. package/dist/{chunk-JRW6LCIA.js → chunk-V6YGLAQC.js} +2 -2
  61. package/dist/{chunk-54YIL7WM.js → chunk-WPPDNS63.js} +4 -4
  62. package/dist/{chunk-CQZVJVME.js → chunk-YCMVNXAX.js} +2 -2
  63. package/dist/design-canvas/index.js +3 -3
  64. package/dist/openui/index.js +3 -3
  65. package/dist/operator/index.js +2 -2
  66. package/dist/platform/billable-turn-admission.d.ts +13 -9
  67. package/dist/platform/delegated-keys.d.ts +4 -3
  68. package/dist/platform/delegated-turn-keys.d.ts +17 -6
  69. package/dist/platform/index.js +80 -23
  70. package/dist/platform/index.js.map +1 -1
  71. package/dist/preset-cloudflare/index.d.ts +2 -0
  72. package/dist/preset-cloudflare/index.js +344 -0
  73. package/dist/preset-cloudflare/index.js.map +1 -1
  74. package/dist/preset-cloudflare/native-completion-owner.d.ts +90 -0
  75. package/dist/preset-cloudflare/native-completion-store.d.ts +56 -0
  76. package/dist/preset-cloudflare/native-completion-workflow.d.ts +10 -0
  77. package/dist/public-consultation/index.js +28 -7
  78. package/dist/public-consultation/index.js.map +1 -1
  79. package/dist/rollout/d1.d.ts +103 -3
  80. package/dist/rollout/d1.js +152 -5
  81. package/dist/rollout/d1.js.map +1 -1
  82. package/dist/runtime/index.js +3 -4
  83. package/dist/runtime/index.js.map +1 -1
  84. package/dist/runtime/router-turn.d.ts +4 -0
  85. package/dist/runtime/router-turn.js +2 -3
  86. package/dist/sandbox/index.js +3 -4
  87. package/dist/sandbox/sandbox-run-tool.d.ts +5 -0
  88. package/dist/sequences/index.js +5 -5
  89. package/dist/signoff/cli.js +15 -3
  90. package/dist/signoff/cli.js.map +1 -1
  91. package/dist/signoff/config.d.ts +3 -1
  92. package/dist/signoff/index.d.ts +2 -1
  93. package/dist/signoff/index.js +3 -1
  94. package/dist/signoff/phases.d.ts +3 -0
  95. package/dist/signoff/proof.js +3 -0
  96. package/dist/signoff/proof.js.map +1 -1
  97. package/dist/signoff/run.d.ts +3 -1
  98. package/dist/signoff/types.d.ts +13 -0
  99. package/dist/skills-placement/box.js +5 -5
  100. package/dist/skills-placement/index.js +2 -2
  101. package/dist/tools/index.js +1 -1
  102. package/dist/turn-stream/adapters.d.ts +10 -4
  103. package/dist/turn-stream/index.js +33 -356
  104. package/dist/turn-stream/index.js.map +1 -1
  105. package/dist/turn-trace/index.d.ts +1 -0
  106. package/dist/turn-trace/index.js +4 -5
  107. package/dist/turn-trace/phase-timing.d.ts +20 -0
  108. package/dist/turn-trace/recorder.d.ts +3 -0
  109. package/dist/turn-trace/turn-facts.d.ts +17 -0
  110. package/dist/web-react/agent-profile-editor.js +1 -1
  111. package/dist/web-react/chat-stream.d.ts +0 -7
  112. package/dist/web-react/index.js +7 -9
  113. package/dist/work-product/index.js +7 -7
  114. package/package.json +1 -1
  115. package/dist/chat-routes/minted-thread.d.ts +0 -63
  116. package/dist/chunk-6R73V3Y5.js +0 -17
  117. package/dist/chunk-6R73V3Y5.js.map +0 -1
  118. package/dist/chunk-CCVWR33L.js +0 -99
  119. package/dist/chunk-CCVWR33L.js.map +0 -1
  120. package/dist/chunk-EFQUAWWF.js +0 -1749
  121. package/dist/chunk-EFQUAWWF.js.map +0 -1
  122. package/dist/chunk-G7M2C72Q.js.map +0 -1
  123. package/dist/chunk-GIEUZBQQ.js.map +0 -1
  124. package/dist/chunk-ISRPOPMM.js.map +0 -1
  125. package/dist/chunk-KS4I7KVC.js.map +0 -1
  126. package/dist/chunk-MRZP65DZ.js.map +0 -1
  127. package/dist/chunk-PCAY23GS.js.map +0 -1
  128. package/dist/chunk-UW2DKTEM.js.map +0 -1
  129. package/dist/chunk-VK3F4N4U.js +0 -133
  130. package/dist/chunk-VK3F4N4U.js.map +0 -1
  131. /package/dist/{chunk-4P5NFBWX.js.map → chunk-BI5AZAOO.js.map} +0 -0
  132. /package/dist/{chunk-IUVDR3KJ.js.map → chunk-NHVSO47Q.js.map} +0 -0
  133. /package/dist/{chunk-FAXSYC2C.js.map → chunk-RZLCBWGG.js.map} +0 -0
  134. /package/dist/{chunk-JRW6LCIA.js.map → chunk-V6YGLAQC.js.map} +0 -0
  135. /package/dist/{chunk-54YIL7WM.js.map → chunk-WPPDNS63.js.map} +0 -0
  136. /package/dist/{chunk-CQZVJVME.js.map → chunk-YCMVNXAX.js.map} +0 -0
@@ -0,0 +1,225 @@
1
+ import {
2
+ toChatMessageParts
3
+ } from "./chunk-RZLCBWGG.js";
4
+ import {
5
+ asRecord
6
+ } from "./chunk-VUBJZEZB.js";
7
+
8
+ // src/chat-routes/draft-persistence.ts
9
+ var CONTENT_EVENT_TYPES = /* @__PURE__ */ new Set([
10
+ "text",
11
+ "reasoning",
12
+ "tool_call",
13
+ "tool_result",
14
+ "usage",
15
+ "notice",
16
+ "error",
17
+ "file",
18
+ "interaction",
19
+ "interaction.cancel",
20
+ "plan.submitted",
21
+ "message.part.updated"
22
+ ]);
23
+ var DEFAULT_INTERVAL_MS = 2e3;
24
+ var DEFAULT_BACKOFF_BYTES = 262144;
25
+ var DEFAULT_MAX_DRAFT_TOOL_OUTPUT_BYTES = 32768;
26
+ function isDraftContentEvent(event) {
27
+ return typeof event?.type === "string" && CONTENT_EVENT_TYPES.has(event.type);
28
+ }
29
+ function capDraftToolOutput(part, maxBytes) {
30
+ if (maxBytes <= 0) return part;
31
+ if (String(part.type ?? "") !== "tool") return part;
32
+ const state = part.state;
33
+ if (!state || typeof state !== "object") return part;
34
+ const record = state;
35
+ const output = record.output;
36
+ if (output === void 0 || output === null) return part;
37
+ const serialized = typeof output === "string" ? output : safeStringify(output);
38
+ if (serialized.length <= maxBytes) return part;
39
+ const metadata = record.metadata && typeof record.metadata === "object" ? record.metadata : {};
40
+ return {
41
+ ...part,
42
+ state: {
43
+ ...record,
44
+ output: `${serialized.slice(0, maxBytes)}\u2026[draft-truncated ${serialized.length - maxBytes} chars]`,
45
+ metadata: { ...metadata, draftTruncated: true }
46
+ }
47
+ };
48
+ }
49
+ function safeStringify(value) {
50
+ try {
51
+ return JSON.stringify(value) ?? "";
52
+ } catch {
53
+ return String(value);
54
+ }
55
+ }
56
+ function createAssistantDraftWriter(options) {
57
+ const log = options.log ?? (() => {
58
+ });
59
+ const baseIntervalMs = options.intervalMs ?? DEFAULT_INTERVAL_MS;
60
+ const backoffBytes = options.backoffBytes ?? DEFAULT_BACKOFF_BYTES;
61
+ const maxToolOutput = options.maxDraftToolOutputBytes ?? DEFAULT_MAX_DRAFT_TOOL_OUTPUT_BYTES;
62
+ let dirty = false;
63
+ let closed = false;
64
+ let inFlight;
65
+ let lastWriteAt = 0;
66
+ let lastBlobBytes = 0;
67
+ let rowId;
68
+ let writes = 0;
69
+ function currentIntervalMs() {
70
+ if (lastBlobBytes >= backoffBytes * 10) return baseIntervalMs * 5;
71
+ if (lastBlobBytes >= backoffBytes) return Math.round(baseIntervalMs * 2.5);
72
+ return baseIntervalMs;
73
+ }
74
+ async function projectValues(snapshot) {
75
+ const transform = options.transformText;
76
+ const content = transform ? await transform(snapshot.content) : snapshot.content;
77
+ let parts;
78
+ if (snapshot.parts) {
79
+ const capped = snapshot.parts.map((part) => capDraftToolOutput(part, maxToolOutput));
80
+ const redacted = transform ? await Promise.all(
81
+ capped.map(
82
+ async (part) => String(part.type ?? "") === "text" ? { ...part, text: await transform(String(part.text ?? "")) } : part
83
+ )
84
+ ) : capped;
85
+ parts = toChatMessageParts(redacted);
86
+ }
87
+ const usage = snapshot.usage ?? {};
88
+ return {
89
+ content,
90
+ ...parts && parts.length > 0 ? { parts } : {},
91
+ ...snapshot.model ? { model: snapshot.model } : {},
92
+ ...usage.inputTokens !== void 0 ? { inputTokens: usage.inputTokens } : {},
93
+ ...usage.outputTokens !== void 0 ? { outputTokens: usage.outputTokens } : {},
94
+ ...usage.reasoningTokens !== void 0 ? { reasoningTokens: usage.reasoningTokens } : {},
95
+ ...usage.cacheReadTokens !== void 0 ? { cacheReadTokens: usage.cacheReadTokens } : {},
96
+ ...usage.cacheWriteTokens !== void 0 ? { cacheWriteTokens: usage.cacheWriteTokens } : {},
97
+ ...usage.costUsd !== void 0 ? { costUsd: usage.costUsd } : {}
98
+ };
99
+ }
100
+ async function adoptRow() {
101
+ if (rowId) return rowId;
102
+ const existing = (await options.store.listMessages(options.threadId)).find(
103
+ (message) => message.id === options.messageId
104
+ );
105
+ if (existing) rowId = existing.id;
106
+ return rowId;
107
+ }
108
+ async function writeOnce(values) {
109
+ if (await adoptRow()) {
110
+ await options.store.updateMessage(rowId, values);
111
+ writes += 1;
112
+ return;
113
+ }
114
+ const inserted = await options.store.appendMessage({
115
+ id: options.messageId,
116
+ threadId: options.threadId,
117
+ role: "assistant",
118
+ ...values
119
+ });
120
+ rowId = rowIdOf(inserted) ?? options.messageId;
121
+ writes += 1;
122
+ }
123
+ function trigger() {
124
+ if (closed) return;
125
+ if (!dirty) return;
126
+ if (inFlight) return;
127
+ const now = Date.now();
128
+ if (lastWriteAt !== 0 && now - lastWriteAt < currentIntervalMs()) return;
129
+ const snapshot = options.snapshot();
130
+ if (!snapshot) return;
131
+ if (!snapshot.content && (!snapshot.parts || snapshot.parts.length === 0)) return;
132
+ dirty = false;
133
+ lastWriteAt = now;
134
+ inFlight = (async () => {
135
+ try {
136
+ const values = await projectValues(snapshot);
137
+ lastBlobBytes = values.parts ? safeStringify(values.parts).length : 0;
138
+ await writeOnce(values);
139
+ } catch (err) {
140
+ log("[chat-routes] incremental assistant persistence failed", {
141
+ messageId: options.messageId,
142
+ error: err instanceof Error ? err.message : String(err)
143
+ });
144
+ } finally {
145
+ inFlight = void 0;
146
+ if (dirty && !closed) trigger();
147
+ }
148
+ })();
149
+ }
150
+ return {
151
+ notify(event) {
152
+ if (closed) return;
153
+ if (isDraftContentEvent(event)) dirty = true;
154
+ trigger();
155
+ },
156
+ async close() {
157
+ closed = true;
158
+ if (inFlight) await inFlight;
159
+ },
160
+ async finalize(values) {
161
+ closed = true;
162
+ if (inFlight) await inFlight;
163
+ await writeOnce(values);
164
+ },
165
+ rowId: () => rowId,
166
+ async discard() {
167
+ closed = true;
168
+ if (inFlight) await inFlight;
169
+ if (!options.store.deleteMessage) return;
170
+ try {
171
+ if (!await adoptRow()) return;
172
+ await options.store.deleteMessage(rowId);
173
+ rowId = void 0;
174
+ } catch (err) {
175
+ log("[chat-routes] draft assistant row discard failed", {
176
+ messageId: options.messageId,
177
+ error: err instanceof Error ? err.message : String(err)
178
+ });
179
+ }
180
+ },
181
+ writeCount: () => writes
182
+ };
183
+ }
184
+ function storeSupportsDraftPersistence(store) {
185
+ return typeof store.updateMessage === "function";
186
+ }
187
+ function rowIdOf(inserted) {
188
+ const id = inserted?.id;
189
+ return typeof id === "string" && id ? id : null;
190
+ }
191
+ function assistantRowIdForTurn(turnKey) {
192
+ return `assistant:${turnKey}`;
193
+ }
194
+
195
+ // src/chat-routes/sandbox-turn-usage.ts
196
+ function addStepFinishUsage(part, usage) {
197
+ const tokens = asRecord(part.tokens);
198
+ if (tokens) {
199
+ const cache = asRecord(tokens.cache);
200
+ const add = (current, value) => {
201
+ const n = Number(value);
202
+ if (!Number.isFinite(n)) return current;
203
+ return (current ?? 0) + n;
204
+ };
205
+ usage.inputTokens = add(usage.inputTokens, tokens.input);
206
+ usage.outputTokens = add(usage.outputTokens, tokens.output);
207
+ usage.reasoningTokens = add(usage.reasoningTokens, tokens.reasoning);
208
+ if (cache) {
209
+ usage.cacheReadTokens = add(usage.cacheReadTokens, cache.read);
210
+ usage.cacheWriteTokens = add(usage.cacheWriteTokens, cache.write);
211
+ }
212
+ }
213
+ const cost = Number(part.cost);
214
+ if (Number.isFinite(cost)) usage.costUsd = (usage.costUsd ?? 0) + cost;
215
+ }
216
+
217
+ export {
218
+ isDraftContentEvent,
219
+ createAssistantDraftWriter,
220
+ storeSupportsDraftPersistence,
221
+ rowIdOf,
222
+ assistantRowIdForTurn,
223
+ addStepFinishUsage
224
+ };
225
+ //# sourceMappingURL=chunk-N6URQ6DM.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/chat-routes/draft-persistence.ts","../src/chat-routes/sandbox-turn-usage.ts"],"sourcesContent":["/**\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'\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\n ? await Promise.all(\n capped.map(async (part) =>\n String((part as { type?: unknown }).type ?? '') === 'text'\n ? { ...part, text: await transform(String((part as { text?: unknown }).text ?? '')) }\n : part,\n ),\n )\n : 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 ...(usage.inputTokens !== undefined ? { inputTokens: usage.inputTokens } : {}),\n ...(usage.outputTokens !== undefined ? { outputTokens: usage.outputTokens } : {}),\n ...(usage.reasoningTokens !== undefined ? { reasoningTokens: usage.reasoningTokens } : {}),\n ...(usage.cacheReadTokens !== undefined ? { cacheReadTokens: usage.cacheReadTokens } : {}),\n ...(usage.cacheWriteTokens !== undefined ? { cacheWriteTokens: usage.cacheWriteTokens } : {}),\n ...(usage.costUsd !== undefined ? { costUsd: usage.costUsd } : {}),\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","import { asRecord, type JsonRecord } from '../stream/index'\nimport type { ChatTurnUsage } from './turn-routes'\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.costUsd = (usage.costUsd ?? 0) + cost\n}\n"],"mappings":";;;;;;;;AAoKA,IAAM,sBAA2C,oBAAI,IAAI;AAAA,EACvD;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AAED,IAAM,sBAAsB;AAC5B,IAAM,wBAAwB;AAC9B,IAAM,sCAAsC;AAGrC,SAAS,oBAAoB,OAAoC;AACtE,SAAO,OAAO,OAAO,SAAS,YAAY,oBAAoB,IAAI,MAAM,IAAI;AAC9E;AAKA,SAAS,mBAAmB,MAA+B,UAA2C;AACpG,MAAI,YAAY,EAAG,QAAO;AAC1B,MAAI,OAAO,KAAK,QAAQ,EAAE,MAAM,OAAQ,QAAO;AAC/C,QAAM,QAAQ,KAAK;AACnB,MAAI,CAAC,SAAS,OAAO,UAAU,SAAU,QAAO;AAChD,QAAM,SAAS;AACf,QAAM,SAAS,OAAO;AACtB,MAAI,WAAW,UAAa,WAAW,KAAM,QAAO;AACpD,QAAM,aAAa,OAAO,WAAW,WAAW,SAAS,cAAc,MAAM;AAC7E,MAAI,WAAW,UAAU,SAAU,QAAO;AAC1C,QAAM,WAAY,OAAO,YAAY,OAAO,OAAO,aAAa,WAAW,OAAO,WAAW,CAAC;AAC9F,SAAO;AAAA,IACL,GAAG;AAAA,IACH,OAAO;AAAA,MACL,GAAG;AAAA,MACH,QAAQ,GAAG,W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F4N4U.js";
24
21
  import {
25
22
  resolveTangleExecutionEnvironment,
26
23
  trimOrNull
27
24
  } from "./chunk-D6UJEOZQ.js";
28
25
  import {
29
- formatServerTiming
30
- } from "./chunk-PCAY23GS.js";
26
+ formatServerTiming,
27
+ nextCallIndex
28
+ } from "./chunk-AVBNS64P.js";
31
29
  import {
32
30
  fail,
33
31
  isRuntimeAuthRefreshDenied,
@@ -589,7 +587,11 @@ function createSandboxRunTool(options) {
589
587
  return fail2("invalid_arguments", `task must be 1 to ${TASK_LIMIT} characters`);
590
588
  }
591
589
  const started = Date.now();
592
- const signal = AbortSignal.any([AbortSignal.timeout(timeoutMs), ...options.signal ? [options.signal] : []]);
590
+ const signal = AbortSignal.any([
591
+ AbortSignal.timeout(timeoutMs),
592
+ ...options.signal ? [options.signal] : [],
593
+ ...context?.signal ? [context.signal] : []
594
+ ]);
593
595
  if (options.warm) await options.warm.leases.turn(options.warm.key).catch(() => {
594
596
  });
595
597
  const capped = (work) => Promise.race([work, new Promise((_, reject) => {
@@ -604,7 +606,7 @@ function createSandboxRunTool(options) {
604
606
  } catch (error) {
605
607
  claim?.end(void 0, error instanceof SandboxRunError ? error.code : "sandbox_unavailable");
606
608
  if (error instanceof SandboxRunError) return fail2(error.code, error.message, error.cause);
607
- return fail2("sandbox_unavailable", "The sandbox for this workspace could not start, so this work was not done.", error);
609
+ return fail2("sandbox_unavailable", "The workspace computer could not be acquired. Its availability could not be confirmed.", error);
608
610
  }
609
611
  emit("box_ready", { ms: Date.now() - started });
610
612
  let answer;
@@ -620,12 +622,13 @@ Your part of it:
620
622
  signal,
621
623
  timeoutMs: Math.max(1, timeoutMs - (Date.now() - started)),
622
624
  emit,
625
+ ...context?.callId ? { callId: context.callId } : {},
623
626
  ...context?.trace ? { trace: context.trace } : {},
624
627
  ...context?.span ? { span: context.span } : {}
625
628
  }));
626
629
  } catch (error) {
627
- const timedOut = signal.aborted && !options.signal?.aborted;
628
- return fail2("sandbox_failed", timedOut ? `The sandbox did not finish within ${Math.round(timeoutMs / 1e3)} s, so this work was not done.` : "The sandbox run failed, so this work was not done.", error);
630
+ const timedOut = signal.aborted && !options.signal?.aborted && !context?.signal?.aborted;
631
+ return fail2("sandbox_failed", timedOut ? `The computer step did not return an answer within ${Math.round(timeoutMs / 1e3)} s. Its completion could not be confirmed.` : "The computer step failed to return an answer. Its completion could not be confirmed.", error);
629
632
  }
630
633
  if (!answer.trim()) return fail2("sandbox_empty", "The sandbox finished without an answer.");
631
634
  return { answer, ms: Date.now() - started };
@@ -3583,6 +3586,9 @@ async function mintSandboxScopedToken(box, options) {
3583
3586
  }
3584
3587
 
3585
3588
  export {
3589
+ DEFAULT_ESCALATION_TOOLS,
3590
+ escalationHints,
3591
+ createEscalationSpeculator,
3586
3592
  traceSandboxPromptEvents,
3587
3593
  createCacheReuseStore,
3588
3594
  backendModelFields,
@@ -3594,10 +3600,6 @@ export {
3594
3600
  createSandboxTerminalConnectionRoute,
3595
3601
  sandboxPrewarmClaimKey,
3596
3602
  createSandboxPrewarmer,
3597
- SandboxRunError,
3598
- SANDBOX_RUN_DESCRIPTION,
3599
- sandboxPromptRunner,
3600
- createSandboxRunTool,
3601
3603
  SANDBOX_EXEC_DESCRIPTION,
3602
3604
  createSandboxExecTool,
3603
3605
  DEFAULT_PREWARM_CLAIM_TABLE,
@@ -3629,9 +3631,6 @@ export {
3629
3631
  WARM_LEASE_DECLINED_UNTIL_DDL,
3630
3632
  WARM_LEASE_PENDING_DDL,
3631
3633
  createD1WarmLeaseStore,
3632
- DEFAULT_ESCALATION_TOOLS,
3633
- escalationHints,
3634
- createEscalationSpeculator,
3635
3634
  resolveSandboxClientCredentials,
3636
3635
  DEFAULT_SANDBOX_RESOURCES,
3637
3636
  PYPI_EGRESS_DOMAINS,
@@ -3684,6 +3683,10 @@ export {
3684
3683
  secretStoreFromClient,
3685
3684
  storeSecret,
3686
3685
  deleteSecret,
3687
- mintSandboxScopedToken
3686
+ mintSandboxScopedToken,
3687
+ SandboxRunError,
3688
+ SANDBOX_RUN_DESCRIPTION,
3689
+ sandboxPromptRunner,
3690
+ createSandboxRunTool
3688
3691
  };
3689
- //# sourceMappingURL=chunk-ISRPOPMM.js.map
3692
+ //# sourceMappingURL=chunk-ND5XWLRU.js.map