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,7 @@ 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 { CustomApis, validateCustomApiRefs, } from "./customApis.js";
7
8
  import { CoreAPIError } from "./errors.js";
8
9
  import { inlineAgentName } from "./ids.js";
9
10
  import { refuse } from "./refusals.js";
@@ -24,7 +25,31 @@ const ALLOWED_SARVAM_KEYS = new Set([
24
25
  "knowledge_bases",
25
26
  "clarify",
26
27
  "apps",
28
+ "custom_apis",
27
29
  ]);
30
+ function customApiEntries(infos) {
31
+ return infos.map((c) => ({ id: c.id, name: c.name, host: c.host }));
32
+ }
33
+ function readManagedCustomApis(settings) {
34
+ if (!settings)
35
+ return [];
36
+ const rawMeta = isObj(settings["metadata"]) ? settings["metadata"] : {};
37
+ const compat = isObj(rawMeta["sdk_compat"]) ? rawMeta["sdk_compat"] : {};
38
+ const rawList = compat["custom_apis"];
39
+ if (!Array.isArray(rawList))
40
+ return [];
41
+ const out = [];
42
+ for (const item of rawList) {
43
+ if (isObj(item) && typeof item["id"] === "string" && item["id"]) {
44
+ out.push({
45
+ id: item["id"],
46
+ name: typeof item["name"] === "string" ? item["name"] : "",
47
+ host: item["host"] !== undefined && item["host"] !== null ? String(item["host"]) : null,
48
+ });
49
+ }
50
+ }
51
+ return out;
52
+ }
28
53
  function isObj(v) {
29
54
  return v !== null && typeof v === "object" && !Array.isArray(v);
30
55
  }
@@ -55,7 +80,7 @@ function validateSarvamKeys(sarvam, provider) {
55
80
  }
56
81
  }
57
82
  }
