@tangle-network/agent-app 0.63.5 → 0.63.7

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 (41) hide show
  1. package/dist/assistant/index.js +1 -1
  2. package/dist/chat-routes/default-backend.d.ts +46 -0
  3. package/dist/chat-routes/dispatch-first.d.ts +3 -2
  4. package/dist/chat-routes/index.d.ts +1 -0
  5. package/dist/chat-routes/index.js +13 -345
  6. package/dist/chat-routes/index.js.map +1 -1
  7. package/dist/chat-routes/route-prewarm.d.ts +2 -0
  8. package/dist/chat-routes/route-storage.d.ts +13 -4
  9. package/dist/chat-routes/sandbox-model-source.d.ts +1 -0
  10. package/dist/chat-routes/turn-ownership.d.ts +2 -1
  11. package/dist/chat-routes/turn-route-contracts.d.ts +21 -5
  12. package/dist/{chunk-XYSKMHWG.js → chunk-42QCR4CV.js} +548 -15
  13. package/dist/chunk-42QCR4CV.js.map +1 -0
  14. package/dist/{chunk-JRTWTADT.js → chunk-E3AOUTIR.js} +5 -2
  15. package/dist/chunk-E3AOUTIR.js.map +1 -0
  16. package/dist/{chunk-IDG2XR5O.js → chunk-EKXG4JSN.js} +2 -2
  17. package/dist/chunk-EKXG4JSN.js.map +1 -0
  18. package/dist/{chunk-4CALWPN5.js → chunk-L6BS2XTE.js} +20 -16
  19. package/dist/chunk-L6BS2XTE.js.map +1 -0
  20. package/dist/{chunk-YCMVNXAX.js → chunk-NUWSPR5O.js} +2 -2
  21. package/dist/{chunk-OCR36QGZ.js → chunk-UVMKP5IK.js} +65 -28
  22. package/dist/chunk-UVMKP5IK.js.map +1 -0
  23. package/dist/public-consultation/index.js +3 -3
  24. package/dist/runtime/index.js +2 -2
  25. package/dist/runtime/router-turn.d.ts +2 -2
  26. package/dist/runtime/router-turn.js +1 -1
  27. package/dist/sandbox/index.js +1 -1
  28. package/dist/sandbox/prompt-events.d.ts +1 -1
  29. package/dist/sandbox/sandbox-run-error.d.ts +8 -0
  30. package/dist/sandbox/sandbox-run-tool.d.ts +5 -9
  31. package/dist/signoff/cli.js +1 -1
  32. package/dist/signoff/index.js +1 -1
  33. package/dist/web-react/durable-plan-flow.d.ts +10 -0
  34. package/dist/web-react/index.js +1 -1
  35. package/package.json +1 -1
  36. package/dist/chunk-4CALWPN5.js.map +0 -1
  37. package/dist/chunk-IDG2XR5O.js.map +0 -1
  38. package/dist/chunk-JRTWTADT.js.map +0 -1
  39. package/dist/chunk-OCR36QGZ.js.map +0 -1
  40. package/dist/chunk-XYSKMHWG.js.map +0 -1
  41. /package/dist/{chunk-YCMVNXAX.js.map → chunk-NUWSPR5O.js.map} +0 -0
@@ -16,11 +16,22 @@ import {
16
16
  withD1QueryCount
17
17
  } from "./chunk-MM6RLOXF.js";
