@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.
- package/dist/assistant/index.js +1 -1
- 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-XYSKMHWG.js → chunk-42QCR4CV.js} +548 -15
- package/dist/chunk-42QCR4CV.js.map +1 -0
- 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-4CALWPN5.js → chunk-L6BS2XTE.js} +20 -16
- package/dist/chunk-L6BS2XTE.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/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/dist/web-react/durable-plan-flow.d.ts +10 -0
- package/dist/web-react/index.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-4CALWPN5.js.map +0 -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
package/dist/assistant/index.js
CHANGED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import type { Harness } from '../harness/index';
|
|
2
|
+
import type { SandboxRuntimeConfig } from '../sandbox/configuration';
|
|
3
|
+
import type { StreamSandboxPromptOptions } from '../sandbox/prompt-options';
|
|
4
|
+
import type { ChatTurnStoreBindings } from './route-storage';
|
|
5
|
+
import { type ModelPolicy } from '../policy-filters/index';
|
|
6
|
+
import type { ChatTurnProduceArgs, ChatTurnHybridConfiguration } from './turn-route-contracts';
|
|
7
|
+
/** Worker bindings are explicit; no ambient deployment credentials replace product policy. */
|
|
8
|
+
export interface ChatTurnEnvironment {
|
|
9
|
+
DB?: ChatTurnStoreBindings['db'];
|
|
10
|
+
TURN_STREAM?: ChatTurnStoreBindings['lock']['namespace'];
|
|
11
|
+
TURN_STREAM_DO?: ChatTurnStoreBindings['lock']['namespace'];
|
|
12
|
+
TURN_STREAM_AUTH_SECRET?: string;
|
|
13
|
+
D1_REGION?: ChatTurnStoreBindings['region'];
|
|
14
|
+
TANGLE_API_KEY?: string;
|
|
15
|
+
TANGLE_ROUTER_URL?: string;
|
|
16
|
+
MODEL_NAME?: string;
|
|
17
|
+
SANDBOX_API_KEY?: string;
|
|
18
|
+
SANDBOX_GATEWAY_URL?: string;
|
|
19
|
+
}
|
|
20
|
+
/** Domain data for the default lane, instead of constructing producers or admission hooks. */
|
|
21
|
+
export interface ChatTurnDefaultBackend {
|
|
22
|
+
model?: string;
|
|
23
|
+
systemPrompt?: string;
|
|
24
|
+
harness?: Harness;
|
|
25
|
+
effort?: StreamSandboxPromptOptions['effort'];
|
|
26
|
+
interactions?: StreamSandboxPromptOptions['interactions'];
|
|
27
|
+
/** Existing product provisioning, credentials, profiles and egress policy remain authoritative. */
|
|
28
|
+
shell?: SandboxRuntimeConfig;
|
|
29
|
+
/** Explicitly keep every turn on the sandbox lane. */
|
|
30
|
+
router?: false;
|
|
31
|
+
}
|
|
32
|
+
export declare function defaultChatShell(projectId: string, env: ChatTurnEnvironment, config: ChatTurnDefaultBackend): SandboxRuntimeConfig;
|
|
33
|
+
export declare function createDefaultChatBackend<TContext, TResource>(projectId: string, env: ChatTurnEnvironment, config: ChatTurnDefaultBackend, bindings?: ChatTurnStoreBindings, modelPolicy?: ModelPolicy): {
|
|
34
|
+
when: (args: ChatTurnProduceArgs<TContext, TResource>) => boolean;
|
|
35
|
+
router(args: ChatTurnProduceArgs<TContext, TResource>): Promise<ChatTurnHybridConfiguration>;
|
|
36
|
+
sandbox: (args: ChatTurnProduceArgs<TContext, TResource>) => Promise<{
|
|
37
|
+
model: string;
|
|
38
|
+
modelPolicy: ModelPolicy<import("../policy-filters/index").PolicyFilterContext> | undefined;
|
|
39
|
+
modelFailover: false;
|
|
40
|
+
errorNotice: boolean;
|
|
41
|
+
openEvents: ({ model, signal }: {
|
|
42
|
+
model: string;
|
|
43
|
+
signal: AbortSignal;
|
|
44
|
+
}) => AsyncGenerator<unknown, any, any>;
|
|
45
|
+
}>;
|
|
46
|
+
};
|
|
@@ -5,7 +5,8 @@
|
|
|
5
5
|
* Ordinary functions and Sandbox backends never execute speculatively.
|
|
6
6
|
*/
|
|
7
7
|
import type { TurnTrace } from '../turn-trace/recorder';
|
|
8
|
-
import type { ChatTurnProduceArgs, ChatTurnRouteProducer
|
|
8
|
+
import type { ChatTurnProduceArgs, ChatTurnRouteProducer } from './turn-route-contracts';
|
|
9
|
+
import type { ResolvedChatTurnRoutesOptions } from './route-storage';
|
|
9
10
|
/** Thrown into `args.admitted` when the turn was refused after its producer started. */
|
|
10
11
|
export declare class TurnAdmissionRefusedError extends Error {
|
|
11
12
|
constructor();
|
|
@@ -17,7 +18,7 @@ export interface DispatchedProducer<TContext, TResource = unknown> {
|
|
|
17
18
|
refuse(): void;
|
|
18
19
|
}
|
|
19
20
|
/** Select once, so admission's context mutations cannot switch execution backends. */
|
|
20
|
-
export declare function selectTurnProducer<TContext, TResource = unknown>(produce:
|
|
21
|
+
export declare function selectTurnProducer<TContext, TResource = unknown>(produce: ResolvedChatTurnRoutesOptions<TContext, TResource>['produce'], args: ChatTurnProduceArgs<TContext, TResource>): {
|
|
21
22
|
produce: (args: ChatTurnProduceArgs<TContext, TResource>) => ChatTurnRouteProducer | Promise<ChatTurnRouteProducer>;
|
|
22
23
|
router: boolean;
|
|
23
24
|
};
|
|
@@ -43,7 +43,7 @@ import {
|
|
|
43
43
|
} from "../chunk-BV3VZEKB.js";
|
|
44
44
|
import {
|
|
45
45
|
runProtectedRouterTurn
|
|
46
|
-
} from "../chunk-
|
|
46
|
+
} from "../chunk-NUWSPR5O.js";
|
|
47
47
|
import {
|
|
48
48
|
DEFAULT_MODEL_FIRST_RESPONSE_TIMEOUT_MS,
|
|
49
49
|
DEFAULT_MODEL_STREAM_OPEN_TIMEOUT_MS,
|
|
@@ -53,17 +53,25 @@ import {
|
|
|
53
53
|
INTENT_LINE_TIMEOUT_MS,
|
|
54
54
|
MAX_EMPTY_TURN_RETRIES,
|
|
55
55
|
ModelFailoverTimeoutError,
|
|
56
|
+
UPLOAD_INLINE_MAX_BYTES,
|
|
57
|
+
UPLOAD_MAX_FILE_BYTES,
|
|
58
|
+
buildDispatchParts,
|
|
59
|
+
bytesToBase64,
|
|
56
60
|
cancelChatTurn,
|
|
57
61
|
classifyTerminalFailure,
|
|
58
62
|
createChatTurnRoutes,
|
|
59
63
|
createHybridTurnProducer,
|
|
60
64
|
createRouterTurnProducer,
|
|
61
65
|
createSandboxChatProducer,
|
|
66
|
+
createUploadRoute,
|
|
62
67
|
isCommittingSandboxEvent,
|
|
63
68
|
isLiveLifecycleEvent,
|
|
69
|
+
normalizeChatPromptForSandbox,
|
|
64
70
|
observeTurnCancellation,
|
|
71
|
+
projectDispatchHistory,
|
|
65
72
|
resolveEmptyTurnRetries,
|
|
66
73
|
routerTurnHistory,
|
|
74
|
+
sanitizeUploadFilename,
|
|
67
75
|
startHybridBox,
|
|
68
76
|
streamChatRouteAsSandboxEvents,
|
|
69
77
|
streamWithModelFailover,
|
|
@@ -71,7 +79,7 @@ import {
|
|
|
71
79
|
turnCarriesFiles,
|
|
72
80
|
turnPromptText,
|
|
73
81
|
withProducerStream
|
|
74
|
-
} from "../chunk-
|
|
82
|
+
} from "../chunk-42QCR4CV.js";
|
|
75
83
|
import "../chunk-KH4QSBNI.js";
|
|
76
84
|
import {
|
|
77
85
|
sniffMimeFromName
|
|
@@ -83,9 +91,7 @@ import {
|
|
|
83
91
|
redactErrorMessage
|
|
84
92
|
} from "../chunk-MH74DY2I.js";
|
|
85
93
|
import "../chunk-MM6RLOXF.js";
|
|
86
|
-
import
|
|
87
|
-
flattenHistory
|
|
88
|
-
} from "../chunk-OCR36QGZ.js";
|
|
94
|
+
import "../chunk-UVMKP5IK.js";
|
|
89
95
|
import "../chunk-F4TUZYMX.js";
|
|
90
96
|
import {
|
|
91
97
|
assistantRowIdForTurn,
|
|
@@ -99,7 +105,6 @@ import "../chunk-YG66IHDU.js";
|
|
|
99
105
|
import {
|
|
100
106
|
attachmentInputToPart,
|
|
101
107
|
attachmentKindForMime,
|
|
102
|
-
historyContentWithAttachments,
|
|
103
108
|
toChatMessageParts
|
|
104
109
|
} from "../chunk-RZLCBWGG.js";
|
|
105
110
|
import "../chunk-ZVEEWGDK.js";
|
|
@@ -162,7 +167,7 @@ import "../chunk-S5SRJJQG.js";
|
|
|
162
167
|
import "../chunk-FCYHDENJ.js";
|
|
163
168
|
import "../chunk-UGWQLQDS.js";
|
|
164
169
|
import "../chunk-HRBF4B5L.js";
|
|
165
|
-
import "../chunk-
|
|
170
|
+
import "../chunk-EKXG4JSN.js";
|
|
166
171
|
import "../chunk-D6UJEOZQ.js";
|
|
167
172
|
import "../chunk-AVBNS64P.js";
|
|
168
173
|
import "../chunk-AMUXRAUO.js";
|
|
@@ -172,9 +177,7 @@ import {
|
|
|
172
177
|
} from "../chunk-CTREXL3O.js";
|
|
173
178
|
import "../chunk-ELX5YITO.js";
|
|
174
179
|
import "../chunk-HY57QRRW.js";
|
|
175
|
-
import
|
|
176
|
-
isWorkspaceFileExportable
|
|
177
|
-
} from "../chunk-TXD5HXLE.js";
|
|
180
|
+
import "../chunk-TXD5HXLE.js";
|
|
178
181
|
import {
|
|
179
182
|
persistedPartToPlan,
|
|
180
183
|
planFollowUpTurnId
|
|
@@ -774,115 +777,6 @@ function withDurableChatProjection(producer, projection, log = (message, meta) =
|
|
|
774
777
|
};
|
|
775
778
|
}
|
|
776
779
|
|
|
777
|
-
// src/chat-routes/upload.ts
|
|
778
|
-
var UPLOAD_INLINE_MAX_BYTES = 700 * 1024;
|
|
779
|
-
var UPLOAD_MAX_FILE_BYTES = 8 * 1024 * 1024;
|
|
780
|
-
var DEFAULT_UPLOAD_DIRECTORY = "/workspace/uploads";
|
|
781
|
-
function normalizeUploadDirectory(value) {
|
|
782
|
-
const withoutTrailingSlash = value.trim().replace(/\/+$/, "");
|
|
783
|
-
if (!withoutTrailingSlash.startsWith("/") || withoutTrailingSlash.length === 0) return null;
|
|
784
|
-
const segments = withoutTrailingSlash.slice(1).split("/");
|
|
785
|
-
if (segments.some((segment) => segment.length === 0 || segment === "." || segment === "..")) return null;
|
|
786
|
-
return `/${segments.join("/")}`;
|
|
787
|
-
}
|
|
788
|
-
function sanitizeUploadFilename(name) {
|
|
789
|
-
const base = name.split(/[\\/]/).pop() ?? "file";
|
|
790
|
-
const safe = base.replace(/[^A-Za-z0-9._-]+/g, "_").replace(/^\.+/, "_");
|
|
791
|
-
return (safe || "file").slice(0, 120);
|
|
792
|
-
}
|
|
793
|
-
var BASE64_CHUNK = 32768;
|
|
794
|
-
function bytesToBase64(bytes) {
|
|
795
|
-
let binary = "";
|
|
796
|
-
for (let offset = 0; offset < bytes.length; offset += BASE64_CHUNK) {
|
|
797
|
-
binary += String.fromCharCode(...bytes.subarray(offset, offset + BASE64_CHUNK));
|
|
798
|
-
}
|
|
799
|
-
return btoa(binary);
|
|
800
|
-
}
|
|
801
|
-
function uploadError(status, code, error) {
|
|
802
|
-
return Response.json({ code, error }, { status });
|
|
803
|
-
}
|
|
804
|
-
function createUploadRoute(options) {
|
|
805
|
-
const inlineMaxBytes = options.inlineMaxBytes ?? UPLOAD_INLINE_MAX_BYTES;
|
|
806
|
-
const maxFileBytes = options.maxFileBytes ?? UPLOAD_MAX_FILE_BYTES;
|
|
807
|
-
return async function upload(request) {
|
|
808
|
-
const auth = await options.authorize({ request });
|
|
809
|
-
if (!auth.ok) return auth.response;
|
|
810
|
-
const sink = auth.sink ?? null;
|
|
811
|
-
const configuredUploadDir = auth.uploadDir ?? options.uploadDir ?? DEFAULT_UPLOAD_DIRECTORY;
|
|
812
|
-
let form;
|
|
813
|
-
try {
|
|
814
|
-
form = await request.formData();
|
|
815
|
-
} catch {
|
|
816
|
-
return uploadError(400, "INVALID_UPLOAD", "Expected a multipart/form-data body with file fields");
|
|
817
|
-
}
|
|
818
|
-
const files = [];
|
|
819
|
-
form.forEach((value) => {
|
|
820
|
-
if (value instanceof File) files.push(value);
|
|
821
|
-
});
|
|
822
|
-
if (files.length === 0) {
|
|
823
|
-
return uploadError(400, "INVALID_UPLOAD", "No files in the upload body");
|
|
824
|
-
}
|
|
825
|
-
const uploaded = [];
|
|
826
|
-
for (const file of files) {
|
|
827
|
-
const name = sanitizeUploadFilename(file.name);
|
|
828
|
-
const mediaType = file.type || "application/octet-stream";
|
|
829
|
-
const partType = mediaType.startsWith("image/") ? "image" : "file";
|
|
830
|
-
if (file.size > maxFileBytes) {
|
|
831
|
-
return uploadError(
|
|
832
|
-
413,
|
|
833
|
-
"FILE_TOO_LARGE",
|
|
834
|
-
`${name} is ${file.size}B, over the ${maxFileBytes}B per-file cap`
|
|
835
|
-
);
|
|
836
|
-
}
|
|
837
|
-
const id = crypto.randomUUID();
|
|
838
|
-
if (file.size <= inlineMaxBytes) {
|
|
839
|
-
const base642 = bytesToBase64(new Uint8Array(await file.arrayBuffer()));
|
|
840
|
-
uploaded.push({
|
|
841
|
-
id,
|
|
842
|
-
name,
|
|
843
|
-
size: file.size,
|
|
844
|
-
mediaType,
|
|
845
|
-
inline: true,
|
|
846
|
-
part: {
|
|
847
|
-
type: partType,
|
|
848
|
-
filename: name,
|
|
849
|
-
mediaType,
|
|
850
|
-
url: `data:${mediaType};base64,${base642}`
|
|
851
|
-
}
|
|
852
|
-
});
|
|
853
|
-
continue;
|
|
854
|
-
}
|
|
855
|
-
if (!sink) {
|
|
856
|
-
return uploadError(
|
|
857
|
-
413,
|
|
858
|
-
"SANDBOX_REQUIRED",
|
|
859
|
-
`${name} is ${file.size}B, over the ${inlineMaxBytes}B inline cap, and no sandbox is available to hold it`
|
|
860
|
-
);
|
|
861
|
-
}
|
|
862
|
-
const uploadDir = normalizeUploadDirectory(configuredUploadDir);
|
|
863
|
-
if (!uploadDir) {
|
|
864
|
-
return uploadError(
|
|
865
|
-
500,
|
|
866
|
-
"INVALID_UPLOAD_DIRECTORY",
|
|
867
|
-
'uploadDir must be an absolute path without empty, "." or ".." segments'
|
|
868
|
-
);
|
|
869
|
-
}
|
|
870
|
-
const path = `${uploadDir}/${id}-${name}`;
|
|
871
|
-
const base64 = bytesToBase64(new Uint8Array(await file.arrayBuffer()));
|
|
872
|
-
await sink.write(path, base64, { encoding: "base64" });
|
|
873
|
-
uploaded.push({
|
|
874
|
-
id,
|
|
875
|
-
name,
|
|
876
|
-
size: file.size,
|
|
877
|
-
mediaType,
|
|
878
|
-
inline: false,
|
|
879
|
-
part: { type: partType, filename: name, mediaType, path }
|
|
880
|
-
});
|
|
881
|
-
}
|
|
882
|
-
return Response.json({ files: uploaded });
|
|
883
|
-
};
|
|
884
|
-
}
|
|
885
|
-
|
|
886
780
|
// src/chat-routes/attachment-store.ts
|
|
887
781
|
async function prepareDispatchAttachments(input) {
|
|
888
782
|
const historyBudget = Math.max(
|
|
@@ -1849,232 +1743,6 @@ async function commitUploadBatch(prepared, legacyWriter, auth, atomicWriter, ato
|
|
|
1849
1743
|
return Response.json({ files: uploaded });
|
|
1850
1744
|
}
|
|
1851
1745
|
|
|
1852
|
-
// src/chat-routes/dispatch-parts.ts
|
|
1853
|
-
import { pathToFileURL } from "url";
|
|
1854
|
-
function byteLen(value) {
|
|
1855
|
-
return new TextEncoder().encode(value).length;
|
|
1856
|
-
}
|
|
1857
|
-
async function readSandboxMention(box, absolutePath, options) {
|
|
1858
|
-
const stat = await statSandboxFileSize(box, absolutePath);
|
|
1859
|
-
if (!stat.succeeded) {
|
|
1860
|
-
return { succeeded: false, error: `mentioned sandbox file missing or unreadable: ${absolutePath} \u2014 ${stat.error}` };
|
|
1861
|
-
}
|
|
1862
|
-
if (!options.readBytes) return { succeeded: true, value: { size: stat.value } };
|
|
1863
|
-
const read = await readSandboxBinaryBytes(box, absolutePath, stat.value);
|
|
1864
|
-
if (!read.succeeded) {
|
|
1865
|
-
return { succeeded: false, error: `mentioned sandbox file read failed: ${absolutePath} \u2014 ${read.error}` };
|
|
1866
|
-
}
|
|
1867
|
-
return { succeeded: true, value: { size: stat.value, base64: bytesToBase64(read.value.bytes) } };
|
|
1868
|
-
}
|
|
1869
|
-
function violatesUrlPathXor(part) {
|
|
1870
|
-
if (part.type === "text") return false;
|
|
1871
|
-
const hasUrl = typeof part.url === "string" && (part.url.startsWith("data:") || part.url.startsWith("file://"));
|
|
1872
|
-
const hasPath = "path" in part && typeof part.path === "string" && part.path.startsWith("/");
|
|
1873
|
-
if (part.type === "file") return !hasUrl || hasPath;
|
|
1874
|
-
return hasUrl === hasPath;
|
|
1875
|
-
}
|
|
1876
|
-
function sandboxFileUrl(absolutePath) {
|
|
1877
|
-
if (!absolutePath.startsWith("/")) return void 0;
|
|
1878
|
-
try {
|
|
1879
|
-
return pathToFileURL(absolutePath).href;
|
|
1880
|
-
} catch {
|
|
1881
|
-
return void 0;
|
|
1882
|
-
}
|
|
1883
|
-
}
|
|
1884
|
-
function normalizeChatPromptForSandbox(prompt) {
|
|
1885
|
-
if (typeof prompt === "string") return prompt;
|
|
1886
|
-
return prompt.map((part) => {
|
|
1887
|
-
if (part.type === "text") return part;
|
|
1888
|
-
if ("content" in part) {
|
|
1889
|
-
throw new ChatTurnInputError("Sandbox prompt parts do not accept inline content; provide a URL or path");
|
|
1890
|
-
}
|
|
1891
|
-
const url = typeof part.url === "string" && part.url.length > 0 ? part.url : void 0;
|
|
1892
|
-
const path = typeof part.path === "string" && part.path.length > 0 ? part.path : void 0;
|
|
1893
|
-
if (Boolean(url) === Boolean(path)) {
|
|
1894
|
-
throw new ChatTurnInputError(`Sandbox ${part.type} parts require exactly one URL or path`);
|
|
1895
|
-
}
|
|
1896
|
-
if (path && !path.startsWith("/")) {
|
|
1897
|
-
throw new ChatTurnInputError(`Sandbox ${part.type} paths must be absolute: ${path}`);
|
|
1898
|
-
}
|
|
1899
|
-
if (part.type === "image") {
|
|
1900
|
-
return {
|
|
1901
|
-
type: "image",
|
|
1902
|
-
...part.filename ? { filename: part.filename } : {},
|
|
1903
|
-
...part.mediaType ? { mediaType: part.mediaType } : {},
|
|
1904
|
-
...url ? { url } : { path }
|
|
1905
|
-
};
|
|
1906
|
-
}
|
|
1907
|
-
const filename = part.filename?.trim();
|
|
1908
|
-
if (!filename) {
|
|
1909
|
-
throw new ChatTurnInputError("Sandbox file parts require a filename");
|
|
1910
|
-
}
|
|
1911
|
-
const fileUrl = url ?? sandboxFileUrl(path);
|
|
1912
|
-
if (!fileUrl) {
|
|
1913
|
-
throw new ChatTurnInputError(`Sandbox file paths must be absolute: ${path}`);
|
|
1914
|
-
}
|
|
1915
|
-
return {
|
|
1916
|
-
type: "file",
|
|
1917
|
-
filename,
|
|
1918
|
-
...part.mediaType ? { mediaType: part.mediaType } : {},
|
|
1919
|
-
url: fileUrl
|
|
1920
|
-
};
|
|
1921
|
-
});
|
|
1922
|
-
}
|
|
1923
|
-
function projectDispatchHistory(messages) {
|
|
1924
|
-
return messages.map((message) => ({
|
|
1925
|
-
role: message.role === "assistant" ? "assistant" : "user",
|
|
1926
|
-
content: historyContentWithAttachments(message)
|
|
1927
|
-
}));
|
|
1928
|
-
}
|
|
1929
|
-
function readResultToBase64(read) {
|
|
1930
|
-
if (typeof read.base64 === "string") return read.base64;
|
|
1931
|
-
if (read.bytes) return bytesToBase64(read.bytes);
|
|
1932
|
-
return void 0;
|
|
1933
|
-
}
|
|
1934
|
-
async function buildDispatchParts(input) {
|
|
1935
|
-
const readMention = input.readSandboxMention ?? readSandboxMention;
|
|
1936
|
-
const resolveMentionPath = input.resolveMentionPath ?? input.resolveAttachmentPath;
|
|
1937
|
-
const forcePath = input.forcePath ?? false;
|
|
1938
|
-
const mentions = input.mentions ?? [];
|
|
1939
|
-
const requestMaxBytes = input.requestMaxBytes ?? DISPATCH_REQUEST_MAX_BYTES;
|
|
1940
|
-
const structuralReserveBytes = input.structuralReserveBytes ?? DISPATCH_STRUCTURAL_RESERVE_BYTES;
|
|
1941
|
-
const maxParts = input.maxParts ?? DISPATCH_MAX_PARTS;
|
|
1942
|
-
const parts = [{ type: "text", text: input.text }];
|
|
1943
|
-
const emittedAbsPaths = /* @__PURE__ */ new Set();
|
|
1944
|
-
const flattenedForSizing = flattenHistory(input.text, input.history);
|
|
1945
|
-
const inlineBudget = requestMaxBytes - base64WireLen(byteLen(flattenedForSizing)) - byteLen(JSON.stringify(input.systemPrompt)) - input.profileWireBytes - structuralReserveBytes;
|
|
1946
|
-
let runningInline = 0;
|
|
1947
|
-
for (const attachment of input.attachments) {
|
|
1948
|
-
if (!attachment.path) {
|
|
1949
|
-
return { succeeded: false, error: `attachment path must be non-empty: ${attachment.name}` };
|
|
1950
|
-
}
|
|
1951
|
-
let read;
|
|
1952
|
-
try {
|
|
1953
|
-
read = await input.readAttachment(input.scopeId, attachment.path);
|
|
1954
|
-
} catch (err) {
|
|
1955
|
-
return {
|
|
1956
|
-
succeeded: false,
|
|
1957
|
-
error: `attachment store read failed: ${attachment.path} \u2014 ${err instanceof Error ? err.message : String(err)}`
|
|
1958
|
-
};
|
|
1959
|
-
}
|
|
1960
|
-
if (!read.ok) return { succeeded: false, error: read.reason };
|
|
1961
|
-
const base64 = readResultToBase64(read);
|
|
1962
|
-
if (base64 === void 0) {
|
|
1963
|
-
return { succeeded: false, error: `attachment store read produced no content: ${attachment.path}` };
|
|
1964
|
-
}
|
|
1965
|
-
const mediaType = attachment.mediaType ?? read.mediaType;
|
|
1966
|
-
if (attachment.type === "image" && !mediaType) {
|
|
1967
|
-
return { succeeded: false, error: `attachment is missing a mediaType required for an image data URI: ${attachment.path}` };
|
|
1968
|
-
}
|
|
1969
|
-
const absPath = input.resolveAttachmentPath(attachment.path);
|
|
1970
|
-
emittedAbsPaths.add(absPath);
|
|
1971
|
-
if (attachment.type === "image") {
|
|
1972
|
-
const inlinePart2 = {
|
|
1973
|
-
type: "image",
|
|
1974
|
-
filename: attachment.name,
|
|
1975
|
-
mediaType,
|
|
1976
|
-
url: `data:${mediaType};base64,${base64}`
|
|
1977
|
-
};
|
|
1978
|
-
const cost2 = byteLen(JSON.stringify(inlinePart2));
|
|
1979
|
-
if (!forcePath && runningInline + cost2 <= inlineBudget) {
|
|
1980
|
-
parts.push(inlinePart2);
|
|
1981
|
-
runningInline += cost2;
|
|
1982
|
-
} else {
|
|
1983
|
-
parts.push({ type: "image", filename: attachment.name, mediaType, path: absPath });
|
|
1984
|
-
}
|
|
1985
|
-
continue;
|
|
1986
|
-
}
|
|
1987
|
-
const fileMediaType = mediaType ?? "application/octet-stream";
|
|
1988
|
-
const inlinePart = {
|
|
1989
|
-
type: "file",
|
|
1990
|
-
filename: attachment.name,
|
|
1991
|
-
mediaType: fileMediaType,
|
|
1992
|
-
url: `data:${fileMediaType};base64,${base64}`
|
|
1993
|
-
};
|
|
1994
|
-
const cost = byteLen(JSON.stringify(inlinePart));
|
|
1995
|
-
if (!forcePath && runningInline + cost <= inlineBudget) {
|
|
1996
|
-
parts.push(inlinePart);
|
|
1997
|
-
runningInline += cost;
|
|
1998
|
-
} else {
|
|
1999
|
-
const url = sandboxFileUrl(absPath);
|
|
2000
|
-
if (!url) {
|
|
2001
|
-
return { succeeded: false, error: `resolved attachment path must be absolute: ${absPath}` };
|
|
2002
|
-
}
|
|
2003
|
-
parts.push({ type: "file", filename: attachment.name, mediaType: fileMediaType, url });
|
|
2004
|
-
}
|
|
2005
|
-
}
|
|
2006
|
-
if (mentions.length > 0 && !input.box) {
|
|
2007
|
-
return { succeeded: false, error: "internal error: sandbox mentions require a box to read from" };
|
|
2008
|
-
}
|
|
2009
|
-
for (const mention of mentions) {
|
|
2010
|
-
if (!mention.path) {
|
|
2011
|
-
return { succeeded: false, error: `mention path must be non-empty: ${mention.name}` };
|
|
2012
|
-
}
|
|
2013
|
-
if (!isWorkspaceFileExportable(mention.path)) {
|
|
2014
|
-
return { succeeded: false, error: `mention file is not exportable: ${mention.path}` };
|
|
2015
|
-
}
|
|
2016
|
-
const absPath = resolveMentionPath(mention.path);
|
|
2017
|
-
if (emittedAbsPaths.has(absPath)) continue;
|
|
2018
|
-
emittedAbsPaths.add(absPath);
|
|
2019
|
-
const isImage = mention.mentionKind === "image";
|
|
2020
|
-
const mediaType = isImage ? mediaTypeForMentionPath(mention.path) : void 0;
|
|
2021
|
-
let stat;
|
|
2022
|
-
try {
|
|
2023
|
-
stat = await readMention(input.box, absPath, { readBytes: false });
|
|
2024
|
-
} catch (err) {
|
|
2025
|
-
return { succeeded: false, error: `mention read failed: ${absPath} \u2014 ${err instanceof Error ? err.message : String(err)}` };
|
|
2026
|
-
}
|
|
2027
|
-
if (!stat.succeeded) return { succeeded: false, error: stat.error };
|
|
2028
|
-
const projectedInlineCost = base64WireLen(stat.value.size) + byteLen(JSON.stringify({ type: "image", filename: mention.name, mediaType: mediaType ?? "", url: "" }));
|
|
2029
|
-
if (isImage && mediaType && !forcePath && runningInline + projectedInlineCost <= inlineBudget) {
|
|
2030
|
-
let read;
|
|
2031
|
-
try {
|
|
2032
|
-
read = await readMention(input.box, absPath, { readBytes: true });
|
|
2033
|
-
} catch (err) {
|
|
2034
|
-
return { succeeded: false, error: `mention read failed: ${absPath} \u2014 ${err instanceof Error ? err.message : String(err)}` };
|
|
2035
|
-
}
|
|
2036
|
-
if (!read.succeeded) return { succeeded: false, error: read.error };
|
|
2037
|
-
if (!read.value.base64) return { succeeded: false, error: `mentioned image produced no bytes: ${absPath}` };
|
|
2038
|
-
const inlinePart = {
|
|
2039
|
-
type: "image",
|
|
2040
|
-
filename: mention.name,
|
|
2041
|
-
mediaType,
|
|
2042
|
-
url: `data:${mediaType};base64,${read.value.base64}`
|
|
2043
|
-
};
|
|
2044
|
-
const cost = byteLen(JSON.stringify(inlinePart));
|
|
2045
|
-
if (runningInline + cost <= inlineBudget) {
|
|
2046
|
-
parts.push(inlinePart);
|
|
2047
|
-
runningInline += cost;
|
|
2048
|
-
continue;
|
|
2049
|
-
}
|
|
2050
|
-
}
|
|
2051
|
-
if (isImage && mediaType) {
|
|
2052
|
-
parts.push({ type: "image", filename: mention.name, mediaType, path: absPath });
|
|
2053
|
-
} else {
|
|
2054
|
-
const url = sandboxFileUrl(absPath);
|
|
2055
|
-
if (!url) {
|
|
2056
|
-
return { succeeded: false, error: `resolved mention path must be absolute: ${absPath}` };
|
|
2057
|
-
}
|
|
2058
|
-
parts.push({ type: "file", filename: mention.name, url });
|
|
2059
|
-
}
|
|
2060
|
-
}
|
|
2061
|
-
for (const part of parts) {
|
|
2062
|
-
if (violatesUrlPathXor(part)) {
|
|
2063
|
-
return { succeeded: false, error: "internal error: emitted media part violates the url/path exclusivity invariant" };
|
|
2064
|
-
}
|
|
2065
|
-
}
|
|
2066
|
-
const textPartSize = base64WireLen(byteLen(flattenedForSizing));
|
|
2067
|
-
const mediaPartsSize = parts.slice(1).reduce((total, part) => total + byteLen(JSON.stringify(part)), 0);
|
|
2068
|
-
const systemPromptSize = byteLen(JSON.stringify(input.systemPrompt));
|
|
2069
|
-
if (textPartSize + mediaPartsSize + systemPromptSize + input.profileWireBytes + structuralReserveBytes > requestMaxBytes) {
|
|
2070
|
-
return { succeeded: false, error: "dispatch parts exceed the sandbox proxy request cap even after path demotion" };
|
|
2071
|
-
}
|
|
2072
|
-
if (parts.length > maxParts) {
|
|
2073
|
-
return { succeeded: false, error: `dispatch parts exceed the sidecar per-request cap of ${maxParts}` };
|
|
2074
|
-
}
|
|
2075
|
-
return { succeeded: true, value: parts };
|
|
2076
|
-
}
|
|
2077
|
-
|
|
2078
1746
|
// src/chat-routes/intelligence.ts
|
|
2079
1747
|
function observeChatTurnStream(source, options) {
|
|
2080
1748
|
const { client, sessionId, userId, workspaceId, runId, traceId, model, signal, onObservationError } = options;
|