@tangle-network/agent-app 0.63.60 → 0.63.62

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 (105) hide show
  1. package/dist/{DesignCanvas-Q65UV4D5.js → DesignCanvas-566V5KVC.js} +3 -2
  2. package/dist/{DesignCanvasEditor-THEFESEX.js → DesignCanvasEditor-6XNHSREG.js} +5 -4
  3. package/dist/agent-profiles/d1.js +3 -3
  4. package/dist/agent-profiles/index.js +3 -3
  5. package/dist/app-auth/index.js +2 -1
  6. package/dist/app-auth/index.js.map +1 -1
  7. package/dist/assistant/index.js +6 -5
  8. package/dist/assistant/index.js.map +1 -1
  9. package/dist/chat-react/index.js +3 -3
  10. package/dist/chat-routes/agent-producers.d.ts +39 -0
  11. package/dist/chat-routes/dispatch-parts.d.ts +24 -2
  12. package/dist/chat-routes/hybrid-producer.d.ts +6 -2
  13. package/dist/chat-routes/index.d.ts +1 -0
  14. package/dist/chat-routes/index.js +31 -12
  15. package/dist/chat-routes/index.js.map +1 -1
  16. package/dist/chat-routes/turn-admission.d.ts +3 -3
  17. package/dist/chat-routes/turn-route-contracts.d.ts +39 -1
  18. package/dist/chat-routes/wire.d.ts +35 -4
  19. package/dist/chat-store/index.js +4 -2
  20. package/dist/chat-store/index.js.map +1 -1
  21. package/dist/chat-store/parts.d.ts +19 -3
  22. package/dist/{chunk-6XSQCP6W.js → chunk-43CV4JIT.js} +2 -2
  23. package/dist/{chunk-SFZELD6V.js → chunk-4JTEPK2G.js} +2 -2
  24. package/dist/{chunk-RILVJYXJ.js → chunk-5ERXADSW.js} +2 -2
  25. package/dist/{chunk-LAZCUQFZ.js → chunk-73AVOSH6.js} +179 -86
  26. package/dist/chunk-73AVOSH6.js.map +1 -0
  27. package/dist/{chunk-HHPQMFKP.js → chunk-7O62NYGT.js} +2 -2
  28. package/dist/{chunk-GGJYAV7R.js → chunk-AHBVQRJA.js} +2 -2
  29. package/dist/{chunk-GGJYAV7R.js.map → chunk-AHBVQRJA.js.map} +1 -1
  30. package/dist/{chunk-UTF7H6BK.js → chunk-EUQ46YWK.js} +15 -15
  31. package/dist/chunk-EUQ46YWK.js.map +1 -0
  32. package/dist/{chunk-PIGW5LRM.js → chunk-FJRQCF43.js} +3 -3
  33. package/dist/{chunk-AICYKYYF.js → chunk-GAYWV565.js} +17 -4
  34. package/dist/chunk-GAYWV565.js.map +1 -0
  35. package/dist/{chunk-5C3RXQQ7.js → chunk-H3DAXUKV.js} +2 -2
  36. package/dist/{chunk-SRA7VAVK.js → chunk-HJYEK4SU.js} +2 -2
  37. package/dist/{chunk-P7UB7ZVP.js → chunk-IAK227OO.js} +2 -2
  38. package/dist/{chunk-QGJOT6R6.js → chunk-K2JPSXKI.js} +54 -9
  39. package/dist/{chunk-QGJOT6R6.js.map → chunk-K2JPSXKI.js.map} +1 -1
  40. package/dist/{chunk-QFIVY6WA.js → chunk-NJW4JCSF.js} +2 -2
  41. package/dist/{chunk-IDQ7N36R.js → chunk-Q55WW6DO.js} +15 -15
  42. package/dist/{chunk-H6BRJU5M.js → chunk-RKNNMC6T.js} +1 -1
  43. package/dist/{chunk-KFO5R4SN.js → chunk-RYKANV3P.js} +945 -801
  44. package/dist/chunk-RYKANV3P.js.map +1 -0
  45. package/dist/{chunk-4E2MUVGL.js → chunk-VQIH5NAB.js} +3 -3
  46. package/dist/chunk-XBBXPZJI.js +47 -0
  47. package/dist/chunk-XBBXPZJI.js.map +1 -0
  48. package/dist/{chunk-DCGATWZ5.js → chunk-XPB2UYHU.js} +5 -5
  49. package/dist/{chunk-DCGATWZ5.js.map → chunk-XPB2UYHU.js.map} +1 -1
  50. package/dist/design-canvas/index.js +2 -1
  51. package/dist/design-canvas/index.js.map +1 -1
  52. package/dist/design-canvas-react/engine.js +2 -1
  53. package/dist/design-canvas-react/index.js +5 -4
  54. package/dist/design-canvas-react/index.js.map +1 -1
  55. package/dist/design-canvas-react/lazy.js +1 -1
  56. package/dist/operator/index.js +2 -2
  57. package/dist/platform/index.js +2 -1
  58. package/dist/platform/index.js.map +1 -1
  59. package/dist/preset-cloudflare/index.js +6 -6
  60. package/dist/public-consultation/index.d.ts +2 -2
  61. package/dist/public-consultation/index.js +11 -10
  62. package/dist/public-consultation/index.js.map +1 -1
  63. package/dist/sandbox/index.js +6 -6
  64. package/dist/sequences/index.js +2 -1
  65. package/dist/sequences/index.js.map +1 -1
  66. package/dist/stories/chat/fixtures.d.ts +4 -0
  67. package/dist/theme/brand.generated.d.ts +15 -15
  68. package/dist/theme/dom.js +2 -2
  69. package/dist/theme/index.js +1 -1
  70. package/dist/theme/tokens.css +210 -356
  71. package/dist/tools/index.js +4 -4
  72. package/dist/web/index.d.ts +1 -0
  73. package/dist/web/index.js +7 -1
  74. package/dist/web/speakers.d.ts +30 -0
  75. package/dist/web-react/chat-messages.d.ts +1 -1
  76. package/dist/web-react/chat-stream.d.ts +7 -0
  77. package/dist/web-react/document.js +2 -2
  78. package/dist/web-react/entry-composer.d.ts +2 -2
  79. package/dist/web-react/index.d.ts +3 -0
  80. package/dist/web-react/index.js +18 -5
  81. package/dist/web-react/message-projection.d.ts +19 -0
  82. package/dist/web-react/use-file-mentions.d.ts +23 -4
  83. package/dist/work-product/index.js +2 -2
  84. package/dist/workspace-react/index.d.ts +29 -1
  85. package/dist/workspace-react/index.js +34 -0
  86. package/dist/workspace-react/index.js.map +1 -1
  87. package/package.json +4 -4
  88. package/dist/chunk-AICYKYYF.js.map +0 -1
  89. package/dist/chunk-KFO5R4SN.js.map +0 -1
  90. package/dist/chunk-LAZCUQFZ.js.map +0 -1
  91. package/dist/chunk-UTF7H6BK.js.map +0 -1
  92. /package/dist/{DesignCanvas-Q65UV4D5.js.map → DesignCanvas-566V5KVC.js.map} +0 -0
  93. /package/dist/{DesignCanvasEditor-THEFESEX.js.map → DesignCanvasEditor-6XNHSREG.js.map} +0 -0
  94. /package/dist/{chunk-6XSQCP6W.js.map → chunk-43CV4JIT.js.map} +0 -0
  95. /package/dist/{chunk-SFZELD6V.js.map → chunk-4JTEPK2G.js.map} +0 -0
  96. /package/dist/{chunk-RILVJYXJ.js.map → chunk-5ERXADSW.js.map} +0 -0
  97. /package/dist/{chunk-HHPQMFKP.js.map → chunk-7O62NYGT.js.map} +0 -0
  98. /package/dist/{chunk-PIGW5LRM.js.map → chunk-FJRQCF43.js.map} +0 -0
  99. /package/dist/{chunk-5C3RXQQ7.js.map → chunk-H3DAXUKV.js.map} +0 -0
  100. /package/dist/{chunk-SRA7VAVK.js.map → chunk-HJYEK4SU.js.map} +0 -0
  101. /package/dist/{chunk-P7UB7ZVP.js.map → chunk-IAK227OO.js.map} +0 -0
  102. /package/dist/{chunk-QFIVY6WA.js.map → chunk-NJW4JCSF.js.map} +0 -0
  103. /package/dist/{chunk-IDQ7N36R.js.map → chunk-Q55WW6DO.js.map} +0 -0
  104. /package/dist/{chunk-H6BRJU5M.js.map → chunk-RKNNMC6T.js.map} +0 -0
  105. /package/dist/{chunk-4E2MUVGL.js.map → chunk-VQIH5NAB.js.map} +0 -0
@@ -27,7 +27,7 @@ import {
27
27
  sandboxRunFailureDetail,
28
28
  streamSandboxPrompt,
29
29
  turnStorageBindings
30
- } from "./chunk-IDQ7N36R.js";
30
+ } from "./chunk-Q55WW6DO.js";
31
31
  import {
32
32
  redactErrorMessage
33
33
  } from "./chunk-MH74DY2I.js";