18
18
  import {
19
+ SandboxRunError,
20
+ createD1PrewarmClaimStore,
19
21
  createEscalationSpeculator,
20
22
  createSandboxRunTool,
23
+ createWorkspacePrewarmRoute,
24
+ ensureWorkspaceSandbox,
21
25
  escalationHints,
22
- resolveTurnStorage
23
- } from "./chunk-OCR36QGZ.js";
26
+ flattenHistory,
27
+ isTerminalPromptEvent,
28
+ peekWorkspaceSandbox,
29
+ resolveTurnStorage,
30
+ runForegroundSandboxSingleFlight,
31
+ sandboxPromptRunner,
32
+ streamSandboxPrompt,
33
+ turnStorageBindings
34
+ } from "./chunk-UVMKP5IK.js";
24
35
  import {
25
36
  addStepFinishUsage,
26
37
  assistantRowIdForTurn,
@@ -33,19 +44,25 @@ import {
33
44
  resolveChatTurn
34
45
  } from "./chunk-YG66IHDU.js";
35
46
  import {
47
+ historyContentWithAttachments,
36
48
  mentionInputToPart,
37
49
  toChatMessageParts
38
50
  } from "./chunk-RZLCBWGG.js";
39
51
  import {
40
52
  ChatTurnInputError,
53
+ DISPATCH_MAX_PARTS,
54
+ DISPATCH_REQUEST_MAX_BYTES,
55
+ DISPATCH_STRUCTURAL_RESERVE_BYTES,
41
56
  INLINE_PARTS_MAX_BYTES,
42
57
  TURN_INTENT_EVENT,
43
58
  TURN_PROGRESS_FIRST,
44
59
  TURN_PROGRESS_HEADER,
45
60
  TURN_ROUTE_PHASE_MESSAGES,
46
61
  assertPromptPartsWithinCap,
62
+ base64WireLen,
47
63
  buildTurnPhaseEvent,
48
64
  chatTurnRequestInit,
65
+ mediaTypeForMentionPath,
49
66
  parseChatTurnParts,
50
67
  parseFileMentions,
51
68
  turnResponseEventFor
@@ -87,18 +104,26 @@ import {
87
104
  runWithModelFailover
88
105
  } from "./chunk-ZLX4BA27.js";
89
106
  import {
107
+ assertPolicy,
90
108
  checkModelPolicy
91
109
  } from "./chunk-XELWWXJJ.js";
92
110
  import {
93
111
  composeRouterTurnPromptSections,
94
112
  runRouterTurn
95
- } from "./chunk-IDG2XR5O.js";
113
+ } from "./chunk-EKXG4JSN.js";
96
114
  import {
97
115
  createIntelligenceTurnTraceSink,
98
116
  createTurnTrace,
99
117
  formatServerTiming,
100
118
  otlpTraceId
101
119
  } from "./chunk-AVBNS64P.js";
120
+ import {
121
+ readSandboxBinaryBytes,
122
+ statSandboxFileSize
123
+ } from "./chunk-CTREXL3O.js";
124
+ import {
125
+ isWorkspaceFileExportable
126
+ } from "./chunk-TXD5HXLE.js";
102
127
  import {
103
128
  parsePlanSubmittedEvent,
104
129
  planToPersistedPart
@@ -379,6 +404,8 @@ function createHybridTurnProducer(options) {
379
404
  abort.abort(error);
380
405
  });
381
406
  const timeoutMs = box.timeoutMs ?? DEFAULT_SANDBOX_RUN_TIMEOUT_MS;
407
+ let activeTasks = 0;
408
+ let unconfirmed = false;
382
409
  let start = box.started?.catch((error) => {
383
410
  start = void 0;
384
411
  throw error;
@@ -412,7 +439,16 @@ function createHybridTurnProducer(options) {
412
439
  runTask: async (...args) => {
413
440
  await admitted;
414
441
  stop.throwIfAborted();
415
- return box.runTask(...args);
442
+ if (unconfirmed || activeTasks > 0) throw new SandboxRunError("sandbox_unconfirmed", "An earlier computer step may still be running; no further task was dispatched.");
443
+ activeTasks++;
444
+ try {
445
+ return await box.runTask(...args);
446
+ } catch (error) {
447
+ if (!(error instanceof SandboxRunError) || error.code === "sandbox_unconfirmed") unconfirmed = true;
448
+ throw error;
449
+ } finally {
450
+ activeTasks--;
451
+ }
416
452
  },
417
453
  memberRequest: router.userMessage,
418
454
  timeoutMs,
@@ -444,7 +480,8 @@ ${extra}` : { ...prompt, stable: [...prompt.stable ?? [], extra] }),
444
480
  speculator.onEvent(event);
445
481
  if (event.type === "tool" && event.status === "error" && event.toolName === sandboxRun.name && !stop.aborted) {
446
482
  const code = event.error.code;
447
- if (code === "sandbox_unavailable" || code === "sandbox_failed" || code === "sandbox_empty") {
483
+ if (code === "sandbox_unconfirmed") unconfirmed = true;
484
+ if (code === "sandbox_unavailable" || code === "sandbox_failed" || code === "sandbox_unconfirmed" || code === "sandbox_empty") {
448
485
  warnings.set(event.callId, {
449
486
  type: "notice",
450
487
  noticeKind: "warning",
@@ -487,6 +524,7 @@ ${extra}` : { ...prompt, stable: [...prompt.stable ?? [], extra] }),
487
524
  return {
488
525
  ...producer,
489
526
  stream: events,
527
+ terminalObserved: () => activeTasks === 0 && !unconfirmed,
490
528
  assistantParts: () => withWarnings(producer.assistantParts?.() ?? []),
491
529
  draftParts: () => withWarnings(producer.draftParts?.() ?? []),
492
530
  get model() {
@@ -952,12 +990,17 @@ function createSandboxModelSource(options, log) {
952
990
  const chain = options.model ? buildModelChain(options.model, options.modelFailover === false ? [] : options.fallbackModels ?? []) : [];
953
991
  const pendingModelNotices = [];
954
992
  let modelNoticeCount = 0;
993
+ let openAttempts = 0;
955
994
  let failover;
956
995
  let source;
957
996
  if (options.openEvents) {
997
+ const open = options.openEvents;
958
998
  failover = streamWithModelFailover({
959
999
  models: chain,
960
- open: options.openEvents,
1000
+ open: (args) => {
1001
+ openAttempts += 1;
1002
+ return open(args);
1003
+ },
961
1004
  log,
962
1005
  ...options.modelPolicy ? { policy: options.modelPolicy } : {},
963
1006
  ...options.openTimeoutMs !== void 0 ? { openTimeoutMs: options.openTimeoutMs } : {},
@@ -1001,7 +1044,7 @@ function createSandboxModelSource(options, log) {
1001
1044
  text: `Requested ${sentModel} \u2014 the sandbox answered with ${parsed.servedModel} instead.`
1002
1045
  });
1003
1046
  };
1004
- return { pendingModelNotices, source, captureEffectiveBackend, servedModel, servingModel, failover, modelState };
1047
+ return { pendingModelNotices, source, captureEffectiveBackend, servedModel, servingModel, failover, modelState, openAttempts: () => openAttempts };
1005
1048
  }
1006
1049
 
1007
1050
  // src/chat-routes/sandbox-producer.ts
@@ -1100,7 +1143,9 @@ function sandboxStreamFailureDiagnostic(error) {
1100
1143
  ].join("\n\n");
1101
1144
  const failureNote = diagnosticText ? `sandbox-stream: ${message}; ${diagnosticText}` : `sandbox-stream: ${message}`;
1102
1145
  let code = "sandbox.stream_failed";
1103
- if (error instanceof ModelFailoverTimeoutError) {
1146
+ if (error instanceof SandboxRunError) {
1147
+ code = error.code;
1148
+ } else if (error instanceof ModelFailoverTimeoutError) {
1104
1149
  code = error.code;
1105
1150
  } else if (error instanceof ModelFailoverExhaustedError) {
1106
1151
  code = error.upstreamCode ?? code;
@@ -1110,7 +1155,7 @@ function sandboxStreamFailureDiagnostic(error) {
1110
1155
  function createSandboxChatProducer(options) {
1111
1156
  const log = options.log ?? ((message, meta) => console.error(message, meta ?? ""));
1112
1157
  const renderable = options.isRenderableInteraction ?? isRenderableInteractionKind;
1113
- const { pendingModelNotices, source, captureEffectiveBackend, servedModel, servingModel, failover, modelState } = createSandboxModelSource(options, log);
1158
+ const { pendingModelNotices, source, captureEffectiveBackend, servedModel, servingModel, failover, modelState, openAttempts } = createSandboxModelSource(options, log);
1114
1159
  const projectionState = {
1115
1160
  fullText: "",
1116
1161
  terminalObserved: false,
@@ -1121,9 +1166,12 @@ function createSandboxChatProducer(options) {
1121
1166
  errorNoticeCount: 0
1122
1167
  };
1123
1168
  const { timedParts, drainModelNotices, tracker, recordPersistedPart, reasoningClock, partMap, announcedToolArgs, settledTools, usage, promotedFileParts, emitFinalUsage, emitTerminalizedTools, emitErrorNotice, partOrder } = createSandboxProjection(projectionState, pendingModelNotices);
1169
+ let observedSourceEvent = false;
1170
+ let preflightRefused = false;
1124
1171
  async function* stream() {
1125
1172
  try {
1126
1173
  for await (const raw of source) {
1174
+ observedSourceEvent = true;
1127
1175
  const record = asRecord(raw);
1128
1176
  captureEffectiveBackend(asRecord(record?.data));
1129
1177
  yield* drainModelNotices();
@@ -1241,7 +1289,7 @@ function createSandboxChatProducer(options) {
1241
1289
  continue;
1242
1290
  }
1243
1291
  if (event.type === "done") {
1244
- projectionState.terminalObserved = true;
1292
+ if (isTerminalPromptEvent(record)) projectionState.terminalObserved = true;
1245
1293
  const reported = extractReportedTurnUsage(asRecord(event.data));
1246
1294
  if (reported) {
1247
1295
  applyTerminalUsage(reported, usage);
@@ -1277,6 +1325,7 @@ ${errorContent}` : errorContent;
1277
1325
  }
1278
1326
  yield* drainModelNotices();
1279
1327
  } catch (streamErr) {
1328
+ preflightRefused = !observedSourceEvent && openAttempts() === 1 && streamErr instanceof SandboxRunError && streamErr.code === "sandbox_unavailable";
1280
1329
  const diagnostic = sandboxStreamFailureDiagnostic(streamErr);
1281
1330
  log("[chat-routes] sandbox stream failed", {
1282
1331
  failureNote: diagnostic.failureNote,
@@ -1309,7 +1358,7 @@ ${diagnostic.userMessage}` : diagnostic.userMessage;
1309
1358
  return {
1310
1359
  stream: stream(),
1311
1360
  finalText: () => projectionState.fullText,
1312
- terminalObserved: () => projectionState.terminalObserved,
1361
+ terminalObserved: () => projectionState.terminalObserved || preflightRefused,
1313
1362
  assistantParts: () => finalizePendingInteractionParts(
1314
1363
  finalizeAssistantParts(partOrder, timedParts(), projectionState.fullText),
1315
1364
  projectionState.interactionOutcome
@@ -1702,6 +1751,341 @@ var INTENT_LINE_TIMEOUT_MS = 1500;
1702
1751
  var INTENT_LINE_HISTORY_MESSAGES = 6;
1703
1752
  var INTENT_LINE_MAX_CHARS = 240;
1704
1753
 
1754
+ // src/chat-routes/upload.ts
1755
+ var UPLOAD_INLINE_MAX_BYTES = 700 * 1024;
1756
+ var UPLOAD_MAX_FILE_BYTES = 8 * 1024 * 1024;
1757
+ var DEFAULT_UPLOAD_DIRECTORY = "/workspace/uploads";
1758
+ function normalizeUploadDirectory(value) {
1759
+ const withoutTrailingSlash = value.trim().replace(/\/+$/, "");
1760
+ if (!withoutTrailingSlash.startsWith("/") || withoutTrailingSlash.length === 0) return null;
1761
+ const segments = withoutTrailingSlash.slice(1).split("/");
1762
+ if (segments.some((segment) => segment.length === 0 || segment === "." || segment === "..")) return null;
1763
+ return `/${segments.join("/")}`;
1764
+ }
1765
+ function sanitizeUploadFilename(name) {
1766
+ const base = name.split(/[\\/]/).pop() ?? "file";
1767
+ const safe = base.replace(/[^A-Za-z0-9._-]+/g, "_").replace(/^\.+/, "_");
1768
+ return (safe || "file").slice(0, 120);
1769
+ }
1770
+ var BASE64_CHUNK = 32768;
1771
+ function bytesToBase64(bytes) {
1772
+ let binary = "";
1773
+ for (let offset = 0; offset < bytes.length; offset += BASE64_CHUNK) {
1774
+ binary += String.fromCharCode(...bytes.subarray(offset, offset + BASE64_CHUNK));
1775
+ }
1776
+ return btoa(binary);
1777
+ }
1778
+ function uploadError(status, code, error) {
1779
+ return Response.json({ code, error }, { status });
1780
+ }
1781
+ function createUploadRoute(options) {
1782
+ const inlineMaxBytes = options.inlineMaxBytes ?? UPLOAD_INLINE_MAX_BYTES;
1783
+ const maxFileBytes = options.maxFileBytes ?? UPLOAD_MAX_FILE_BYTES;
1784
+ return async function upload(request) {
1785
+ const auth = await options.authorize({ request });
1786
+ if (!auth.ok) return auth.response;
1787
+ const sink = auth.sink ?? null;
1788
+ const configuredUploadDir = auth.uploadDir ?? options.uploadDir ?? DEFAULT_UPLOAD_DIRECTORY;
1789
+ let form;
1790
+ try {
1791
+ form = await request.formData();
1792
+ } catch {
1793
+ return uploadError(400, "INVALID_UPLOAD", "Expected a multipart/form-data body with file fields");
1794
+ }
1795
+ const files = [];
1796
+ form.forEach((value) => {
1797
+ if (value instanceof File) files.push(value);
1798
+ });
1799
+ if (files.length === 0) {
1800
+ return uploadError(400, "INVALID_UPLOAD", "No files in the upload body");
1801
+ }
1802
+ const uploaded = [];
1803
+ for (const file of files) {
1804
+ const name = sanitizeUploadFilename(file.name);
1805
+ const mediaType = file.type || "application/octet-stream";
1806
+ const partType = mediaType.startsWith("image/") ? "image" : "file";
1807
+ if (file.size > maxFileBytes) {
1808
+ return uploadError(
1809
+ 413,
1810
+ "FILE_TOO_LARGE",
1811
+ `${name} is ${file.size}B, over the ${maxFileBytes}B per-file cap`
1812
+ );
1813
+ }
1814
+ const id = crypto.randomUUID();
1815
+ if (file.size <= inlineMaxBytes) {
1816
+ const base642 = bytesToBase64(new Uint8Array(await file.arrayBuffer()));
1817
+ uploaded.push({
1818
+ id,
1819
+ name,
1820
+ size: file.size,
1821
+ mediaType,
1822
+ inline: true,
1823
+ part: {
1824
+ type: partType,
1825
+ filename: name,
1826
+ mediaType,
1827
+ url: `data:${mediaType};base64,${base642}`
1828
+ }
1829
+ });
1830
+ continue;
1831
+ }
1832
+ if (!sink) {
1833
+ return uploadError(
1834
+ 413,
1835
+ "SANDBOX_REQUIRED",
1836
+ `${name} is ${file.size}B, over the ${inlineMaxBytes}B inline cap, and no sandbox is available to hold it`
1837
+ );
1838
+ }
1839
+ const uploadDir = normalizeUploadDirectory(configuredUploadDir);
1840
+ if (!uploadDir) {
1841
+ return uploadError(
1842
+ 500,
1843
+ "INVALID_UPLOAD_DIRECTORY",
1844
+ 'uploadDir must be an absolute path without empty, "." or ".." segments'
1845
+ );
1846
+ }
1847
+ const path = `${uploadDir}/${id}-${name}`;
1848
+ const base64 = bytesToBase64(new Uint8Array(await file.arrayBuffer()));
1849
+ await sink.write(path, base64, { encoding: "base64" });
1850
+ uploaded.push({
1851
+ id,
1852
+ name,
1853
+ size: file.size,
1854
+ mediaType,
1855
+ inline: false,
1856
+ part: { type: partType, filename: name, mediaType, path }
1857
+ });
1858
+ }
1859
+ return Response.json({ files: uploaded });
1860
+ };
1861
+ }
1862
+
1863
+ // src/chat-routes/dispatch-parts.ts
1864
+ import { pathToFileURL } from "url";
1865
+ function byteLen(value) {
1866
+ return new TextEncoder().encode(value).length;
1867
+ }
1868
+ async function readSandboxMention(box, absolutePath, options) {
1869
+ const stat = await statSandboxFileSize(box, absolutePath);
1870
+ if (!stat.succeeded) {
1871
+ return { succeeded: false, error: `mentioned sandbox file missing or unreadable: ${absolutePath} \u2014 ${stat.error}` };
1872
+ }
1873
+ if (!options.readBytes) return { succeeded: true, value: { size: stat.value } };
1874
+ const read = await readSandboxBinaryBytes(box, absolutePath, stat.value);
1875
+ if (!read.succeeded) {
1876
+ return { succeeded: false, error: `mentioned sandbox file read failed: ${absolutePath} \u2014 ${read.error}` };
1877
+ }
1878
+ return { succeeded: true, value: { size: stat.value, base64: bytesToBase64(read.value.bytes) } };
1879
+ }
1880
+ function violatesUrlPathXor(part) {
1881
+ if (part.type === "text") return false;
1882
+ const hasUrl = typeof part.url === "string" && (part.url.startsWith("data:") || part.url.startsWith("file://"));
1883
+ const hasPath = "path" in part && typeof part.path === "string" && part.path.startsWith("/");
1884
+ if (part.type === "file") return !hasUrl || hasPath;
1885
+ return hasUrl === hasPath;
1886
+ }
1887
+ function sandboxFileUrl(absolutePath) {
1888
+ if (!absolutePath.startsWith("/")) return void 0;
1889
+ try {
1890
+ return pathToFileURL(absolutePath).href;
1891
+ } catch {
1892
+ return void 0;
1893
+ }
1894
+ }
1895
+ function normalizeChatPromptForSandbox(prompt) {
1896
+ if (typeof prompt === "string") return prompt;
1897
+ return prompt.map((part) => {
1898
+ if (part.type === "text") return part;
1899
+ if ("content" in part) {
1900
+ throw new ChatTurnInputError("Sandbox prompt parts do not accept inline content; provide a URL or path");
1901
+ }
1902
+ const url = typeof part.url === "string" && part.url.length > 0 ? part.url : void 0;
1903
+ const path = typeof part.path === "string" && part.path.length > 0 ? part.path : void 0;
1904
+ if (Boolean(url) === Boolean(path)) {
1905
+ throw new ChatTurnInputError(`Sandbox ${part.type} parts require exactly one URL or path`);
1906
+ }
1907
+ if (path && !path.startsWith("/")) {
1908
+ throw new ChatTurnInputError(`Sandbox ${part.type} paths must be absolute: ${path}`);
1909
+ }
1910
+ if (part.type === "image") {
1911
+ return {
1912
+ type: "image",
1913
+ ...part.filename ? { filename: part.filename } : {},
1914
+ ...part.mediaType ? { mediaType: part.mediaType } : {},
1915
+ ...url ? { url } : { path }
1916
+ };
1917
+ }
1918
+ const filename = part.filename?.trim();
1919
+ if (!filename) {
1920
+ throw new ChatTurnInputError("Sandbox file parts require a filename");
1921
+ }
1922
+ const fileUrl = url ?? sandboxFileUrl(path);
1923
+ if (!fileUrl) {
1924
+ throw new ChatTurnInputError(`Sandbox file paths must be absolute: ${path}`);
1925
+ }
1926
+ return {
1927
+ type: "file",
1928
+ filename,
1929
+ ...part.mediaType ? { mediaType: part.mediaType } : {},
1930
+ url: fileUrl
1931
+ };
1932
+ });
1933
+ }
1934
+ function projectDispatchHistory(messages) {
1935
+ return messages.map((message) => ({
1936
+ role: message.role === "assistant" ? "assistant" : "user",
1937
+ content: historyContentWithAttachments(message)
1938
+ }));
1939
+ }
1940
+ function readResultToBase64(read) {
1941
+ if (typeof read.base64 === "string") return read.base64;
1942
+ if (read.bytes) return bytesToBase64(read.bytes);
1943
+ return void 0;
1944
+ }
1945
+ async function buildDispatchParts(input) {
1946
+ const readMention = input.readSandboxMention ?? readSandboxMention;
1947
+ const resolveMentionPath = input.resolveMentionPath ?? input.resolveAttachmentPath;
1948
+ const forcePath = input.forcePath ?? false;
1949
+ const mentions = input.mentions ?? [];
1950
+ const requestMaxBytes = input.requestMaxBytes ?? DISPATCH_REQUEST_MAX_BYTES;
1951
+ const structuralReserveBytes = input.structuralReserveBytes ?? DISPATCH_STRUCTURAL_RESERVE_BYTES;
1952
+ const maxParts = input.maxParts ?? DISPATCH_MAX_PARTS;
1953
+ const parts = [{ type: "text", text: input.text }];
1954
+ const emittedAbsPaths = /* @__PURE__ */ new Set();
1955
+ const flattenedForSizing = flattenHistory(input.text, input.history);
1956
+ const inlineBudget = requestMaxBytes - base64WireLen(byteLen(flattenedForSizing)) - byteLen(JSON.stringify(input.systemPrompt)) - input.profileWireBytes - structuralReserveBytes;
1957
+ let runningInline = 0;
1958
+ for (const attachment of input.attachments) {
1959
+ if (!attachment.path) {
1960
+ return { succeeded: false, error: `attachment path must be non-empty: ${attachment.name}` };
1961
+ }
1962
+ let read;
1963
+ try {
1964
+ read = await input.readAttachment(input.scopeId, attachment.path);
1965
+ } catch (err) {
1966
+ return {
1967
+ succeeded: false,
1968
+ error: `attachment store read failed: ${attachment.path} \u2014 ${err instanceof Error ? err.message : String(err)}`
1969
+ };
1970
+ }
1971
+ if (!read.ok) return { succeeded: false, error: read.reason };
1972
+ const base64 = readResultToBase64(read);
1973
+ if (base64 === void 0) {
1974
+ return { succeeded: false, error: `attachment store read produced no content: ${attachment.path}` };
1975
+ }
1976
+ const mediaType = attachment.mediaType ?? read.mediaType;
1977
+ if (attachment.type === "image" && !mediaType) {
1978
+ return { succeeded: false, error: `attachment is missing a mediaType required for an image data URI: ${attachment.path}` };
1979
+ }
1980
+ const absPath = input.resolveAttachmentPath(attachment.path);
1981
+ emittedAbsPaths.add(absPath);
1982
+ if (attachment.type === "image") {
1983
+ const inlinePart2 = {
1984
+ type: "image",
1985
+ filename: attachment.name,
1986
+ mediaType,
1987
+ url: `data:${mediaType};base64,${base64}`
1988
+ };
1989
+ const cost2 = byteLen(JSON.stringify(inlinePart2));
1990
+ if (!forcePath && runningInline + cost2 <= inlineBudget) {
1991
+ parts.push(inlinePart2);
1992
+ runningInline += cost2;
1993
+ } else {
1994
+ parts.push({ type: "image", filename: attachment.name, mediaType, path: absPath });
1995
+ }
1996
+ continue;
1997
+ }
1998
+ const fileMediaType = mediaType ?? "application/octet-stream";
1999
+ const inlinePart = {
2000
+ type: "file",
2001
+ filename: attachment.name,
2002
+ mediaType: fileMediaType,
2003
+ url: `data:${fileMediaType};base64,${base64}`
2004
+ };
2005
+ const cost = byteLen(JSON.stringify(inlinePart));
2006
+ if (!forcePath && runningInline + cost <= inlineBudget) {
2007
+ parts.push(inlinePart);
2008
+ runningInline += cost;
2009
+ } else {
2010
+ const url = sandboxFileUrl(absPath);
2011
+ if (!url) {
2012
+ return { succeeded: false, error: `resolved attachment path must be absolute: ${absPath}` };
2013
+ }
2014
+ parts.push({ type: "file", filename: attachment.name, mediaType: fileMediaType, url });
2015
+ }
2016
+ }
2017
+ if (mentions.length > 0 && !input.box) {
2018
+ return { succeeded: false, error: "internal error: sandbox mentions require a box to read from" };
2019
+ }
2020
+ for (const mention of mentions) {
2021
+ if (!mention.path) {
2022
+ return { succeeded: false, error: `mention path must be non-empty: ${mention.name}` };
2023
+ }
2024
+ if (!isWorkspaceFileExportable(mention.path)) {
2025
+ return { succeeded: false, error: `mention file is not exportable: ${mention.path}` };
2026
+ }
2027
+ const absPath = resolveMentionPath(mention.path);
2028
+ if (emittedAbsPaths.has(absPath)) continue;
2029
+ emittedAbsPaths.add(absPath);
2030
+ const isImage = mention.mentionKind === "image";
2031
+ const mediaType = isImage ? mediaTypeForMentionPath(mention.path) : void 0;
2032
+ let stat;
2033
+ try {
2034
+ stat = await readMention(input.box, absPath, { readBytes: false });
2035
+ } catch (err) {
2036
+ return { succeeded: false, error: `mention read failed: ${absPath} \u2014 ${err instanceof Error ? err.message : String(err)}` };
2037
+ }
2038
+ if (!stat.succeeded) return { succeeded: false, error: stat.error };
2039
+ const projectedInlineCost = base64WireLen(stat.value.size) + byteLen(JSON.stringify({ type: "image", filename: mention.name, mediaType: mediaType ?? "", url: "" }));
2040
+ if (isImage && mediaType && !forcePath && runningInline + projectedInlineCost <= inlineBudget) {
2041
+ let read;
2042
+ try {
2043
+ read = await readMention(input.box, absPath, { readBytes: true });
2044
+ } catch (err) {
2045
+ return { succeeded: false, error: `mention read failed: ${absPath} \u2014 ${err instanceof Error ? err.message : String(err)}` };
2046
+ }
2047
+ if (!read.succeeded) return { succeeded: false, error: read.error };
2048
+ if (!read.value.base64) return { succeeded: false, error: `mentioned image produced no bytes: ${absPath}` };
2049
+ const inlinePart = {
2050
+ type: "image",
2051
+ filename: mention.name,
2052
+ mediaType,
2053
+ url: `data:${mediaType};base64,${read.value.base64}`
2054
+ };
2055
+ const cost = byteLen(JSON.stringify(inlinePart));
2056
+ if (runningInline + cost <= inlineBudget) {
2057
+ parts.push(inlinePart);
2058
+ runningInline += cost;
2059
+ continue;
2060
+ }
2061
+ }
2062
+ if (isImage && mediaType) {
2063
+ parts.push({ type: "image", filename: mention.name, mediaType, path: absPath });
2064
+ } else {
2065
+ const url = sandboxFileUrl(absPath);
2066
+ if (!url) {
2067
+ return { succeeded: false, error: `resolved mention path must be absolute: ${absPath}` };
2068
+ }
2069
+ parts.push({ type: "file", filename: mention.name, url });
2070
+ }
2071
+ }
2072
+ for (const part of parts) {
2073
+ if (violatesUrlPathXor(part)) {
2074
+ return { succeeded: false, error: "internal error: emitted media part violates the url/path exclusivity invariant" };
2075
+ }
2076
+ }
2077
+ const textPartSize = base64WireLen(byteLen(flattenedForSizing));
2078
+ const mediaPartsSize = parts.slice(1).reduce((total, part) => total + byteLen(JSON.stringify(part)), 0);
2079
+ const systemPromptSize = byteLen(JSON.stringify(input.systemPrompt));
2080
+ if (textPartSize + mediaPartsSize + systemPromptSize + input.profileWireBytes + structuralReserveBytes > requestMaxBytes) {
2081
+ return { succeeded: false, error: "dispatch parts exceed the sandbox proxy request cap even after path demotion" };
2082
+ }
2083
+ if (parts.length > maxParts) {
2084
+ return { succeeded: false, error: `dispatch parts exceed the sidecar per-request cap of ${maxParts}` };
2085
+ }
2086
+ return { succeeded: true, value: parts };
2087
+ }
2088
+
1705
2089
  // src/chat-routes/turn-prefetch.ts
1706
2090
  function startTurnPrefetch(prefetch, input) {
1707
2091
  let started;
@@ -1855,6 +2239,10 @@ function createChatTurnOwnership(state, log, turnStreamId, options) {
1855
2239
  };
1856
2240
  const releaseLock = async () => {
1857
2241
  if (state.completionHandoff || !state.lockAcquired || state.lockReleased) return;
2242
+ if (state.producer?.terminalObserved && !state.producer.terminalObserved()) {
2243
+ await state.closeCancellation?.();
2244
+ return;
2245
+ }
1858
2246
  state.lockReleased = true;
1859
2247
  try {
1860
2248
  await state.closeCancellation?.();
@@ -2310,7 +2698,7 @@ async function runAdmittedTurn({
2310
2698
  }
2311
2699
  }
2312
2700
  progress?.("preparing", progressMessages.preparing);
2313
- const { endTrace, exportTraceInBackground, fireTerminalLifecycle, assistantRowId, exportTrace, runAfterSettle } = createTurnSettlement(state, trace, options, executionId, traceSink, identity, traceOptions, context, turnStreamId, log, ctx);
2701
+ const { endTrace, exportTraceInBackground, fireTerminalLifecycle, assistantRowId, exportTrace, runAfterSettle } = createTurnSettlement(state, trace, options, executionId, traceSink, identity, traceOptions, context, turnStreamId, log, ctx, () => produceArgs.userMessageId);
2314
2702
  try {
2315
2703
  if (state.lockAcquired && JSON.stringify(await trace.measure("admission.history_recheck", "admission", readHistory)) !== historyBeforeLock) {
2316
2704
  await releaseLock();
@@ -2540,7 +2928,7 @@ async function prepareAdmittedTurn(options, trace, log, tenantId, userId, payloa
2540
2928
  const turnStreamId = crypto.randomUUID();
2541
2929
  return { turnStreamId, identity, executionId, chatTurn, readHistory, historyBeforeLock };
2542
2930
  }
2543
- function createTurnSettlement(state, trace, options, executionId, traceSink, identity, traceOptions, context, turnStreamId, log, ctx) {
2931
+ function createTurnSettlement(state, trace, options, executionId, traceSink, identity, traceOptions, context, turnStreamId, log, ctx, userMessageId) {
2544
2932
  const assistantRowId = () => state.assistantMessageId ?? state.draft?.rowId() ?? null;
2545
2933
  const endTrace = (failed, terminalError) => {
2546
2934
  const failureCode = failed ? failureCodeOf(state.lastFailureData) ?? (terminalError instanceof Error ? terminalError.name : "turn_failed") : void 0;
@@ -2579,6 +2967,10 @@ function createTurnSettlement(state, trace, options, executionId, traceSink, ide
2579
2967
  state.lifecycleSettled = true;
2580
2968
  const snapshot = endTrace(failed, terminalError);
2581
2969
  const lifecycle = options.lifecycle;
2970
+ const backend = {
2971
+ userMessageId: userMessageId(),
2972
+ backendTerminal: Boolean(state.producer) && (state.producer?.terminalObserved?.() ?? true)
2973
+ };
2582
2974
  const durationMs = Date.now() - state.turnStartedAtMs;
2583
2975
  const timing = settledTurnTiming(turnStreamId, {
2584
2976
  requestAt: trace.startedAt,
@@ -2598,6 +2990,7 @@ function createTurnSettlement(state, trace, options, executionId, traceSink, ide
2598
2990
  context,
2599
2991
  durationMs,
2600
2992
  ...timing,
2993
+ ...backend,
2601
2994
  error: terminalError ?? state.lastFailureData ?? new Error("chat turn failed")
2602
2995
  });
2603
2996
  } else {
@@ -2610,6 +3003,7 @@ function createTurnSettlement(state, trace, options, executionId, traceSink, ide
2610
3003
  context,
2611
3004
  durationMs,
2612
3005
  ...timing,
3006
+ ...backend,
2613
3007
  finalText: state.cancellationAbort?.signal.aborted ? "" : state.producer?.finalText() ?? "",
2614
3008
  usage: state.producer?.usage?.() ?? {},
2615
3009
  assistantMessageId: assistantRowId(),
@@ -2789,6 +3183,8 @@ function createTurnEngine(identity, ctx, log, state, dispatched, produceArgs, tr
2789
3183
  const attribution = state.producer?.modelAttribution?.();
2790
3184
  return trace.measure("persist.on_turn_complete", "persist", () => options.onTurnComplete({
2791
3185
  identity: turnIdentity,
3186
+ userMessageId: produceArgs.userMessageId,
3187
+ backendTerminal: state.producer?.terminalObserved?.() ?? true,
2792
3188
  finalText,
2793
3189
  context,
2794
3190
  failed: state.runFailed,
@@ -2910,6 +3306,129 @@ function earlyTurnWork(started, log) {
2910
3306
  };
2911
3307
  }
2912
3308
 
3309
+ // src/chat-routes/default-backend.ts
3310
+ function defaultChatShell(projectId, env, config) {
3311
+ return config.shell ?? {
3312
+ credentials: () => env.SANDBOX_API_KEY?.trim() && env.SANDBOX_GATEWAY_URL?.trim() ? { apiKey: env.SANDBOX_API_KEY.trim(), baseUrl: env.SANDBOX_GATEWAY_URL.trim() } : null,
3313
+ name: (workspaceId) => `${projectId}-${workspaceId}`.slice(0, 63),
3314
+ metadata: (harness) => ({ app: projectId, harness }),
3315
+ connectedIntegrationIds: async () => [],
3316
+ env: async () => ({}),
3317
+ files: async () => [],
3318
+ secrets: async () => [],
3319
+ profile: ({ systemPrompt, extraMcp }) => ({
3320
+ name: projectId,
3321
+ prompt: { systemPrompt: systemPrompt ?? config.systemPrompt ?? "" },
3322
+ ...extraMcp && Object.keys(extraMcp).length ? { mcp: extraMcp } : {}
3323
+ }),
3324
+ provider: {
3325
+ apiKey: env.TANGLE_API_KEY,
3326
+ routerBaseUrl: env.TANGLE_ROUTER_URL,
3327
+ modelName: env.MODEL_NAME,
3328
+ defaultModel: config.model
3329
+ }
3330
+ };
3331
+ }
3332
+ function createDefaultChatBackend(projectId, env, config, bindings, modelPolicy) {
3333
+ const shell = defaultChatShell(projectId, env, config);
3334
+ const harness = config.harness ?? "opencode";
3335
+ const acquire = (args) => {
3336
+ const scope = { workspaceId: args.identity.tenantId, userId: args.identity.userId };
3337
+ if (!bindings) throw new Error("Default sandbox execution requires durable D1 claim bindings");
3338
+ return runForegroundSandboxSingleFlight({
3339
+ claim: createD1PrewarmClaimStore(bindings.db),
3340
+ workspaceId: scope.workspaceId,
3341
+ harness,
3342
+ provision: () => ensureWorkspaceSandbox(shell, { ...scope, harness, trace: args.trace }),
3343
+ peek: () => peekWorkspaceSandbox(shell, scope),
3344
+ adopt: ({ box }) => box
3345
+ });
3346
+ };
3347
+ const modelFor = (args) => {
3348
+ const model = args.body.model ?? env.MODEL_NAME ?? config.model;
3349
+ if (!model?.trim()) throw new Error("Default chat requires MODEL_NAME or produce.model");
3350
+ return model;
3351
+ };
3352
+ const promptOptions = (args) => ({
3353
+ model: modelFor(args),
3354
+ harness,
3355
+ sessionId: args.identity.sessionId,
3356
+ executionId: args.executionId,
3357
+ turnId: args.executionId,
3358
+ trace: args.trace,
3359
+ signal: args.admissionSignal,
3360
+ detach: true,
3361
+ systemPrompt: config.systemPrompt,
3362
+ interactions: config.interactions,
3363
+ effort: args.executionLimits?.maxReasoningTokens === 0 ? "none" : args.body.effort ?? config.effort,
3364
+ ...args.executionLimits?.maxOutputTokens !== void 0 ? {
3365
+ maxOutputTokens: args.executionLimits.maxOutputTokens,
3366
+ maxTotalOutputTokens: args.executionLimits.maxOutputTokens
3367
+ } : {},
3368
+ ...args.executionLimits?.maxReasoningTokens ? { maxReasoningTokens: args.executionLimits.maxReasoningTokens } : {}
3369
+ });
3370
+ return {
3371
+ when: (args) => config.router !== false && Boolean(env.TANGLE_API_KEY?.trim()) && !turnCarriesFiles(args.prompt) && !args.executionLimits?.maxReasoningTokens,
3372
+ async router(args) {
3373
+ const model = modelFor(args);
3374
+ if (modelPolicy) await assertPolicy({ kind: "model", id: model, ...modelPolicy });
3375
+ const base = env.TANGLE_ROUTER_URL?.trim().replace(/\/+$/, "");
3376
+ return {
3377
+ apiKey: env.TANGLE_API_KEY.trim(),
3378
+ model,
3379
+ reasoningEffort: args.executionLimits?.maxReasoningTokens === 0 ? "none" : args.body.effort ?? config.effort,
3380
+ ...args.executionLimits?.maxOutputTokens !== void 0 ? {
3381
+ maxTokens: args.executionLimits.maxOutputTokens,
3382
+ maxCompletionTokens: args.executionLimits.maxOutputTokens
3383
+ } : {},
3384
+ ...base ? { baseUrl: base.endsWith("/v1") ? base : `${base}/v1` } : {},
3385
+ systemPrompt: { profile: shell.profile({ systemPrompt: config.systemPrompt, harness }) },
3386
+ box: { acquire: () => acquire(args), runTask: sandboxPromptRunner(shell, {
3387
+ ...promptOptions(args),
3388
+ sessionId: `sandbox-run-${args.identity.sessionId}`
3389
+ }) }
3390
+ };
3391
+ },
3392
+ sandbox: async (args) => {
3393
+ const model = modelFor(args);
3394
+ if (modelPolicy) await assertPolicy({ kind: "model", id: model, ...modelPolicy });
3395
+ const box = await acquire(args);
3396
+ return {
3397
+ model,
3398
+ modelPolicy,
3399
+ modelFailover: false,
3400
+ errorNotice: true,
3401
+ openEvents: ({ model: model2, signal }) => streamSandboxPrompt(
3402
+ shell,
3403
+ box,
3404
+ normalizeChatPromptForSandbox(args.prompt),
3405
+ { ...promptOptions(args), model: model2, signal }
3406
+ )
3407
+ };
3408
+ }
3409
+ };
3410
+ }
3411
+
3412
+ // src/chat-routes/route-prewarm.ts
3413
+ function createChatPrewarm(options) {
3414
+ if (options.prewarm === false) return async () => new Response(null, { status: 405 });
3415
+ const bindings = options.turnLock === false ? void 0 : turnStorageBindings(options);
3416
+ const route = createWorkspacePrewarmRoute({
3417
+ turnStore: bindings,
3418
+ authorize: async ({ request, threadId }) => {
3419
+ const auth = await options.authorize({ request, intent: "running", threadId });
3420
+ if (!auth.ok) return { status: "denied", response: auth.response };
3421
+ if (auth.intent !== void 0 && auth.intent !== "running") return {
3422
+ status: "denied",
3423
+ response: Response.json({ error: "Authorization did not allow this read.", code: "chat_authorization_intent_mismatch" }, { status: 403 })
3424
+ };
3425
+ if (!bindings) return { status: "declined", reason: "lock_not_configured" };
3426
+ return { status: "allowed", workspaceId: auth.tenantId, steps: [] };
3427
+ }
3428
+ });
3429
+ return (request) => route(request, void 0);
3430
+ }
3431
+
2913
3432
  // src/chat-routes/turn-routes.ts
2914
3433
  async function admitTurn(request, trace, options, waitUntil) {
2915
3434
  const parse = trace.start("admission.parse", "admission");
@@ -2941,7 +3460,12 @@ async function admitTurn(request, trace, options, waitUntil) {
2941
3460
  }
2942
3461
  }
2943
3462
  function createChatTurnRoutes(input) {
2944
- const options = resolveTurnStorage(input);
3463
+ const produce = input.produce;
3464
+ const options = {
3465
+ ...input,
3466
+ ...resolveTurnStorage(input),
3467
+ produce: typeof produce === "function" || produce && "router" in produce && typeof produce.router === "function" ? produce : createDefaultChatBackend(input.projectId, input.env ?? {}, produce ?? {}, turnStorageBindings(input), input.modelPolicy)
3468
+ };
2945
3469
  const log = options.log ?? ((message, meta) => console.error(message, meta ?? ""));
2946
3470
  const draftStore = options.store;
2947
3471
  const draftTuning = storeSupportsDraftPersistence(draftStore) ? {} : null;
@@ -3160,6 +3684,7 @@ function createChatTurnRoutes(input) {
3160
3684
  return Response.json({ running: ids });
3161
3685
  }
3162
3686
  return {
3687
+ prewarm: createChatPrewarm(input),
3163
3688
  turn: (request, ctx) => withD1QueryCount(() => turn(request, ctx)),
3164
3689
  cancel: (request) => cancelChatTurn(request, { authorize: options.authorize, cancel: options.cancel, log }),
3165
3690
  replay,
@@ -3375,7 +3900,15 @@ export {
3375
3900
  INTENT_LINE_TIMEOUT_MS,
3376
3901
  INTENT_LINE_HISTORY_MESSAGES,
3377
3902
  INTENT_LINE_MAX_CHARS,
3903
+ UPLOAD_INLINE_MAX_BYTES,
3904
+ UPLOAD_MAX_FILE_BYTES,
3905
+ sanitizeUploadFilename,
3906
+ bytesToBase64,
3907
+ createUploadRoute,
3908
+ normalizeChatPromptForSandbox,
3909
+ projectDispatchHistory,
3910
+ buildDispatchParts,
3378
3911
  createChatTurnRoutes,
3379
3912
  streamChatRouteAsSandboxEvents
3380
3913
  };
3381
- //# sourceMappingURL=chunk-XYSKMHWG.js.map
3914
+ //# sourceMappingURL=chunk-42QCR4CV.js.map