sarvam-agents-client 0.5.3 → 0.5.4

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 (32) hide show
  1. package/dist/compat/core/agents.d.ts +6 -1
  2. package/dist/compat/core/agents.js +237 -27
  3. package/dist/compat/core/customApis.d.ts +76 -0
  4. package/dist/compat/core/customApis.js +424 -0
  5. package/dist/compat/core/data.js +1 -1
  6. package/dist/compat/openai/client.d.ts +3 -0
  7. package/dist/compat/openai/client.js +5 -1
  8. package/dist/compat/openai/index.d.ts +1 -0
  9. package/dist/compat/openai/index.js +0 -1
  10. package/dist/compat/openai/resources/agents.js +8 -1
  11. package/dist/compat/openai/resources/sarvam.d.ts +26 -0
  12. package/dist/compat/openai/resources/sarvam.js +56 -0
  13. package/dist/esm/compat/core/agents.d.ts +6 -1
  14. package/dist/esm/compat/core/agents.js +237 -27
  15. package/dist/esm/compat/core/customApis.d.ts +76 -0
  16. package/dist/esm/compat/core/customApis.js +419 -0
  17. package/dist/esm/compat/core/data.js +1 -1
  18. package/dist/esm/compat/openai/client.d.ts +3 -0
  19. package/dist/esm/compat/openai/client.js +5 -1
  20. package/dist/esm/compat/openai/index.d.ts +1 -0
  21. package/dist/esm/compat/openai/index.js +0 -1
  22. package/dist/esm/compat/openai/resources/agents.js +8 -1
  23. package/dist/esm/compat/openai/resources/sarvam.d.ts +26 -0
  24. package/dist/esm/compat/openai/resources/sarvam.js +51 -0
  25. package/package.json +1 -1
  26. package/src/compat/core/agents.ts +265 -36
  27. package/src/compat/core/customApis.ts +506 -0
  28. package/src/compat/core/data.ts +1 -1
  29. package/src/compat/openai/client.ts +7 -1
  30. package/src/compat/openai/index.ts +9 -0
  31. package/src/compat/openai/resources/agents.ts +9 -1
  32. package/src/compat/openai/resources/sarvam.ts +94 -0
@@ -4,6 +4,12 @@ import { rawAgent } from "../../compose/agent.js";
4
4
  import { NotSupportedByServerError, UserError } from "../../compose/errors.js";
5
5
  import { settingsFingerprint } from "../../compose/fingerprint.js";
6
6
  import { SettingsTransport } from "../../compose/settingsTransport.js";
7
+ import {
8
+ CustomApis,
9
+ validateCustomApiRefs,
10
+ type CustomApiAgentEntry,
11
+ type CustomApiInfo,
12
+ } from "./customApis.js";
7
13
  import { CoreAPIError } from "./errors.js";
8
14
  import { Http } from "./http.js";
9
15
  import { inlineAgentName } from "./ids.js";
@@ -27,6 +33,7 @@ const ALLOWED_SARVAM_KEYS = new Set([
27
33
  "knowledge_bases",
28
34
  "clarify",
29
35
  "apps",
36
+ "custom_apis",
30
37
  ]);
31
38
 
