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,12 +1,15 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.Turns = exports.Listener = exports.ListenerRegistry = exports.DEFAULT_POLL_TIMEOUT_MS = void 0;
4
+ exports.prefetchRemoteParts = prefetchRemoteParts;
4
5
  /** Core Turns service: send, steer, stop, clarify, and in-process/cross-process stream follow. */
6
+ const node_crypto_1 = require("node:crypto");
5
7
  const QueueApi_js_1 = require("../../apis/QueueApi.js");
6
8
  const ResponsesApi_js_1 = require("../../apis/ResponsesApi.js");
7
9
  const streaming_js_1 = require("../../streaming.js");
8
10
  const errors_js_1 = require("./errors.js");
9
11
  const events_js_1 = require("./events.js");
12
+ const files_js_1 = require("./files.js");
10
13
  const refusals_js_1 = require("./refusals.js");
11
14
  const NO_ACTIVE_CODES = new Set([
12
15
  "NO_ACTIVE_TURN",
@@ -16,16 +19,125 @@ const NO_ACTIVE_CODES = new Set([
16
19
  ]);
17
20
  const UNITERATED_TTL_MS = 60000;
18
21
  exports.DEFAULT_POLL_TIMEOUT_MS = 300000;
19
- function toMessageParts(parts, provider = "openai") {
22
+ async function prefetchRemoteParts(http, parts) {
23
+ var _a;
24
+ let attachmentCount = 0;
25
+ let usedBytes = 0;
26
+ for (const p of parts) {
27
+ if (p.type !== "text")
28
+ attachmentCount += 1;
29
+ if (p.type === "inline_file")
30
+ usedBytes += p.data.byteLength;
31
+ }
32
+ if (attachmentCount > files_js_1.MAX_ATTACHMENTS_PER_MESSAGE) {
33
+ throw new errors_js_1.CoreAPIError(`A message can contain at most ${files_js_1.MAX_ATTACHMENTS_PER_MESSAGE} attachments (got ${attachmentCount}).`, { status: 400, code: "invalid_request_error", param: "input" });
34
+ }
35
+ if (usedBytes > files_js_1.MAX_TOTAL_ATTACHMENT_BYTES) {
36
+ throw new errors_js_1.CoreAPIError(`Combined attachment size exceeds the maximum of ${Math.floor(files_js_1.MAX_TOTAL_ATTACHMENT_BYTES / (1024 * 1024))} MB per message.`, { status: 400, code: "invalid_request_error", param: "input" });
37
+ }
38
+ if (!parts.some((p) => p.type === "remote_file"))
39
+ return parts;
20
40
  const out = [];
21
41
  for (const p of parts) {
22
- if (p.type === "text")
23
- out.push({ type: "text", text: p.text });
24
- else
25
- (0, refusals_js_1.refuse)(provider, "input.input_file");
42
+ if (p.type === "remote_file") {
43
+ const remainingBudget = files_js_1.MAX_TOTAL_ATTACHMENT_BYTES - usedBytes;
44
+ if (remainingBudget <= 0) {
45
+ throw new errors_js_1.CoreAPIError(`Combined attachment size exceeds the maximum of ${Math.floor(files_js_1.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" });
46
+ }
47
+ const fetched = await (0, files_js_1.fetchRemoteFile)(http, p.url, {
48
+ kind: p.kind,
49
+ filename: p.filename,
50
+ mediaType: p.mediaType,
51
+ param: p.param,
52
+ maxBytes: remainingBudget,
53
+ });
54
+ usedBytes += fetched.data.byteLength;
55
+ out.push({
56
+ type: "inline_file",
57
+ data: fetched.data,
58
+ mediaType: fetched.mediaType,
59
+ filename: fetched.filename,
60
+ kind: p.kind,
61
+ param: p.param,
62
+ });
63
+ }
64
+ else {
65
+ out.push(p);
66
+ }
26
67
  }
27
68
  return out;
28
69
  }
70
+ async function resolveMessageParts(http, sessionId, parts, provider = "openai", opts = {}) {
71
+ var _a, _b, _c, _d;
72
+ // Guard: verify every file_id belongs to this session BEFORE downloading remote URLs or uploading anything.
73
+ const hasRefs = parts.some((p) => p.type === "file_ref");
74
+ const sessionArtifacts = hasRefs ? await (0, files_js_1.listSessionArtifacts)(http, sessionId) : new Map();
75
+ for (const p of parts) {
76
+ if (p.type === "file_ref") {
77
+ const found = sessionArtifacts.get(p.fileId);
78
+ if (!found) {
79
+ throw new errors_js_1.CoreAPIError(`file_id ${JSON.stringify(p.fileId)} does not belong to session ${JSON.stringify(sessionId)}. ` +
80
+ "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" });
81
+ }
82
+ if (p.kind === "image") {
83
+ const norm = (0, files_js_1.normalizeMime)(found.mediaType);
84
+ if (!norm || !files_js_1.ACCEPTED_IMAGE_MIMES.has(norm)) {
85
+ const accepted = Array.from(files_js_1.ACCEPTED_IMAGE_MIMES).sort().join(", ");
86
+ throw new errors_js_1.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" });
87
+ }
88
+ }
89
+ }
90
+ }
91
+ const prepared = await prefetchRemoteParts(http, parts);
92
+ const out = [];
93
+ const newlyUploaded = [];
94
+ try {
95
+ for (let idx = 0; idx < prepared.length; idx++) {
96
+ const p = prepared[idx];
97
+ if (p.type === "text") {
98
+ out.push({ type: "text", text: p.text });
99
+ }
100
+ else if (p.type === "inline_file") {
101
+ const sha = (0, node_crypto_1.createHash)("sha256").update(p.data).digest("hex");
102
+ const cached = opts.idempotencyKey && opts.uploadCache
103
+ ? opts.uploadCache.get(sessionId, opts.idempotencyKey, idx, sha)
104
+ : undefined;
105
+ if (cached) {
106
+ out.push((0, files_js_1.makeFileMessagePart)(cached.artifactId, cached.filename, cached.mediaType));
107
+ continue;
108
+ }
109
+ const uploaded = await (0, files_js_1.uploadArtifact)(http, sessionId, p.data, {
110
+ filename: p.filename,
111
+ mediaType: p.mediaType,
112
+ });
113
+ let cacheEntry;
114
+ if (opts.idempotencyKey && opts.uploadCache) {
115
+ cacheEntry = [sessionId, opts.idempotencyKey, idx, sha];
116
+ opts.uploadCache.put(sessionId, opts.idempotencyKey, idx, sha, uploaded);
117
+ }
118
+ newlyUploaded.push({ artifactId: uploaded.artifactId, cacheEntry });
119
+ out.push((0, files_js_1.makeFileMessagePart)(uploaded.artifactId, uploaded.filename, uploaded.mediaType));
120
+ }
121
+ else if (p.type === "file_ref") {
122
+ const found = sessionArtifacts.get(p.fileId);
123
+ out.push((0, files_js_1.makeFileMessagePart)(found.artifactId, (_c = p.filename) !== null && _c !== void 0 ? _c : found.filename, (_d = p.mediaType) !== null && _d !== void 0 ? _d : found.mediaType));
124
+ }
125
+ else {
126
+ (0, refusals_js_1.refuse)(provider, "input", { reason: "unsupported input part" });
127
+ }
128
+ }
129
+ }
130
+ catch (err) {
131
+ for (const item of newlyUploaded) {
132
+ await (0, files_js_1.deleteArtifactBestEffort)(http, sessionId, item.artifactId);
133
+ if (item.cacheEntry && opts.uploadCache) {
134
+ opts.uploadCache.evict(...item.cacheEntry);
135
+ }
136
+ }
137
+ throw err;
138
+ }
139
+ return { msgParts: out, newlyUploaded };
140
+ }
29
141
  const WeakRefImpl = globalThis.WeakRef;
30
142
  const FinalizationRegistryImpl = globalThis.FinalizationRegistry;
31
143
  const listenerFinalizer = FinalizationRegistryImpl
@@ -284,7 +396,7 @@ class Listener {
284
396
  exports.Listener = Listener;
285
397
  class Turns {
286
398
  constructor(_http, _sessions, opts = {}) {
287
- var _a, _b, _c;
399
+ var _a, _b, _c, _d;
288
400
  this._http = _http;
289
401
  this._sessions = _sessions;
290
402
  this.queueApi = new QueueApi_js_1.QueueApi(_http.sdkConfig);
@@ -292,6 +404,7 @@ class Turns {
292
404
  this.pollIntervalMs = (_a = opts.pollIntervalMs) !== null && _a !== void 0 ? _a : 1000;
293
405
  this.provider = (_b = opts.provider) !== null && _b !== void 0 ? _b : "openai";
294
406
  this._registry = (_c = opts.registry) !== null && _c !== void 0 ? _c : new ListenerRegistry();
407
+ this.uploadCache = (_d = opts.uploadCache) !== null && _d !== void 0 ? _d : new files_js_1.AttachmentUploadCache();
295
408
  }
296
409
  handoffOrClose(sessionId, stream) {
297
410
  return this._registry.handoffOrClose(sessionId, stream);
@@ -302,28 +415,58 @@ class Turns {
302
415
  this._registry.register(sessionId, listener);
303
416
  return listener;
304
417
  }
305
- async send(sessionId, agentId, parts, opts = {}) {
306
- var _a;
307
- const msgId = (_a = opts.key) !== null && _a !== void 0 ? _a : this._http.newIdempotencyKey();
418
+ async resolveParts(sessionId, parts, opts = {}) {
419
+ const { msgParts } = await resolveMessageParts(this._http, sessionId, parts, this.provider, {
420
+ idempotencyKey: opts.key,
421
+ uploadCache: this.uploadCache,
422
+ });
423
+ return msgParts;
424
+ }
425
+ async sendMessageParts(sessionId, agentId, msgParts, opts) {
308
426
  const stream = await this._http.call(() => (0, streaming_js_1.streamResponse)(this._http.sdkConfig, {
309
427
  id: sessionId,
310
428
  agentId: agentId !== null && agentId !== void 0 ? agentId : undefined,
311
- message: { id: msgId, role: "user", parts: toMessageParts(parts, this.provider) },
429
+ message: { id: opts.msgId, role: "user", parts: msgParts },
312
430
  }), { idempotent: false });
313
431
  if (opts.returnStream)
314
432
  return stream;
315
433
  this.handoffOrClose(sessionId, stream);
316
434
  return null;
317
435
  }
436
+ async send(sessionId, agentId, parts, opts = {}) {
437
+ var _a;
438
+ const msgId = (_a = opts.key) !== null && _a !== void 0 ? _a : this._http.newIdempotencyKey();
439
+ const { msgParts, newlyUploaded } = await resolveMessageParts(this._http, sessionId, parts, this.provider, {
440
+ idempotencyKey: opts.key,
441
+ uploadCache: this.uploadCache,
442
+ });
443
+ try {
444
+ return await this.sendMessageParts(sessionId, agentId, msgParts, { msgId, returnStream: opts.returnStream });
445
+ }
446
+ catch (err) {
447
+ if (err instanceof errors_js_1.CoreAPIError && err.status !== null && err.status >= 400 && err.status < 500) {
448
+ for (const item of newlyUploaded) {
449
+ await (0, files_js_1.deleteArtifactBestEffort)(this._http, sessionId, item.artifactId);
450
+ if (item.cacheEntry)
451
+ this.uploadCache.evict(...item.cacheEntry);
452
+ }
453
+ }
454
+ throw err;
455
+ }
456
+ }
318
457
  async steer(sessionId, agentId, parts, opts = {}) {
319
458
  var _a, _b, _c;
320
459
  const msgId = (_a = opts.key) !== null && _a !== void 0 ? _a : this._http.newIdempotencyKey();
321
460
  const delivery = (_b = opts.delivery) !== null && _b !== void 0 ? _b : "now";
461
+ const { msgParts, newlyUploaded } = await resolveMessageParts(this._http, sessionId, parts, this.provider, {
462
+ idempotencyKey: opts.key,
463
+ uploadCache: this.uploadCache,
464
+ });
322
465
  try {
323
466
  await this._http.call(() => this.queueApi.queueMessage({
324
467
  conversationId: sessionId,
325
468
  queueMessageInput: {
326
- message: { id: msgId, role: "user", parts: toMessageParts(parts, this.provider) },
469
+ message: { id: msgId, role: "user", parts: msgParts },
327
470
  delivery,
328
471
  agentId: agentId !== null && agentId !== void 0 ? agentId : undefined,
329
472
  },
@@ -331,14 +474,22 @@ class Turns {
331
474
  }
332
475
  catch (err) {
333
476
  // Fall back to starting a new turn only when Panja rejects with a no-active-turn error.
477
+ // Reuse already-resolved msgParts so inline files are never uploaded twice.
334
478
  // A 202 queued response (even with reason=no_active_turn) means Panja already accepted
335
479
  // and queued the message, so we must not double-post to /v1/responses.
336
480
  if (err instanceof errors_js_1.CoreAPIError &&
337
481
  (err.status === 404 || err.status === 409) &&
338
482
  NO_ACTIVE_CODES.has((_c = err.code) !== null && _c !== void 0 ? _c : "")) {
339
- await this.send(sessionId, agentId, parts, { key: msgId });
483
+ await this.sendMessageParts(sessionId, agentId, msgParts, { msgId });
340
484
  return;
341
485
  }
486
+ if (err instanceof errors_js_1.CoreAPIError && err.status !== null && err.status >= 400 && err.status < 500) {
487
+ for (const item of newlyUploaded) {
488
+ await (0, files_js_1.deleteArtifactBestEffort)(this._http, sessionId, item.artifactId);
489
+ if (item.cacheEntry)
490
+ this.uploadCache.evict(...item.cacheEntry);
491
+ }
492
+ }
342
493
  throw err;
343
494
  }
344
495
  }
@@ -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;
@@ -4,6 +4,7 @@ exports.OpenAI = void 0;
4
4
  /** OpenAI drop-in client (client.beta.agents...) backed by compat/core. */
5
5
  const agents_js_1 = require("../core/agents.js");
6
6
  const errors_js_1 = require("../core/errors.js");
7
+ const files_js_1 = require("../core/files.js");
7
8
  const http_js_1 = require("../core/http.js");
8
9
  const models_js_1 = require("../core/models.js");
9
10
  const sessions_js_1 = require("../core/sessions.js");
@@ -37,7 +38,7 @@ function makeRawProxy(target, http) {
37
38
  }
38
39
  class OpenAI {
39
40
  constructor(opts = {}) {
40
- var _a, _b, _c, _d, _e;
41
+ var _a, _b, _c, _d, _e, _f;
41
42
  this.initOpts = { ...opts };
42
43
  try {
43
44
  this.http = new http_js_1.Http({
@@ -49,7 +50,11 @@ class OpenAI {
49
50
  defaultQuery: opts.defaultQuery,
50
51
  provider: "openai",
51
52
  fetch: opts.fetch,
52
- }, opts._sleep ? { sleep: opts._sleep } : undefined);
53
+ allowPrivateRemoteUrls: opts.allowPrivateRemoteUrls,
54
+ }, {
55
+ ...(opts._sleep ? { sleep: opts._sleep } : {}),
56
+ ...(opts._resolveHost ? { resolveHost: opts._resolveHost } : {}),
57
+ });
53
58
  }
54
59
  catch (err) {
55
60
  if (err instanceof errors_js_1.CoreAPIError)
@@ -66,10 +71,12 @@ class OpenAI {
66
71
  const sessionsCore = new sessions_js_1.Sessions(this.http, { provider: "openai", updateQueue: this.sessionUpdateQueue });
67
72
  this.listenerRegistry = (_d = opts._sharedRegistry) !== null && _d !== void 0 ? _d : new turns_js_1.ListenerRegistry();
68
73
  this.toolResultStore = (_e = opts._sharedToolStore) !== null && _e !== void 0 ? _e : new toolResults_js_1.ToolResultStore();
74
+ this.uploadCache = (_f = opts._sharedUploadCache) !== null && _f !== void 0 ? _f : new files_js_1.AttachmentUploadCache();
69
75
  const turnsCore = new turns_js_1.Turns(this.http, sessionsCore, {
70
76
  pollIntervalMs: opts._pollIntervalMs,
71
77
  provider: "openai",
72
78
  registry: this.listenerRegistry,
79
+ uploadCache: this.uploadCache,
73
80
  });
74
81
  const toolResultsCore = new toolResults_js_1.ToolResults(this.http, sessionsCore, turnsCore, {
75
82
  store: this.toolResultStore,
@@ -91,6 +98,7 @@ class OpenAI {
91
98
  _sharedRegistry: this.listenerRegistry,
92
99
  _sharedToolStore: this.toolResultStore,
93
100
  _sharedSessionQueue: this.sessionUpdateQueue,
101
+ _sharedUploadCache: this.uploadCache,
94
102
  });
95
103
  }
96
104
  close() {