@@ -37,7 +37,7 @@ import {
37
37
  createAssistantDraftWriter,
38
38
  rowIdOf,
39
39
  storeSupportsDraftPersistence
40
- } from "./chunk-HHPQMFKP.js";
40
+ } from "./chunk-7O62NYGT.js";
41
41
  import {
42
42
  normalizeClientTurnId,
43
43
  resolveChatTurn
@@ -46,7 +46,7 @@ import {
46
46
  historyContentWithAttachments,
47
47
  mentionInputToPart,
48
48
  toChatMessageParts
49
- } from "./chunk-AICYKYYF.js";
49
+ } from "./chunk-GAYWV565.js";
50
50
  import {
51
51
  asRecord,
52
52
  asString,
@@ -88,15 +88,16 @@ import {
88
88
  TURN_PROGRESS_FIRST,
89
89
  TURN_PROGRESS_HEADER,
90
90
  TURN_ROUTE_PHASE_MESSAGES,
91
+ agentMentionsOf,
91
92
  assertPromptPartsWithinCap,
92
93
  base64WireLen,
93
94
  buildTurnPhaseEvent,
94
95
  chatTurnRequestInit,
95
96
  mediaTypeForMentionPath,
96
97
  parseChatTurnParts,
97
- parseFileMentions,
98
+ parseMentions,
98
99
  turnResponseEventFor
99
- } from "./chunk-QGJOT6R6.js";
100
+ } from "./chunk-K2JPSXKI.js";
100
101
  import {
101
102
  ModelFailoverExhaustedError,
102
103
  buildModelChain,
@@ -131,6 +132,378 @@ import {
131
132
  isWorkspaceFileExportable
132
133
  } from "./chunk-TXD5HXLE.js";
133
134
 
135
+ // src/chat-routes/upload.ts
136
+ var UPLOAD_INLINE_MAX_BYTES = 700 * 1024;
137
+ var UPLOAD_MAX_FILE_BYTES = 8 * 1024 * 1024;
138
+ var DEFAULT_UPLOAD_DIRECTORY = "/workspace/uploads";
139
+ function normalizeUploadDirectory(value) {
140
+ const withoutTrailingSlash = value.trim().replace(/\/+$/, "");
141
+ if (!withoutTrailingSlash.startsWith("/") || withoutTrailingSlash.length === 0) return null;
142
+ const segments = withoutTrailingSlash.slice(1).split("/");
143
+ if (segments.some((segment) => segment.length === 0 || segment === "." || segment === "..")) return null;
144
+ return `/${segments.join("/")}`;
145
+ }
146
+ function sanitizeUploadFilename(name) {
147
+ const base = name.split(/[\\/]/).pop() ?? "file";
148
+ const safe = base.replace(/[^A-Za-z0-9._-]+/g, "_").replace(/^\.+/, "_");
149
+ return (safe || "file").slice(0, 120);
150
+ }
151
+ var BASE64_CHUNK = 32768;
152
+ function bytesToBase64(bytes) {
153
+ let binary = "";
154
+ for (let offset = 0; offset < bytes.length; offset += BASE64_CHUNK) {
155
+ binary += String.fromCharCode(...bytes.subarray(offset, offset + BASE64_CHUNK));
156
+ }
157
+ return btoa(binary);
158
+ }
159
+ function uploadError(status, code, error) {
160
+ return Response.json({ code, error }, { status });
161
+ }
162
+ function createUploadRoute(options) {
163
+ const inlineMaxBytes = options.inlineMaxBytes ?? UPLOAD_INLINE_MAX_BYTES;
164
+ const maxFileBytes = options.maxFileBytes ?? UPLOAD_MAX_FILE_BYTES;
165
+ return async function upload(request) {
166
+ const auth = await options.authorize({ request });
167
+ if (!auth.ok) return auth.response;
168
+ const sink = auth.sink ?? null;
169
+ const configuredUploadDir = auth.uploadDir ?? options.uploadDir ?? DEFAULT_UPLOAD_DIRECTORY;
170
+ let form;
171
+ try {
172
+ form = await request.formData();
173
+ } catch {
174
+ return uploadError(400, "INVALID_UPLOAD", "Expected a multipart/form-data body with file fields");
175
+ }
176
+ const files = [];
177
+ form.forEach((value) => {
178
+ if (value instanceof File) files.push(value);
179
+ });
180
+ if (files.length === 0) {
181
+ return uploadError(400, "INVALID_UPLOAD", "No files in the upload body");
182
+ }
183
+ const uploaded = [];
184
+ for (const file of files) {
185
+ const name = sanitizeUploadFilename(file.name);
186
+ const mediaType = file.type || "application/octet-stream";
187
+ const partType = mediaType.startsWith("image/") ? "image" : "file";
188
+ if (file.size > maxFileBytes) {
189
+ return uploadError(
190
+ 413,
191
+ "FILE_TOO_LARGE",
192
+ `${name} is ${file.size}B, over the ${maxFileBytes}B per-file cap`
193
+ );
194
+ }
195
+ const id = crypto.randomUUID();
196
+ if (file.size <= inlineMaxBytes) {
197
+ const base642 = bytesToBase64(new Uint8Array(await file.arrayBuffer()));
198
+ uploaded.push({
199
+ id,
200
+ name,
201
+ size: file.size,
202
+ mediaType,
203
+ inline: true,
204
+ part: {
205
+ type: partType,
206
+ filename: name,
207
+ mediaType,
208
+ url: `data:${mediaType};base64,${base642}`
209
+ }
210
+ });
211
+ continue;
212
+ }
213
+ if (!sink) {
214
+ return uploadError(
215
+ 413,
216
+ "SANDBOX_REQUIRED",
217
+ `${name} is ${file.size}B, over the ${inlineMaxBytes}B inline cap, and no sandbox is available to hold it`
218
+ );
219
+ }
220
+ const uploadDir = normalizeUploadDirectory(configuredUploadDir);
221
+ if (!uploadDir) {
222
+ return uploadError(
223
+ 500,
224
+ "INVALID_UPLOAD_DIRECTORY",
225
+ 'uploadDir must be an absolute path without empty, "." or ".." segments'
226
+ );
227
+ }
228
+ const path = `${uploadDir}/${id}-${name}`;
229
+ const base64 = bytesToBase64(new Uint8Array(await file.arrayBuffer()));
230
+ await sink.write(path, base64, { encoding: "base64" });
231
+ uploaded.push({
232
+ id,
233
+ name,
234
+ size: file.size,
235
+ mediaType,
236
+ inline: false,
237
+ part: { type: partType, filename: name, mediaType, path }
238
+ });
239
+ }
240
+ return Response.json({ files: uploaded });
241
+ };
242
+ }
243
+
244
+ // src/chat-routes/dispatch-parts.ts
245
+ import { pathToFileURL } from "url";
246
+ function byteLen(value) {
247
+ return new TextEncoder().encode(value).length;
248
+ }
249
+ async function readSandboxMention(box, absolutePath, options) {
250
+ const stat = await statSandboxFileSize(box, absolutePath);
251
+ if (!stat.succeeded) {
252
+ return { succeeded: false, error: `mentioned sandbox file missing or unreadable: ${absolutePath} \u2014 ${stat.error}` };
253
+ }
254
+ if (!options.readBytes) return { succeeded: true, value: { size: stat.value } };
255
+ const read = await readSandboxBinaryBytes(box, absolutePath, stat.value);
256
+ if (!read.succeeded) {
257
+ return { succeeded: false, error: `mentioned sandbox file read failed: ${absolutePath} \u2014 ${read.error}` };
258
+ }
259
+ return { succeeded: true, value: { size: stat.value, base64: bytesToBase64(read.value.bytes) } };
260
+ }
261
+ function violatesUrlPathXor(part) {
262
+ if (part.type === "text") return false;
263
+ const hasUrl = typeof part.url === "string" && (part.url.startsWith("data:") || part.url.startsWith("file://"));
264
+ const hasPath = "path" in part && typeof part.path === "string" && part.path.startsWith("/");
265
+ if (part.type === "file") return !hasUrl || hasPath;
266
+ return hasUrl === hasPath;
267
+ }
268
+ function sandboxFileUrl(absolutePath) {
269
+ if (!absolutePath.startsWith("/")) return void 0;
270
+ try {
271
+ return pathToFileURL(absolutePath).href;
272
+ } catch {
273
+ return void 0;
274
+ }
275
+ }
276
+ function normalizeChatPromptForSandbox(prompt) {
277
+ if (typeof prompt === "string") return prompt;
278
+ return prompt.map((part) => {
279
+ if (part.type === "text") return part;
280
+ if ("content" in part) {
281
+ throw new ChatTurnInputError("Sandbox prompt parts do not accept inline content; provide a URL or path");
282
+ }
283
+ const url = typeof part.url === "string" && part.url.length > 0 ? part.url : void 0;
284
+ const path = typeof part.path === "string" && part.path.length > 0 ? part.path : void 0;
285
+ if (Boolean(url) === Boolean(path)) {
286
+ throw new ChatTurnInputError(`Sandbox ${part.type} parts require exactly one URL or path`);
287
+ }
288
+ if (path && !path.startsWith("/")) {
289
+ throw new ChatTurnInputError(`Sandbox ${part.type} paths must be absolute: ${path}`);
290
+ }
291
+ if (part.type === "image") {
292
+ return {
293
+ type: "image",
294
+ ...part.filename ? { filename: part.filename } : {},
295
+ ...part.mediaType ? { mediaType: part.mediaType } : {},
296
+ ...url ? { url } : { path }
297
+ };
298
+ }
299
+ const filename = part.filename?.trim();
300
+ if (!filename) {
301
+ throw new ChatTurnInputError("Sandbox file parts require a filename");
302
+ }
303
+ const fileUrl = url ?? sandboxFileUrl(path);
304
+ if (!fileUrl) {
305
+ throw new ChatTurnInputError(`Sandbox file paths must be absolute: ${path}`);
306
+ }
307
+ return {
308
+ type: "file",
309
+ filename,
310
+ ...part.mediaType ? { mediaType: part.mediaType } : {},
311
+ url: fileUrl
312
+ };
313
+ });
314
+ }
315
+ function projectDispatchHistory(messages, view = {}) {
316
+ const out = [];
317
+ const textOf = (message) => view.attachments === false ? message.content : historyContentWithAttachments(message);
318
+ for (const message of messages) {
319
+ if (message.role !== "assistant") {
320
+ out.push({ role: "user", content: textOf(message) });
321
+ continue;
322
+ }
323
+ const slices = speakerSlices(message);
324
+ if (slices.length === 0) {
325
+ const owner = view.owner;
326
+ const foreign = view.pov !== void 0 && owner !== void 0 && owner.id !== view.pov;
327
+ out.push({
328
+ role: foreign ? "user" : "assistant",
329
+ content: foreign ? tagged(owner.name, textOf(message)) : textOf(message)
330
+ });
331
+ continue;
332
+ }
333
+ for (const slice of slices) {
334
+ const text = textOf({ role: "assistant", content: slice.text, parts: slice.parts });
335
+ if (view.pov === void 0) out.push({ role: "assistant", content: tagged(slice.name, text) });
336
+ else if (slice.id === view.pov) out.push({ role: "assistant", content: text });
337
+ else out.push({ role: "user", content: tagged(slice.name, text) });
338
+ }
339
+ }
340
+ return out;
341
+ }
342
+ var tagged = (name, text) => `[${name}] ${text}`;
343
+ function speakerSlices(message) {
344
+ const parts = message.parts ?? [];
345
+ const slices = [];
346
+ let current = null;
347
+ for (const part of parts) {
348
+ if (part.type === "speaker" && typeof part.id === "string" && typeof part.name === "string") {
349
+ current = { id: part.id, name: part.name, text: "", parts: [] };
350
+ slices.push(current);
351
+ } else if (current) {
352
+ current.parts.push(part);
353
+ if (part.type === "text" && typeof part.text === "string") current.text += part.text;
354
+ }
355
+ }
356
+ return slices;
357
+ }
358
+ function readResultToBase64(read) {
359
+ if (typeof read.base64 === "string") return read.base64;
360
+ if (read.bytes) return bytesToBase64(read.bytes);
361
+ return void 0;
362
+ }
363
+ async function buildDispatchParts(input) {
364
+ const readMention = input.readSandboxMention ?? readSandboxMention;
365
+ const resolveMentionPath = input.resolveMentionPath ?? input.resolveAttachmentPath;
366
+ const forcePath = input.forcePath ?? false;
367
+ const mentions = (input.mentions ?? []).filter((mention) => mention.mentionKind !== "agent");
368
+ const requestMaxBytes = input.requestMaxBytes ?? DISPATCH_REQUEST_MAX_BYTES;
369
+ const structuralReserveBytes = input.structuralReserveBytes ?? DISPATCH_STRUCTURAL_RESERVE_BYTES;
370
+ const maxParts = input.maxParts ?? DISPATCH_MAX_PARTS;
371
+ const parts = [{ type: "text", text: input.text }];
372
+ const emittedAbsPaths = /* @__PURE__ */ new Set();
373
+ const flattenedForSizing = flattenHistory(input.text, input.history);
374
+ const inlineBudget = requestMaxBytes - base64WireLen(byteLen(flattenedForSizing)) - byteLen(JSON.stringify(input.systemPrompt)) - input.profileWireBytes - structuralReserveBytes;
375
+ let runningInline = 0;
376
+ for (const attachment of input.attachments) {
377
+ if (!attachment.path) {
378
+ return { succeeded: false, error: `attachment path must be non-empty: ${attachment.name}` };
379
+ }
380
+ let read;
381
+ try {
382
+ read = await input.readAttachment(input.scopeId, attachment.path);
383
+ } catch (err) {
384
+ return {
385
+ succeeded: false,
386
+ error: `attachment store read failed: ${attachment.path} \u2014 ${err instanceof Error ? err.message : String(err)}`
387
+ };
388
+ }
389
+ if (!read.ok) return { succeeded: false, error: read.reason };
390
+ const base64 = readResultToBase64(read);
391
+ if (base64 === void 0) {
392
+ return { succeeded: false, error: `attachment store read produced no content: ${attachment.path}` };
393
+ }
394
+ const mediaType = attachment.mediaType ?? read.mediaType;
395
+ if (attachment.type === "image" && !mediaType) {
396
+ return { succeeded: false, error: `attachment is missing a mediaType required for an image data URI: ${attachment.path}` };
397
+ }
398
+ const absPath = input.resolveAttachmentPath(attachment.path);
399
+ emittedAbsPaths.add(absPath);
400
+ if (attachment.type === "image") {
401
+ const inlinePart2 = {
402
+ type: "image",
403
+ filename: attachment.name,
404
+ mediaType,
405
+ url: `data:${mediaType};base64,${base64}`
406
+ };
407
+ const cost2 = byteLen(JSON.stringify(inlinePart2));
408
+ if (!forcePath && runningInline + cost2 <= inlineBudget) {
409
+ parts.push(inlinePart2);
410
+ runningInline += cost2;
411
+ } else {
412
+ parts.push({ type: "image", filename: attachment.name, mediaType, path: absPath });
413
+ }
414
+ continue;
415
+ }
416
+ const fileMediaType = mediaType ?? "application/octet-stream";
417
+ const inlinePart = {
418
+ type: "file",
419
+ filename: attachment.name,
420
+ mediaType: fileMediaType,
421
+ url: `data:${fileMediaType};base64,${base64}`
422
+ };
423
+ const cost = byteLen(JSON.stringify(inlinePart));
424
+ if (!forcePath && runningInline + cost <= inlineBudget) {
425
+ parts.push(inlinePart);
426
+ runningInline += cost;
427
+ } else {
428
+ const url = sandboxFileUrl(absPath);
429
+ if (!url) {
430
+ return { succeeded: false, error: `resolved attachment path must be absolute: ${absPath}` };
431
+ }
432
+ parts.push({ type: "file", filename: attachment.name, mediaType: fileMediaType, url });
433
+ }
434
+ }
435
+ if (mentions.length > 0 && !input.box) {
436
+ return { succeeded: false, error: "internal error: sandbox mentions require a box to read from" };
437
+ }
438
+ for (const mention of mentions) {
439
+ if (!mention.path) {
440
+ return { succeeded: false, error: `mention path must be non-empty: ${mention.name}` };
441
+ }
442
+ if (!isWorkspaceFileExportable(mention.path)) {
443
+ return { succeeded: false, error: `mention file is not exportable: ${mention.path}` };
444
+ }
445
+ const absPath = resolveMentionPath(mention.path);
446
+ if (emittedAbsPaths.has(absPath)) continue;
447
+ emittedAbsPaths.add(absPath);
448
+ const isImage = mention.mentionKind === "image";
449
+ const mediaType = isImage ? mediaTypeForMentionPath(mention.path) : void 0;
450
+ let stat;
451
+ try {
452
+ stat = await readMention(input.box, absPath, { readBytes: false });
453
+ } catch (err) {
454
+ return { succeeded: false, error: `mention read failed: ${absPath} \u2014 ${err instanceof Error ? err.message : String(err)}` };
455
+ }
456
+ if (!stat.succeeded) return { succeeded: false, error: stat.error };
457
+ const projectedInlineCost = base64WireLen(stat.value.size) + byteLen(JSON.stringify({ type: "image", filename: mention.name, mediaType: mediaType ?? "", url: "" }));
458
+ if (isImage && mediaType && !forcePath && runningInline + projectedInlineCost <= inlineBudget) {
459
+ let read;
460
+ try {
461
+ read = await readMention(input.box, absPath, { readBytes: true });
462
+ } catch (err) {
463
+ return { succeeded: false, error: `mention read failed: ${absPath} \u2014 ${err instanceof Error ? err.message : String(err)}` };
464
+ }
465
+ if (!read.succeeded) return { succeeded: false, error: read.error };
466
+ if (!read.value.base64) return { succeeded: false, error: `mentioned image produced no bytes: ${absPath}` };
467
+ const inlinePart = {
468
+ type: "image",
469
+ filename: mention.name,
470
+ mediaType,
471
+ url: `data:${mediaType};base64,${read.value.base64}`
472
+ };
473
+ const cost = byteLen(JSON.stringify(inlinePart));
474
+ if (runningInline + cost <= inlineBudget) {
475
+ parts.push(inlinePart);
476
+ runningInline += cost;
477
+ continue;
478
+ }
479
+ }
480
+ if (isImage && mediaType) {
481
+ parts.push({ type: "image", filename: mention.name, mediaType, path: absPath });
482
+ } else {
483
+ const url = sandboxFileUrl(absPath);
484
+ if (!url) {
485
+ return { succeeded: false, error: `resolved mention path must be absolute: ${absPath}` };
486
+ }
487
+ parts.push({ type: "file", filename: mention.name, url });
488
+ }
489
+ }
490
+ for (const part of parts) {
491
+ if (violatesUrlPathXor(part)) {
492
+ return { succeeded: false, error: "internal error: emitted media part violates the url/path exclusivity invariant" };
493
+ }
494
+ }
495
+ const textPartSize = base64WireLen(byteLen(flattenedForSizing));
496
+ const mediaPartsSize = parts.slice(1).reduce((total, part) => total + byteLen(JSON.stringify(part)), 0);
497
+ const systemPromptSize = byteLen(JSON.stringify(input.systemPrompt));
498
+ if (textPartSize + mediaPartsSize + systemPromptSize + input.profileWireBytes + structuralReserveBytes > requestMaxBytes) {
499
+ return { succeeded: false, error: "dispatch parts exceed the sandbox proxy request cap even after path demotion" };
500
+ }
501
+ if (parts.length > maxParts) {
502
+ return { succeeded: false, error: `dispatch parts exceed the sidecar per-request cap of ${maxParts}` };
503
+ }
504
+ return { succeeded: true, value: parts };
505
+ }
506
+
134
507
  // src/chat-routes/reasoning-clock.ts
135
508
  function createReasoningClock(now = Date.now) {
136
509
  const runs = /* @__PURE__ */ new Map();
@@ -399,8 +772,9 @@ function turnPromptText(prompt) {
399
772
  function turnCarriesFiles(prompt) {
400
773
  return typeof prompt !== "string" && prompt.some((part) => part.type !== "text");
401
774
  }
402
- function routerTurnHistory(priorMessages, limit = 40) {
403
- return priorMessages.filter((message) => (message.role === "user" || message.role === "assistant") && Boolean(message.content?.trim())).slice(-limit).map(({ role, content }) => ({ role, content }));
775
+ function routerTurnHistory(priorMessages, limit = 40, view = {}) {
776
+ const rows = priorMessages.filter((message) => message.role === "user" || message.role === "assistant");
777
+ return projectDispatchHistory(rows, { ...view, attachments: false }).filter((message) => Boolean(message.content.trim())).slice(-limit);
404
778
  }
405
779
  function createHybridTurnProducer(options) {
406
780
  const { box, tools = [], speculateOn, attachments, onSpeculate, guidance, onSettled, admitted, signal, ...router } = options;
@@ -1321,831 +1695,457 @@ function createSandboxChatProducer(options) {
1321
1695
  const reported = extractReportedTurnUsage(asRecord(event.data));
1322
1696
  if (reported) {
1323
1697
  applyTerminalUsage(reported, usage);
1324
- yield* emitFinalUsage();
1325
- }
1326
- yield* emitTerminalizedTools();
1327
- yield toProducerWireEvent(record);
1328
- continue;
1329
- }
1330
- if (event.type === "error") {
1331
- const message = sandboxStreamErrorMessage(event.data);
1332
- const errorContent = projectionState.fullText.trim() ? `The sandbox model stream stopped before a clean completion.
1333
-
1334
- Error: ${message}` : `The sandbox agent returned an error before producing a visible answer.
1335
-
1336
- Error: ${message}`;
1337
- if (options.errorNotice) {
1338
- yield* emitErrorNotice(errorContent, sandboxStreamErrorCode(event.data));
1339
- } else if (options.includeErrorText !== false) {
1340
- const errorDelta = projectionState.fullText ? `
1341
-
1342
- ---
1343
- ${errorContent}` : errorContent;
1344
- projectionState.fullText += errorDelta;
1345
- yield { type: "text", text: errorDelta };
1346
- }
1347
- projectionState.interactionOutcome = "expired";
1348
- yield* emitTerminalizedTools();
1349
- yield toProducerWireEvent(record);
1350
- continue;
1351
- }
1352
- yield toProducerWireEvent(record);
1353
- }
1354
- yield* drainModelNotices();
1355
- } catch (streamErr) {
1356
- preflightRefused = !observedSourceEvent && openAttempts() === 1 && streamErr instanceof SandboxRunError && streamErr.code === "sandbox_unavailable";
1357
- const diagnostic = sandboxStreamFailureDiagnostic(streamErr);
1358
- log("[chat-routes] sandbox stream failed", {
1359
- failureNote: diagnostic.failureNote,
1360
- error: streamErr instanceof Error ? streamErr.message : String(streamErr)
1361
- });
1362
- if (options.errorNotice) {
1363
- yield* emitErrorNotice(diagnostic.userMessage, diagnostic.code);
1364
- } else if (options.includeErrorText !== false) {
1365
- const errorDelta = projectionState.fullText ? `
1366
-
1367
- ---
1368
- ${diagnostic.userMessage}` : diagnostic.userMessage;
1369
- projectionState.fullText += errorDelta;
1370
- yield { type: "text", text: errorDelta };
1371
- }
1372
- projectionState.interactionOutcome = "expired";
1373
- yield* emitTerminalizedTools();
1374
- yield {
1375
- type: "error",
1376
- data: {
1377
- message: diagnostic.userMessage,
1378
- code: diagnostic.code,
1379
- details: { failureNote: diagnostic.failureNote }
1380
- }
1381
- };
1382
- } finally {
1383
- reasoningClock.settle();
1384
- }
1385
- }
1386
- return {
1387
- stream: stream(),
1388
- finalText: () => projectionState.fullText,
1389
- terminalObserved: () => projectionState.terminalObserved || preflightRefused,
1390
- assistantParts: () => finalizePendingInteractionParts(
1391
- finalizeAssistantParts(partOrder, timedParts(), projectionState.fullText),
1392
- projectionState.interactionOutcome
1393
- ),
1394
- // Mid-stream snapshot for incremental persistence: the same accumulators,
1395
- // WITHOUT the two completion-time settlements (`terminalizeDanglingTool*`
1396
- // and `finalizePendingInteractionParts`). A running tool and an unanswered
1397
- // ask are the correct live state; settling them early would persist
1398
- // phantom failures the final write then reverses.
1399
- draftParts: () => draftAssistantParts(partOrder, timedParts(), projectionState.fullText),
1400
- usage: () => usage,
1401
- // A GETTER, not a captured value: `turn-routes` reads `producer.model` at
1402
- // draft-snapshot and persist time, both of which happen after the stream
1403
- // resolved which model serves. A plain property would freeze the PREFERRED
1404
- // model into the row and make a downgrade unattributable — the exact
1405
- // failure mode this work exists to prevent.
1406
- get model() {
1407
- return servedModel();
1408
- },
1409
- modelFailover: () => ({
1410
- model: servingModel(),
1411
- attempts: failover?.attempts() ?? [],
1412
- usedFallback: failover?.usedFallback() ?? false
1413
- }),
1414
- modelAttribution: () => ({
1415
- ...options.model ? { requestedModel: options.model } : {},
1416
- ...modelState.effectiveBackend ?? {},
1417
- echoReceived: modelState.effectiveBackend !== void 0
1418
- })
1419
- };
1420
- }
1421
- function createSandboxProjection(projectionState, pendingModelNotices) {
1422
- const partOrder = [];
1423
- const partMap = /* @__PURE__ */ new Map();
1424
- const tracker = { seen: /* @__PURE__ */ new Map() };
1425
- const reasoningClock = createReasoningClock();
1426
- const usage = {};
1427
- const announcedToolArgs = /* @__PURE__ */ new Map();
1428
- const settledTools = /* @__PURE__ */ new Set();
1429
- const promotedFileParts = /* @__PURE__ */ new Map();
1430
- function recordPersistedPart(part, delta, keyOverride) {
1431
- const persisted = normalizePersistedPart(part);
1432
- if (!persisted) return;
1433
- const key = keyOverride ?? getPartKey(persisted);
1434
- if (!partMap.has(key)) partOrder.push(key);
1435
- partMap.set(key, mergePersistedPart(partMap.get(key), persisted, delta));
1436
- }
1437
- function* emitTerminalizedTools() {
1438
- if (projectionState.danglingToolsTerminalized) return;
1439
- projectionState.danglingToolsTerminalized = true;
1440
- const updates = terminalizeDanglingAssistantToolUpdates(partOrder, partMap, projectionState.fullText);
1441
- for (const part of updates) {
1442
- const toolId = asString(part.id);
1443
- if (!toolId || settledTools.has(toolId)) continue;
1444
- settledTools.add(toolId);
1445
- const state = asRecord(part.state);
1446
- yield {
1447
- type: "tool_result",
1448
- toolCallId: toolId,
1449
- toolName: asString(part.tool) ?? "tool",
1450
- outcome: {
1451
- ok: false,
1452
- ...asString(state?.error) ? { message: asString(state?.error) } : {}
1453
- }
1454
- };
1455
- }
1456
- }
1457
- function* emitFinalUsage() {
1458
- const promptTokens = usage.inputTokens ?? 0;
1459
- const completionTokens = usage.outputTokens ?? 0;
1460
- if (promptTokens || completionTokens) {
1461
- yield {
1462
- type: "usage",
1463
- usage: {
1464
- promptTokens,
1465
- completionTokens,
1466
- ...usage.reasoningTokens !== void 0 ? { reasoningTokens: usage.reasoningTokens } : {},
1467
- ...usage.costUsd !== void 0 ? { providerCostUsd: usage.costUsd } : {}
1468
- }
1469
- };
1470
- }
1471
- }
1472
- function* drainModelNotices() {
1473
- while (pendingModelNotices.length > 0) {
1474
- const queued = pendingModelNotices.shift();
1475
- const notice = noticePart("warning", queued.id, queued.text);
1476
- recordPersistedPart(notice, void 0, noticePartKey(notice.id));
1477
- yield { type: "notice", id: notice.id, noticeKind: "warning", text: queued.text };
1478
- }
1479
- }
1480
- function* emitErrorNotice(text, code) {
1481
- projectionState.errorNoticeCount += 1;
1482
- const notice = noticePart("error", `error-${projectionState.errorNoticeCount}`, text, code);
1483
- recordPersistedPart(notice, void 0, noticePartKey(notice.id));
1484
- yield { type: "notice", id: notice.id, noticeKind: "error", text, code };
1485
- }
1486
- const timedParts = () => {
1487
- const timed = new Map(partMap);
1488
- for (const [key, part] of partMap) {
1489
- if (part.type !== "reasoning") continue;
1490
- const time = reasoningClock.time(key, asRecord(part.time));
1491
- if (time) timed.set(key, { ...part, time });
1492
- }
1493
- return timed;
1494
- };
1495
- return { timedParts, drainModelNotices, tracker, recordPersistedPart, reasoningClock, partMap, announcedToolArgs, settledTools, usage, promotedFileParts, emitFinalUsage, emitTerminalizedTools, emitErrorNotice, partOrder };
1496
- }
1497
- async function* projectSandboxMessagePart(event, tracker, recordPersistedPart, reasoningClock, projectionState, partMap, announcedToolArgs, settledTools, usage, options, log, promotedFileParts) {
1498
- if (event.type === "message.part.updated") {
1499
- const part = asRecord(event.data?.part);
1500
- if (!part) return;
1501
- const rawDelta = event.data?.delta;
1502
- const partType = String(part.type ?? "");
1503
- if (partType === "text" || partType === "reasoning") {
1504
- const key = getPartKey(part);
1505
- const delta = textDelta(tracker, key, part, rawDelta);
1506
- recordPersistedPart(part, delta || void 0);
1507
- if (delta) {
1508
- if (partType === "reasoning") reasoningClock.reasoning(key);
1509
- else reasoningClock.settle();
1510
- if (partType === "text") projectionState.fullText += delta;
1511
- yield { type: partType, text: delta };
1512
- }
1513
- return;
1514
- }
1515
- if (partType === "tool") {
1516
- reasoningClock.settle();
1517
- recordPersistedPart(part, void 0);
1518
- const persisted = partMap.get(getPartKey(part));
1519
- const state = asRecord(persisted?.state);
1520
- const toolId = String(persisted?.id ?? "");
1521
- const toolName = String(persisted?.tool ?? "tool");
1522
- const args = asRecord(state?.input) ?? {};
1523
- const hasPopulatedArgs = Object.keys(args).length > 0;
1524
- const announcedWithPopulatedArgs = announcedToolArgs.get(toolId);
1525
- if (toolId && (announcedWithPopulatedArgs === void 0 || !announcedWithPopulatedArgs && hasPopulatedArgs && !settledTools.has(toolId))) {
1526
- announcedToolArgs.set(toolId, hasPopulatedArgs);
1527
- yield {
1528
- type: "tool_call",
1529
- call: { toolCallId: toolId, toolName, args }
1530
- };
1531
- }
1532
- const status = String(state?.status ?? "");
1533
- if (toolId && (status === "completed" || status === "error") && !settledTools.has(toolId)) {
1534
- settledTools.add(toolId);
1535
- yield {
1536
- type: "tool_result",
1537
- toolCallId: toolId,
1538
- toolName,
1539
- outcome: {
1540
- ok: status === "completed",
1541
- ...state?.output !== void 0 ? { result: state.output } : {},
1542
- ...asString(state?.error) ? { message: asString(state?.error) } : {}
1543
- }
1544
- };
1545
- }
1546
- return;
1547
- }
1548
- if (partType === "step-finish") {
1549
- addStepFinishUsage(part, usage);
1550
- recordPersistedPart(part, void 0, `step-finish:#${projectionState.stepCounter++}`);
1551
- const promptTokens = usage.inputTokens ?? 0;
1552
- const completionTokens = usage.outputTokens ?? 0;
1553
- if (promptTokens || completionTokens) {
1554
- yield {
1555
- type: "usage",
1556
- usage: {
1557
- promptTokens,
1558
- completionTokens,
1559
- ...usage.reasoningTokens !== void 0 ? { reasoningTokens: usage.reasoningTokens } : {},
1560
- ...usage.costUsd !== void 0 ? { providerCostUsd: usage.costUsd } : {}
1698
+ yield* emitFinalUsage();
1561
1699
  }
1562
- };
1700
+ yield* emitTerminalizedTools();
1701
+ yield toProducerWireEvent(record);
1702
+ continue;
1703
+ }
1704
+ if (event.type === "error") {
1705
+ const message = sandboxStreamErrorMessage(event.data);
1706
+ const errorContent = projectionState.fullText.trim() ? `The sandbox model stream stopped before a clean completion.
1707
+
1708
+ Error: ${message}` : `The sandbox agent returned an error before producing a visible answer.
1709
+
1710
+ Error: ${message}`;
1711
+ if (options.errorNotice) {
1712
+ yield* emitErrorNotice(errorContent, sandboxStreamErrorCode(event.data));
1713
+ } else if (options.includeErrorText !== false) {
1714
+ const errorDelta = projectionState.fullText ? `
1715
+
1716
+ ---
1717
+ ${errorContent}` : errorContent;
1718
+ projectionState.fullText += errorDelta;
1719
+ yield { type: "text", text: errorDelta };
1720
+ }
1721
+ projectionState.interactionOutcome = "expired";
1722
+ yield* emitTerminalizedTools();
1723
+ yield toProducerWireEvent(record);
1724
+ continue;
1725
+ }
1726
+ yield toProducerWireEvent(record);
1563
1727
  }
1564
- return;
1565
- }
1566
- if (partType === "step-start") {
1567
- recordPersistedPart(part, void 0, `step-start:#${projectionState.stepCounter}`);
1568
- return;
1569
- }
1570
- if (partType === "file" && options.promoteFilePart) {
1571
- const promote = options.promoteFilePart;
1572
- const rawId = asString(part.id);
1573
- const rawUrl = asString(part.url);
1574
- const memoKey = rawId ? `id:${rawId}` : rawUrl ? `url:${rawUrl}` : void 0;
1575
- const attempt = () => Promise.resolve().then(() => promote(part)).catch((err) => {
1576
- const reason = err instanceof Error ? err.message : String(err);
1577
- log("[chat-routes] file part promotion threw", { key: memoKey ?? "(keyless)", error: reason });
1578
- return { succeeded: false, reason };
1728
+ yield* drainModelNotices();
1729
+ } catch (streamErr) {
1730
+ preflightRefused = !observedSourceEvent && openAttempts() === 1 && streamErr instanceof SandboxRunError && streamErr.code === "sandbox_unavailable";
1731
+ const diagnostic = sandboxStreamFailureDiagnostic(streamErr);
1732
+ log("[chat-routes] sandbox stream failed", {
1733
+ failureNote: diagnostic.failureNote,
1734
+ error: streamErr instanceof Error ? streamErr.message : String(streamErr)
1579
1735
  });
1580
- let pending;
1581
- if (memoKey) {
1582
- pending = promotedFileParts.get(memoKey) ?? attempt();
1583
- promotedFileParts.set(memoKey, pending);
1584
- } else {
1585
- pending = attempt();
1586
- }
1587
- const outcome = await pending;
1588
- if (outcome.succeeded) {
1589
- recordPersistedPart(outcome.part, void 0, outcome.key);
1590
- } else if (outcome.part) {
1591
- recordPersistedPart(outcome.part, void 0, outcome.key);
1592
- } else {
1593
- recordPersistedPart(part, void 0);
1594
- }
1595
- return;
1596
- }
1597
- recordPersistedPart(part, void 0);
1598
- return;
1599
- }
1600
- }
1736
+ if (options.errorNotice) {
1737
+ yield* emitErrorNotice(diagnostic.userMessage, diagnostic.code);
1738
+ } else if (options.includeErrorText !== false) {
1739
+ const errorDelta = projectionState.fullText ? `
1601
1740
 
1602
- // src/chat-routes/cancellation.ts
1603
- var targetChanged = () => Response.json({
1604
- error: "This Stop no longer matches the current turn attempt. Refresh its current state.",
1605
- code: "CANCEL_TARGET_CHANGED"
1606
- }, { status: 409 });
1607
- var stateChanged = () => Response.json({
1608
- error: "This turn changed while Stop was pending. Refresh before trying Stop again.",
1609
- code: "CANCEL_STATE_CHANGED"
1610
- }, { status: 409 });
1611
- var success = (sandboxInterrupted) => Response.json({ succeeded: true, sandboxInterrupted });
1612
- async function cancelChatTurn(request, options) {
1613
- if (!options.cancel || request.method !== "POST") {
1614
- return Response.json({ error: "Method not allowed" }, { status: 405 });
1615
- }
1616
- const [raw, invalid] = await parseJsonObjectBody(request, { maxBytes: INLINE_PARTS_MAX_BYTES });
1617
- if (invalid) return invalid;
1618
- const threadId = typeof raw.threadId === "string" ? raw.threadId.trim() : "";
1619
- const turnId = typeof raw.turnId === "string" ? raw.turnId.trim() : "";
1620
- if (!threadId || !turnId) {
1621
- return Response.json({ error: "Missing workspaceId, threadId, or turnId" }, { status: 400 });
1622
- }
1623
- const body = {
1624
- ...raw,
1625
- threadId,
1626
- turnId,
1627
- cancellationToken: typeof raw.cancellationToken === "string" ? raw.cancellationToken : void 0
1628
- };
1629
- const log = options.log ?? ((message, meta) => console.error(message, meta ?? {}));
1630
- try {
1631
- const auth = await options.authorize({ request, intent: "cancel", body, threadId });
1632
- if (!auth.ok) return auth.response;
1633
- if (auth.intent !== void 0 && auth.intent !== "cancel") {
1634
- return Response.json({ error: "Authorization did not allow this turn cancellation.", code: "chat_authorization_intent_mismatch" }, { status: 403 });
1635
- }
1636
- const target = await options.cancel.target({
1637
- request,
1638
- body,
1639
- tenantId: auth.tenantId,
1640
- userId: auth.userId,
1641
- ..."context" in auth ? { context: auth.context } : {}
1642
- });
1643
- if (target instanceof Response) return target;
1644
- if (target.requiresDispatchToken && (!body.cancellationToken || body.cancellationToken !== target.dispatchToken)) {
1645
- return targetChanged();
1646
- }
1647
- if (target.status === "stopped" || target.status === "answered") return success(false);
1648
- if (target.control) {
1649
- const intent = await target.control.request(target.capturedMetadata);
1650
- return intent.requested ? Response.json({ succeeded: true, sandboxInterrupted: false, cancellationRequested: true }) : targetChanged();
1651
- }
1652
- const markStopped = async () => await target.markStopped(target.capturedMetadata, (/* @__PURE__ */ new Date()).toISOString()) ? null : stateChanged();
1653
- if (!target.native) return await markStopped() ?? success(false);
1654
- const native = target.native;
1655
- if (native.state !== "running" || !native.executionId || !native.sessionId || !native.sandboxId) {
1656
- return Response.json({
1657
- error: "This turn has no confirmed native execution to stop. Refresh and try again.",
1658
- code: "NATIVE_CANCEL_TARGET_UNAVAILABLE"
1659
- }, { status: 409 });
1660
- }
1661
- const source = await native.source();
1662
- if (!source || source.id !== native.sandboxId) {
1663
- return Response.json({ error: "The turn was not marked stopped because its original sandbox is unavailable." }, { status: 503 });
1664
- }
1665
- try {
1666
- const session = source.session(native.sessionId);
1667
- const interrupted = await session.interrupt({ executionId: native.executionId });
1668
- if (!interrupted.cancelled) {
1669
- const current = await session.status();
1670
- const anotherExecution = typeof current?.activeExecutionId === "string" && current.activeExecutionId.length > 0 && current.activeExecutionId !== native.executionId;
1671
- const terminal = current && ["completed", "failed", "cancelled"].includes(current.status ?? "");
1672
- if (!current || current.id !== native.sessionId || current.activeExecutionId === native.executionId || !anotherExecution && !terminal) {
1673
- throw new Error("The targeted native execution has not been confirmed stopped");
1674
- }
1741
+ ---
1742
+ ${diagnostic.userMessage}` : diagnostic.userMessage;
1743
+ projectionState.fullText += errorDelta;
1744
+ yield { type: "text", text: errorDelta };
1675
1745
  }
1676
- return await markStopped() ?? success(interrupted.cancelled);
1677
- } catch (error) {
1678
- log("[chat-routes] native cancellation failed", { error: redactErrorMessage(error) });
1679
- return Response.json({ error: "The turn was not marked stopped because its native execution could not be confirmed interrupted." }, { status: 502 });
1746
+ projectionState.interactionOutcome = "expired";
1747
+ yield* emitTerminalizedTools();
1748
+ yield {
1749
+ type: "error",
1750
+ data: {
1751
+ message: diagnostic.userMessage,
1752
+ code: diagnostic.code,
1753
+ details: { failureNote: diagnostic.failureNote }
1754
+ }
1755
+ };
1756
+ } finally {
1757
+ reasoningClock.settle();
1680
1758
  }
1681
- } catch (error) {
1682
- if (error instanceof Response) return error;
1683
- log("[chat-routes] cancellation failed", { error: redactErrorMessage(error) });
1684
- return Response.json({ error: "Turn cancellation is temporarily unavailable." }, { status: 503 });
1685
- }
1686
- }
1687
- async function* observeTurnCancellation(source, args, cancel, abort) {
1688
- if (!args.userMessageId) {
1689
- yield* source;
1690
- return;
1691
1759
  }
1692
- const iterator = source[Symbol.asyncIterator]();
1693
- let closed = false, stopped = false, drained = false, warned = false;
1694
- let polling;
1695
- let notifyStop;
1696
- const stop = new Promise((resolve) => {
1697
- notifyStop = () => {
1698
- resolve({ done: true, value: void 0 });
1699
- };
1700
- });
1701
- const body = {
1702
- ...args.body,
1703
- threadId: args.identity.sessionId,
1704
- turnId: typeof args.body.turnId === "string" ? args.body.turnId : "",
1705
- cancellationToken: typeof args.body.cancellationToken === "string" ? args.body.cancellationToken : void 0
1760
+ return {
1761
+ stream: stream(),
1762
+ finalText: () => projectionState.fullText,
1763
+ terminalObserved: () => projectionState.terminalObserved || preflightRefused,
1764
+ assistantParts: () => finalizePendingInteractionParts(
1765
+ finalizeAssistantParts(partOrder, timedParts(), projectionState.fullText),
1766
+ projectionState.interactionOutcome
1767
+ ),
1768
+ // Mid-stream snapshot for incremental persistence: the same accumulators,
1769
+ // WITHOUT the two completion-time settlements (`terminalizeDanglingTool*`
1770
+ // and `finalizePendingInteractionParts`). A running tool and an unanswered
1771
+ // ask are the correct live state; settling them early would persist
1772
+ // phantom failures the final write then reverses.
1773
+ draftParts: () => draftAssistantParts(partOrder, timedParts(), projectionState.fullText),
1774
+ usage: () => usage,
1775
+ // A GETTER, not a captured value: `turn-routes` reads `producer.model` at
1776
+ // draft-snapshot and persist time, both of which happen after the stream
1777
+ // resolved which model serves. A plain property would freeze the PREFERRED
1778
+ // model into the row and make a downgrade unattributable — the exact
1779
+ // failure mode this work exists to prevent.
1780
+ get model() {
1781
+ return servedModel();
1782
+ },
1783
+ modelFailover: () => ({
1784
+ model: servingModel(),
1785
+ attempts: failover?.attempts() ?? [],
1786
+ usedFallback: failover?.usedFallback() ?? false
1787
+ }),
1788
+ modelAttribution: () => ({
1789
+ ...options.model ? { requestedModel: options.model } : {},
1790
+ ...modelState.effectiveBackend ?? {},
1791
+ echoReceived: modelState.effectiveBackend !== void 0
1792
+ })
1706
1793
  };
1707
- const readTarget = async () => {
1708
- if (closed) return true;
1709
- try {
1710
- const target = await cancel.target({
1711
- request: args.request,
1712
- body,
1713
- tenantId: args.identity.tenantId,
1714
- userId: args.identity.userId,
1715
- context: args.context,
1716
- messageId: args.userMessageId
1717
- });
1718
- if (closed) return true;
1719
- if (target instanceof Response) return false;
1720
- if (target.status === "stopped" || target.status === "superseded") {
1721
- stopped = true;
1722
- abort.abort(new Error("The captured turn was stopped or superseded."));
1723
- notifyStop();
1724
- } else if (target.status === "answered") clearInterval(timer);
1725
- return true;
1726
- } catch (error) {
1727
- if (!warned) {
1728
- warned = true;
1729
- console.error("[chat-routes] stop observation unavailable", { error: redactErrorMessage(error) });
1730
- }
1731
- return false;
1794
+ }
1795
+ function createSandboxProjection(projectionState, pendingModelNotices) {
1796
+ const partOrder = [];
1797
+ const partMap = /* @__PURE__ */ new Map();
1798
+ const tracker = { seen: /* @__PURE__ */ new Map() };
1799
+ const reasoningClock = createReasoningClock();
1800
+ const usage = {};
1801
+ const announcedToolArgs = /* @__PURE__ */ new Map();
1802
+ const settledTools = /* @__PURE__ */ new Set();
1803
+ const promotedFileParts = /* @__PURE__ */ new Map();
1804
+ function recordPersistedPart(part, delta, keyOverride) {
1805
+ const persisted = normalizePersistedPart(part);
1806
+ if (!persisted) return;
1807
+ const key = keyOverride ?? getPartKey(persisted);
1808
+ if (!partMap.has(key)) partOrder.push(key);
1809
+ partMap.set(key, mergePersistedPart(partMap.get(key), persisted, delta));
1810
+ }
1811
+ function* emitTerminalizedTools() {
1812
+ if (projectionState.danglingToolsTerminalized) return;
1813
+ projectionState.danglingToolsTerminalized = true;
1814
+ const updates = terminalizeDanglingAssistantToolUpdates(partOrder, partMap, projectionState.fullText);
1815
+ for (const part of updates) {
1816
+ const toolId = asString(part.id);
1817
+ if (!toolId || settledTools.has(toolId)) continue;
1818
+ settledTools.add(toolId);
1819
+ const state = asRecord(part.state);
1820
+ yield {
1821
+ type: "tool_result",
1822
+ toolCallId: toolId,
1823
+ toolName: asString(part.tool) ?? "tool",
1824
+ outcome: {
1825
+ ok: false,
1826
+ ...asString(state?.error) ? { message: asString(state?.error) } : {}
1827
+ }
1828
+ };
1732
1829
  }
1733
- };
1734
- const poll = () => polling ??= readTarget().finally(() => {
1735
- polling = void 0;
1736
- });
1737
- const timer = setInterval(() => {
1738
- void poll();
1739
- }, 1e3);
1740
- try {
1741
- let pending = iterator.next();
1742
- void pending.catch(() => {
1743
- });
1744
- void poll();
1745
- while (!stopped) {
1746
- let next;
1747
- try {
1748
- next = await Promise.race([pending, stop]);
1749
- } catch (error) {
1750
- if (stopped) return;
1751
- throw error;
1752
- }
1753
- if (stopped) return;
1754
- if (next.done) {
1755
- await polling;
1756
- if (!await poll()) throw new Error("The captured turn state could not be confirmed at completion");
1757
- if (stopped) return;
1758
- drained = true;
1759
- return;
1760
- }
1761
- yield next.value;
1762
- pending = iterator.next();
1763
- void pending.catch(() => {
1764
- });
1830
+ }
1831
+ function* emitFinalUsage() {
1832
+ const promptTokens = usage.inputTokens ?? 0;
1833
+ const completionTokens = usage.outputTokens ?? 0;
1834
+ if (promptTokens || completionTokens) {
1835
+ yield {
1836
+ type: "usage",
1837
+ usage: {
1838
+ promptTokens,
1839
+ completionTokens,
1840
+ ...usage.reasoningTokens !== void 0 ? { reasoningTokens: usage.reasoningTokens } : {},
1841
+ ...usage.costUsd !== void 0 ? { providerCostUsd: usage.costUsd } : {}
1842
+ }
1843
+ };
1765
1844
  }
1766
- } finally {
1767
- closed = true;
1768
- clearInterval(timer);
1769
- if (!drained) {
1770
- const cleanup = iterator.return?.().catch(() => {
1771
- });
1772
- if (cleanup) args.waitUntil?.(cleanup);
1845
+ }
1846
+ function* drainModelNotices() {
1847
+ while (pendingModelNotices.length > 0) {
1848
+ const queued = pendingModelNotices.shift();
1849
+ const notice = noticePart("warning", queued.id, queued.text);
1850
+ recordPersistedPart(notice, void 0, noticePartKey(notice.id));
1851
+ yield { type: "notice", id: notice.id, noticeKind: "warning", text: queued.text };
1773
1852
  }
1774
1853
  }
1775
- }
1776
-
1777
- // src/chat-routes/turn-route-contracts.ts
1778
- var INTENT_LINE_TIMEOUT_MS = 1500;
1779
- var INTENT_LINE_HISTORY_MESSAGES = 6;
1780
- var INTENT_LINE_MAX_CHARS = 240;
1781
-
1782
- // src/chat-routes/upload.ts
1783
- var UPLOAD_INLINE_MAX_BYTES = 700 * 1024;
1784
- var UPLOAD_MAX_FILE_BYTES = 8 * 1024 * 1024;
1785
- var DEFAULT_UPLOAD_DIRECTORY = "/workspace/uploads";
1786
- function normalizeUploadDirectory(value) {
1787
- const withoutTrailingSlash = value.trim().replace(/\/+$/, "");
1788
- if (!withoutTrailingSlash.startsWith("/") || withoutTrailingSlash.length === 0) return null;
1789
- const segments = withoutTrailingSlash.slice(1).split("/");
1790
- if (segments.some((segment) => segment.length === 0 || segment === "." || segment === "..")) return null;
1791
- return `/${segments.join("/")}`;
1792
- }
1793
- function sanitizeUploadFilename(name) {
1794
- const base = name.split(/[\\/]/).pop() ?? "file";
1795
- const safe = base.replace(/[^A-Za-z0-9._-]+/g, "_").replace(/^\.+/, "_");
1796
- return (safe || "file").slice(0, 120);
1797
- }
1798
- var BASE64_CHUNK = 32768;
1799
- function bytesToBase64(bytes) {
1800
- let binary = "";
1801
- for (let offset = 0; offset < bytes.length; offset += BASE64_CHUNK) {
1802
- binary += String.fromCharCode(...bytes.subarray(offset, offset + BASE64_CHUNK));
1854
+ function* emitErrorNotice(text, code) {
1855
+ projectionState.errorNoticeCount += 1;
1856
+ const notice = noticePart("error", `error-${projectionState.errorNoticeCount}`, text, code);
1857
+ recordPersistedPart(notice, void 0, noticePartKey(notice.id));
1858
+ yield { type: "notice", id: notice.id, noticeKind: "error", text, code };
1803
1859
  }
1804
- return btoa(binary);
1805
- }
1806
- function uploadError(status, code, error) {
1807
- return Response.json({ code, error }, { status });
1808
- }
1809
- function createUploadRoute(options) {
1810
- const inlineMaxBytes = options.inlineMaxBytes ?? UPLOAD_INLINE_MAX_BYTES;
1811
- const maxFileBytes = options.maxFileBytes ?? UPLOAD_MAX_FILE_BYTES;
1812
- return async function upload(request) {
1813
- const auth = await options.authorize({ request });
1814
- if (!auth.ok) return auth.response;
1815
- const sink = auth.sink ?? null;
1816
- const configuredUploadDir = auth.uploadDir ?? options.uploadDir ?? DEFAULT_UPLOAD_DIRECTORY;
1817
- let form;
1818
- try {
1819
- form = await request.formData();
1820
- } catch {
1821
- return uploadError(400, "INVALID_UPLOAD", "Expected a multipart/form-data body with file fields");
1860
+ const timedParts = () => {
1861
+ const timed = new Map(partMap);
1862
+ for (const [key, part] of partMap) {
1863
+ if (part.type !== "reasoning") continue;
1864
+ const time = reasoningClock.time(key, asRecord(part.time));
1865
+ if (time) timed.set(key, { ...part, time });
1822
1866
  }
1823
- const files = [];
1824
- form.forEach((value) => {
1825
- if (value instanceof File) files.push(value);
1826
- });
1827
- if (files.length === 0) {
1828
- return uploadError(400, "INVALID_UPLOAD", "No files in the upload body");
1867
+ return timed;
1868
+ };
1869
+ return { timedParts, drainModelNotices, tracker, recordPersistedPart, reasoningClock, partMap, announcedToolArgs, settledTools, usage, promotedFileParts, emitFinalUsage, emitTerminalizedTools, emitErrorNotice, partOrder };
1870
+ }
1871
+ async function* projectSandboxMessagePart(event, tracker, recordPersistedPart, reasoningClock, projectionState, partMap, announcedToolArgs, settledTools, usage, options, log, promotedFileParts) {
1872
+ if (event.type === "message.part.updated") {
1873
+ const part = asRecord(event.data?.part);
1874
+ if (!part) return;
1875
+ const rawDelta = event.data?.delta;
1876
+ const partType = String(part.type ?? "");
1877
+ if (partType === "text" || partType === "reasoning") {
1878
+ const key = getPartKey(part);
1879
+ const delta = textDelta(tracker, key, part, rawDelta);
1880
+ recordPersistedPart(part, delta || void 0);
1881
+ if (delta) {
1882
+ if (partType === "reasoning") reasoningClock.reasoning(key);
1883
+ else reasoningClock.settle();
1884
+ if (partType === "text") projectionState.fullText += delta;
1885
+ yield { type: partType, text: delta };
1886
+ }
1887
+ return;
1829
1888
  }
1830
- const uploaded = [];
1831
- for (const file of files) {
1832
- const name = sanitizeUploadFilename(file.name);
1833
- const mediaType = file.type || "application/octet-stream";
1834
- const partType = mediaType.startsWith("image/") ? "image" : "file";
1835
- if (file.size > maxFileBytes) {
1836
- return uploadError(
1837
- 413,
1838
- "FILE_TOO_LARGE",
1839
- `${name} is ${file.size}B, over the ${maxFileBytes}B per-file cap`
1840
- );
1889
+ if (partType === "tool") {
1890
+ reasoningClock.settle();
1891
+ recordPersistedPart(part, void 0);
1892
+ const persisted = partMap.get(getPartKey(part));
1893
+ const state = asRecord(persisted?.state);
1894
+ const toolId = String(persisted?.id ?? "");
1895
+ const toolName = String(persisted?.tool ?? "tool");
1896
+ const args = asRecord(state?.input) ?? {};
1897
+ const hasPopulatedArgs = Object.keys(args).length > 0;
1898
+ const announcedWithPopulatedArgs = announcedToolArgs.get(toolId);
1899
+ if (toolId && (announcedWithPopulatedArgs === void 0 || !announcedWithPopulatedArgs && hasPopulatedArgs && !settledTools.has(toolId))) {
1900
+ announcedToolArgs.set(toolId, hasPopulatedArgs);
1901
+ yield {
1902
+ type: "tool_call",
1903
+ call: { toolCallId: toolId, toolName, args }
1904
+ };
1841
1905
  }
1842
- const id = crypto.randomUUID();
1843
- if (file.size <= inlineMaxBytes) {
1844
- const base642 = bytesToBase64(new Uint8Array(await file.arrayBuffer()));
1845
- uploaded.push({
1846
- id,
1847
- name,
1848
- size: file.size,
1849
- mediaType,
1850
- inline: true,
1851
- part: {
1852
- type: partType,
1853
- filename: name,
1854
- mediaType,
1855
- url: `data:${mediaType};base64,${base642}`
1906
+ const status = String(state?.status ?? "");
1907
+ if (toolId && (status === "completed" || status === "error") && !settledTools.has(toolId)) {
1908
+ settledTools.add(toolId);
1909
+ yield {
1910
+ type: "tool_result",
1911
+ toolCallId: toolId,
1912
+ toolName,
1913
+ outcome: {
1914
+ ok: status === "completed",
1915
+ ...state?.output !== void 0 ? { result: state.output } : {},
1916
+ ...asString(state?.error) ? { message: asString(state?.error) } : {}
1856
1917
  }
1857
- });
1858
- continue;
1859
- }
1860
- if (!sink) {
1861
- return uploadError(
1862
- 413,
1863
- "SANDBOX_REQUIRED",
1864
- `${name} is ${file.size}B, over the ${inlineMaxBytes}B inline cap, and no sandbox is available to hold it`
1865
- );
1918
+ };
1866
1919
  }
1867
- const uploadDir = normalizeUploadDirectory(configuredUploadDir);
1868
- if (!uploadDir) {
1869
- return uploadError(
1870
- 500,
1871
- "INVALID_UPLOAD_DIRECTORY",
1872
- 'uploadDir must be an absolute path without empty, "." or ".." segments'
1873
- );
1920
+ return;
1921
+ }
1922
+ if (partType === "step-finish") {
1923
+ addStepFinishUsage(part, usage);
1924
+ recordPersistedPart(part, void 0, `step-finish:#${projectionState.stepCounter++}`);
1925
+ const promptTokens = usage.inputTokens ?? 0;
1926
+ const completionTokens = usage.outputTokens ?? 0;
1927
+ if (promptTokens || completionTokens) {
1928
+ yield {
1929
+ type: "usage",
1930
+ usage: {
1931
+ promptTokens,
1932
+ completionTokens,
1933
+ ...usage.reasoningTokens !== void 0 ? { reasoningTokens: usage.reasoningTokens } : {},
1934
+ ...usage.costUsd !== void 0 ? { providerCostUsd: usage.costUsd } : {}
1935
+ }
1936
+ };
1874
1937
  }
1875
- const path = `${uploadDir}/${id}-${name}`;
1876
- const base64 = bytesToBase64(new Uint8Array(await file.arrayBuffer()));
1877
- await sink.write(path, base64, { encoding: "base64" });
1878
- uploaded.push({
1879
- id,
1880
- name,
1881
- size: file.size,
1882
- mediaType,
1883
- inline: false,
1884
- part: { type: partType, filename: name, mediaType, path }
1938
+ return;
1939
+ }
1940
+ if (partType === "step-start") {
1941
+ recordPersistedPart(part, void 0, `step-start:#${projectionState.stepCounter}`);
1942
+ return;
1943
+ }
1944
+ if (partType === "file" && options.promoteFilePart) {
1945
+ const promote = options.promoteFilePart;
1946
+ const rawId = asString(part.id);
1947
+ const rawUrl = asString(part.url);
1948
+ const memoKey = rawId ? `id:${rawId}` : rawUrl ? `url:${rawUrl}` : void 0;
1949
+ const attempt = () => Promise.resolve().then(() => promote(part)).catch((err) => {
1950
+ const reason = err instanceof Error ? err.message : String(err);
1951
+ log("[chat-routes] file part promotion threw", { key: memoKey ?? "(keyless)", error: reason });
1952
+ return { succeeded: false, reason };
1885
1953
  });
1954
+ let pending;
1955
+ if (memoKey) {
1956
+ pending = promotedFileParts.get(memoKey) ?? attempt();
1957
+ promotedFileParts.set(memoKey, pending);
1958
+ } else {
1959
+ pending = attempt();
1960
+ }
1961
+ const outcome = await pending;
1962
+ if (outcome.succeeded) {
1963
+ recordPersistedPart(outcome.part, void 0, outcome.key);
1964
+ } else if (outcome.part) {
1965
+ recordPersistedPart(outcome.part, void 0, outcome.key);
1966
+ } else {
1967
+ recordPersistedPart(part, void 0);
1968
+ }
1969
+ return;
1886
1970
  }
1887
- return Response.json({ files: uploaded });
1888
- };
1971
+ recordPersistedPart(part, void 0);
1972
+ return;
1973
+ }
1889
1974
  }
1890
1975
 
1891
- // src/chat-routes/dispatch-parts.ts
1892
- import { pathToFileURL } from "url";
1893
- function byteLen(value) {
1894
- return new TextEncoder().encode(value).length;
1895
- }
1896
- async function readSandboxMention(box, absolutePath, options) {
1897
- const stat = await statSandboxFileSize(box, absolutePath);
1898
- if (!stat.succeeded) {
1899
- return { succeeded: false, error: `mentioned sandbox file missing or unreadable: ${absolutePath} \u2014 ${stat.error}` };
1976
+ // src/chat-routes/cancellation.ts
1977
+ var targetChanged = () => Response.json({
1978
+ error: "This Stop no longer matches the current turn attempt. Refresh its current state.",
1979
+ code: "CANCEL_TARGET_CHANGED"
1980
+ }, { status: 409 });
1981
+ var stateChanged = () => Response.json({
1982
+ error: "This turn changed while Stop was pending. Refresh before trying Stop again.",
1983
+ code: "CANCEL_STATE_CHANGED"
1984
+ }, { status: 409 });
1985
+ var success = (sandboxInterrupted) => Response.json({ succeeded: true, sandboxInterrupted });
1986
+ async function cancelChatTurn(request, options) {
1987
+ if (!options.cancel || request.method !== "POST") {
1988
+ return Response.json({ error: "Method not allowed" }, { status: 405 });
1900
1989
  }
1901
- if (!options.readBytes) return { succeeded: true, value: { size: stat.value } };
1902
- const read = await readSandboxBinaryBytes(box, absolutePath, stat.value);
1903
- if (!read.succeeded) {
1904
- return { succeeded: false, error: `mentioned sandbox file read failed: ${absolutePath} \u2014 ${read.error}` };
1990
+ const [raw, invalid] = await parseJsonObjectBody(request, { maxBytes: INLINE_PARTS_MAX_BYTES });
1991
+ if (invalid) return invalid;
1992
+ const threadId = typeof raw.threadId === "string" ? raw.threadId.trim() : "";
1993
+ const turnId = typeof raw.turnId === "string" ? raw.turnId.trim() : "";
1994
+ if (!threadId || !turnId) {
1995
+ return Response.json({ error: "Missing workspaceId, threadId, or turnId" }, { status: 400 });
1905
1996
  }
1906
- return { succeeded: true, value: { size: stat.value, base64: bytesToBase64(read.value.bytes) } };
1907
- }
1908
- function violatesUrlPathXor(part) {
1909
- if (part.type === "text") return false;
1910
- const hasUrl = typeof part.url === "string" && (part.url.startsWith("data:") || part.url.startsWith("file://"));
1911
- const hasPath = "path" in part && typeof part.path === "string" && part.path.startsWith("/");
1912
- if (part.type === "file") return !hasUrl || hasPath;
1913
- return hasUrl === hasPath;
1914
- }
1915
- function sandboxFileUrl(absolutePath) {
1916
- if (!absolutePath.startsWith("/")) return void 0;
1997
+ const body = {
1998
+ ...raw,
1999
+ threadId,
2000
+ turnId,
2001
+ cancellationToken: typeof raw.cancellationToken === "string" ? raw.cancellationToken : void 0
2002
+ };
2003
+ const log = options.log ?? ((message, meta) => console.error(message, meta ?? {}));
1917
2004
  try {
1918
- return pathToFileURL(absolutePath).href;
1919
- } catch {
1920
- return void 0;
1921
- }
1922
- }
1923
- function normalizeChatPromptForSandbox(prompt) {
1924
- if (typeof prompt === "string") return prompt;
1925
- return prompt.map((part) => {
1926
- if (part.type === "text") return part;
1927
- if ("content" in part) {
1928
- throw new ChatTurnInputError("Sandbox prompt parts do not accept inline content; provide a URL or path");
1929
- }
1930
- const url = typeof part.url === "string" && part.url.length > 0 ? part.url : void 0;
1931
- const path = typeof part.path === "string" && part.path.length > 0 ? part.path : void 0;
1932
- if (Boolean(url) === Boolean(path)) {
1933
- throw new ChatTurnInputError(`Sandbox ${part.type} parts require exactly one URL or path`);
1934
- }
1935
- if (path && !path.startsWith("/")) {
1936
- throw new ChatTurnInputError(`Sandbox ${part.type} paths must be absolute: ${path}`);
2005
+ const auth = await options.authorize({ request, intent: "cancel", body, threadId });
2006
+ if (!auth.ok) return auth.response;
2007
+ if (auth.intent !== void 0 && auth.intent !== "cancel") {
2008
+ return Response.json({ error: "Authorization did not allow this turn cancellation.", code: "chat_authorization_intent_mismatch" }, { status: 403 });
1937
2009
  }
1938
- if (part.type === "image") {
1939
- return {
1940
- type: "image",
1941
- ...part.filename ? { filename: part.filename } : {},
1942
- ...part.mediaType ? { mediaType: part.mediaType } : {},
1943
- ...url ? { url } : { path }
1944
- };
2010
+ const target = await options.cancel.target({
2011
+ request,
2012
+ body,
2013
+ tenantId: auth.tenantId,
2014
+ userId: auth.userId,
2015
+ ..."context" in auth ? { context: auth.context } : {}
2016
+ });
2017
+ if (target instanceof Response) return target;
2018
+ if (target.requiresDispatchToken && (!body.cancellationToken || body.cancellationToken !== target.dispatchToken)) {
2019
+ return targetChanged();
1945
2020
  }
1946
- const filename = part.filename?.trim();
1947
- if (!filename) {
1948
- throw new ChatTurnInputError("Sandbox file parts require a filename");
2021
+ if (target.status === "stopped" || target.status === "answered") return success(false);
2022
+ if (target.control) {
2023
+ const intent = await target.control.request(target.capturedMetadata);
2024
+ return intent.requested ? Response.json({ succeeded: true, sandboxInterrupted: false, cancellationRequested: true }) : targetChanged();
1949
2025
  }
1950
- const fileUrl = url ?? sandboxFileUrl(path);
1951
- if (!fileUrl) {
1952
- throw new ChatTurnInputError(`Sandbox file paths must be absolute: ${path}`);
2026
+ const markStopped = async () => await target.markStopped(target.capturedMetadata, (/* @__PURE__ */ new Date()).toISOString()) ? null : stateChanged();
2027
+ if (!target.native) return await markStopped() ?? success(false);
2028
+ const native = target.native;
2029
+ if (native.state !== "running" || !native.executionId || !native.sessionId || !native.sandboxId) {
2030
+ return Response.json({
2031
+ error: "This turn has no confirmed native execution to stop. Refresh and try again.",
2032
+ code: "NATIVE_CANCEL_TARGET_UNAVAILABLE"
2033
+ }, { status: 409 });
1953
2034
  }
1954
- return {
1955
- type: "file",
1956
- filename,
1957
- ...part.mediaType ? { mediaType: part.mediaType } : {},
1958
- url: fileUrl
1959
- };
1960
- });
1961
- }
1962
- function projectDispatchHistory(messages) {
1963
- return messages.map((message) => ({
1964
- role: message.role === "assistant" ? "assistant" : "user",
1965
- content: historyContentWithAttachments(message)
1966
- }));
1967
- }
1968
- function readResultToBase64(read) {
1969
- if (typeof read.base64 === "string") return read.base64;
1970
- if (read.bytes) return bytesToBase64(read.bytes);
1971
- return void 0;
1972
- }
1973
- async function buildDispatchParts(input) {
1974
- const readMention = input.readSandboxMention ?? readSandboxMention;
1975
- const resolveMentionPath = input.resolveMentionPath ?? input.resolveAttachmentPath;
1976
- const forcePath = input.forcePath ?? false;
1977
- const mentions = input.mentions ?? [];
1978
- const requestMaxBytes = input.requestMaxBytes ?? DISPATCH_REQUEST_MAX_BYTES;
1979
- const structuralReserveBytes = input.structuralReserveBytes ?? DISPATCH_STRUCTURAL_RESERVE_BYTES;
1980
- const maxParts = input.maxParts ?? DISPATCH_MAX_PARTS;
1981
- const parts = [{ type: "text", text: input.text }];
1982
- const emittedAbsPaths = /* @__PURE__ */ new Set();
1983
- const flattenedForSizing = flattenHistory(input.text, input.history);
1984
- const inlineBudget = requestMaxBytes - base64WireLen(byteLen(flattenedForSizing)) - byteLen(JSON.stringify(input.systemPrompt)) - input.profileWireBytes - structuralReserveBytes;
1985
- let runningInline = 0;
1986
- for (const attachment of input.attachments) {
1987
- if (!attachment.path) {
1988
- return { succeeded: false, error: `attachment path must be non-empty: ${attachment.name}` };
2035
+ const source = await native.source();
2036
+ if (!source || source.id !== native.sandboxId) {
2037
+ return Response.json({ error: "The turn was not marked stopped because its original sandbox is unavailable." }, { status: 503 });
1989
2038
  }
1990
- let read;
1991
2039
  try {
1992
- read = await input.readAttachment(input.scopeId, attachment.path);
1993
- } catch (err) {
1994
- return {
1995
- succeeded: false,
1996
- error: `attachment store read failed: ${attachment.path} \u2014 ${err instanceof Error ? err.message : String(err)}`
1997
- };
1998
- }
1999
- if (!read.ok) return { succeeded: false, error: read.reason };
2000
- const base64 = readResultToBase64(read);
2001
- if (base64 === void 0) {
2002
- return { succeeded: false, error: `attachment store read produced no content: ${attachment.path}` };
2003
- }
2004
- const mediaType = attachment.mediaType ?? read.mediaType;
2005
- if (attachment.type === "image" && !mediaType) {
2006
- return { succeeded: false, error: `attachment is missing a mediaType required for an image data URI: ${attachment.path}` };
2007
- }
2008
- const absPath = input.resolveAttachmentPath(attachment.path);
2009
- emittedAbsPaths.add(absPath);
2010
- if (attachment.type === "image") {
2011
- const inlinePart2 = {
2012
- type: "image",
2013
- filename: attachment.name,
2014
- mediaType,
2015
- url: `data:${mediaType};base64,${base64}`
2016
- };
2017
- const cost2 = byteLen(JSON.stringify(inlinePart2));
2018
- if (!forcePath && runningInline + cost2 <= inlineBudget) {
2019
- parts.push(inlinePart2);
2020
- runningInline += cost2;
2021
- } else {
2022
- parts.push({ type: "image", filename: attachment.name, mediaType, path: absPath });
2023
- }
2024
- continue;
2025
- }
2026
- const fileMediaType = mediaType ?? "application/octet-stream";
2027
- const inlinePart = {
2028
- type: "file",
2029
- filename: attachment.name,
2030
- mediaType: fileMediaType,
2031
- url: `data:${fileMediaType};base64,${base64}`
2032
- };
2033
- const cost = byteLen(JSON.stringify(inlinePart));
2034
- if (!forcePath && runningInline + cost <= inlineBudget) {
2035
- parts.push(inlinePart);
2036
- runningInline += cost;
2037
- } else {
2038
- const url = sandboxFileUrl(absPath);
2039
- if (!url) {
2040
- return { succeeded: false, error: `resolved attachment path must be absolute: ${absPath}` };
2040
+ const session = source.session(native.sessionId);
2041
+ const interrupted = await session.interrupt({ executionId: native.executionId });
2042
+ if (!interrupted.cancelled) {
2043
+ const current = await session.status();
2044
+ const anotherExecution = typeof current?.activeExecutionId === "string" && current.activeExecutionId.length > 0 && current.activeExecutionId !== native.executionId;
2045
+ const terminal = current && ["completed", "failed", "cancelled"].includes(current.status ?? "");
2046
+ if (!current || current.id !== native.sessionId || current.activeExecutionId === native.executionId || !anotherExecution && !terminal) {
2047
+ throw new Error("The targeted native execution has not been confirmed stopped");
2048
+ }
2041
2049
  }
2042
- parts.push({ type: "file", filename: attachment.name, mediaType: fileMediaType, url });
2050
+ return await markStopped() ?? success(interrupted.cancelled);
2051
+ } catch (error) {
2052
+ log("[chat-routes] native cancellation failed", { error: redactErrorMessage(error) });
2053
+ return Response.json({ error: "The turn was not marked stopped because its native execution could not be confirmed interrupted." }, { status: 502 });
2043
2054
  }
2055
+ } catch (error) {
2056
+ if (error instanceof Response) return error;
2057
+ log("[chat-routes] cancellation failed", { error: redactErrorMessage(error) });
2058
+ return Response.json({ error: "Turn cancellation is temporarily unavailable." }, { status: 503 });
2044
2059
  }
2045
- if (mentions.length > 0 && !input.box) {
2046
- return { succeeded: false, error: "internal error: sandbox mentions require a box to read from" };
2060
+ }
2061
+ async function* observeTurnCancellation(source, args, cancel, abort) {
2062
+ if (!args.userMessageId) {
2063
+ yield* source;
2064
+ return;
2047
2065
  }
2048
- for (const mention of mentions) {
2049
- if (!mention.path) {
2050
- return { succeeded: false, error: `mention path must be non-empty: ${mention.name}` };
2051
- }
2052
- if (!isWorkspaceFileExportable(mention.path)) {
2053
- return { succeeded: false, error: `mention file is not exportable: ${mention.path}` };
2054
- }
2055
- const absPath = resolveMentionPath(mention.path);
2056
- if (emittedAbsPaths.has(absPath)) continue;
2057
- emittedAbsPaths.add(absPath);
2058
- const isImage = mention.mentionKind === "image";
2059
- const mediaType = isImage ? mediaTypeForMentionPath(mention.path) : void 0;
2060
- let stat;
2066
+ const iterator = source[Symbol.asyncIterator]();
2067
+ let closed = false, stopped = false, drained = false, warned = false;
2068
+ let polling;
2069
+ let notifyStop;
2070
+ const stop = new Promise((resolve) => {
2071
+ notifyStop = () => {
2072
+ resolve({ done: true, value: void 0 });
2073
+ };
2074
+ });
2075
+ const body = {
2076
+ ...args.body,
2077
+ threadId: args.identity.sessionId,
2078
+ turnId: typeof args.body.turnId === "string" ? args.body.turnId : "",
2079
+ cancellationToken: typeof args.body.cancellationToken === "string" ? args.body.cancellationToken : void 0
2080
+ };
2081
+ const readTarget = async () => {
2082
+ if (closed) return true;
2061
2083
  try {
2062
- stat = await readMention(input.box, absPath, { readBytes: false });
2063
- } catch (err) {
2064
- return { succeeded: false, error: `mention read failed: ${absPath} \u2014 ${err instanceof Error ? err.message : String(err)}` };
2084
+ const target = await cancel.target({
2085
+ request: args.request,
2086
+ body,
2087
+ tenantId: args.identity.tenantId,
2088
+ userId: args.identity.userId,
2089
+ context: args.context,
2090
+ messageId: args.userMessageId
2091
+ });
2092
+ if (closed) return true;
2093
+ if (target instanceof Response) return false;
2094
+ if (target.status === "stopped" || target.status === "superseded") {
2095
+ stopped = true;
2096
+ abort.abort(new Error("The captured turn was stopped or superseded."));
2097
+ notifyStop();
2098
+ } else if (target.status === "answered") clearInterval(timer);
2099
+ return true;
2100
+ } catch (error) {
2101
+ if (!warned) {
2102
+ warned = true;
2103
+ console.error("[chat-routes] stop observation unavailable", { error: redactErrorMessage(error) });
2104
+ }
2105
+ return false;
2065
2106
  }
2066
- if (!stat.succeeded) return { succeeded: false, error: stat.error };
2067
- const projectedInlineCost = base64WireLen(stat.value.size) + byteLen(JSON.stringify({ type: "image", filename: mention.name, mediaType: mediaType ?? "", url: "" }));
2068
- if (isImage && mediaType && !forcePath && runningInline + projectedInlineCost <= inlineBudget) {
2069
- let read;
2107
+ };
2108
+ const poll = () => polling ??= readTarget().finally(() => {
2109
+ polling = void 0;
2110
+ });
2111
+ const timer = setInterval(() => {
2112
+ void poll();
2113
+ }, 1e3);
2114
+ try {
2115
+ let pending = iterator.next();
2116
+ void pending.catch(() => {
2117
+ });
2118
+ void poll();
2119
+ while (!stopped) {
2120
+ let next;
2070
2121
  try {
2071
- read = await readMention(input.box, absPath, { readBytes: true });
2072
- } catch (err) {
2073
- return { succeeded: false, error: `mention read failed: ${absPath} \u2014 ${err instanceof Error ? err.message : String(err)}` };
2074
- }
2075
- if (!read.succeeded) return { succeeded: false, error: read.error };
2076
- if (!read.value.base64) return { succeeded: false, error: `mentioned image produced no bytes: ${absPath}` };
2077
- const inlinePart = {
2078
- type: "image",
2079
- filename: mention.name,
2080
- mediaType,
2081
- url: `data:${mediaType};base64,${read.value.base64}`
2082
- };
2083
- const cost = byteLen(JSON.stringify(inlinePart));
2084
- if (runningInline + cost <= inlineBudget) {
2085
- parts.push(inlinePart);
2086
- runningInline += cost;
2087
- continue;
2122
+ next = await Promise.race([pending, stop]);
2123
+ } catch (error) {
2124
+ if (stopped) return;
2125
+ throw error;
2088
2126
  }
2089
- }
2090
- if (isImage && mediaType) {
2091
- parts.push({ type: "image", filename: mention.name, mediaType, path: absPath });
2092
- } else {
2093
- const url = sandboxFileUrl(absPath);
2094
- if (!url) {
2095
- return { succeeded: false, error: `resolved mention path must be absolute: ${absPath}` };
2127
+ if (stopped) return;
2128
+ if (next.done) {
2129
+ await polling;
2130
+ if (!await poll()) throw new Error("The captured turn state could not be confirmed at completion");
2131
+ if (stopped) return;
2132
+ drained = true;
2133
+ return;
2096
2134
  }
2097
- parts.push({ type: "file", filename: mention.name, url });
2135
+ yield next.value;
2136
+ pending = iterator.next();
2137
+ void pending.catch(() => {
2138
+ });
2098
2139
  }
2099
- }
2100
- for (const part of parts) {
2101
- if (violatesUrlPathXor(part)) {
2102
- return { succeeded: false, error: "internal error: emitted media part violates the url/path exclusivity invariant" };
2140
+ } finally {
2141
+ closed = true;
2142
+ clearInterval(timer);
2143
+ if (!drained) {
2144
+ const cleanup = iterator.return?.().catch(() => {
2145
+ });
2146
+ if (cleanup) args.waitUntil?.(cleanup);
2103
2147
  }
2104
2148
  }
2105
- const textPartSize = base64WireLen(byteLen(flattenedForSizing));
2106
- const mediaPartsSize = parts.slice(1).reduce((total, part) => total + byteLen(JSON.stringify(part)), 0);
2107
- const systemPromptSize = byteLen(JSON.stringify(input.systemPrompt));
2108
- if (textPartSize + mediaPartsSize + systemPromptSize + input.profileWireBytes + structuralReserveBytes > requestMaxBytes) {
2109
- return { succeeded: false, error: "dispatch parts exceed the sandbox proxy request cap even after path demotion" };
2110
- }
2111
- if (parts.length > maxParts) {
2112
- return { succeeded: false, error: `dispatch parts exceed the sidecar per-request cap of ${maxParts}` };
2113
- }
2114
- return { succeeded: true, value: parts };
2115
- }
2116
-
2117
- // src/chat-routes/turn-prefetch.ts
2118
- function startTurnPrefetch(prefetch, input) {
2119
- let started;
2120
- const start = (identity) => {
2121
- const abort = new AbortController();
2122
- const result = input.trace.measure("admission.prefetch", "admission", async () => prefetch({
2123
- ...input,
2124
- tenantId: identity.tenantId,
2125
- userId: identity.userId,
2126
- signal: abort.signal
2127
- }));
2128
- result.catch(() => {
2129
- });
2130
- started = { identity: { ...identity }, abort, result };
2131
- };
2132
- return {
2133
- identified(identity) {
2134
- if (!started) start(identity);
2135
- },
2136
- admitted(identity) {
2137
- if (started && (started.identity.tenantId !== identity.tenantId || started.identity.userId !== identity.userId)) {
2138
- started.abort.abort();
2139
- started = void 0;
2140
- }
2141
- if (!started) start(identity);
2142
- return started.result;
2143
- },
2144
- discard() {
2145
- started?.abort.abort();
2146
- started = void 0;
2147
- }
2148
- };
2149
2149
  }
2150
2150
 
2151
2151
  // src/chat-routes/turn-admission.ts
@@ -2170,7 +2170,7 @@ function validateTurnBody(body) {
2170
2170
  if (typeof rawContent !== "string") throw new ChatTurnInputError("content must be a string");
2171
2171
  const content = rawContent.trim();
2172
2172
  const fileParts = parseChatTurnParts(body.parts);
2173
- const mentions = parseFileMentions(body.mentions);
2173
+ const mentions = parseMentions(body.mentions);
2174
2174
  const hasAttachments = Array.isArray(body.attachments) && body.attachments.length > 0;
2175
2175
  if (!content && fileParts.length === 0 && mentions.length === 0 && !hasAttachments) {
2176
2176
  throw new ChatTurnInputError("Missing content (send text, parts, mentions, attachments, or any combination)");
@@ -2203,6 +2203,144 @@ function userPartsWithFiles(userParts, fileParts, mentions) {
2203
2203
  ]);
2204
2204
  }
2205
2205
 
2206
+ // src/chat-routes/agent-producers.ts
2207
+ async function addressAgents(input) {
2208
+ const addressed = agentMentionsOf(input.mentions);
2209
+ if (addressed.length === 0) return input.produceArgs;
2210
+ const { agents } = input.options;
2211
+ if (!agents) {
2212
+ return errorResponse(new ChatTurnInputError("This chat does not address agents by mention", 400, "agents_unsupported"));
2213
+ }
2214
+ const targets = await input.trace.measure("admission.agents", "admission", () => agents.resolve({ identity: input.identity, context: input.context, mentions: addressed }));
2215
+ const byId = new Map(targets.map((target) => [target.id, target]));
2216
+ const unknown = addressed.find((mention) => !byId.has(mention.agentId));
2217
+ if (unknown) return errorResponse(new ChatTurnInputError(`Unknown agent @${unknown.handle}`, 400, "unknown_agent"));
2218
+ return { ...input.produceArgs, agents: addressed.map((mention) => byId.get(mention.agentId)) };
2219
+ }
2220
+ var SPEAKER_EVENT = "speaker";
2221
+ function speakerPart(agent) {
2222
+ return { type: "speaker", id: agent.id, name: agent.name, handle: agent.handle };
2223
+ }
2224
+ async function composeAgentProducers(args, produce) {
2225
+ const agents = args.agents ?? [];
2226
+ if (agents.length === 0) throw new Error("composeAgentProducers needs at least one responder");
2227
+ const producers = agents.map(() => void 0);
2228
+ const cleanups = [];
2229
+ const slots = agents.map(() => ({ queue: [], done: false, error: void 0, waiters: [] }));
2230
+ const notify = (slot) => {
2231
+ for (const wake of slot.waiters.splice(0)) wake();
2232
+ };
2233
+ agents.forEach((agent, index) => {
2234
+ const slot = slots[index];
2235
+ void (async () => {
2236
+ try {
2237
+ const producer = await produce({ ...args, agent, executionId: `${args.executionId}-${index + 1}` });
2238
+ producers[index] = producer;
2239
+ if (producer.cleanup) cleanups.push(producer.cleanup);
2240
+ for await (const event of producer.stream) {
2241
+ slot.queue.push(event);
2242
+ notify(slot);
2243
+ }
2244
+ } catch (error) {
2245
+ slot.error = error;
2246
+ } finally {
2247
+ slot.done = true;
2248
+ notify(slot);
2249
+ }
2250
+ })();
2251
+ });
2252
+ const stream = (async function* () {
2253
+ for (const [index, agent] of agents.entries()) {
2254
+ if (args.admissionSignal?.aborted) return;
2255
+ yield { type: SPEAKER_EVENT, id: agent.id, name: agent.name, handle: agent.handle };
2256
+ const slot = slots[index];
2257
+ for (; ; ) {
2258
+ if (slot.queue.length > 0) {
2259
+ yield slot.queue.shift();
2260
+ continue;
2261
+ }
2262
+ if (slot.done) {
2263
+ if (slot.error !== void 0) throw slot.error;
2264
+ break;
2265
+ }
2266
+ await new Promise((wake) => {
2267
+ slot.waiters.push(wake);
2268
+ if (slot.queue.length > 0 || slot.done) notify(slot);
2269
+ });
2270
+ }
2271
+ }
2272
+ })();
2273
+ const entries = () => agents.flatMap((agent, index) => producers[index] ? [{ agent, producer: producers[index] }] : []);
2274
+ const partsOf = (entry, read) => {
2275
+ const own = entry.producer[read]?.();
2276
+ const text = entry.producer.finalText();
2277
+ const parts = own ?? (text ? [{ type: "text", text }] : []);
2278
+ return [speakerPart(entry.agent), ...parts];
2279
+ };
2280
+ const last = () => entries().at(-1)?.producer;
2281
+ return {
2282
+ stream,
2283
+ finalText: () => entries().map(({ producer }) => producer.finalText()).filter((text) => text.trim() !== "").join("\n\n"),
2284
+ assistantParts: () => entries().flatMap((entry) => partsOf(entry, "assistantParts")),
2285
+ draftParts: () => entries().flatMap((entry) => partsOf(entry, "draftParts")),
2286
+ usage: () => entries().reduce((sum, { producer }) => {
2287
+ const usage = producer.usage?.() ?? {};
2288
+ for (const [key, value] of Object.entries(usage)) {
2289
+ if (typeof value === "number") sum[key] = (sum[key] ?? 0) + value;
2290
+ }
2291
+ return sum;
2292
+ }, {}),
2293
+ terminalObserved: () => entries().every(({ producer }) => producer.terminalObserved?.() ?? true),
2294
+ get model() {
2295
+ return last()?.model;
2296
+ },
2297
+ modelFailover: () => last()?.modelFailover?.(),
2298
+ modelAttribution: () => last()?.modelAttribution?.(),
2299
+ cleanup: (async () => {
2300
+ await Promise.all(cleanups);
2301
+ })()
2302
+ };
2303
+ }
2304
+
2305
+ // src/chat-routes/turn-route-contracts.ts
2306
+ var INTENT_LINE_TIMEOUT_MS = 1500;
2307
+ var INTENT_LINE_HISTORY_MESSAGES = 6;
2308
+ var INTENT_LINE_MAX_CHARS = 240;
2309
+
2310
+ // src/chat-routes/turn-prefetch.ts
2311
+ function startTurnPrefetch(prefetch, input) {
2312
+ let started;
2313
+ const start = (identity) => {
2314
+ const abort = new AbortController();
2315
+ const result = input.trace.measure("admission.prefetch", "admission", async () => prefetch({
2316
+ ...input,
2317
+ tenantId: identity.tenantId,
2318
+ userId: identity.userId,
2319
+ signal: abort.signal
2320
+ }));
2321
+ result.catch(() => {
2322
+ });
2323
+ started = { identity: { ...identity }, abort, result };
2324
+ };
2325
+ return {
2326
+ identified(identity) {
2327
+ if (!started) start(identity);
2328
+ },
2329
+ admitted(identity) {
2330
+ if (started && (started.identity.tenantId !== identity.tenantId || started.identity.userId !== identity.userId)) {
2331
+ started.abort.abort();
2332
+ started = void 0;
2333
+ }
2334
+ if (!started) start(identity);
2335
+ return started.result;
2336
+ },
2337
+ discard() {
2338
+ started?.abort.abort();
2339
+ started = void 0;
2340
+ }
2341
+ };
2342
+ }
2343
+
2206
2344
  // src/chat-routes/turn-execution.ts
2207
2345
  import { deriveExecutionId, handleChatTurn } from "@tangle-network/agent-runtime/durable";
2208
2346
 
@@ -2288,7 +2426,7 @@ function routerRouteProducer(value, args) {
2288
2426
  const options = {
2289
2427
  ...value,
2290
2428
  userMessage: value.userMessage ?? turnPromptText(args.prompt),
2291
- history: value.history ?? routerTurnHistory(args.priorMessages),
2429
+ history: value.history ?? routerTurnHistory(args.priorMessages, void 0, { pov: args.agent?.id }),
2292
2430
  trace: args.trace,
2293
2431
  traceId: args.trace?.traceId,
2294
2432
  signal: args.admissionSignal,
@@ -2694,8 +2832,11 @@ async function runAdmittedTurn({
2694
2832
  ...admitted.prefetched ? { prefetched: admitted.prefetched } : {},
2695
2833
  ...ctx?.executionLimits ? { executionLimits: ctx.executionLimits } : {}
2696
2834
  };
2835
+ const addressed = await addressAgents({ options, mentions, identity, context, produceArgs, trace });
2836
+ if (addressed instanceof Response) return addressed;
2837
+ produceArgs = addressed;
2697
2838
  const selected = selectTurnProducer(options.produce, produceArgs);
2698
- const dispatched = dispatchFirstFor(selected, produceArgs, trace);
2839
+ const dispatched = produceArgs.agents ? void 0 : dispatchFirstFor(selected, produceArgs, trace);
2699
2840
  if (dispatched) early.add(dispatched.refuse);
2700
2841
  const turnLock = options.turnLock;
2701
2842
  if (turnLock) {
@@ -3085,7 +3226,7 @@ function createTurnEngine(identity, ctx, log, state, dispatched, produceArgs, tr
3085
3226
  produce: () => ({
3086
3227
  stream: (async function* () {
3087
3228
  const producerStream = async function* () {
3088
- const started = dispatched ? dispatched.take(produceArgs) : trace.measure("admission.produce", "admission", () => produce(produceArgs));
3229
+ const started = dispatched ? dispatched.take(produceArgs) : produceArgs.agents ? trace.measure("admission.produce", "admission", () => composeAgentProducers(produceArgs, produce)) : trace.measure("admission.produce", "admission", () => produce(produceArgs));
3089
3230
  if (!dispatched) {
3090
3231
  const cleanup = started.then((producer) => producer.cleanup, () => void 0);
3091
3232
  ctx?.waitUntil?.(cleanup);
@@ -3901,6 +4042,14 @@ function toSandboxEvent(event) {
3901
4042
  }
3902
4043
 
3903
4044
  export {
4045
+ UPLOAD_INLINE_MAX_BYTES,
4046
+ UPLOAD_MAX_FILE_BYTES,
4047
+ sanitizeUploadFilename,
4048
+ bytesToBase64,
4049
+ createUploadRoute,
4050
+ normalizeChatPromptForSandbox,
4051
+ projectDispatchHistory,
4052
+ buildDispatchParts,
3904
4053
  createRouterTurnProducer,
3905
4054
  HYBRID_TURN_GUIDANCE,
3906
4055
  startHybridBox,
@@ -3922,18 +4071,13 @@ export {
3922
4071
  withProducerStream,
3923
4072
  cancelChatTurn,
3924
4073
  observeTurnCancellation,
4074
+ SPEAKER_EVENT,
4075
+ speakerPart,
4076
+ composeAgentProducers,
3925
4077
  INTENT_LINE_TIMEOUT_MS,
3926
4078
  INTENT_LINE_HISTORY_MESSAGES,
3927
4079
  INTENT_LINE_MAX_CHARS,
3928
- UPLOAD_INLINE_MAX_BYTES,
3929
- UPLOAD_MAX_FILE_BYTES,
3930
- sanitizeUploadFilename,
3931
- bytesToBase64,
3932
- createUploadRoute,
3933
- normalizeChatPromptForSandbox,
3934
- projectDispatchHistory,
3935
- buildDispatchParts,
3936
4080
  createChatTurnRoutes,
3937
4081
  streamChatRouteAsSandboxEvents
3938
4082
  };
3939
- //# sourceMappingURL=chunk-KFO5R4SN.js.map
4083
+ //# sourceMappingURL=chunk-RYKANV3P.js.map