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