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
@@ -1,9 +1,11 @@
1
1
  /** Core Turns service: send, steer, stop, clarify, and in-process/cross-process stream follow. */
2
+ import { createHash } from "node:crypto";
2
3
  import { QueueApi } from "../../apis/QueueApi.js";
3
4
  import { ResponsesApi } from "../../apis/ResponsesApi.js";
4
5
  import { answerClarify, reconnect, streamResponse } from "../../streaming.js";
5
6
  import { CoreAPIError, CoreTimeoutError } from "./errors.js";
6
7
  import { TurnEvents } from "./events.js";
8
+ import { ACCEPTED_IMAGE_MIMES, AttachmentUploadCache, deleteArtifactBestEffort, fetchRemoteFile, listSessionArtifacts, makeFileMessagePart, MAX_ATTACHMENTS_PER_MESSAGE, MAX_TOTAL_ATTACHMENT_BYTES, normalizeMime, uploadArtifact, } from "./files.js";
7
9
  import { refuse } from "./refusals.js";
8
10
  const NO_ACTIVE_CODES = new Set([
9
11
  "NO_ACTIVE_TURN",
@@ -13,16 +15,125 @@ const NO_ACTIVE_CODES = new Set([
13
15
  ]);
14
16
  const UNITERATED_TTL_MS = 60000;
15
17
  export const DEFAULT_POLL_TIMEOUT_MS = 300000;
16
- function toMessageParts(parts, provider = "openai") {
18
+ export async function prefetchRemoteParts(http, parts) {
19
+ var _a;
20
+ let attachmentCount = 0;
21
+ let usedBytes = 0;
22
+ for (const p of parts) {
23
+ if (p.type !== "text")
24
+ attachmentCount += 1;
25
+ if (p.type === "inline_file")
26
+ usedBytes += p.data.byteLength;
27
+ }
28
+ if (attachmentCount > MAX_ATTACHMENTS_PER_MESSAGE) {
29
+ throw new CoreAPIError(`A message can contain at most ${MAX_ATTACHMENTS_PER_MESSAGE} attachments (got ${attachmentCount}).`, { status: 400, code: "invalid_request_error", param: "input" });
30
+ }
31
+ if (usedBytes > MAX_TOTAL_ATTACHMENT_BYTES) {
32
+ throw new CoreAPIError(`Combined attachment size exceeds the maximum of ${Math.floor(MAX_TOTAL_ATTACHMENT_BYTES / (1024 * 1024))} MB per message.`, { status: 400, code: "invalid_request_error", param: "input" });
33
+ }
34
+ if (!parts.some((p) => p.type === "remote_file"))
35
+ return parts;
17
36
  const out = [];
18
37
  for (const p of parts) {
19
- if (p.type === "text")
20
- out.push({ type: "text", text: p.text });
21
- else
22
- refuse(provider, "input.input_file");
38
+ if (p.type === "remote_file") {
39
+ const remainingBudget = MAX_TOTAL_ATTACHMENT_BYTES - usedBytes;
40
+ if (remainingBudget <= 0) {
41
+ throw new CoreAPIError(`Combined attachment size exceeds the maximum of ${Math.floor(MAX_TOTAL_ATTACHMENT_BYTES / (1024 * 1024))} MB per message.`, { status: 400, code: "invalid_request_error", param: (_a = p.param) !== null && _a !== void 0 ? _a : "input" });
42
+ }
43
+ const fetched = await fetchRemoteFile(http, p.url, {
44
+ kind: p.kind,
45
+ filename: p.filename,
46
+ mediaType: p.mediaType,
47
+ param: p.param,
48
+ maxBytes: remainingBudget,
49
+ });
50
+ usedBytes += fetched.data.byteLength;
51
+ out.push({
52
+ type: "inline_file",
53
+ data: fetched.data,
54
+ mediaType: fetched.mediaType,
55
+ filename: fetched.filename,
56
+ kind: p.kind,
57
+ param: p.param,
58
+ });
59
+ }
60
+ else {
61
+ out.push(p);
62
+ }
23
63
  }
24
64
  return out;
25
65
  }
66
+ async function resolveMessageParts(http, sessionId, parts, provider = "openai", opts = {}) {
67
+ var _a, _b, _c, _d;
68
+ // Guard: verify every file_id belongs to this session BEFORE downloading remote URLs or uploading anything.
69
+ const hasRefs = parts.some((p) => p.type === "file_ref");
70
+ const sessionArtifacts = hasRefs ? await listSessionArtifacts(http, sessionId) : new Map();
71
+ for (const p of parts) {
72
+ if (p.type === "file_ref") {
73
+ const found = sessionArtifacts.get(p.fileId);
74
+ if (!found) {
75
+ throw new CoreAPIError(`file_id ${JSON.stringify(p.fileId)} does not belong to session ${JSON.stringify(sessionId)}. ` +
76
+ "Panja artifacts are scoped to a single session; pass an artifact_id from this session or provide inline data/URL instead.", { status: 400, code: "invalid_request_error", param: (_a = p.param) !== null && _a !== void 0 ? _a : "file_id" });
77
+ }
78
+ if (p.kind === "image") {
79
+ const norm = normalizeMime(found.mediaType);
80
+ if (!norm || !ACCEPTED_IMAGE_MIMES.has(norm)) {
81
+ const accepted = Array.from(ACCEPTED_IMAGE_MIMES).sort().join(", ");
82
+ throw new CoreAPIError(`file_id ${JSON.stringify(p.fileId)} has media type ${JSON.stringify(found.mediaType)}, which is not a supported image type (${accepted}).`, { status: 400, code: "invalid_request_error", param: (_b = p.param) !== null && _b !== void 0 ? _b : "file_id" });
83
+ }
84
+ }
85
+ }
86
+ }
87
+ const prepared = await prefetchRemoteParts(http, parts);
88
+ const out = [];
89
+ const newlyUploaded = [];
90
+ try {
91
+ for (let idx = 0; idx < prepared.length; idx++) {
92
+ const p = prepared[idx];
93
+ if (p.type === "text") {
94
+ out.push({ type: "text", text: p.text });
95
+ }
96
+ else if (p.type === "inline_file") {
97
+ const sha = createHash("sha256").update(p.data).digest("hex");
98
+ const cached = opts.idempotencyKey && opts.uploadCache
99
+ ? opts.uploadCache.get(sessionId, opts.idempotencyKey, idx, sha)
100
+ : undefined;
101
+ if (cached) {
102
+ out.push(makeFileMessagePart(cached.artifactId, cached.filename, cached.mediaType));
103
+ continue;
104
+ }
105
+ const uploaded = await uploadArtifact(http, sessionId, p.data, {
106
+ filename: p.filename,
107
+ mediaType: p.mediaType,
108
+ });
109
+ let cacheEntry;
110
+ if (opts.idempotencyKey && opts.uploadCache) {
111
+ cacheEntry = [sessionId, opts.idempotencyKey, idx, sha];
112
+ opts.uploadCache.put(sessionId, opts.idempotencyKey, idx, sha, uploaded);
113
+ }
114
+ newlyUploaded.push({ artifactId: uploaded.artifactId, cacheEntry });
115
+ out.push(makeFileMessagePart(uploaded.artifactId, uploaded.filename, uploaded.mediaType));
116
+ }
117
+ else if (p.type === "file_ref") {
118
+ const found = sessionArtifacts.get(p.fileId);
119
+ out.push(makeFileMessagePart(found.artifactId, (_c = p.filename) !== null && _c !== void 0 ? _c : found.filename, (_d = p.mediaType) !== null && _d !== void 0 ? _d : found.mediaType));
120
+ }
121
+ else {
122
+ refuse(provider, "input", { reason: "unsupported input part" });
123
+ }
124
+ }
125
+ }
126
+ catch (err) {
127
+ for (const item of newlyUploaded) {
128
+ await deleteArtifactBestEffort(http, sessionId, item.artifactId);
129
+ if (item.cacheEntry && opts.uploadCache) {
130
+ opts.uploadCache.evict(...item.cacheEntry);
131
+ }
132
+ }
133
+ throw err;
134
+ }
135
+ return { msgParts: out, newlyUploaded };
136
+ }
26
137
  const WeakRefImpl = globalThis.WeakRef;
27
138
  const FinalizationRegistryImpl = globalThis.FinalizationRegistry;
28
139
  const listenerFinalizer = FinalizationRegistryImpl
@@ -279,7 +390,7 @@ export class Listener {
279
390
  }
280
391
  export class Turns {
281
392
  constructor(_http, _sessions, opts = {}) {
282
- var _a, _b, _c;
393
+ var _a, _b, _c, _d;
283
394
  this._http = _http;
284
395
  this._sessions = _sessions;
285
396
  this.queueApi = new QueueApi(_http.sdkConfig);
@@ -287,6 +398,7 @@ export class Turns {
287
398
  this.pollIntervalMs = (_a = opts.pollIntervalMs) !== null && _a !== void 0 ? _a : 1000;
288
399
  this.provider = (_b = opts.provider) !== null && _b !== void 0 ? _b : "openai";
289
400
  this._registry = (_c = opts.registry) !== null && _c !== void 0 ? _c : new ListenerRegistry();
401
+ this.uploadCache = (_d = opts.uploadCache) !== null && _d !== void 0 ? _d : new AttachmentUploadCache();
290
402
  }
291
403
  handoffOrClose(sessionId, stream) {
292
404
  return this._registry.handoffOrClose(sessionId, stream);
@@ -297,28 +409,58 @@ export class Turns {
297
409
  this._registry.register(sessionId, listener);
298
410
  return listener;
299
411
  }
300
- async send(sessionId, agentId, parts, opts = {}) {
301
- var _a;
302
- const msgId = (_a = opts.key) !== null && _a !== void 0 ? _a : this._http.newIdempotencyKey();
412
+ async resolveParts(sessionId, parts, opts = {}) {
413
+ const { msgParts } = await resolveMessageParts(this._http, sessionId, parts, this.provider, {
414
+ idempotencyKey: opts.key,
415
+ uploadCache: this.uploadCache,
416
+ });
417
+ return msgParts;
418
+ }
419
+ async sendMessageParts(sessionId, agentId, msgParts, opts) {
303
420
  const stream = await this._http.call(() => streamResponse(this._http.sdkConfig, {
304
421
  id: sessionId,
305
422
  agentId: agentId !== null && agentId !== void 0 ? agentId : undefined,
306
- message: { id: msgId, role: "user", parts: toMessageParts(parts, this.provider) },
423
+ message: { id: opts.msgId, role: "user", parts: msgParts },
307
424
  }), { idempotent: false });
308
425
  if (opts.returnStream)
309
426
  return stream;
310
427
  this.handoffOrClose(sessionId, stream);
311
428
  return null;
312
429
  }
430
+ async send(sessionId, agentId, parts, opts = {}) {
431
+ var _a;
432
+ const msgId = (_a = opts.key) !== null && _a !== void 0 ? _a : this._http.newIdempotencyKey();
433
+ const { msgParts, newlyUploaded } = await resolveMessageParts(this._http, sessionId, parts, this.provider, {
434
+ idempotencyKey: opts.key,
435
+ uploadCache: this.uploadCache,
436
+ });
437
+ try {
438
+ return await this.sendMessageParts(sessionId, agentId, msgParts, { msgId, returnStream: opts.returnStream });
439
+ }
440
+ catch (err) {
441
+ if (err instanceof CoreAPIError && err.status !== null && err.status >= 400 && err.status < 500) {
442
+ for (const item of newlyUploaded) {
443
+ await deleteArtifactBestEffort(this._http, sessionId, item.artifactId);
444
+ if (item.cacheEntry)
445
+ this.uploadCache.evict(...item.cacheEntry);
446
+ }
447
+ }
448
+ throw err;
449
+ }
450
+ }
313
451
  async steer(sessionId, agentId, parts, opts = {}) {
314
452
  var _a, _b, _c;
315
453
  const msgId = (_a = opts.key) !== null && _a !== void 0 ? _a : this._http.newIdempotencyKey();
316
454
  const delivery = (_b = opts.delivery) !== null && _b !== void 0 ? _b : "now";
455
+ const { msgParts, newlyUploaded } = await resolveMessageParts(this._http, sessionId, parts, this.provider, {
456
+ idempotencyKey: opts.key,
457
+ uploadCache: this.uploadCache,
458
+ });
317
459
  try {
318
460
  await this._http.call(() => this.queueApi.queueMessage({
319
461
  conversationId: sessionId,
320
462
  queueMessageInput: {
321
- message: { id: msgId, role: "user", parts: toMessageParts(parts, this.provider) },
463
+ message: { id: msgId, role: "user", parts: msgParts },
322
464
  delivery,
323
465
  agentId: agentId !== null && agentId !== void 0 ? agentId : undefined,
324
466
  },
@@ -326,14 +468,22 @@ export class Turns {
326
468
  }
327
469
  catch (err) {
328
470
  // Fall back to starting a new turn only when Panja rejects with a no-active-turn error.
471
+ // Reuse already-resolved msgParts so inline files are never uploaded twice.
329
472
  // A 202 queued response (even with reason=no_active_turn) means Panja already accepted
330
473
  // and queued the message, so we must not double-post to /v1/responses.
331
474
  if (err instanceof CoreAPIError &&
332
475
  (err.status === 404 || err.status === 409) &&
333
476
  NO_ACTIVE_CODES.has((_c = err.code) !== null && _c !== void 0 ? _c : "")) {
334
- await this.send(sessionId, agentId, parts, { key: msgId });
477
+ await this.sendMessageParts(sessionId, agentId, msgParts, { msgId });
335
478
  return;
336
479
  }
480
+ if (err instanceof CoreAPIError && err.status !== null && err.status >= 400 && err.status < 500) {
481
+ for (const item of newlyUploaded) {
482
+ await deleteArtifactBestEffort(this._http, sessionId, item.artifactId);
483
+ if (item.cacheEntry)
484
+ this.uploadCache.evict(...item.cacheEntry);
485
+ }
486
+ }
337
487
  throw err;
338
488
  }
339
489
  }
@@ -1,3 +1,4 @@
1
+ import { AttachmentUploadCache } from "../core/files.js";
1
2
  import { SessionUpdateQueue } from "../core/sessions.js";
2
3
  import { ToolResultStore } from "../core/toolResults.js";
3
4
  import { ListenerRegistry } from "../core/turns.js";
@@ -14,12 +15,15 @@ export interface OpenAIOptions {
14
15
  defaultQuery?: Record<string, string>;
15
16
  modelMap?: Record<string, string>;
16
17
  strictModels?: boolean;
18
+ allowPrivateRemoteUrls?: boolean;
17
19
  fetch?: typeof globalThis.fetch;
18
20
  _sleep?: (ms: number) => Promise<void>;
19
21
  _pollIntervalMs?: number;
22
+ _resolveHost?: (host: string) => Promise<string[]>;
20
23
  _sharedRegistry?: ListenerRegistry;
21
24
  _sharedToolStore?: ToolResultStore;
22
25
  _sharedSessionQueue?: SessionUpdateQueue;
26
+ _sharedUploadCache?: AttachmentUploadCache;
23
27
  }
24
28
  export type RawResponseProxy<T> = {
25
29
  readonly [K in keyof T]: T[K] extends (...args: infer A) => Promise<infer R> ? (...args: A) => Promise<RawResponse<R>> : T[K] extends (...args: infer A) => infer R ? (...args: A) => Promise<RawResponse<R>> : T[K] extends object ? RawResponseProxy<T[K]> : T[K];
@@ -50,6 +54,7 @@ export declare class OpenAI {
50
54
  private readonly listenerRegistry;
51
55
  private readonly toolResultStore;
52
56
  private readonly sessionUpdateQueue;
57
+ private readonly uploadCache;
53
58
  constructor(opts?: OpenAIOptions);
54
59
  get withRawResponse(): RawResponseClient;
55
60
  withOptions(overrides: Partial<OpenAIOptions>): OpenAI;
@@ -1,6 +1,7 @@
1
1
  /** OpenAI drop-in client (client.beta.agents...) backed by compat/core. */
2
2
  import { Agents } from "../core/agents.js";
3
3
  import { CoreAPIError } from "../core/errors.js";
4
+ import { AttachmentUploadCache } from "../core/files.js";
4
5
  import { DEFAULT_MAX_RETRIES, DEFAULT_TIMEOUT_MS, Http } from "../core/http.js";
5
6
  import { ModelResolver } from "../core/models.js";
6
7
  import { Sessions, SessionUpdateQueue } from "../core/sessions.js";
@@ -34,7 +35,7 @@ function makeRawProxy(target, http) {
34
35
  }
35
36
  export class OpenAI {
36
37
  constructor(opts = {}) {
37
- var _a, _b, _c, _d, _e;
38
+ var _a, _b, _c, _d, _e, _f;
38
39
  this.initOpts = { ...opts };
39
40
  try {
40
41
  this.http = new Http({
@@ -46,7 +47,11 @@ export class OpenAI {
46
47
  defaultQuery: opts.defaultQuery,
47
48
  provider: "openai",
48
49
  fetch: opts.fetch,
49
- }, opts._sleep ? { sleep: opts._sleep } : undefined);
50
+ allowPrivateRemoteUrls: opts.allowPrivateRemoteUrls,
51
+ }, {
52
+ ...(opts._sleep ? { sleep: opts._sleep } : {}),
53
+ ...(opts._resolveHost ? { resolveHost: opts._resolveHost } : {}),
54
+ });
50
55
  }
51
56
  catch (err) {
52
57
  if (err instanceof CoreAPIError)
@@ -63,10 +68,12 @@ export class OpenAI {
63
68
  const sessionsCore = new Sessions(this.http, { provider: "openai", updateQueue: this.sessionUpdateQueue });
64
69
  this.listenerRegistry = (_d = opts._sharedRegistry) !== null && _d !== void 0 ? _d : new ListenerRegistry();
65
70
  this.toolResultStore = (_e = opts._sharedToolStore) !== null && _e !== void 0 ? _e : new ToolResultStore();
71
+ this.uploadCache = (_f = opts._sharedUploadCache) !== null && _f !== void 0 ? _f : new AttachmentUploadCache();
66
72
  const turnsCore = new Turns(this.http, sessionsCore, {
67
73
  pollIntervalMs: opts._pollIntervalMs,
68
74
  provider: "openai",
69
75
  registry: this.listenerRegistry,
76
+ uploadCache: this.uploadCache,
70
77
  });
71
78
  const toolResultsCore = new ToolResults(this.http, sessionsCore, turnsCore, {
72
79
  store: this.toolResultStore,
@@ -88,6 +95,7 @@ export class OpenAI {
88
95
  _sharedRegistry: this.listenerRegistry,
89
96
  _sharedToolStore: this.toolResultStore,
90
97
  _sharedSessionQueue: this.sessionUpdateQueue,
98
+ _sharedUploadCache: this.uploadCache,
91
99
  });
92
100
  }
93
101
  close() {
@@ -1,4 +1,6 @@
1
1
  /** OpenAI beta.agents.sessions.events and beta.agents.sessions.items resources. */
2
+ import { CoreAPIError } from "../../core/errors.js";
3
+ import { ARTIFACT_URI_PREFIX, decodeBase64Bytes, inferMimeFromFilename, isOpenAIFileId, MAX_ATTACHMENTS_PER_MESSAGE, MAX_TOTAL_ATTACHMENT_BYTES, normalizeMime, parseDataUri, sanitizeFilename, validateFileMime, validateImageMime, validateRemoteUrl, verifyImageBytes, } from "../../core/files.js";
2
4
  import { history as loadHistory } from "../../core/history.js";
3
5
  import { CursorPager } from "../../core/paging.js";
4
6
  import { BadRequestError, wrapCoreErrors } from "../errors.js";
@@ -8,6 +10,162 @@ import { checkExtraParams, refuseOpenAI } from "../types.js";
8
10
  function isObj(v) {
9
11
  return v !== null && typeof v === "object" && !Array.isArray(v);
10
12
  }
13
+ function parseInputImage(block, path) {
14
+ var _a;
15
+ if (block["detail"] !== undefined && block["detail"] !== null) {
16
+ refuseOpenAI("input.input_image.detail", { param: `${path}.detail` });
17
+ }
18
+ let rawUrl = block["image_url"];
19
+ if (isObj(rawUrl)) {
20
+ if (rawUrl["detail"] !== undefined && rawUrl["detail"] !== null) {
21
+ refuseOpenAI("input.input_image.detail", { param: `${path}.image_url.detail` });
22
+ }
23
+ rawUrl = rawUrl["url"];
24
+ }
25
+ const rawFileId = block["file_id"];
26
+ const hasUrl = rawUrl !== undefined && rawUrl !== null && rawUrl !== "";
27
+ const hasFileId = rawFileId !== undefined && rawFileId !== null && rawFileId !== "";
28
+ if (hasUrl === hasFileId) {
29
+ throw new BadRequestError(`${path} must specify exactly one of 'image_url' or 'file_id'.`, {
30
+ status: 400,
31
+ param: path,
32
+ });
33
+ }
34
+ const rawFilename = block["filename"];
35
+ if (rawFilename !== undefined && rawFilename !== null && typeof rawFilename !== "string") {
36
+ throw new BadRequestError(`${path}.filename must be a string.`, { status: 400, param: `${path}.filename` });
37
+ }
38
+ const filename = typeof rawFilename === "string" ? rawFilename : undefined;
39
+ if (hasFileId) {
40
+ const fidParam = `${path}.file_id`;
41
+ if (typeof rawFileId !== "string" || !rawFileId.trim()) {
42
+ throw new BadRequestError(`${path}.file_id must be a non-empty string.`, { status: 400, param: fidParam });
43
+ }
44
+ const fid = rawFileId.trim();
45
+ if (isOpenAIFileId(fid)) {
46
+ throw new BadRequestError(`OpenAI file_id ${JSON.stringify(fid)} is not supported; pass a Sarvam artifact_id belonging to this session, ` +
47
+ "a base64 data: URI, or an http(s) image_url.", { status: 400, param: fidParam });
48
+ }
49
+ return { type: "file_ref", fileId: fid, filename, kind: "image", param: fidParam };
50
+ }
51
+ const urlParam = `${path}.image_url`;
52
+ if (typeof rawUrl !== "string" || !rawUrl.trim()) {
53
+ throw new BadRequestError(`${path}.image_url must be a non-empty string.`, { status: 400, param: urlParam });
54
+ }
55
+ const trimmed = rawUrl.trim();
56
+ if (trimmed.startsWith(ARTIFACT_URI_PREFIX)) {
57
+ const aid = trimmed.slice(ARTIFACT_URI_PREFIX.length).trim();
58
+ if (!aid || isOpenAIFileId(aid)) {
59
+ throw new BadRequestError(`Invalid artifact URI ${JSON.stringify(trimmed)}; pass an artifact://<artifact_id> belonging to this session.`, { status: 400, param: urlParam });
60
+ }
61
+ return { type: "file_ref", fileId: aid, filename, kind: "image", param: urlParam };
62
+ }
63
+ try {
64
+ if (trimmed.startsWith("data:")) {
65
+ const { mime, data } = parseDataUri(trimmed, urlParam);
66
+ const validMime = validateImageMime(mime, urlParam);
67
+ const verifiedMime = verifyImageBytes(data, validMime, urlParam);
68
+ const fname = sanitizeFilename(filename, "image", verifiedMime);
69
+ return { type: "inline_file", data, mediaType: verifiedMime, filename: fname, kind: "image", param: urlParam };
70
+ }
71
+ const validUrl = validateRemoteUrl(trimmed, urlParam);
72
+ return { type: "remote_file", url: validUrl, kind: "image", filename, param: urlParam };
73
+ }
74
+ catch (err) {
75
+ if (err instanceof CoreAPIError) {
76
+ throw new BadRequestError(err.message, { status: 400, param: (_a = err.param) !== null && _a !== void 0 ? _a : urlParam });
77
+ }
78
+ throw err;
79
+ }
80
+ }
81
+ function parseInputFile(block, path) {
82
+ var _a, _b, _c, _d, _e, _f;
83
+ const rawData = block["file_data"];
84
+ const rawUrl = block["file_url"];
85
+ const rawFileId = block["file_id"];
86
+ const hasData = rawData !== undefined && rawData !== null && rawData !== "";
87
+ const hasUrl = rawUrl !== undefined && rawUrl !== null && rawUrl !== "";
88
+ const hasFileId = rawFileId !== undefined && rawFileId !== null && rawFileId !== "";
89
+ if (Number(hasData) + Number(hasUrl) + Number(hasFileId) !== 1) {
90
+ throw new BadRequestError(`${path} must specify exactly one of 'file_data', 'file_url', or 'file_id'.`, {
91
+ status: 400,
92
+ param: path,
93
+ });
94
+ }
95
+ const rawFilename = block["filename"];
96
+ if (rawFilename !== undefined && rawFilename !== null && typeof rawFilename !== "string") {
97
+ throw new BadRequestError(`${path}.filename must be a string.`, { status: 400, param: `${path}.filename` });
98
+ }
99
+ const filename = typeof rawFilename === "string" ? rawFilename : undefined;
100
+ const rawMime = block["media_type"] !== undefined ? block["media_type"] : block["mime_type"];
101
+ if (rawMime !== undefined && rawMime !== null && typeof rawMime !== "string") {
102
+ throw new BadRequestError(`${path}.media_type must be a string.`, { status: 400, param: `${path}.media_type` });
103
+ }
104
+ const mimeStr = typeof rawMime === "string" ? rawMime : undefined;
105
+ if (hasFileId) {
106
+ const fidParam = `${path}.file_id`;
107
+ if (typeof rawFileId !== "string" || !rawFileId.trim()) {
108
+ throw new BadRequestError(`${path}.file_id must be a non-empty string.`, { status: 400, param: fidParam });
109
+ }
110
+ const fid = rawFileId.trim();
111
+ if (isOpenAIFileId(fid)) {
112
+ throw new BadRequestError(`OpenAI file_id ${JSON.stringify(fid)} is not supported; pass a Sarvam artifact_id belonging to this session, ` +
113
+ "file_data (base64), or an http(s) file_url.", { status: 400, param: fidParam });
114
+ }
115
+ return {
116
+ type: "file_ref",
117
+ fileId: fid,
118
+ mediaType: (_a = normalizeMime(mimeStr)) !== null && _a !== void 0 ? _a : undefined,
119
+ filename,
120
+ kind: "file",
121
+ param: fidParam,
122
+ };
123
+ }
124
+ if (hasUrl) {
125
+ const urlParam = `${path}.file_url`;
126
+ if (typeof rawUrl !== "string" || !rawUrl.trim()) {
127
+ throw new BadRequestError(`${path}.file_url must be a non-empty string.`, { status: 400, param: urlParam });
128
+ }
129
+ try {
130
+ const validUrl = validateRemoteUrl(rawUrl, urlParam);
131
+ const checkedMime = mimeStr ? validateFileMime(mimeStr, `${path}.media_type`) : undefined;
132
+ return { type: "remote_file", url: validUrl, kind: "file", filename, mediaType: checkedMime, param: urlParam };
133
+ }
134
+ catch (err) {
135
+ if (err instanceof CoreAPIError) {
136
+ throw new BadRequestError(err.message, { status: 400, param: (_b = err.param) !== null && _b !== void 0 ? _b : urlParam });
137
+ }
138
+ throw err;
139
+ }
140
+ }
141
+ const dataParam = `${path}.file_data`;
142
+ if (typeof rawData !== "string" || !rawData.trim()) {
143
+ throw new BadRequestError(`${path}.file_data must be a non-empty string.`, { status: 400, param: dataParam });
144
+ }
145
+ const trimmed = rawData.trim();
146
+ try {
147
+ let data;
148
+ let validMime;
149
+ if (trimmed.startsWith("data:")) {
150
+ const parsed = parseDataUri(trimmed, dataParam);
151
+ data = parsed.data;
152
+ validMime = validateFileMime((_c = normalizeMime(mimeStr)) !== null && _c !== void 0 ? _c : parsed.mime, dataParam);
153
+ }
154
+ else {
155
+ data = decodeBase64Bytes(trimmed, dataParam);
156
+ const chosen = (_e = (_d = normalizeMime(mimeStr)) !== null && _d !== void 0 ? _d : inferMimeFromFilename(filename)) !== null && _e !== void 0 ? _e : "application/octet-stream";
157
+ validMime = validateFileMime(chosen, dataParam);
158
+ }
159
+ const fname = sanitizeFilename(filename, "file", validMime);
160
+ return { type: "inline_file", data, mediaType: validMime, filename: fname, kind: "file", param: dataParam };
161
+ }
162
+ catch (err) {
163
+ if (err instanceof CoreAPIError) {
164
+ throw new BadRequestError(err.message, { status: 400, param: (_f = err.param) !== null && _f !== void 0 ? _f : dataParam });
165
+ }
166
+ throw err;
167
+ }
168
+ }
11
169
  export function parseInputParts(rawInput) {
12
170
  var _a;
13
171
  if (typeof rawInput === "string")
@@ -32,10 +190,11 @@ export function parseInputParts(rawInput) {
32
190
  else if (Array.isArray(content)) {
33
191
  for (let j = 0; j < content.length; j++) {
34
192
  const block = content[j];
193
+ const blockPath = `input[${i}].content[${j}]`;
35
194
  if (!isObj(block)) {
36
- throw new BadRequestError(`input[${i}].content[${j}] must be an object.`, {
195
+ throw new BadRequestError(`${blockPath} must be an object.`, {
37
196
  status: 400,
38
- param: `input[${i}].content[${j}]`,
197
+ param: blockPath,
39
198
  });
40
199
  }
41
200
  const btype = block["type"];
@@ -43,10 +202,10 @@ export function parseInputParts(rawInput) {
43
202
  parts.push({ type: "text", text: String((_a = block["text"]) !== null && _a !== void 0 ? _a : "") });
44
203
  }
45
204
  else if (btype === "input_image") {
46
- refuseOpenAI("input.input_image");
205
+ parts.push(parseInputImage(block, blockPath));
47
206
  }
48
207
  else if (btype === "input_file") {
49
- refuseOpenAI("input.input_file");
208
+ parts.push(parseInputFile(block, blockPath));
50
209
  }
51
210
  else {
52
211
  refuseOpenAI(`input.${String(btype)}`, { reason: "unsupported input content part", param: "input" });
@@ -60,6 +219,20 @@ export function parseInputParts(rawInput) {
60
219
  });
61
220
  }
62
221
  }
222
+ let attachmentCount = 0;
223
+ let inlineBytes = 0;
224
+ for (const p of parts) {
225
+ if (p.type !== "text")
226
+ attachmentCount += 1;
227
+ if (p.type === "inline_file")
228
+ inlineBytes += p.data.byteLength;
229
+ }
230
+ if (attachmentCount > MAX_ATTACHMENTS_PER_MESSAGE) {
231
+ throw new BadRequestError(`A message can contain at most ${MAX_ATTACHMENTS_PER_MESSAGE} attachments (got ${attachmentCount}).`, { status: 400, param: "input" });
232
+ }
233
+ if (inlineBytes > MAX_TOTAL_ATTACHMENT_BYTES) {
234
+ throw new BadRequestError(`Combined attachment size exceeds the maximum of ${Math.floor(MAX_TOTAL_ATTACHMENT_BYTES / (1024 * 1024))} MB per message.`, { status: 400, param: "input" });
235
+ }
63
236
  return parts;
64
237
  }
65
238
  function stringifyToolOutput(output) {
@@ -201,18 +374,42 @@ export class EventsResource {
201
374
  }
202
375
  }
203
376
  function recordsToItems(records) {
377
+ var _a;
204
378
  const items = [];
205
379
  for (const rec of records) {
206
380
  for (const ev of rec.events) {
207
381
  if (ev.kind === "text_done") {
208
- const partType = rec.role === "user" ? "input_text" : "output_text";
209
- items.push({
210
- id: ev.itemId,
211
- type: "message",
212
- role: rec.role,
213
- status: "completed",
214
- content: [{ type: partType, text: ev.text }],
215
- });
382
+ if (rec.role === "user") {
383
+ const blocks = [];
384
+ const atts = (_a = ev.attachments) !== null && _a !== void 0 ? _a : [];
385
+ if (ev.text || atts.length === 0) {
386
+ blocks.push({ type: "input_text", text: ev.text });
387
+ }
388
+ for (const att of atts) {
389
+ if ((att.mediaType || "").toLowerCase().startsWith("image/")) {
390
+ blocks.push({ type: "input_image", image_url: `${ARTIFACT_URI_PREFIX}${att.fileId}` });
391
+ }
392
+ else {
393
+ blocks.push({ type: "input_file", file_id: att.fileId, filename: att.filename });
394
+ }
395
+ }
396
+ items.push({
397
+ id: ev.itemId,
398
+ type: "message",
399
+ role: rec.role,
400
+ status: "completed",
401
+ content: blocks,
402
+ });
403
+ }
404
+ else {
405
+ items.push({
406
+ id: ev.itemId,
407
+ type: "message",
408
+ role: rec.role,
409
+ status: "completed",
410
+ content: [{ type: "output_text", text: ev.text }],
411
+ });
412
+ }
216
413
  }
217
414
  else if (ev.kind === "tool_called") {
218
415
  const itype = ev.name === "web_search" ? "web_search_call" : "sarvam.tool_call";
@@ -1,4 +1,5 @@
1
1
  import { CursorPager } from "../../core/paging.js";
2
+ import { prefetchRemoteParts } from "../../core/turns.js";
2
3
  import { BadRequestError, wrapCoreErrors } from "../errors.js";
3
4
  import { SyncCursorPage } from "../pages.js";
4
5
  import { AgentSessionEventStream } from "../stream.js";
@@ -83,7 +84,7 @@ export class SessionsResource {
83
84
  this.traces = new RefusedResource("beta.agents.sessions.traces");
84
85
  }
85
86
  async create(params = {}, options) {
86
- var _a;
87
+ var _a, _b;
87
88
  const known = new Set([
88
89
  "environment", "agent", "agent_id", "input", "metadata", "stream", "pin_agent_version", "sarvam_config", "idempotency_key",
89
90
  ]);
@@ -111,7 +112,15 @@ export class SessionsResource {
111
112
  throw new BadRequestError("Pass exactly one of 'agent' or 'agent_id'.", { status: 400, param: "agent" });
112
113
  }
113
114
  // Validate input before deploying an inline agent or creating a conversation.
114
- const parsedParts = hasInput ? parseInputParts(params["input"]) : null;
115
+ let parsedParts = hasInput ? parseInputParts(params["input"]) : null;
116
+ if (parsedParts !== null) {
117
+ for (const p of parsedParts) {
118
+ if (p.type === "file_ref") {
119
+ throw new BadRequestError(`file_id ${JSON.stringify(p.fileId)} cannot be used on sessions.create because Panja artifacts are scoped to an ` +
120
+ "existing session; pass inline base64 data or an http(s) URL instead.", { status: 400, param: (_b = p.param) !== null && _b !== void 0 ? _b : "file_id" });
121
+ }
122
+ }
123
+ }
115
124
  let resolvedAgentId;
116
125
  if (hasAgent) {
117
126
  if (!isObj(params["agent"])) {
@@ -142,6 +151,11 @@ export class SessionsResource {
142
151
  }
143
152
  resolvedAgentId = aid;
144
153
  }
154
+ // Fetch any remote URLs BEFORE creating the conversation so a bad/oversized URL never orphans a session.
155
+ if (parsedParts !== null) {
156
+ const toPrefetch = parsedParts;
157
+ parsedParts = await wrapCoreErrors(() => this.http.withRequestOptions(reqOpts, () => prefetchRemoteParts(this.http, toPrefetch)));
158
+ }
145
159
  const meta = isObj(params["metadata"])
146
160
  ? Object.fromEntries(Object.entries(params["metadata"]).map(([k, v]) => [k, String(v)]))
147
161
  : undefined;
@@ -162,12 +176,27 @@ export class SessionsResource {
162
176
  return evStream;
163
177
  };
164
178
  if (parsedParts !== null) {
179
+ let msgParts;
180
+ try {
181
+ const toResolve = parsedParts;
182
+ msgParts = await wrapCoreErrors(() => this.http.withRequestOptions(reqOpts, () => this.turns.resolveParts(sessionRec.id, toResolve)));
183
+ }
184
+ catch (err) {
185
+ try {
186
+ await this.sessions.delete(sessionRec.id);
187
+ }
188
+ catch (_c) {
189
+ // Best-effort cleanup of empty conversation after failed upload.
190
+ }
191
+ throw err;
192
+ }
193
+ const msgId = this.http.newIdempotencyKey();
165
194
  if (stream) {
166
- const rawStream = await wrapCoreErrors(() => this.http.withRequestOptions(reqOpts, () => this.turns.send(sessionRec.id, resolvedAgentId, parsedParts, { returnStream: true })));
195
+ const rawStream = await wrapCoreErrors(() => this.http.withRequestOptions(reqOpts, () => this.turns.sendMessageParts(sessionRec.id, resolvedAgentId, msgParts, { msgId, returnStream: true })));
167
196
  const listener = this.turns.listen(sessionRec.id, { initialStream: rawStream, reqOpts });
168
197
  return bindSignal(new AgentSessionEventStream(sessionRec.id, { listener, sessionCreated: sessionObj }));
169
198
  }
170
- await wrapCoreErrors(() => this.http.withRequestOptions(reqOpts, () => this.turns.send(sessionRec.id, resolvedAgentId, parsedParts)));
199
+ await wrapCoreErrors(() => this.http.withRequestOptions(reqOpts, () => this.turns.sendMessageParts(sessionRec.id, resolvedAgentId, msgParts, { msgId, returnStream: false })));
171
200
  return sessionObj;
172
201
  }
173
202
  if (stream) {