sarvam-agents-client 0.5.1 → 0.5.2
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/compat/core/data.js +5 -14
- package/dist/compat/core/events.d.ts +6 -0
- package/dist/compat/core/files.d.ts +65 -0
- package/dist/compat/core/files.js +851 -0
- package/dist/compat/core/history.js +32 -7
- package/dist/compat/core/http.d.ts +52 -0
- package/dist/compat/core/http.js +309 -0
- package/dist/compat/core/turns.d.ts +29 -0
- package/dist/compat/core/turns.js +163 -12
- package/dist/compat/openai/client.d.ts +5 -0
- package/dist/compat/openai/client.js +10 -2
- package/dist/compat/openai/resources/events.js +218 -21
- package/dist/compat/openai/resources/sessions.js +33 -4
- package/dist/esm/compat/core/data.js +5 -14
- package/dist/esm/compat/core/events.d.ts +6 -0
- package/dist/esm/compat/core/files.d.ts +65 -0
- package/dist/esm/compat/core/files.js +829 -0
- package/dist/esm/compat/core/history.js +32 -7
- package/dist/esm/compat/core/http.d.ts +52 -0
- package/dist/esm/compat/core/http.js +307 -0
- package/dist/esm/compat/core/turns.d.ts +29 -0
- package/dist/esm/compat/core/turns.js +162 -12
- package/dist/esm/compat/openai/client.d.ts +5 -0
- package/dist/esm/compat/openai/client.js +10 -2
- package/dist/esm/compat/openai/resources/events.js +209 -12
- package/dist/esm/compat/openai/resources/sessions.js +33 -4
- package/package.json +1 -1
- package/src/compat/core/data.ts +5 -14
- package/src/compat/core/events.ts +7 -1
- package/src/compat/core/files.ts +913 -0
- package/src/compat/core/history.ts +32 -7
- package/src/compat/core/http.ts +338 -1
- package/src/compat/core/turns.ts +214 -13
- package/src/compat/openai/client.ts +13 -1
- package/src/compat/openai/resources/events.ts +239 -12
- package/src/compat/openai/resources/sessions.ts +39 -4
|
@@ -0,0 +1,829 @@
|
|
|
1
|
+
/** Artifact upload, remote URL fetch with SSRF/deadline guards, and session artifact verification. */
|
|
2
|
+
import { createHash } from "node:crypto";
|
|
3
|
+
import { isIP } from "node:net";
|
|
4
|
+
import { ArtifactsApi } from "../../apis/ArtifactsApi.js";
|
|
5
|
+
import { CoreAPIError, CoreConnectionError, CoreTimeoutError, CoreUserAbortError, mapPanjaError } from "./errors.js";
|
|
6
|
+
/** Matches Panja's artifact_contract.limits.MAX_UPLOAD_BYTES (20 MiB). */
|
|
7
|
+
export const MAX_UPLOAD_BYTES = 20 * 1024 * 1024;
|
|
8
|
+
/** Maximum number of file/image attachments in a single message (below Panja's 32-attachment cap). */
|
|
9
|
+
export const MAX_ATTACHMENTS_PER_MESSAGE = 20;
|
|
10
|
+
/** Maximum combined size of all attachments in a single message (50 MiB). */
|
|
11
|
+
export const MAX_TOTAL_ATTACHMENT_BYTES = 50 * 1024 * 1024;
|
|
12
|
+
export const MAX_REDIRECTS = 5;
|
|
13
|
+
export const DEFAULT_REMOTE_FETCH_TIMEOUT_MS = 30000;
|
|
14
|
+
export const ARTIFACT_URI_PREFIX = "artifact://";
|
|
15
|
+
const REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]);
|
|
16
|
+
const OPENAI_FILE_ID_PREFIX = "file-";
|
|
17
|
+
const BLOCKED_HOSTNAMES = new Set([
|
|
18
|
+
"localhost",
|
|
19
|
+
"localhost.localdomain",
|
|
20
|
+
"ip6-localhost",
|
|
21
|
+
"ip6-loopback",
|
|
22
|
+
"metadata.google.internal",
|
|
23
|
+
"metadata.azure.internal",
|
|
24
|
+
]);
|
|
25
|
+
const BLOCKED_HOST_SUFFIXES = [".localhost", ".local", ".internal"];
|
|
26
|
+
export const ACCEPTED_IMAGE_MIMES = new Set([
|
|
27
|
+
"image/png",
|
|
28
|
+
"image/jpeg",
|
|
29
|
+
"image/webp",
|
|
30
|
+
"image/gif",
|
|
31
|
+
]);
|
|
32
|
+
const MIME_RE = /^[a-z0-9][a-z0-9!#$&^_.+-]{0,62}\/[a-z0-9][a-z0-9!#$&^_.+-]{0,62}$/;
|
|
33
|
+
const DISALLOWED_MIME_PREFIXES = new Set(["multipart", "message", "model"]);
|
|
34
|
+
const EXT_TO_MIME = {
|
|
35
|
+
".png": "image/png",
|
|
36
|
+
".jpg": "image/jpeg",
|
|
37
|
+
".jpeg": "image/jpeg",
|
|
38
|
+
".webp": "image/webp",
|
|
39
|
+
".gif": "image/gif",
|
|
40
|
+
".svg": "image/svg+xml",
|
|
41
|
+
".bmp": "image/bmp",
|
|
42
|
+
".tif": "image/tiff",
|
|
43
|
+
".tiff": "image/tiff",
|
|
44
|
+
".pdf": "application/pdf",
|
|
45
|
+
".txt": "text/plain",
|
|
46
|
+
".md": "text/markdown",
|
|
47
|
+
".markdown": "text/markdown",
|
|
48
|
+
".csv": "text/csv",
|
|
49
|
+
".tsv": "text/tab-separated-values",
|
|
50
|
+
".json": "application/json",
|
|
51
|
+
".jsonl": "application/x-ndjson",
|
|
52
|
+
".ndjson": "application/x-ndjson",
|
|
53
|
+
".xml": "application/xml",
|
|
54
|
+
".yaml": "application/yaml",
|
|
55
|
+
".yml": "application/yaml",
|
|
56
|
+
".toml": "application/toml",
|
|
57
|
+
".html": "text/html",
|
|
58
|
+
".htm": "text/html",
|
|
59
|
+
".css": "text/css",
|
|
60
|
+
".js": "text/javascript",
|
|
61
|
+
".mjs": "text/javascript",
|
|
62
|
+
".ts": "text/plain",
|
|
63
|
+
".py": "text/x-python",
|
|
64
|
+
".sh": "text/x-shellscript",
|
|
65
|
+
".sql": "application/sql",
|
|
66
|
+
".doc": "application/msword",
|
|
67
|
+
".docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
|
|
68
|
+
".xls": "application/vnd.ms-excel",
|
|
69
|
+
".xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
|
70
|
+
".ppt": "application/vnd.ms-powerpoint",
|
|
71
|
+
".pptx": "application/vnd.openxmlformats-officedocument.presentationml.presentation",
|
|
72
|
+
".rtf": "application/rtf",
|
|
73
|
+
".epub": "application/epub+zip",
|
|
74
|
+
".zip": "application/zip",
|
|
75
|
+
".gz": "application/gzip",
|
|
76
|
+
".tar": "application/x-tar",
|
|
77
|
+
".mp3": "audio/mpeg",
|
|
78
|
+
".wav": "audio/wav",
|
|
79
|
+
".m4a": "audio/mp4",
|
|
80
|
+
".ogg": "audio/ogg",
|
|
81
|
+
".flac": "audio/flac",
|
|
82
|
+
".mp4": "video/mp4",
|
|
83
|
+
".webm": "video/webm",
|
|
84
|
+
};
|
|
85
|
+
const MIME_TO_EXT = {
|
|
86
|
+
"image/png": ".png",
|
|
87
|
+
"image/jpeg": ".jpg",
|
|
88
|
+
"image/webp": ".webp",
|
|
89
|
+
"image/gif": ".gif",
|
|
90
|
+
"image/svg+xml": ".svg",
|
|
91
|
+
"application/pdf": ".pdf",
|
|
92
|
+
"text/plain": ".txt",
|
|
93
|
+
"text/markdown": ".md",
|
|
94
|
+
"text/csv": ".csv",
|
|
95
|
+
"text/tab-separated-values": ".tsv",
|
|
96
|
+
"application/json": ".json",
|
|
97
|
+
"application/xml": ".xml",
|
|
98
|
+
"text/xml": ".xml",
|
|
99
|
+
"application/yaml": ".yaml",
|
|
100
|
+
"text/html": ".html",
|
|
101
|
+
"application/zip": ".zip",
|
|
102
|
+
"application/gzip": ".gz",
|
|
103
|
+
"audio/mpeg": ".mp3",
|
|
104
|
+
"audio/wav": ".wav",
|
|
105
|
+
"video/mp4": ".mp4",
|
|
106
|
+
};
|
|
107
|
+
const HTML_EXTS = new Set([".html", ".htm", ".xhtml"]);
|
|
108
|
+
export class AttachmentUploadCache {
|
|
109
|
+
constructor(maxEntries = 512) {
|
|
110
|
+
this.store = new Map();
|
|
111
|
+
this.max = Math.max(1, maxEntries);
|
|
112
|
+
}
|
|
113
|
+
keyOf(sessionId, idempotencyKey, partIndex, sha256Hex) {
|
|
114
|
+
return `${sessionId}\0${idempotencyKey}\0${partIndex}\0${sha256Hex}`;
|
|
115
|
+
}
|
|
116
|
+
get(sessionId, idempotencyKey, partIndex, sha256Hex) {
|
|
117
|
+
const k = this.keyOf(sessionId, idempotencyKey, partIndex, sha256Hex);
|
|
118
|
+
const val = this.store.get(k);
|
|
119
|
+
if (val !== undefined) {
|
|
120
|
+
this.store.delete(k);
|
|
121
|
+
this.store.set(k, val);
|
|
122
|
+
}
|
|
123
|
+
return val;
|
|
124
|
+
}
|
|
125
|
+
put(sessionId, idempotencyKey, partIndex, sha256Hex, artifact) {
|
|
126
|
+
const k = this.keyOf(sessionId, idempotencyKey, partIndex, sha256Hex);
|
|
127
|
+
this.store.delete(k);
|
|
128
|
+
this.store.set(k, artifact);
|
|
129
|
+
while (this.store.size > this.max) {
|
|
130
|
+
const oldest = this.store.keys().next().value;
|
|
131
|
+
if (oldest === undefined)
|
|
132
|
+
break;
|
|
133
|
+
this.store.delete(oldest);
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
evict(sessionId, idempotencyKey, partIndex, sha256Hex) {
|
|
137
|
+
this.store.delete(this.keyOf(sessionId, idempotencyKey, partIndex, sha256Hex));
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
function badInput(message, param) {
|
|
141
|
+
return new CoreAPIError(message, { status: 400, code: "invalid_request_error", param: param !== null && param !== void 0 ? param : null });
|
|
142
|
+
}
|
|
143
|
+
export function isOpenAIFileId(fileId) {
|
|
144
|
+
return fileId.startsWith(OPENAI_FILE_ID_PREFIX);
|
|
145
|
+
}
|
|
146
|
+
export function normalizeMime(raw) {
|
|
147
|
+
if (!raw || typeof raw !== "string")
|
|
148
|
+
return null;
|
|
149
|
+
const head = raw.split(";", 1)[0].trim().toLowerCase();
|
|
150
|
+
if (!head)
|
|
151
|
+
return null;
|
|
152
|
+
return head === "image/jpg" ? "image/jpeg" : head;
|
|
153
|
+
}
|
|
154
|
+
function fileExt(name) {
|
|
155
|
+
if (!name)
|
|
156
|
+
return "";
|
|
157
|
+
const trimmed = name.trim().toLowerCase();
|
|
158
|
+
const slash = Math.max(trimmed.lastIndexOf("/"), trimmed.lastIndexOf("\\"));
|
|
159
|
+
const base = slash >= 0 ? trimmed.slice(slash + 1) : trimmed;
|
|
160
|
+
const dot = base.lastIndexOf(".");
|
|
161
|
+
return dot > 0 ? base.slice(dot) : "";
|
|
162
|
+
}
|
|
163
|
+
export function inferMimeFromFilename(filename) {
|
|
164
|
+
var _a;
|
|
165
|
+
const ext = fileExt(filename);
|
|
166
|
+
return ext ? ((_a = EXT_TO_MIME[ext]) !== null && _a !== void 0 ? _a : null) : null;
|
|
167
|
+
}
|
|
168
|
+
export function sanitizeFilename(name, defaultStem, mediaType) {
|
|
169
|
+
var _a;
|
|
170
|
+
if (name && typeof name === "string") {
|
|
171
|
+
const norm = name.replace(/\\/g, "/");
|
|
172
|
+
const base = norm.slice(norm.lastIndexOf("/") + 1).trim();
|
|
173
|
+
const cleaned = base.replace(/[\x00-\x1f\x7f]+/g, "");
|
|
174
|
+
if (cleaned && cleaned !== "." && cleaned !== "..") {
|
|
175
|
+
return cleaned.slice(0, 512);
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
const ext = (_a = MIME_TO_EXT[mediaType]) !== null && _a !== void 0 ? _a : ".bin";
|
|
179
|
+
return `${defaultStem}${ext}`;
|
|
180
|
+
}
|
|
181
|
+
export function sniffImageMime(data) {
|
|
182
|
+
if (data.length >= 8 &&
|
|
183
|
+
data[0] === 0x89 && data[1] === 0x50 && data[2] === 0x4e && data[3] === 0x47 &&
|
|
184
|
+
data[4] === 0x0d && data[5] === 0x0a && data[6] === 0x1a && data[7] === 0x0a) {
|
|
185
|
+
return "image/png";
|
|
186
|
+
}
|
|
187
|
+
if (data.length >= 3 && data[0] === 0xff && data[1] === 0xd8 && data[2] === 0xff) {
|
|
188
|
+
return "image/jpeg";
|
|
189
|
+
}
|
|
190
|
+
if (data.length >= 6 &&
|
|
191
|
+
data[0] === 0x47 && data[1] === 0x49 && data[2] === 0x46 && data[3] === 0x38 &&
|
|
192
|
+
(data[4] === 0x37 || data[4] === 0x39) && data[5] === 0x61) {
|
|
193
|
+
return "image/gif";
|
|
194
|
+
}
|
|
195
|
+
if (data.length >= 12 &&
|
|
196
|
+
data[0] === 0x52 && data[1] === 0x49 && data[2] === 0x46 && data[3] === 0x46 &&
|
|
197
|
+
data[8] === 0x57 && data[9] === 0x45 && data[10] === 0x42 && data[11] === 0x50) {
|
|
198
|
+
return "image/webp";
|
|
199
|
+
}
|
|
200
|
+
return null;
|
|
201
|
+
}
|
|
202
|
+
export function verifyImageBytes(data, declaredMime, param) {
|
|
203
|
+
const sniffed = sniffImageMime(data);
|
|
204
|
+
if (!sniffed) {
|
|
205
|
+
const accepted = Array.from(ACCEPTED_IMAGE_MIMES).sort().join(", ");
|
|
206
|
+
throw badInput(`Image payload bytes do not match any supported image format (${accepted}).`, param);
|
|
207
|
+
}
|
|
208
|
+
const normDeclared = normalizeMime(declaredMime);
|
|
209
|
+
if (normDeclared && normDeclared !== "application/octet-stream" && normDeclared !== sniffed) {
|
|
210
|
+
throw badInput(`Declared image media type ${JSON.stringify(normDeclared)} does not match actual image bytes (${JSON.stringify(sniffed)}).`, param);
|
|
211
|
+
}
|
|
212
|
+
return sniffed;
|
|
213
|
+
}
|
|
214
|
+
export function validateImageMime(mime, param) {
|
|
215
|
+
const norm = normalizeMime(mime);
|
|
216
|
+
if (!norm || !ACCEPTED_IMAGE_MIMES.has(norm)) {
|
|
217
|
+
const accepted = Array.from(ACCEPTED_IMAGE_MIMES).sort().join(", ");
|
|
218
|
+
throw badInput(`Unsupported image media type ${JSON.stringify(mime !== null && mime !== void 0 ? mime : "")}; expected one of: ${accepted}.`, param);
|
|
219
|
+
}
|
|
220
|
+
return norm;
|
|
221
|
+
}
|
|
222
|
+
export function validateFileMime(mime, param) {
|
|
223
|
+
const norm = normalizeMime(mime);
|
|
224
|
+
if (!norm || norm.length > 128 || !MIME_RE.test(norm)) {
|
|
225
|
+
throw badInput(`Unsupported or invalid media type ${JSON.stringify(mime !== null && mime !== void 0 ? mime : "")}.`, param);
|
|
226
|
+
}
|
|
227
|
+
const top = norm.split("/", 1)[0];
|
|
228
|
+
if (DISALLOWED_MIME_PREFIXES.has(top)) {
|
|
229
|
+
throw badInput(`Unsupported file media type ${JSON.stringify(norm)}.`, param);
|
|
230
|
+
}
|
|
231
|
+
return norm;
|
|
232
|
+
}
|
|
233
|
+
/** O(n) stack-safe strict base64 validation (safe for 20+ MB payloads without regex backtracking). */
|
|
234
|
+
function isValidStrictBase64(cleaned) {
|
|
235
|
+
const len = cleaned.length;
|
|
236
|
+
if (len === 0 || len % 4 !== 0)
|
|
237
|
+
return false;
|
|
238
|
+
let padStart = -1;
|
|
239
|
+
for (let i = 0; i < len; i++) {
|
|
240
|
+
const c = cleaned.charCodeAt(i);
|
|
241
|
+
if (c === 61) {
|
|
242
|
+
// '='
|
|
243
|
+
if (padStart === -1)
|
|
244
|
+
padStart = i;
|
|
245
|
+
continue;
|
|
246
|
+
}
|
|
247
|
+
if (padStart !== -1) {
|
|
248
|
+
// Non-padding character after '='
|
|
249
|
+
return false;
|
|
250
|
+
}
|
|
251
|
+
const isAlphaNum = (c >= 65 && c <= 90) || // A-Z
|
|
252
|
+
(c >= 97 && c <= 122) || // a-z
|
|
253
|
+
(c >= 48 && c <= 57) || // 0-9
|
|
254
|
+
c === 43 || // +
|
|
255
|
+
c === 47; // /
|
|
256
|
+
if (!isAlphaNum)
|
|
257
|
+
return false;
|
|
258
|
+
}
|
|
259
|
+
if (padStart !== -1 && len - padStart > 2)
|
|
260
|
+
return false;
|
|
261
|
+
return true;
|
|
262
|
+
}
|
|
263
|
+
export function decodeBase64Bytes(raw, param) {
|
|
264
|
+
const cleaned = raw.replace(/\s+/g, "");
|
|
265
|
+
if (!cleaned) {
|
|
266
|
+
throw badInput("Base64 payload must not be empty.", param);
|
|
267
|
+
}
|
|
268
|
+
const estBytes = Math.floor((cleaned.length * 3) / 4);
|
|
269
|
+
if (estBytes > MAX_UPLOAD_BYTES + 4) {
|
|
270
|
+
throw badInput(`File exceeds the maximum upload size of ${Math.floor(MAX_UPLOAD_BYTES / (1024 * 1024))} MB.`, param);
|
|
271
|
+
}
|
|
272
|
+
if (!isValidStrictBase64(cleaned)) {
|
|
273
|
+
throw badInput("Invalid base64 payload.", param);
|
|
274
|
+
}
|
|
275
|
+
const buf = Buffer.from(cleaned, "base64");
|
|
276
|
+
if (buf.length === 0) {
|
|
277
|
+
throw badInput("File payload must not be empty.", param);
|
|
278
|
+
}
|
|
279
|
+
if (buf.length > MAX_UPLOAD_BYTES) {
|
|
280
|
+
throw badInput(`File exceeds the maximum upload size of ${Math.floor(MAX_UPLOAD_BYTES / (1024 * 1024))} MB.`, param);
|
|
281
|
+
}
|
|
282
|
+
return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength);
|
|
283
|
+
}
|
|
284
|
+
export function parseDataUri(raw, param) {
|
|
285
|
+
if (!raw.startsWith("data:")) {
|
|
286
|
+
throw badInput("Expected a data: URI.", param);
|
|
287
|
+
}
|
|
288
|
+
const comma = raw.indexOf(",");
|
|
289
|
+
if (comma === -1) {
|
|
290
|
+
throw badInput("Malformed data: URI (missing comma separator).", param);
|
|
291
|
+
}
|
|
292
|
+
const header = raw.slice(5, comma);
|
|
293
|
+
const payload = raw.slice(comma + 1);
|
|
294
|
+
const segments = header.split(";").map((s) => s.trim()).filter(Boolean);
|
|
295
|
+
if (!segments.some((s) => s.toLowerCase() === "base64")) {
|
|
296
|
+
throw badInput("Only base64-encoded data: URIs (data:<mime>;base64,...) are supported.", param);
|
|
297
|
+
}
|
|
298
|
+
const nonB64 = segments.filter((s) => s.toLowerCase() !== "base64");
|
|
299
|
+
const mimeRaw = nonB64.length > 0 && nonB64[0].includes("/") ? nonB64[0] : null;
|
|
300
|
+
const mime = normalizeMime(mimeRaw);
|
|
301
|
+
if (!mime) {
|
|
302
|
+
throw badInput("data: URI must include a valid media type (e.g. data:image/png;base64,...).", param);
|
|
303
|
+
}
|
|
304
|
+
const data = decodeBase64Bytes(payload, param);
|
|
305
|
+
return { mime, data };
|
|
306
|
+
}
|
|
307
|
+
export function validateRemoteUrl(url, param) {
|
|
308
|
+
if (typeof url !== "string" || !url.trim()) {
|
|
309
|
+
throw badInput("URL must be a non-empty string.", param);
|
|
310
|
+
}
|
|
311
|
+
const trimmed = url.trim();
|
|
312
|
+
let parsed;
|
|
313
|
+
try {
|
|
314
|
+
parsed = new URL(trimmed);
|
|
315
|
+
}
|
|
316
|
+
catch (_a) {
|
|
317
|
+
throw badInput(`Invalid URL ${JSON.stringify(trimmed)}.`, param);
|
|
318
|
+
}
|
|
319
|
+
if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
|
|
320
|
+
const scheme = parsed.protocol.replace(/:$/, "");
|
|
321
|
+
throw badInput(`Unsupported URL scheme ${JSON.stringify(scheme)}; only http:// and https:// URLs are allowed.`, param);
|
|
322
|
+
}
|
|
323
|
+
if (!parsed.hostname) {
|
|
324
|
+
throw badInput("URL must include a valid host.", param);
|
|
325
|
+
}
|
|
326
|
+
return trimmed;
|
|
327
|
+
}
|
|
328
|
+
function isBlockedIpv4Octets(a, b, c) {
|
|
329
|
+
if (a === 0)
|
|
330
|
+
return true; // 0.0.0.0/8 unspecified
|
|
331
|
+
if (a === 10)
|
|
332
|
+
return true; // 10.0.0.0/8 RFC1918
|
|
333
|
+
if (a === 100 && b >= 64 && b <= 127)
|
|
334
|
+
return true; // 100.64.0.0/10 CGNAT
|
|
335
|
+
if (a === 127)
|
|
336
|
+
return true; // 127.0.0.0/8 loopback
|
|
337
|
+
if (a === 169 && b === 254)
|
|
338
|
+
return true; // 169.254.0.0/16 link-local / cloud metadata
|
|
339
|
+
if (a === 172 && b >= 16 && b <= 31)
|
|
340
|
+
return true; // 172.16.0.0/12 RFC1918
|
|
341
|
+
if (a === 192 && b === 0 && (c === 0 || c === 2))
|
|
342
|
+
return true; // IETF / TEST-NET-1
|
|
343
|
+
if (a === 192 && b === 168)
|
|
344
|
+
return true; // 192.168.0.0/16 RFC1918
|
|
345
|
+
if (a === 198 && (b === 18 || b === 19))
|
|
346
|
+
return true; // 198.18.0.0/15 benchmarking
|
|
347
|
+
if (a === 198 && b === 51 && c === 100)
|
|
348
|
+
return true; // TEST-NET-2
|
|
349
|
+
if (a === 203 && b === 0 && c === 113)
|
|
350
|
+
return true; // TEST-NET-3
|
|
351
|
+
if (a >= 224)
|
|
352
|
+
return true; // multicast (224/4) & reserved/broadcast (240/4)
|
|
353
|
+
return false;
|
|
354
|
+
}
|
|
355
|
+
function parseIpv6Groups(raw) {
|
|
356
|
+
let addr = raw.toLowerCase();
|
|
357
|
+
// Convert embedded dotted-quad IPv4 suffix (e.g. ::ffff:169.254.169.254) into two 16-bit groups.
|
|
358
|
+
const lastColon = addr.lastIndexOf(":");
|
|
359
|
+
if (lastColon !== -1 && addr.includes(".")) {
|
|
360
|
+
const v4Part = addr.slice(lastColon + 1);
|
|
361
|
+
const octets = v4Part.split(".").map(Number);
|
|
362
|
+
if (octets.length !== 4 || octets.some((n) => !Number.isInteger(n) || n < 0 || n > 255))
|
|
363
|
+
return null;
|
|
364
|
+
const hi = ((octets[0] << 8) | octets[1]).toString(16);
|
|
365
|
+
const lo = ((octets[2] << 8) | octets[3]).toString(16);
|
|
366
|
+
addr = `${addr.slice(0, lastColon + 1)}${hi}:${lo}`;
|
|
367
|
+
}
|
|
368
|
+
const halves = addr.split("::");
|
|
369
|
+
if (halves.length > 2)
|
|
370
|
+
return null;
|
|
371
|
+
const left = halves[0] ? halves[0].split(":") : [];
|
|
372
|
+
const right = halves.length === 2 && halves[1] ? halves[1].split(":") : [];
|
|
373
|
+
const missing = halves.length === 2 ? 8 - (left.length + right.length) : 0;
|
|
374
|
+
if (missing < 0 || (halves.length === 1 && left.length !== 8))
|
|
375
|
+
return null;
|
|
376
|
+
const full = [...left, ...Array(missing).fill("0"), ...right];
|
|
377
|
+
if (full.length !== 8)
|
|
378
|
+
return null;
|
|
379
|
+
const groups = [];
|
|
380
|
+
for (const g of full) {
|
|
381
|
+
if (!/^[0-9a-f]{1,4}$/.test(g))
|
|
382
|
+
return null;
|
|
383
|
+
groups.push(parseInt(g, 16));
|
|
384
|
+
}
|
|
385
|
+
return groups;
|
|
386
|
+
}
|
|
387
|
+
export function isBlockedIp(rawIp) {
|
|
388
|
+
let cleaned = rawIp.trim();
|
|
389
|
+
if (cleaned.startsWith("[") && cleaned.endsWith("]")) {
|
|
390
|
+
cleaned = cleaned.slice(1, -1);
|
|
391
|
+
}
|
|
392
|
+
const zoneIdx = cleaned.indexOf("%");
|
|
393
|
+
if (zoneIdx !== -1)
|
|
394
|
+
cleaned = cleaned.slice(0, zoneIdx);
|
|
395
|
+
const kind = isIP(cleaned);
|
|
396
|
+
if (kind === 4) {
|
|
397
|
+
const parts = cleaned.split(".").map(Number);
|
|
398
|
+
return isBlockedIpv4Octets(parts[0], parts[1], parts[2]);
|
|
399
|
+
}
|
|
400
|
+
if (kind === 6) {
|
|
401
|
+
const g = parseIpv6Groups(cleaned);
|
|
402
|
+
if (!g)
|
|
403
|
+
return true;
|
|
404
|
+
// Unspecified :: and loopback ::1
|
|
405
|
+
const firstSixZero = g[0] === 0 && g[1] === 0 && g[2] === 0 && g[3] === 0 && g[4] === 0 && g[5] === 0;
|
|
406
|
+
if (firstSixZero && g[6] === 0 && (g[7] === 0 || g[7] === 1))
|
|
407
|
+
return true;
|
|
408
|
+
// IPv4-mapped ::ffff:a.b.c.d
|
|
409
|
+
if (g[0] === 0 && g[1] === 0 && g[2] === 0 && g[3] === 0 && g[4] === 0 && g[5] === 0xffff) {
|
|
410
|
+
return isBlockedIpv4Octets((g[6] >> 8) & 0xff, g[6] & 0xff, (g[7] >> 8) & 0xff);
|
|
411
|
+
}
|
|
412
|
+
// 6to4 2002::/16 (embeds IPv4 in g[1], g[2])
|
|
413
|
+
if (g[0] === 0x2002) {
|
|
414
|
+
return isBlockedIpv4Octets((g[1] >> 8) & 0xff, g[1] & 0xff, (g[2] >> 8) & 0xff);
|
|
415
|
+
}
|
|
416
|
+
// Teredo 2001:0000::/32
|
|
417
|
+
if (g[0] === 0x2001 && g[1] === 0x0000)
|
|
418
|
+
return true;
|
|
419
|
+
// Documentation 2001:db8::/32
|
|
420
|
+
if (g[0] === 0x2001 && g[1] === 0x0db8)
|
|
421
|
+
return true;
|
|
422
|
+
// Discard 0100::/64
|
|
423
|
+
if (g[0] === 0x0100 && g[1] === 0 && g[2] === 0 && g[3] === 0)
|
|
424
|
+
return true;
|
|
425
|
+
// ULA fc00::/7
|
|
426
|
+
if ((g[0] & 0xfe00) === 0xfc00)
|
|
427
|
+
return true;
|
|
428
|
+
// Link-local fe80::/10 and site-local fec0::/10
|
|
429
|
+
if ((g[0] & 0xffc0) === 0xfe80 || (g[0] & 0xffc0) === 0xfec0)
|
|
430
|
+
return true;
|
|
431
|
+
// Multicast ff00::/8
|
|
432
|
+
if ((g[0] & 0xff00) === 0xff00)
|
|
433
|
+
return true;
|
|
434
|
+
return false;
|
|
435
|
+
}
|
|
436
|
+
return true;
|
|
437
|
+
}
|
|
438
|
+
/**
|
|
439
|
+
* Validate that ``rawUrl`` does not target a private, loopback, link-local, or reserved address,
|
|
440
|
+
* and return the validated IP address to pin the socket connection to (closing the DNS rebinding
|
|
441
|
+
* TOCTOU gap), or ``null`` when ``allowPrivateRemoteUrls`` is enabled.
|
|
442
|
+
*/
|
|
443
|
+
export async function checkRemoteHostAllowed(http, rawUrl, param) {
|
|
444
|
+
if (http.config.allowPrivateRemoteUrls)
|
|
445
|
+
return null;
|
|
446
|
+
const parsed = new URL(rawUrl);
|
|
447
|
+
let host = parsed.hostname.trim().toLowerCase().replace(/\.+$/, "");
|
|
448
|
+
if (!host) {
|
|
449
|
+
throw badInput("URL must include a valid host.", param);
|
|
450
|
+
}
|
|
451
|
+
if (BLOCKED_HOSTNAMES.has(host) || BLOCKED_HOST_SUFFIXES.some((sfx) => host.endsWith(sfx))) {
|
|
452
|
+
throw badInput(`Remote URL host ${JSON.stringify(host)} is a private or local address and is blocked by default; ` +
|
|
453
|
+
"pass allowPrivateRemoteUrls: true to opt in.", param);
|
|
454
|
+
}
|
|
455
|
+
const unbracketed = host.startsWith("[") && host.endsWith("]") ? host.slice(1, -1) : host;
|
|
456
|
+
const zoneStripped = unbracketed.includes("%") ? unbracketed.slice(0, unbracketed.indexOf("%")) : unbracketed;
|
|
457
|
+
if (isIP(zoneStripped) !== 0) {
|
|
458
|
+
if (isBlockedIp(zoneStripped)) {
|
|
459
|
+
throw badInput(`Remote URL address ${JSON.stringify(zoneStripped)} is a private, loopback, or link-local address and is blocked by default; ` +
|
|
460
|
+
"pass allowPrivateRemoteUrls: true to opt in.", param);
|
|
461
|
+
}
|
|
462
|
+
return zoneStripped;
|
|
463
|
+
}
|
|
464
|
+
let resolvedIps;
|
|
465
|
+
try {
|
|
466
|
+
resolvedIps = await http.resolveHost(host);
|
|
467
|
+
}
|
|
468
|
+
catch (err) {
|
|
469
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
470
|
+
throw new CoreConnectionError(`Failed to resolve host ${JSON.stringify(host)}: ${msg}`);
|
|
471
|
+
}
|
|
472
|
+
if (resolvedIps.length === 0) {
|
|
473
|
+
throw new CoreConnectionError(`Failed to resolve host ${JSON.stringify(host)}: no addresses returned.`);
|
|
474
|
+
}
|
|
475
|
+
for (const addr of resolvedIps) {
|
|
476
|
+
if (isBlockedIp(addr)) {
|
|
477
|
+
throw badInput(`Remote URL host ${JSON.stringify(host)} resolved to blocked private/loopback/link-local address ${JSON.stringify(addr)}; ` +
|
|
478
|
+
"pass allowPrivateRemoteUrls: true to opt in.", param);
|
|
479
|
+
}
|
|
480
|
+
}
|
|
481
|
+
const first = resolvedIps[0].trim();
|
|
482
|
+
const zoneIdx = first.indexOf("%");
|
|
483
|
+
return zoneIdx !== -1 ? first.slice(0, zoneIdx) : first;
|
|
484
|
+
}
|
|
485
|
+
function redactUrlForError(rawUrl) {
|
|
486
|
+
try {
|
|
487
|
+
const u = new URL(rawUrl);
|
|
488
|
+
return `${u.protocol}//${u.host}${u.pathname}`;
|
|
489
|
+
}
|
|
490
|
+
catch (_a) {
|
|
491
|
+
return rawUrl;
|
|
492
|
+
}
|
|
493
|
+
}
|
|
494
|
+
function filenameFromContentDisposition(headerVal) {
|
|
495
|
+
if (!headerVal)
|
|
496
|
+
return null;
|
|
497
|
+
const mStar = /filename\*\s*=\s*(?:[A-Za-z0-9_-]*'')?([^;\s]+)/i.exec(headerVal);
|
|
498
|
+
if (mStar) {
|
|
499
|
+
try {
|
|
500
|
+
return decodeURIComponent(mStar[1].trim().replace(/^"|"$/g, ""));
|
|
501
|
+
}
|
|
502
|
+
catch (_a) {
|
|
503
|
+
return mStar[1].trim().replace(/^"|"$/g, "");
|
|
504
|
+
}
|
|
505
|
+
}
|
|
506
|
+
const m = /filename\s*=\s*"([^"]+)"|filename\s*=\s*([^;\s]+)/i.exec(headerVal);
|
|
507
|
+
if (m) {
|
|
508
|
+
return (m[1] || m[2] || "").trim() || null;
|
|
509
|
+
}
|
|
510
|
+
return null;
|
|
511
|
+
}
|
|
512
|
+
function filenameFromUrl(rawUrl) {
|
|
513
|
+
try {
|
|
514
|
+
const u = new URL(rawUrl);
|
|
515
|
+
const decoded = decodeURIComponent(u.pathname || "").replace(/\/+$/, "");
|
|
516
|
+
const base = decoded.slice(decoded.lastIndexOf("/") + 1);
|
|
517
|
+
return base || null;
|
|
518
|
+
}
|
|
519
|
+
catch (_a) {
|
|
520
|
+
return null;
|
|
521
|
+
}
|
|
522
|
+
}
|
|
523
|
+
function headersToRecord(h) {
|
|
524
|
+
const out = {};
|
|
525
|
+
h.forEach((v, k) => { out[k.toLowerCase()] = v; });
|
|
526
|
+
return out;
|
|
527
|
+
}
|
|
528
|
+
function wrapFetchError(err, urlForError) {
|
|
529
|
+
if (err instanceof CoreAPIError)
|
|
530
|
+
return err;
|
|
531
|
+
if (err instanceof Error) {
|
|
532
|
+
if (err.name === "TimeoutError") {
|
|
533
|
+
return new CoreTimeoutError(`Timed out downloading ${urlForError}: ${err.message}`);
|
|
534
|
+
}
|
|
535
|
+
if (err.name === "AbortError") {
|
|
536
|
+
return new CoreUserAbortError("Request was aborted.");
|
|
537
|
+
}
|
|
538
|
+
return new CoreConnectionError(`Failed to download ${urlForError}: ${err.message}`);
|
|
539
|
+
}
|
|
540
|
+
return new CoreConnectionError(`Failed to download ${urlForError}: ${String(err)}`);
|
|
541
|
+
}
|
|
542
|
+
export async function fetchRemoteFile(http, url, opts) {
|
|
543
|
+
var _a, _b, _c, _d, _e;
|
|
544
|
+
let currentUrl = validateRemoteUrl(url, opts.param);
|
|
545
|
+
const sizeLimit = opts.maxBytes !== undefined ? Math.min(MAX_UPLOAD_BYTES, opts.maxBytes) : MAX_UPLOAD_BYTES;
|
|
546
|
+
const totalTimeoutMs = http.effectiveRemoteTimeoutMs(DEFAULT_REMOTE_FETCH_TIMEOUT_MS);
|
|
547
|
+
const deadline = Date.now() + totalTimeoutMs;
|
|
548
|
+
let redirects = 0;
|
|
549
|
+
let fetched;
|
|
550
|
+
for (;;) {
|
|
551
|
+
const pinnedIp = await checkRemoteHostAllowed(http, currentUrl, opts.param);
|
|
552
|
+
const remainingMs = deadline - Date.now();
|
|
553
|
+
if (remainingMs <= 0) {
|
|
554
|
+
throw new CoreTimeoutError(`Timed out downloading ${redactUrlForError(currentUrl)} after ${totalTimeoutMs}ms.`);
|
|
555
|
+
}
|
|
556
|
+
try {
|
|
557
|
+
fetched = await http.externalFetch(currentUrl, {
|
|
558
|
+
method: "GET",
|
|
559
|
+
headers: {
|
|
560
|
+
Accept: opts.kind === "image" ? "image/*,*/*;q=0.8" : "*/*",
|
|
561
|
+
"Accept-Encoding": "identity",
|
|
562
|
+
},
|
|
563
|
+
}, { timeoutOverrideMs: remainingMs, pinnedIp });
|
|
564
|
+
}
|
|
565
|
+
catch (err) {
|
|
566
|
+
throw wrapFetchError(err, redactUrlForError(currentUrl));
|
|
567
|
+
}
|
|
568
|
+
const status = fetched.response.status;
|
|
569
|
+
if (REDIRECT_STATUSES.has(status)) {
|
|
570
|
+
const location = fetched.response.headers.get("location");
|
|
571
|
+
fetched.cleanup();
|
|
572
|
+
try {
|
|
573
|
+
void ((_a = fetched.response.body) === null || _a === void 0 ? void 0 : _a.cancel().catch(() => { }));
|
|
574
|
+
}
|
|
575
|
+
catch ( /* ignore */_f) { /* ignore */ }
|
|
576
|
+
if (!location) {
|
|
577
|
+
throw badInput(`Remote URL ${redactUrlForError(currentUrl)} returned redirect ${status} without a Location header.`, opts.param);
|
|
578
|
+
}
|
|
579
|
+
redirects += 1;
|
|
580
|
+
if (redirects > MAX_REDIRECTS) {
|
|
581
|
+
throw badInput(`Remote URL ${redactUrlForError(url)} exceeded the maximum of ${MAX_REDIRECTS} redirects.`, opts.param);
|
|
582
|
+
}
|
|
583
|
+
let nextParsed;
|
|
584
|
+
try {
|
|
585
|
+
nextParsed = new URL(location.trim(), currentUrl);
|
|
586
|
+
}
|
|
587
|
+
catch (_g) {
|
|
588
|
+
throw badInput(`Remote URL returned an invalid redirect Location ${JSON.stringify(location)}.`, opts.param);
|
|
589
|
+
}
|
|
590
|
+
if ((nextParsed.protocol !== "http:" && nextParsed.protocol !== "https:") || !nextParsed.hostname) {
|
|
591
|
+
const scheme = nextParsed.protocol.replace(/:$/, "");
|
|
592
|
+
throw badInput(`Refused redirect to non-http(s) scheme ${JSON.stringify(scheme)}.`, opts.param);
|
|
593
|
+
}
|
|
594
|
+
currentUrl = nextParsed.toString();
|
|
595
|
+
continue;
|
|
596
|
+
}
|
|
597
|
+
break;
|
|
598
|
+
}
|
|
599
|
+
const { response: resp, racePromise, cleanup } = fetched;
|
|
600
|
+
try {
|
|
601
|
+
if (resp.status < 200 || resp.status >= 300) {
|
|
602
|
+
try {
|
|
603
|
+
void ((_b = resp.body) === null || _b === void 0 ? void 0 : _b.cancel().catch(() => { }));
|
|
604
|
+
}
|
|
605
|
+
catch ( /* ignore */_h) { /* ignore */ }
|
|
606
|
+
throw badInput(`Failed to fetch remote ${opts.kind} (${redactUrlForError(currentUrl)} returned HTTP ${resp.status}).`, opts.param);
|
|
607
|
+
}
|
|
608
|
+
const clRaw = resp.headers.get("content-length");
|
|
609
|
+
if (clRaw !== null) {
|
|
610
|
+
const clVal = Number(clRaw.trim());
|
|
611
|
+
if (Number.isFinite(clVal) && clVal > sizeLimit) {
|
|
612
|
+
try {
|
|
613
|
+
void ((_c = resp.body) === null || _c === void 0 ? void 0 : _c.cancel().catch(() => { }));
|
|
614
|
+
}
|
|
615
|
+
catch ( /* ignore */_j) { /* ignore */ }
|
|
616
|
+
throw badInput(`Remote ${opts.kind} exceeds the maximum upload size of ${Math.floor(MAX_UPLOAD_BYTES / (1024 * 1024))} MB.`, opts.param);
|
|
617
|
+
}
|
|
618
|
+
}
|
|
619
|
+
const chunks = [];
|
|
620
|
+
let total = 0;
|
|
621
|
+
if (resp.body) {
|
|
622
|
+
const reader = resp.body.getReader();
|
|
623
|
+
try {
|
|
624
|
+
for (;;) {
|
|
625
|
+
if (Date.now() > deadline) {
|
|
626
|
+
throw new CoreTimeoutError(`Timed out reading ${redactUrlForError(currentUrl)} after ${totalTimeoutMs}ms.`);
|
|
627
|
+
}
|
|
628
|
+
const readPromise = reader.read();
|
|
629
|
+
const { done, value } = await (racePromise ? Promise.race([readPromise, racePromise]) : readPromise);
|
|
630
|
+
if (done)
|
|
631
|
+
break;
|
|
632
|
+
if (!value || value.byteLength === 0)
|
|
633
|
+
continue;
|
|
634
|
+
total += value.byteLength;
|
|
635
|
+
if (total > sizeLimit) {
|
|
636
|
+
try {
|
|
637
|
+
await reader.cancel();
|
|
638
|
+
}
|
|
639
|
+
catch ( /* ignore */_k) { /* ignore */ }
|
|
640
|
+
throw badInput(`Remote ${opts.kind} exceeds the maximum upload size of ${Math.floor(MAX_UPLOAD_BYTES / (1024 * 1024))} MB.`, opts.param);
|
|
641
|
+
}
|
|
642
|
+
chunks.push(value);
|
|
643
|
+
}
|
|
644
|
+
}
|
|
645
|
+
catch (err) {
|
|
646
|
+
try {
|
|
647
|
+
await reader.cancel();
|
|
648
|
+
}
|
|
649
|
+
catch ( /* ignore */_l) { /* ignore */ }
|
|
650
|
+
throw wrapFetchError(err, redactUrlForError(currentUrl));
|
|
651
|
+
}
|
|
652
|
+
}
|
|
653
|
+
else {
|
|
654
|
+
const abPromise = resp.arrayBuffer();
|
|
655
|
+
const ab = await (racePromise ? Promise.race([abPromise, racePromise]) : abPromise);
|
|
656
|
+
if (ab.byteLength > sizeLimit) {
|
|
657
|
+
throw badInput(`Remote ${opts.kind} exceeds the maximum upload size of ${Math.floor(MAX_UPLOAD_BYTES / (1024 * 1024))} MB.`, opts.param);
|
|
658
|
+
}
|
|
659
|
+
total = ab.byteLength;
|
|
660
|
+
if (total > 0)
|
|
661
|
+
chunks.push(new Uint8Array(ab));
|
|
662
|
+
}
|
|
663
|
+
if (total === 0) {
|
|
664
|
+
throw badInput(`Remote ${opts.kind} at ${redactUrlForError(currentUrl)} returned an empty body.`, opts.param);
|
|
665
|
+
}
|
|
666
|
+
const data = new Uint8Array(total);
|
|
667
|
+
let offset = 0;
|
|
668
|
+
for (const c of chunks) {
|
|
669
|
+
data.set(c, offset);
|
|
670
|
+
offset += c.byteLength;
|
|
671
|
+
}
|
|
672
|
+
const rawCt = resp.headers.get("content-type");
|
|
673
|
+
const headerMime = normalizeMime(rawCt);
|
|
674
|
+
const cdName = filenameFromContentDisposition(resp.headers.get("content-disposition"));
|
|
675
|
+
const urlName = filenameFromUrl(currentUrl);
|
|
676
|
+
const candidateName = (_e = (_d = opts.filename) !== null && _d !== void 0 ? _d : cdName) !== null && _e !== void 0 ? _e : urlName;
|
|
677
|
+
let resolvedMime;
|
|
678
|
+
if (opts.kind === "image") {
|
|
679
|
+
if (headerMime && headerMime !== "application/octet-stream" && !ACCEPTED_IMAGE_MIMES.has(headerMime)) {
|
|
680
|
+
const accepted = Array.from(ACCEPTED_IMAGE_MIMES).sort().join(", ");
|
|
681
|
+
throw badInput(`Remote image at ${redactUrlForError(currentUrl)} returned unsupported Content-Type ${JSON.stringify(headerMime)}; expected one of: ${accepted}.`, opts.param);
|
|
682
|
+
}
|
|
683
|
+
resolvedMime = verifyImageBytes(data, headerMime, opts.param);
|
|
684
|
+
}
|
|
685
|
+
else {
|
|
686
|
+
const explicitMime = normalizeMime(opts.mediaType);
|
|
687
|
+
const inferredMime = inferMimeFromFilename(candidateName);
|
|
688
|
+
const ext = fileExt(candidateName);
|
|
689
|
+
if (headerMime === "text/html" && explicitMime !== "text/html" && ext && !HTML_EXTS.has(ext)) {
|
|
690
|
+
throw badInput(`Remote file at ${redactUrlForError(currentUrl)} returned Content-Type 'text/html' instead of expected file type for ${JSON.stringify(candidateName)}.`, opts.param);
|
|
691
|
+
}
|
|
692
|
+
let chosenMime = explicitMime;
|
|
693
|
+
if (!chosenMime) {
|
|
694
|
+
if (headerMime && headerMime !== "application/octet-stream") {
|
|
695
|
+
chosenMime = headerMime;
|
|
696
|
+
}
|
|
697
|
+
else if (inferredMime) {
|
|
698
|
+
chosenMime = inferredMime;
|
|
699
|
+
}
|
|
700
|
+
else {
|
|
701
|
+
chosenMime = headerMime !== null && headerMime !== void 0 ? headerMime : "application/octet-stream";
|
|
702
|
+
}
|
|
703
|
+
}
|
|
704
|
+
resolvedMime = validateFileMime(chosenMime, opts.param);
|
|
705
|
+
}
|
|
706
|
+
const resolvedName = sanitizeFilename(candidateName, opts.kind === "image" ? "image" : "file", resolvedMime);
|
|
707
|
+
return { data, mediaType: resolvedMime, filename: resolvedName };
|
|
708
|
+
}
|
|
709
|
+
finally {
|
|
710
|
+
cleanup();
|
|
711
|
+
}
|
|
712
|
+
}
|
|
713
|
+
export async function deleteArtifactBestEffort(http, sessionId, artifactId) {
|
|
714
|
+
try {
|
|
715
|
+
const artifactsApi = new ArtifactsApi(http.sdkConfig);
|
|
716
|
+
await http.call(() => artifactsApi.deleteArtifact({ conversationId: sessionId, artifactId }), { idempotent: true, maxRetries: 0 });
|
|
717
|
+
}
|
|
718
|
+
catch (_a) {
|
|
719
|
+
// Best-effort rollback cleanup.
|
|
720
|
+
}
|
|
721
|
+
}
|
|
722
|
+
export async function uploadArtifact(http, sessionId, data, opts) {
|
|
723
|
+
var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o;
|
|
724
|
+
const sizeBytes = data.byteLength;
|
|
725
|
+
if (sizeBytes <= 0) {
|
|
726
|
+
throw badInput("File payload must not be empty.", "input");
|
|
727
|
+
}
|
|
728
|
+
if (sizeBytes > MAX_UPLOAD_BYTES) {
|
|
729
|
+
throw badInput(`File exceeds the maximum upload size of ${Math.floor(MAX_UPLOAD_BYTES / (1024 * 1024))} MB.`, "input");
|
|
730
|
+
}
|
|
731
|
+
const safeName = sanitizeFilename(opts.filename, "file", opts.mediaType);
|
|
732
|
+
const artifactsApi = new ArtifactsApi(http.sdkConfig);
|
|
733
|
+
const mint = await http.call(() => artifactsApi.mintUploadUrl({
|
|
734
|
+
uploadUrlBody: {
|
|
735
|
+
conversationId: sessionId,
|
|
736
|
+
filename: safeName,
|
|
737
|
+
mimeType: opts.mediaType,
|
|
738
|
+
sizeBytes,
|
|
739
|
+
},
|
|
740
|
+
}), { idempotent: true });
|
|
741
|
+
const rawMint = mint;
|
|
742
|
+
const uploadUrl = ((_a = mint.uploadUrl) !== null && _a !== void 0 ? _a : rawMint["upload_url"]);
|
|
743
|
+
const storagePath = ((_b = mint.storagePath) !== null && _b !== void 0 ? _b : rawMint["storage_path"]);
|
|
744
|
+
const mintedId = ((_e = (_d = (_c = mint.artifactId) !== null && _c !== void 0 ? _c : rawMint["artifact_id"]) !== null && _d !== void 0 ? _d : mint.uploadToken) !== null && _e !== void 0 ? _e : rawMint["upload_token"]);
|
|
745
|
+
if (typeof uploadUrl !== "string" || !uploadUrl || typeof storagePath !== "string" || !storagePath) {
|
|
746
|
+
throw new CoreAPIError("Panja upload-url response was missing uploadUrl or storagePath.", {
|
|
747
|
+
status: 502,
|
|
748
|
+
code: "api_error",
|
|
749
|
+
});
|
|
750
|
+
}
|
|
751
|
+
await http.call(async () => {
|
|
752
|
+
var _a;
|
|
753
|
+
const { response, racePromise, cleanup } = await http.externalFetch(uploadUrl, {
|
|
754
|
+
method: "PUT",
|
|
755
|
+
headers: {
|
|
756
|
+
"Content-Type": opts.mediaType,
|
|
757
|
+
"Content-Length": String(sizeBytes),
|
|
758
|
+
},
|
|
759
|
+
body: Buffer.from(data.buffer, data.byteOffset, data.byteLength),
|
|
760
|
+
});
|
|
761
|
+
try {
|
|
762
|
+
if (response.status < 200 || response.status >= 300) {
|
|
763
|
+
const textPromise = response.text().catch(() => "");
|
|
764
|
+
const text = await (racePromise ? Promise.race([textPromise, racePromise]) : textPromise);
|
|
765
|
+
throw mapPanjaError(response.status, text, headersToRecord(response.headers));
|
|
766
|
+
}
|
|
767
|
+
try {
|
|
768
|
+
void ((_a = response.body) === null || _a === void 0 ? void 0 : _a.cancel().catch(() => { }));
|
|
769
|
+
}
|
|
770
|
+
catch ( /* ignore */_b) { /* ignore */ }
|
|
771
|
+
}
|
|
772
|
+
finally {
|
|
773
|
+
cleanup();
|
|
774
|
+
}
|
|
775
|
+
}, { idempotent: true });
|
|
776
|
+
const sha256Hex = createHash("sha256").update(data).digest("hex");
|
|
777
|
+
const committed = await http.call(() => artifactsApi.commitArtifact({
|
|
778
|
+
commitBody: {
|
|
779
|
+
conversationId: sessionId,
|
|
780
|
+
artifactId: mintedId ? String(mintedId) : undefined,
|
|
781
|
+
storagePath,
|
|
782
|
+
filename: safeName,
|
|
783
|
+
mimeType: opts.mediaType,
|
|
784
|
+
sizeBytes,
|
|
785
|
+
sha256Hex,
|
|
786
|
+
},
|
|
787
|
+
}), { idempotent: false });
|
|
788
|
+
const rawCommitted = committed;
|
|
789
|
+
const artifactId = String((_j = (_h = (_g = (_f = committed.artifactId) !== null && _f !== void 0 ? _f : committed.id) !== null && _g !== void 0 ? _g : rawCommitted["artifact_id"]) !== null && _h !== void 0 ? _h : mintedId) !== null && _j !== void 0 ? _j : "");
|
|
790
|
+
const origName = String((_l = (_k = committed.originalName) !== null && _k !== void 0 ? _k : rawCommitted["original_name"]) !== null && _l !== void 0 ? _l : safeName);
|
|
791
|
+
const mime = String((_o = (_m = committed.mimeType) !== null && _m !== void 0 ? _m : rawCommitted["mime_type"]) !== null && _o !== void 0 ? _o : opts.mediaType);
|
|
792
|
+
if (!artifactId) {
|
|
793
|
+
throw new CoreAPIError("Panja artifact commit response was missing artifactId.", {
|
|
794
|
+
status: 502,
|
|
795
|
+
code: "api_error",
|
|
796
|
+
});
|
|
797
|
+
}
|
|
798
|
+
return { artifactId, filename: origName, mediaType: mime };
|
|
799
|
+
}
|
|
800
|
+
export async function listSessionArtifacts(http, sessionId) {
|
|
801
|
+
var _a, _b, _c, _d, _e, _f, _g;
|
|
802
|
+
const artifactsApi = new ArtifactsApi(http.sdkConfig);
|
|
803
|
+
const resp = await http.call(() => artifactsApi.listConversationArtifacts({ conversationId: sessionId }), { idempotent: true });
|
|
804
|
+
const items = ((_a = resp.data) !== null && _a !== void 0 ? _a : []);
|
|
805
|
+
const out = new Map();
|
|
806
|
+
for (const item of items) {
|
|
807
|
+
const aid = String((_c = (_b = item["artifactId"]) !== null && _b !== void 0 ? _b : item["artifact_id"]) !== null && _c !== void 0 ? _c : "");
|
|
808
|
+
const name = String((_e = (_d = item["originalName"]) !== null && _d !== void 0 ? _d : item["original_name"]) !== null && _e !== void 0 ? _e : aid);
|
|
809
|
+
const mime = String((_g = (_f = item["mimeType"]) !== null && _f !== void 0 ? _f : item["mime_type"]) !== null && _g !== void 0 ? _g : "application/octet-stream");
|
|
810
|
+
if (aid) {
|
|
811
|
+
out.set(aid, { artifactId: aid, filename: name, mediaType: mime });
|
|
812
|
+
}
|
|
813
|
+
}
|
|
814
|
+
return out;
|
|
815
|
+
}
|
|
816
|
+
export function makeFileMessagePart(artifactId, filename, mediaType) {
|
|
817
|
+
return {
|
|
818
|
+
type: "file",
|
|
819
|
+
mediaType,
|
|
820
|
+
filename,
|
|
821
|
+
url: `${ARTIFACT_URI_PREFIX}${artifactId}`,
|
|
822
|
+
providerMetadata: {
|
|
823
|
+
custom: {
|
|
824
|
+
artifactId,
|
|
825
|
+
filename,
|
|
826
|
+
},
|
|
827
|
+
},
|
|
828
|
+
};
|
|
829
|
+
}
|