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