58
- function specToSettings(spec, sarvamModel, baseSettings) {
83
+ function specToSettings(spec, sarvamModel, baseSettings, managedCustomApis) {
59
84
  var _a, _b, _c;
60
85
  validateSarvamKeys((_a = spec.sarvam) !== null && _a !== void 0 ? _a : {}, spec.provider);
61
86
  // Preserve unmapped settings & non-sdk_compat metadata from baseSettings.
@@ -98,6 +123,8 @@ function specToSettings(spec, sarvamModel, baseSettings) {
98
123
  else
99
124
  delete out["output_schema"];
100
125
  for (const [k, v] of Object.entries((_b = spec.sarvam) !== null && _b !== void 0 ? _b : {})) {
126
+ if (k === "custom_apis")
127
+ continue;
101
128
  if (v === undefined)
102
129
  continue;
103
130
  if (v === null) {
@@ -126,6 +153,20 @@ function specToSettings(spec, sarvamModel, baseSettings) {
126
153
  compatMeta["reasoning_summary"] = spec.reasoningSummary;
127
154
  if (spec.outputSchemaName !== undefined && spec.outputSchemaName !== null)
128
155
  compatMeta["output_schema_name"] = spec.outputSchemaName;
156
+ const effectiveCustomApis = managedCustomApis !== undefined && managedCustomApis !== null
157
+ ? managedCustomApis
158
+ : readManagedCustomApis(baseSettings);
159
+ if (effectiveCustomApis.length > 0) {
160
+ // Panja rejects null values inside agent.json, so omit keys whose value is null/undefined.
161
+ compatMeta["custom_apis"] = effectiveCustomApis.map((entry) => {
162
+ const cleaned = {};
163
+ for (const [k, v] of Object.entries(entry)) {
164
+ if (v !== null && v !== undefined)
165
+ cleaned[k] = clone(v);
166
+ }
167
+ return cleaned;
168
+ });
169
+ }
129
170
  const existingMeta = isObj(out["metadata"]) ? clone(out["metadata"]) : {};
130
171
  delete existingMeta["sdk_name"];
131
172
  delete existingMeta["sdk_hash"];
@@ -164,22 +205,33 @@ function settingsToRecord(id, name, instructions, settings, version, createdAt)
164
205
  multiAgentEnabled,
165
206
  archived,
166
207
  };
167
- return { id, spec, version, createdAt, archived, sarvamModel, rawSettings: clone(settings) };
208
+ return {
209
+ id,
210
+ spec,
211
+ version,
212
+ createdAt,
213
+ archived,
214
+ sarvamModel,
215
+ rawSettings: clone(settings),
216
+ customApis: readManagedCustomApis(settings),
217
+ unmanagedCustomApis: [],
218
+ };
168
219
  }
169
220
  export class Agents {
170
- constructor(http, models) {
221
+ constructor(http, models, customApis) {
171
222
  this.http = http;
172
223
  this.models = models;
173
224
  this.inlineInflight = new Map();
174
225
  this.transport = new SettingsTransport(http.sdkConfig);
175
226
  this.api = new AgentsApi(http.sdkConfig);
227
+ this.customApis = customApis !== null && customApis !== void 0 ? customApis : new CustomApis(http);
176
228
  }
177
- async buildRaw(spec, pathOf, baseSettings) {
229
+ async buildRaw(spec, pathOf, baseSettings, managedCustomApis) {
178
230
  const resolved = await this.models.resolve(spec.model);
179
231
  const effective = clone(spec);
180
232
  if (!effective.requestedModel)
181
233
  effective.requestedModel = resolved.requested;
182
- const settings = specToSettings(effective, resolved.sarvamId, baseSettings);
234
+ const settings = specToSettings(effective, resolved.sarvamId, baseSettings, managedCustomApis);
183
235
  try {
184
236
  return { agent: rawAgent(effective.name, effective.instructions, settings), sarvamModel: resolved.sarvamId };
185
237
  }
@@ -190,11 +242,21 @@ export class Agents {
190
242
  }
191
243
  }
192
244
  async create(spec, opts = {}) {
193
- var _a;
194
- const { agent } = await this.buildRaw(spec, opts.pathOf);
245
+ var _a, _b;
246
+ const sarvamCfg = (_a = spec.sarvam) !== null && _a !== void 0 ? _a : {};
247
+ let resolvedCas = [];
248
+ if (opts._resolvedCustomApis !== undefined) {
249
+ resolvedCas = [...opts._resolvedCustomApis];
250
+ }
251
+ else if ("custom_apis" in sarvamCfg && sarvamCfg["custom_apis"] !== null && sarvamCfg["custom_apis"] !== undefined) {
252
+ const refs = validateCustomApiRefs(sarvamCfg["custom_apis"]);
253
+ resolvedCas = await this.customApis.resolveRefs(refs);
254
+ }
255
+ const managedEntries = customApiEntries(resolvedCas);
256
+ const { agent } = await this.buildRaw(spec, opts.pathOf, undefined, managedEntries);
257
+ let remote;
195
258
  try {
196
- const remote = await this.http.call(() => this.transport.createAgent(agent), { idempotent: false });
197
- return settingsToRecord(remote.agentId, remote.name, remote.instructions, remote.settings, (_a = remote.liveVersion) !== null && _a !== void 0 ? _a : null, iso(remote.createdAt));
259
+ remote = await this.http.call(() => this.transport.createAgent(agent), { idempotent: false });
198
260
  }
199
261
  catch (err) {
200
262
  if (err instanceof UserError)
@@ -204,13 +266,40 @@ export class Agents {
204
266
  }
205
267
  throw err;
206
268
  }
269
+ if (resolvedCas.length > 0) {
270
+ try {
271
+ for (const ca of resolvedCas) {
272
+ await this.customApis.bind(remote.agentId, ca.id);
273
+ }
274
+ }
275
+ catch (err) {
276
+ try {
277
+ await this.http.call(() => this.transport.deleteAgent(remote.agentId), { idempotent: true });
278
+ }
279
+ catch (_c) {
280
+ // Best-effort cleanup of half-created agent.
281
+ }
282
+ throw err;
283
+ }
284
+ }
285
+ const rec = settingsToRecord(remote.agentId, remote.name, remote.instructions, remote.settings, (_b = remote.liveVersion) !== null && _b !== void 0 ? _b : null, iso(remote.createdAt));
286
+ if (managedEntries.length > 0) {
287
+ rec.customApis = managedEntries;
288
+ }
289
+ return rec;
207
290
  }
208
291
  async retrieve(agentId) {
209
292
  var _a;
210
- const [resource, instr] = await Promise.all([
211
- this.http.call(() => this.api.getAgent({ agentId }), { idempotent: true }),
212
- this.http.call(() => this.api.getInstructions({ agentId }), { idempotent: true }),
213
- ]);
293
+ const resource = await this.http.call(() => this.api.getAgent({ agentId }), { idempotent: true });
294
+ let liveCustomApis = null;
295
+ try {
296
+ liveCustomApis = await this.customApis.listForAgent(agentId);
297
+ }
298
+ catch (err) {
299
+ if (!(err instanceof CoreAPIError && err.status === 404))
300
+ throw err;
301
+ }
302
+ const instr = await this.http.call(() => this.api.getInstructions({ agentId }), { idempotent: true });
214
303
  let settings = isObj(resource.settings) ? { ...resource.settings } : {};
215
304
  if (Object.keys(settings).length === 0) {
216
305
  try {
@@ -222,10 +311,24 @@ export class Agents {
222
311
  throw err;
223
312
  }
224
313
  }
225
- return settingsToRecord(resource.id, resource.name, instr.data, settings, (_a = resource.liveVersion) !== null && _a !== void 0 ? _a : null, iso(resource.createdAt));
314
+ const rec = settingsToRecord(resource.id, resource.name, instr.data, settings, (_a = resource.liveVersion) !== null && _a !== void 0 ? _a : null, iso(resource.createdAt));
315
+ if (liveCustomApis !== null) {
316
+ const liveById = new Map();
317
+ for (const item of liveCustomApis) {
318
+ if (item.id)
319
+ liveById.set(item.id, item);
320
+ }
321
+ const managedIds = rec.customApis.map((c) => c.id).filter(Boolean);
322
+ const managedSet = new Set(managedIds);
323
+ rec.customApis = managedIds
324
+ .map((cid) => liveById.get(cid))
325
+ .filter((x) => x !== undefined);
326
+ rec.unmanagedCustomApis = liveCustomApis.filter((item) => !managedSet.has(item.id));
327
+ }
328
+ return rec;
226
329
  }
227
330
  async update(agentId, change, opts = {}) {
228
- var _a;
331
+ var _a, _b, _c;
229
332
  const current = await this.retrieve(agentId);
230
333
  if (current.archived) {
231
334
  throw new CoreAPIError(`Cannot update archived agent ${agentId}.`, {
@@ -239,24 +342,112 @@ export class Agents {
239
342
  throw new CoreAPIError(`Agent ${agentId} is at version ${current.version}, expected ${opts.expectedVersion}`, { status: 409, code: "version_conflict" });
240
343
  }
241
344
  }
345
+ const prevManaged = readManagedCustomApis(current.rawSettings);
242
346
  const updatedSpec = change(clone(current.spec));
243
- const { agent } = await this.buildRaw(updatedSpec, opts.pathOf, current.rawSettings);
347
+ const sarvamCfg = (_a = updatedSpec.sarvam) !== null && _a !== void 0 ? _a : {};
348
+ const customApisSpecified = "custom_apis" in sarvamCfg;
349
+ if (!customApisSpecified) {
350
+ const { agent } = await this.buildRaw(updatedSpec, opts.pathOf, current.rawSettings);
351
+ const currentHash = settingsFingerprint(current.spec.instructions, current.rawSettings);
352
+ if (updatedSpec.name === current.spec.name && agent.specHash() === currentHash) {
353
+ return current;
354
+ }
355
+ try {
356
+ const remote = await this.http.call(() => this.transport.updateAgent(agentId, agent), { idempotent: false });
357
+ const rec = settingsToRecord(remote.agentId, remote.name, remote.instructions, remote.settings, (_b = remote.liveVersion) !== null && _b !== void 0 ? _b : null, current.createdAt);
358
+ rec.customApis = [...current.customApis];
359
+ rec.unmanagedCustomApis = [...current.unmanagedCustomApis];
360
+ return rec;
361
+ }
362
+ catch (err) {
363
+ if (err instanceof UserError)
364
+ throw mapUserError(err, opts.pathOf);
365
+ if (err instanceof NotSupportedByServerError) {
366
+ throw new CoreAPIError(err.message, { status: 400, code: "unsupported_by_sarvam" });
367
+ }
368
+ throw err;
369
+ }
370
+ }
371
+ const rawRefs = sarvamCfg["custom_apis"];
372
+ let resolvedCas = [];
373
+ if (rawRefs !== null && rawRefs !== undefined) {
374
+ const refs = validateCustomApiRefs(rawRefs);
375
+ resolvedCas = await this.customApis.resolveRefs(refs);
376
+ }
377
+ const managedEntries = customApiEntries(resolvedCas);
378
+ const { agent } = await this.buildRaw(updatedSpec, opts.pathOf, current.rawSettings, managedEntries);
379
+ const live = await this.customApis.listForAgent(agentId);
380
+ const liveIds = new Set(live.map((i) => i.id).filter(Boolean));
381
+ const prevManagedIds = prevManaged.map((i) => i.id).filter(Boolean);
382
+ const prevManagedSet = new Set(prevManagedIds);
383
+ const targetIds = resolvedCas.map((c) => c.id);
384
+ const targetSet = new Set(targetIds);
385
+ const toBind = targetIds.filter((cid) => !liveIds.has(cid));
386
+ const toUnbind = prevManagedIds.filter((cid) => !targetSet.has(cid) && liveIds.has(cid));
387
+ const unmanaged = live.filter((item) => !targetSet.has(item.id) && !prevManagedSet.has(item.id));
244
388
  const currentHash = settingsFingerprint(current.spec.instructions, current.rawSettings);
245
- if (updatedSpec.name === current.spec.name && agent.specHash() === currentHash) {
389
+ const settingsChanged = updatedSpec.name !== current.spec.name || agent.specHash() !== currentHash;
390
+ if (!settingsChanged && toBind.length === 0 && toUnbind.length === 0) {
391
+ current.customApis = managedEntries;
392
+ current.unmanagedCustomApis = unmanaged;
246
393
  return current;
247
394
  }
395
+ const boundNow = [];
396
+ const unboundNow = [];
397
+ const rollbackBindings = async () => {
398
+ for (const cid of boundNow) {
399
+ try {
400
+ await this.customApis.unbind(agentId, cid);
401
+ }
402
+ catch (_a) {
403
+ // Best-effort rollback of newly added binds.
404
+ }
405
+ }
406
+ for (const cid of unboundNow) {
407
+ try {
408
+ await this.customApis.bind(agentId, cid);
409
+ }
410
+ catch (_b) {
411
+ // Best-effort rollback of newly removed binds.
412
+ }
413
+ }
414
+ };
248
415
  try {
249
- const remote = await this.http.call(() => this.transport.updateAgent(agentId, agent), { idempotent: false });
250
- return settingsToRecord(remote.agentId, remote.name, remote.instructions, remote.settings, (_a = remote.liveVersion) !== null && _a !== void 0 ? _a : null, current.createdAt);
416
+ for (const cid of toUnbind) {
417
+ await this.customApis.unbind(agentId, cid);
418
+ unboundNow.push(cid);
419
+ }
420
+ for (const cid of toBind) {
421
+ await this.customApis.bind(agentId, cid);
422
+ boundNow.push(cid);
423
+ }
251
424
  }
252
425
  catch (err) {
253
- if (err instanceof UserError)
254
- throw mapUserError(err, opts.pathOf);
255
- if (err instanceof NotSupportedByServerError) {
256
- throw new CoreAPIError(err.message, { status: 400, code: "unsupported_by_sarvam" });
257
- }
426
+ await rollbackBindings();
258
427
  throw err;
259
428
  }
429
+ let rec;
430
+ if (settingsChanged) {
431
+ try {
432
+ const remote = await this.http.call(() => this.transport.updateAgent(agentId, agent), { idempotent: false });
433
+ rec = settingsToRecord(remote.agentId, remote.name, remote.instructions, remote.settings, (_c = remote.liveVersion) !== null && _c !== void 0 ? _c : null, current.createdAt);
434
+ }
435
+ catch (err) {
436
+ await rollbackBindings();
437
+ if (err instanceof UserError)
438
+ throw mapUserError(err, opts.pathOf);
439
+ if (err instanceof NotSupportedByServerError) {
440
+ throw new CoreAPIError(err.message, { status: 400, code: "unsupported_by_sarvam" });
441
+ }
442
+ throw err;
443
+ }
444
+ }
445
+ else {
446
+ rec = clone(current);
447
+ }
448
+ rec.customApis = managedEntries;
449
+ rec.unmanagedCustomApis = unmanaged;
450
+ return rec;
260
451
  }
261
452
  async list(offset = 0, limit = 20) {
262
453
  var _a;
@@ -306,11 +497,19 @@ export class Agents {
306
497
  return settingsToRecord(chosen.id, chosen.name, chosen.instructions, chosen.settings, chosen.version, chosen.createdAt);
307
498
  }
308
499
  async ensureInline(spec, opts = {}) {
500
+ var _a;
501
+ const sarvamCfg = (_a = spec.sarvam) !== null && _a !== void 0 ? _a : {};
502
+ let resolvedCas = [];
503
+ if ("custom_apis" in sarvamCfg && sarvamCfg["custom_apis"] !== null && sarvamCfg["custom_apis"] !== undefined) {
504
+ const refs = validateCustomApiRefs(sarvamCfg["custom_apis"]);
505
+ resolvedCas = await this.customApis.resolveRefs(refs);
506
+ }
507
+ const managedEntries = customApiEntries(resolvedCas);
309
508
  const resolved = await this.models.resolve(spec.model);
310
509
  const temp = clone(spec);
311
510
  if (!temp.requestedModel)
312
511
  temp.requestedModel = resolved.requested;
313
- const tempSettings = specToSettings(temp, resolved.sarvamId);
512
+ const tempSettings = specToSettings(temp, resolved.sarvamId, undefined, managedEntries);
314
513
  const fp = settingsFingerprint(temp.instructions, tempSettings);
315
514
  temp.name = inlineAgentName(fp);
316
515
  const key = temp.name;
@@ -319,9 +518,20 @@ export class Agents {
319
518
  return inflight;
320
519
  const promise = (async () => {
321
520
  const existing = await this.findInlineByName(key);
322
- if (existing)
521
+ if (existing) {
522
+ if (resolvedCas.length > 0) {
523
+ const live = await this.customApis.listForAgent(existing.id);
524
+ const liveIds = new Set(live.map((i) => i.id).filter(Boolean));
525
+ for (const ca of resolvedCas) {
526
+ if (!liveIds.has(ca.id)) {
527
+ await this.customApis.bind(existing.id, ca.id);
528
+ }
529
+ }
530
+ existing.customApis = managedEntries;
531
+ }
323
532
  return existing;
324
- return this.create(temp, opts);
533
+ }
534
+ return this.create(temp, { ...opts, _resolvedCustomApis: resolvedCas });
325
535
  })();
326
536
  this.inlineInflight.set(key, promise);
327
537
  try {
@@ -0,0 +1,76 @@
1
+ import { Http } from "./http.js";
2
+ export interface CustomApiAttachedAgent {
3
+ readonly id: string;
4
+ readonly name: string;
5
+ }
6
+ export interface CustomApiAgentEntry {
7
+ readonly id: string;
8
+ readonly name: string;
9
+ readonly host: string | null;
10
+ }
11
+ export interface CustomApiInfo {
12
+ readonly id: string;
13
+ readonly name: string;
14
+ readonly description: string;
15
+ readonly host: string;
16
+ readonly authType: string;
17
+ readonly headerNames: readonly string[];
18
+ readonly enabledForChats: boolean;
19
+ readonly agents: readonly CustomApiAttachedAgent[];
20
+ readonly createdAt: string;
21
+ readonly credentialsUpdatedAt: string;
22
+ readonly enabledForChatsError: string | null;
23
+ }
24
+ export interface CustomApiHeaderInput {
25
+ name: string;
26
+ value?: string | null;
27
+ previousName?: string | null;
28
+ previous_name?: string | null;
29
+ }
30
+ export type CustomApiAuthInput = {
31
+ type: "bearer";
32
+ token: string;
33
+ } | {
34
+ type: "basic";
35
+ username: string;
36
+ password: string;
37
+ } | {
38
+ type: "headers";
39
+ headers: CustomApiHeaderInput[] | Record<string, string | null>;
40
+ };
41
+ export interface CustomApiCreateParams {
42
+ name: string;
43
+ host: string;
44
+ auth: CustomApiAuthInput;
45
+ description?: string | null;
46
+ enabledForChats?: boolean;
47
+ enabled_for_chats?: boolean;
48
+ }
49
+ export interface CustomApiUpdateParams {
50
+ name?: string;
51
+ description?: string | null;
52
+ host?: string;
53
+ auth?: CustomApiAuthInput;
54
+ enabledForChats?: boolean;
55
+ enabled_for_chats?: boolean;
56
+ }
57
+ export declare function validateCustomApiRefs(refs: unknown, param?: string): string[];
58
+ export declare class CustomApis {
59
+ private readonly http;
60
+ private readonly api;
61
+ constructor(http: Http);
62
+ list(opts?: {
63
+ q?: string;
64
+ }): Promise<CustomApiInfo[]>;
65
+ get(customApiId: string): Promise<CustomApiInfo>;
66
+ retrieve(customApiId: string): Promise<CustomApiInfo>;
67
+ create(params: CustomApiCreateParams): Promise<CustomApiInfo>;
68
+ update(customApiId: string, params: CustomApiUpdateParams): Promise<CustomApiInfo>;
69
+ delete(customApiId: string, opts?: {
70
+ force?: boolean;
71
+ }): Promise<void>;
72
+ listForAgent(agentId: string): Promise<CustomApiAgentEntry[]>;
73
+ bind(agentId: string, customApiId: string): Promise<void>;
74
+ unbind(agentId: string, customApiId: string): Promise<void>;
75
+ resolveRefs(refs: readonly string[], paramPrefix?: string): Promise<CustomApiInfo[]>;
76
+ }