32
39
  export interface AgentSpec {
@@ -57,6 +64,31 @@ export interface AgentRecord {
57
64
  archived: boolean;
58
65
  sarvamModel: string | null;
59
66
  rawSettings: Record<string, unknown>;
67
+ customApis: CustomApiAgentEntry[];
68
+ unmanagedCustomApis: CustomApiAgentEntry[];
69
+ }
70
+
71
+ function customApiEntries(infos: readonly CustomApiInfo[]): CustomApiAgentEntry[] {
72
+ return infos.map((c) => ({ id: c.id, name: c.name, host: c.host }));
73
+ }
74
+
75
+ function readManagedCustomApis(settings: Record<string, unknown> | undefined): CustomApiAgentEntry[] {
76
+ if (!settings) return [];
77
+ const rawMeta = isObj(settings["metadata"]) ? settings["metadata"] : {};
78
+ const compat = isObj(rawMeta["sdk_compat"]) ? rawMeta["sdk_compat"] : {};
79
+ const rawList = compat["custom_apis"];
80
+ if (!Array.isArray(rawList)) return [];
81
+ const out: CustomApiAgentEntry[] = [];
82
+ for (const item of rawList) {
83
+ if (isObj(item) && typeof item["id"] === "string" && item["id"]) {
84
+ out.push({
85
+ id: item["id"],
86
+ name: typeof item["name"] === "string" ? item["name"] : "",
87
+ host: item["host"] !== undefined && item["host"] !== null ? String(item["host"]) : null,
88
+ });
89
+ }
90
+ }
91
+ return out;
60
92
  }
61
93
 
62
94
  function isObj(v: unknown): v is Record<string, unknown> {
@@ -96,6 +128,7 @@ function specToSettings(
96
128
  spec: AgentSpec,
97
129
  sarvamModel: string | null,
98
130
  baseSettings?: Record<string, unknown>,
131
+ managedCustomApis?: CustomApiAgentEntry[] | null,
99
132
  ): Record<string, unknown> {
100
133
  validateSarvamKeys(spec.sarvam ?? {}, spec.provider);
101
134
 
@@ -133,6 +166,7 @@ function specToSettings(
133
166
  else delete out["output_schema"];
134
167
 
135
168
  for (const [k, v] of Object.entries(spec.sarvam ?? {})) {
169
+ if (k === "custom_apis") continue;
136
170
  if (v === undefined) continue;
137
171
  if (v === null) {
138
172
  delete out[k];
@@ -157,6 +191,21 @@ function specToSettings(
157
191
  if (spec.reasoningSummary !== undefined && spec.reasoningSummary !== null) compatMeta["reasoning_summary"] = spec.reasoningSummary;
158
192
  if (spec.outputSchemaName !== undefined && spec.outputSchemaName !== null) compatMeta["output_schema_name"] = spec.outputSchemaName;
159
193
 
194
+ const effectiveCustomApis =
195
+ managedCustomApis !== undefined && managedCustomApis !== null
196
+ ? managedCustomApis
197
+ : readManagedCustomApis(baseSettings);
198
+ if (effectiveCustomApis.length > 0) {
199
+ // Panja rejects null values inside agent.json, so omit keys whose value is null/undefined.
200
+ compatMeta["custom_apis"] = effectiveCustomApis.map((entry) => {
201
+ const cleaned: Record<string, unknown> = {};
202
+ for (const [k, v] of Object.entries(entry)) {
203
+ if (v !== null && v !== undefined) cleaned[k] = clone(v);
204
+ }
205
+ return cleaned;
206
+ });
207
+ }
208
+
160
209
  const existingMeta = isObj(out["metadata"]) ? clone(out["metadata"]) : {};
161
210
  delete existingMeta["sdk_name"];
162
211
  delete existingMeta["sdk_hash"];
@@ -203,31 +252,45 @@ function settingsToRecord(
203
252
  multiAgentEnabled,
204
253
  archived,
205
254
  };
206
- return { id, spec, version, createdAt, archived, sarvamModel, rawSettings: clone(settings) };
255
+ return {
256
+ id,
257
+ spec,
258
+ version,
259
+ createdAt,
260
+ archived,
261
+ sarvamModel,
262
+ rawSettings: clone(settings),
263
+ customApis: readManagedCustomApis(settings),
264
+ unmanagedCustomApis: [],
265
+ };
207
266
  }
208
267
 
209
268
  export class Agents {
210
269
  private readonly transport: SettingsTransport;
211
270
  private readonly api: AgentsApi;
271
+ private readonly customApis: CustomApis;
212
272
  private readonly inlineInflight = new Map<string, Promise<AgentRecord>>();
213
273
 
214
274
  constructor(
215
275
  private readonly http: Http,
216
276
  private readonly models: ModelResolver,
277
+ customApis?: CustomApis,
217
278
  ) {
218
279
  this.transport = new SettingsTransport(http.sdkConfig);
219
280
  this.api = new AgentsApi(http.sdkConfig);
281
+ this.customApis = customApis ?? new CustomApis(http);
220
282
  }
221
283
 
222
284
  private async buildRaw(
223
285
  spec: AgentSpec,
224
286
  pathOf?: (field: string) => string,
225
287
  baseSettings?: Record<string, unknown>,
288
+ managedCustomApis?: CustomApiAgentEntry[] | null,
226
289
  ) {
227
290
  const resolved = await this.models.resolve(spec.model);
228
291
  const effective = clone(spec);
229
292
  if (!effective.requestedModel) effective.requestedModel = resolved.requested;
230
- const settings = specToSettings(effective, resolved.sarvamId, baseSettings);
293
+ const settings = specToSettings(effective, resolved.sarvamId, baseSettings, managedCustomApis);
231
294
  try {
232
295
  return { agent: rawAgent(effective.name, effective.instructions, settings), sarvamModel: resolved.sarvamId };
233
296
  } catch (err) {
@@ -238,22 +301,25 @@ export class Agents {
238
301
 
239
302
  async create(
240
303
  spec: AgentSpec,
241
- opts: { pathOf?: (field: string) => string } = {},
304
+ opts: { pathOf?: (field: string) => string; _resolvedCustomApis?: CustomApiInfo[] } = {},
242
305
  ): Promise<AgentRecord> {
243
- const { agent } = await this.buildRaw(spec, opts.pathOf);
306
+ const sarvamCfg = spec.sarvam ?? {};
307
+ let resolvedCas: CustomApiInfo[] = [];
308
+ if (opts._resolvedCustomApis !== undefined) {
309
+ resolvedCas = [...opts._resolvedCustomApis];
310
+ } else if ("custom_apis" in sarvamCfg && sarvamCfg["custom_apis"] !== null && sarvamCfg["custom_apis"] !== undefined) {
311
+ const refs = validateCustomApiRefs(sarvamCfg["custom_apis"]);
312
+ resolvedCas = await this.customApis.resolveRefs(refs);
313
+ }
314
+ const managedEntries = customApiEntries(resolvedCas);
315
+
316
+ const { agent } = await this.buildRaw(spec, opts.pathOf, undefined, managedEntries);
317
+ let remote;
244
318
  try {
245
- const remote = await this.http.call(
319
+ remote = await this.http.call(
246
320
  () => this.transport.createAgent(agent),
247
321
  { idempotent: false },
248
322
  );
249
- return settingsToRecord(
250
- remote.agentId,
251
- remote.name,
252
- remote.instructions,
253
- remote.settings,
254
- remote.liveVersion ?? null,
255
- iso((remote as unknown as { createdAt?: unknown }).createdAt),
256
- );
257
323
  } catch (err) {
258
324
  if (err instanceof UserError) throw mapUserError(err, opts.pathOf);
259
325
  if (err instanceof NotSupportedByServerError) {
@@ -261,13 +327,45 @@ export class Agents {
261
327
  }
262
328
  throw err;
263
329
  }
330
+
331
+ if (resolvedCas.length > 0) {
332
+ try {
333
+ for (const ca of resolvedCas) {
334
+ await this.customApis.bind(remote.agentId, ca.id);
335
+ }
336
+ } catch (err) {
337
+ try {
338
+ await this.http.call(() => this.transport.deleteAgent(remote.agentId), { idempotent: true });
339
+ } catch {
340
+ // Best-effort cleanup of half-created agent.
341
+ }
342
+ throw err;
343
+ }
344
+ }
345
+
346
+ const rec = settingsToRecord(
347
+ remote.agentId,
348
+ remote.name,
349
+ remote.instructions,
350
+ remote.settings,
351
+ remote.liveVersion ?? null,
352
+ iso((remote as unknown as { createdAt?: unknown }).createdAt),
353
+ );
354
+ if (managedEntries.length > 0) {
355
+ rec.customApis = managedEntries;
356
+ }
357
+ return rec;
264
358
  }
265
359
 
266
360
  async retrieve(agentId: string): Promise<AgentRecord> {
267
- const [resource, instr] = await Promise.all([
268
- this.http.call(() => this.api.getAgent({ agentId }), { idempotent: true }),
269
- this.http.call(() => this.api.getInstructions({ agentId }), { idempotent: true }),
270
- ]);
361
+ const resource = await this.http.call(() => this.api.getAgent({ agentId }), { idempotent: true });
362
+ let liveCustomApis: CustomApiAgentEntry[] | null = null;
363
+ try {
364
+ liveCustomApis = await this.customApis.listForAgent(agentId);
365
+ } catch (err) {
366
+ if (!(err instanceof CoreAPIError && err.status === 404)) throw err;
367
+ }
368
+ const instr = await this.http.call(() => this.api.getInstructions({ agentId }), { idempotent: true });
271
369
  let settings: Record<string, unknown> = isObj(resource.settings) ? { ...resource.settings } : {};
272
370
  if (Object.keys(settings).length === 0) {
273
371
  try {
@@ -277,7 +375,7 @@ export class Agents {
277
375
  if (!(err instanceof CoreAPIError && err.status === 404)) throw err;
278
376
  }
279
377
  }
280
- return settingsToRecord(
378
+ const rec = settingsToRecord(
281
379
  resource.id,
282
380
  resource.name,
283
381
  instr.data,
@@ -285,6 +383,19 @@ export class Agents {
285
383
  resource.liveVersion ?? null,
286
384
  iso(resource.createdAt),
287
385
  );
386
+ if (liveCustomApis !== null) {
387
+ const liveById = new Map<string, CustomApiAgentEntry>();
388
+ for (const item of liveCustomApis) {
389
+ if (item.id) liveById.set(item.id, item);
390
+ }
391
+ const managedIds = rec.customApis.map((c) => c.id).filter(Boolean);
392
+ const managedSet = new Set(managedIds);
393
+ rec.customApis = managedIds
394
+ .map((cid) => liveById.get(cid))
395
+ .filter((x): x is CustomApiAgentEntry => x !== undefined);
396
+ rec.unmanagedCustomApis = liveCustomApis.filter((item) => !managedSet.has(item.id));
397
+ }
398
+ return rec;
288
399
  }
289
400
 
290
401
  async update(
@@ -311,31 +422,129 @@ export class Agents {
311
422
  );
312
423
  }
313
424
  }
425
+
426
+ const prevManaged = readManagedCustomApis(current.rawSettings);
314
427
  const updatedSpec = change(clone(current.spec));
315
- const { agent } = await this.buildRaw(updatedSpec, opts.pathOf, current.rawSettings);
428
+ const sarvamCfg = updatedSpec.sarvam ?? {};
429
+ const customApisSpecified = "custom_apis" in sarvamCfg;
430
+
431
+ if (!customApisSpecified) {
432
+ const { agent } = await this.buildRaw(updatedSpec, opts.pathOf, current.rawSettings);
433
+ const currentHash = settingsFingerprint(current.spec.instructions, current.rawSettings);
434
+ if (updatedSpec.name === current.spec.name && agent.specHash() === currentHash) {
435
+ return current;
436
+ }
437
+ try {
438
+ const remote = await this.http.call(() => this.transport.updateAgent(agentId, agent), { idempotent: false });
439
+ const rec = settingsToRecord(
440
+ remote.agentId,
441
+ remote.name,
442
+ remote.instructions,
443
+ remote.settings,
444
+ remote.liveVersion ?? null,
445
+ current.createdAt,
446
+ );
447
+ rec.customApis = [...current.customApis];
448
+ rec.unmanagedCustomApis = [...current.unmanagedCustomApis];
449
+ return rec;
450
+ } catch (err) {
451
+ if (err instanceof UserError) throw mapUserError(err, opts.pathOf);
452
+ if (err instanceof NotSupportedByServerError) {
453
+ throw new CoreAPIError(err.message, { status: 400, code: "unsupported_by_sarvam" });
454
+ }
455
+ throw err;
456
+ }
457
+ }
458
+
459
+ const rawRefs = sarvamCfg["custom_apis"];
460
+ let resolvedCas: CustomApiInfo[] = [];
461
+ if (rawRefs !== null && rawRefs !== undefined) {
462
+ const refs = validateCustomApiRefs(rawRefs);
463
+ resolvedCas = await this.customApis.resolveRefs(refs);
464
+ }
465
+ const managedEntries = customApiEntries(resolvedCas);
466
+
467
+ const { agent } = await this.buildRaw(updatedSpec, opts.pathOf, current.rawSettings, managedEntries);
468
+
469
+ const live = await this.customApis.listForAgent(agentId);
470
+ const liveIds = new Set(live.map((i) => i.id).filter(Boolean));
471
+ const prevManagedIds = prevManaged.map((i) => i.id).filter(Boolean);
472
+ const prevManagedSet = new Set(prevManagedIds);
473
+ const targetIds = resolvedCas.map((c) => c.id);
474
+ const targetSet = new Set(targetIds);
475
+
476
+ const toBind = targetIds.filter((cid) => !liveIds.has(cid));
477
+ const toUnbind = prevManagedIds.filter((cid) => !targetSet.has(cid) && liveIds.has(cid));
478
+ const unmanaged = live.filter((item) => !targetSet.has(item.id) && !prevManagedSet.has(item.id));
316
479
 
317
480
  const currentHash = settingsFingerprint(current.spec.instructions, current.rawSettings);
318
- if (updatedSpec.name === current.spec.name && agent.specHash() === currentHash) {
481
+ const settingsChanged = updatedSpec.name !== current.spec.name || agent.specHash() !== currentHash;
482
+ if (!settingsChanged && toBind.length === 0 && toUnbind.length === 0) {
483
+ current.customApis = managedEntries;
484
+ current.unmanagedCustomApis = unmanaged;
319
485
  return current;
320
486
  }
321
487
 
488
+ const boundNow: string[] = [];
489
+ const unboundNow: string[] = [];
490
+ const rollbackBindings = async (): Promise<void> => {
491
+ for (const cid of boundNow) {
492
+ try {
493
+ await this.customApis.unbind(agentId, cid);
494
+ } catch {
495
+ // Best-effort rollback of newly added binds.
496
+ }
497
+ }
498
+ for (const cid of unboundNow) {
499
+ try {
500
+ await this.customApis.bind(agentId, cid);
501
+ } catch {
502
+ // Best-effort rollback of newly removed binds.
503
+ }
504
+ }
505
+ };
506
+
322
507
  try {
323
- const remote = await this.http.call(() => this.transport.updateAgent(agentId, agent), { idempotent: false });
324
- return settingsToRecord(
325
- remote.agentId,
326
- remote.name,
327
- remote.instructions,
328
- remote.settings,
329
- remote.liveVersion ?? null,
330
- current.createdAt,
331
- );
332
- } catch (err) {
333
- if (err instanceof UserError) throw mapUserError(err, opts.pathOf);
334
- if (err instanceof NotSupportedByServerError) {
335
- throw new CoreAPIError(err.message, { status: 400, code: "unsupported_by_sarvam" });
508
+ for (const cid of toUnbind) {
509
+ await this.customApis.unbind(agentId, cid);
510
+ unboundNow.push(cid);
336
511
  }
512
+ for (const cid of toBind) {
513
+ await this.customApis.bind(agentId, cid);
514
+ boundNow.push(cid);
515
+ }
516
+ } catch (err) {
517
+ await rollbackBindings();
337
518
  throw err;
338
519
  }
520
+
521
+ let rec: AgentRecord;
522
+ if (settingsChanged) {
523
+ try {
524
+ const remote = await this.http.call(() => this.transport.updateAgent(agentId, agent), { idempotent: false });
525
+ rec = settingsToRecord(
526
+ remote.agentId,
527
+ remote.name,
528
+ remote.instructions,
529
+ remote.settings,
530
+ remote.liveVersion ?? null,
531
+ current.createdAt,
532
+ );
533
+ } catch (err) {
534
+ await rollbackBindings();
535
+ if (err instanceof UserError) throw mapUserError(err, opts.pathOf);
536
+ if (err instanceof NotSupportedByServerError) {
537
+ throw new CoreAPIError(err.message, { status: 400, code: "unsupported_by_sarvam" });
538
+ }
539
+ throw err;
540
+ }
541
+ } else {
542
+ rec = clone(current);
543
+ }
544
+
545
+ rec.customApis = managedEntries;
546
+ rec.unmanagedCustomApis = unmanaged;
547
+ return rec;
339
548
  }
340
549
 
341
550
  async list(offset = 0, limit = 20): Promise<[AgentRecord[], boolean]> {
@@ -411,10 +620,18 @@ export class Agents {
411
620
  }
412
621
 
413
622
  async ensureInline(spec: AgentSpec, opts: { pathOf?: (field: string) => string } = {}): Promise<AgentRecord> {
623
+ const sarvamCfg = spec.sarvam ?? {};
624
+ let resolvedCas: CustomApiInfo[] = [];
625
+ if ("custom_apis" in sarvamCfg && sarvamCfg["custom_apis"] !== null && sarvamCfg["custom_apis"] !== undefined) {
626
+ const refs = validateCustomApiRefs(sarvamCfg["custom_apis"]);
627
+ resolvedCas = await this.customApis.resolveRefs(refs);
628
+ }
629
+ const managedEntries = customApiEntries(resolvedCas);
630
+
414
631
  const resolved = await this.models.resolve(spec.model);
415
632
  const temp = clone(spec);
416
633
  if (!temp.requestedModel) temp.requestedModel = resolved.requested;
417
- const tempSettings = specToSettings(temp, resolved.sarvamId);
634
+ const tempSettings = specToSettings(temp, resolved.sarvamId, undefined, managedEntries);
418
635
  const fp = settingsFingerprint(temp.instructions, tempSettings);
419
636
  temp.name = inlineAgentName(fp);
420
637
  const key = temp.name;
@@ -424,8 +641,20 @@ export class Agents {
424
641
 
425
642
  const promise = (async () => {
426
643
  const existing = await this.findInlineByName(key);
427
- if (existing) return existing;
428
- return this.create(temp, opts);
644
+ if (existing) {
645
+ if (resolvedCas.length > 0) {
646
+ const live = await this.customApis.listForAgent(existing.id);
647
+ const liveIds = new Set(live.map((i) => i.id).filter(Boolean));
648
+ for (const ca of resolvedCas) {
649
+ if (!liveIds.has(ca.id)) {
650
+ await this.customApis.bind(existing.id, ca.id);
651
+ }
652
+ }
653
+ existing.customApis = managedEntries;
654
+ }
655
+ return existing;
656
+ }
657
+ return this.create(temp, { ...opts, _resolvedCustomApis: resolvedCas });
429
658
  })();
430
659
  this.inlineInflight.set(key, promise);
431
660
  try {