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
@@ -0,0 +1,419 @@
1
+ /** Core Custom APIs service: CRUD, validation, resolution, and agent bindings. */
2
+ import { CustomAPIsApi } from "../../apis/CustomAPIsApi.js";
3
+ import { CoreAPIError } from "./errors.js";
4
+ const PAGE_LIMIT = 100;
5
+ const MAX_PAGES = 50;
6
+ const MAX_NAME_LEN = 256;
7
+ const MAX_DESC_LEN = 200;
8
+ const MAX_HOST_LEN = 253;
9
+ const MAX_SECRET_LEN = 8192;
10
+ const MAX_HEADERS = 16;
11
+ function isObj(v) {
12
+ return v !== null && typeof v === "object" && !Array.isArray(v);
13
+ }
14
+ function asRecord(v) {
15
+ return isObj(v) ? v : {};
16
+ }
17
+ function isoStr(v) {
18
+ if (v instanceof Date)
19
+ return v.toISOString();
20
+ if (typeof v === "string")
21
+ return v;
22
+ return "";
23
+ }
24
+ function badReq(message, param, code = "invalid_request_error") {
25
+ return new CoreAPIError(message, { status: 400, code, param: param !== null && param !== void 0 ? param : null });
26
+ }
27
+ function infoFromModel(raw) {
28
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j;
29
+ const d = asRecord(raw);
30
+ const agentsRaw = Array.isArray(d["agents"]) ? d["agents"] : [];
31
+ const agents = agentsRaw.map((a) => {
32
+ var _a, _b;
33
+ const ar = asRecord(a);
34
+ return Object.freeze({ id: String((_a = ar["id"]) !== null && _a !== void 0 ? _a : ""), name: String((_b = ar["name"]) !== null && _b !== void 0 ? _b : "") });
35
+ });
36
+ const headerNamesRaw = Array.isArray(d["headerNames"])
37
+ ? d["headerNames"]
38
+ : (Array.isArray(d["header_names"]) ? d["header_names"] : []);
39
+ const enabledRaw = "enabledForChats" in d
40
+ ? d["enabledForChats"]
41
+ : ("enabled_for_chats" in d ? d["enabled_for_chats"] : true);
42
+ const errRaw = (_a = d["enabledForChatsError"]) !== null && _a !== void 0 ? _a : d["enabled_for_chats_error"];
43
+ return Object.freeze({
44
+ id: String((_b = d["id"]) !== null && _b !== void 0 ? _b : ""),
45
+ name: String((_c = d["name"]) !== null && _c !== void 0 ? _c : ""),
46
+ description: String((_d = d["description"]) !== null && _d !== void 0 ? _d : ""),
47
+ host: String((_e = d["host"]) !== null && _e !== void 0 ? _e : ""),
48
+ authType: String((_g = (_f = d["authType"]) !== null && _f !== void 0 ? _f : d["auth_type"]) !== null && _g !== void 0 ? _g : ""),
49
+ headerNames: Object.freeze(headerNamesRaw.map((h) => String(h))),
50
+ enabledForChats: Boolean(enabledRaw),
51
+ agents: Object.freeze(agents),
52
+ createdAt: isoStr((_h = d["createdAt"]) !== null && _h !== void 0 ? _h : d["created_at"]),
53
+ credentialsUpdatedAt: isoStr((_j = d["credentialsUpdatedAt"]) !== null && _j !== void 0 ? _j : d["credentials_updated_at"]),
54
+ enabledForChatsError: errRaw !== undefined && errRaw !== null ? String(errRaw) : null,
55
+ });
56
+ }
57
+ function validateName(name, param = "name") {
58
+ if (typeof name !== "string" || !name.trim()) {
59
+ throw badReq("name must be a non-empty string.", param);
60
+ }
61
+ if (name.length > MAX_NAME_LEN) {
62
+ throw badReq(`name must be at most ${MAX_NAME_LEN} characters.`, param);
63
+ }
64
+ return name;
65
+ }
66
+ function validateDescription(description, param = "description") {
67
+ if (description === undefined || description === null)
68
+ return null;
69
+ if (typeof description !== "string") {
70
+ throw badReq("description must be a string or null.", param);
71
+ }
72
+ if (description.length > MAX_DESC_LEN) {
73
+ throw badReq(`description must be at most ${MAX_DESC_LEN} characters.`, param);
74
+ }
75
+ return description;
76
+ }
77
+ function validateHost(host, param = "host") {
78
+ if (typeof host !== "string" || !host.trim()) {
79
+ throw badReq("host must be a non-empty hostname (for example 'api.acme.com').", param);
80
+ }
81
+ const trimmed = host.trim();
82
+ if (trimmed.length > MAX_HOST_LEN) {
83
+ throw badReq(`host must be at most ${MAX_HOST_LEN} characters.`, param);
84
+ }
85
+ if (trimmed.includes("://")) {
86
+ throw badReq("host must be a bare hostname without scheme (for example 'api.acme.com', not a full URL).", param);
87
+ }
88
+ if (/\s/.test(trimmed) || trimmed.includes("/") || trimmed.includes("?") || trimmed.includes("#")) {
89
+ throw badReq("host must be a bare hostname without path, query, or whitespace.", param);
90
+ }
91
+ return trimmed;
92
+ }
93
+ function buildAuth(auth, forUpdate, param = "auth") {
94
+ if (!isObj(auth)) {
95
+ throw badReq("auth must be an object with type 'bearer', 'basic', or 'headers'.", param);
96
+ }
97
+ const atype = auth["type"];
98
+ if (atype === "bearer") {
99
+ const extra = Object.keys(auth).filter((k) => k !== "type" && k !== "token");
100
+ if (extra.length > 0) {
101
+ throw badReq(`Unknown bearer auth key ${JSON.stringify(extra[0])}.`, `${param}.${extra[0]}`);
102
+ }
103
+ const token = auth["token"];
104
+ if (typeof token !== "string" || !token) {
105
+ throw badReq("bearer auth requires a non-empty token string.", `${param}.token`);
106
+ }
107
+ if (token.length > MAX_SECRET_LEN) {
108
+ throw badReq(`bearer token exceeds maximum length of ${MAX_SECRET_LEN}.`, `${param}.token`);
109
+ }
110
+ return { type: "bearer", token };
111
+ }
112
+ if (atype === "basic") {
113
+ const extra = Object.keys(auth).filter((k) => k !== "type" && k !== "username" && k !== "password");
114
+ if (extra.length > 0) {
115
+ throw badReq(`Unknown basic auth key ${JSON.stringify(extra[0])}.`, `${param}.${extra[0]}`);
116
+ }
117
+ const username = auth["username"];
118
+ const password = auth["password"];
119
+ if (typeof username !== "string" || !username) {
120
+ throw badReq("basic auth requires a non-empty username string.", `${param}.username`);
121
+ }
122
+ if (typeof password !== "string" || !password) {
123
+ throw badReq("basic auth requires a non-empty password string.", `${param}.password`);
124
+ }
125
+ if (password.length > MAX_SECRET_LEN) {
126
+ throw badReq(`basic password exceeds maximum length of ${MAX_SECRET_LEN}.`, `${param}.password`);
127
+ }
128
+ return { type: "basic", username, password };
129
+ }
130
+ if (atype === "headers") {
131
+ const extra = Object.keys(auth).filter((k) => k !== "type" && k !== "headers");
132
+ if (extra.length > 0) {
133
+ throw badReq(`Unknown headers auth key ${JSON.stringify(extra[0])}.`, `${param}.${extra[0]}`);
134
+ }
135
+ const rawHeaders = auth["headers"];
136
+ const parsed = [];
137
+ if (isObj(rawHeaders)) {
138
+ for (const [k, v] of Object.entries(rawHeaders)) {
139
+ if (typeof k !== "string" || !k.trim()) {
140
+ throw badReq("Header name must be a non-empty string.", `${param}.headers`);
141
+ }
142
+ if (v === null || v === undefined) {
143
+ if (!forUpdate) {
144
+ throw badReq(`Header ${JSON.stringify(k)} requires a non-empty value on create.`, `${param}.headers`);
145
+ }
146
+ parsed.push({ name: k });
147
+ }
148
+ else if (typeof v !== "string" || !v) {
149
+ throw badReq(`Header ${JSON.stringify(k)} value must be a non-empty string.`, `${param}.headers`);
150
+ }
151
+ else if (v.length > MAX_SECRET_LEN) {
152
+ throw badReq(`Header ${JSON.stringify(k)} value exceeds maximum length of ${MAX_SECRET_LEN}.`, `${param}.headers`);
153
+ }
154
+ else {
155
+ parsed.push({ name: k, value: v });
156
+ }
157
+ }
158
+ }
159
+ else if (Array.isArray(rawHeaders)) {
160
+ for (let i = 0; i < rawHeaders.length; i++) {
161
+ const item = rawHeaders[i];
162
+ const itemParam = `${param}.headers[${i}]`;
163
+ if (!isObj(item)) {
164
+ throw badReq("Each header entry must be an object with 'name' and 'value'.", itemParam);
165
+ }
166
+ const badKeys = Object.keys(item).filter((k) => k !== "name" && k !== "value" && k !== "previousName" && k !== "previous_name");
167
+ if (badKeys.length > 0) {
168
+ throw badReq(`Unknown header key ${JSON.stringify(badKeys[0])}.`, `${itemParam}.${badKeys[0]}`);
169
+ }
170
+ const hname = item["name"];
171
+ if (typeof hname !== "string" || !hname.trim()) {
172
+ throw badReq("Header name must be a non-empty string.", `${itemParam}.name`);
173
+ }
174
+ const hval = item["value"];
175
+ const prevName = "previousName" in item ? item["previousName"] : item["previous_name"];
176
+ if (prevName !== undefined && prevName !== null && (typeof prevName !== "string" || !prevName.trim())) {
177
+ throw badReq("previousName must be a non-empty string or null.", `${itemParam}.previousName`);
178
+ }
179
+ if (hval === undefined || hval === null) {
180
+ if (!forUpdate) {
181
+ throw badReq(`Header ${JSON.stringify(hname)} requires a non-empty value on create.`, `${itemParam}.value`);
182
+ }
183
+ const entry = { name: hname };
184
+ if (typeof prevName === "string")
185
+ entry.previousName = prevName;
186
+ parsed.push(entry);
187
+ }
188
+ else {
189
+ if (typeof hval !== "string" || !hval) {
190
+ throw badReq(`Header ${JSON.stringify(hname)} value must be a non-empty string.`, `${itemParam}.value`);
191
+ }
192
+ if (hval.length > MAX_SECRET_LEN) {
193
+ throw badReq(`Header ${JSON.stringify(hname)} value exceeds maximum length of ${MAX_SECRET_LEN}.`, `${itemParam}.value`);
194
+ }
195
+ const entry = { name: hname, value: hval };
196
+ if (typeof prevName === "string")
197
+ entry.previousName = prevName;
198
+ parsed.push(entry);
199
+ }
200
+ }
201
+ }
202
+ else {
203
+ throw badReq("headers auth requires 'headers' as a non-empty list or name->value mapping.", `${param}.headers`);
204
+ }
205
+ if (parsed.length === 0 || parsed.length > MAX_HEADERS) {
206
+ throw badReq(`headers auth requires between 1 and ${MAX_HEADERS} headers.`, `${param}.headers`);
207
+ }
208
+ return { type: "headers", headers: parsed };
209
+ }
210
+ throw badReq("auth.type must be 'bearer', 'basic', or 'headers'.", `${param}.type`);
211
+ }
212
+ export function validateCustomApiRefs(refs, param = "sarvam_config.custom_apis") {
213
+ if (!Array.isArray(refs)) {
214
+ throw badReq("sarvam_config.custom_apis must be a list of custom API IDs or names.", param);
215
+ }
216
+ const out = [];
217
+ for (let i = 0; i < refs.length; i++) {
218
+ const ref = refs[i];
219
+ if (typeof ref !== "string" || !ref.trim()) {
220
+ throw badReq("Each entry in sarvam_config.custom_apis must be a non-empty string.", `${param}[${i}]`);
221
+ }
222
+ out.push(ref.trim());
223
+ }
224
+ return out;
225
+ }
226
+ export class CustomApis {
227
+ constructor(http) {
228
+ this.http = http;
229
+ this.api = new CustomAPIsApi(http.sdkConfig);
230
+ }
231
+ async list(opts = {}) {
232
+ const rows = [];
233
+ const seenIds = new Set();
234
+ let offset = 0;
235
+ for (let pages = 0; pages < MAX_PAGES; pages += 1) {
236
+ const off = offset;
237
+ const page = await this.http.call(() => this.api.listCustomApis({
238
+ ...(opts.q !== undefined ? { q: opts.q } : {}),
239
+ limit: PAGE_LIMIT,
240
+ offset: off,
241
+ }), { idempotent: true });
242
+ const d = asRecord(page);
243
+ const items = Array.isArray(d["data"]) ? d["data"] : [];
244
+ for (const item of items) {
245
+ const info = infoFromModel(item);
246
+ if (info.id && seenIds.has(info.id))
247
+ continue;
248
+ if (info.id)
249
+ seenIds.add(info.id);
250
+ rows.push(info);
251
+ }
252
+ const hasMore = Boolean(d["hasMore"]);
253
+ if (items.length === 0 || !hasMore)
254
+ break;
255
+ offset += items.length;
256
+ }
257
+ return rows;
258
+ }
259
+ async get(customApiId) {
260
+ if (typeof customApiId !== "string" || !customApiId.trim()) {
261
+ throw badReq("customApiId must be a non-empty string.", "custom_api_id");
262
+ }
263
+ const raw = await this.http.call(() => this.api.getCustomApi({ customApiId }), { idempotent: true });
264
+ return infoFromModel(raw);
265
+ }
266
+ async retrieve(customApiId) {
267
+ return this.get(customApiId);
268
+ }
269
+ async create(params) {
270
+ if (!isObj(params)) {
271
+ throw badReq("create params must be an object.");
272
+ }
273
+ const name = validateName(params.name);
274
+ const host = validateHost(params.host);
275
+ const description = validateDescription(params.description);
276
+ const auth = buildAuth(params.auth, false);
277
+ const enabledRaw = params.enabledForChats !== undefined ? params.enabledForChats : params.enabled_for_chats;
278
+ const enabledForChats = enabledRaw === undefined ? true : enabledRaw;
279
+ if (typeof enabledForChats !== "boolean") {
280
+ throw badReq("enabledForChats must be a boolean.", "enabled_for_chats");
281
+ }
282
+ const body = {
283
+ name,
284
+ host,
285
+ auth,
286
+ enabledForChats,
287
+ ...(description !== null ? { description } : {}),
288
+ };
289
+ const raw = await this.http.call(() => this.api.createCustomApi({ customApiCreate: body }), { idempotent: false });
290
+ return infoFromModel(raw);
291
+ }
292
+ async update(customApiId, params) {
293
+ if (typeof customApiId !== "string" || !customApiId.trim()) {
294
+ throw badReq("customApiId must be a non-empty string.", "custom_api_id");
295
+ }
296
+ if (!isObj(params)) {
297
+ throw badReq("update params must be an object.");
298
+ }
299
+ const body = {};
300
+ let hasField = false;
301
+ if (params.name !== undefined) {
302
+ body.name = validateName(params.name);
303
+ hasField = true;
304
+ }
305
+ if (params.description !== undefined) {
306
+ body.description = validateDescription(params.description);
307
+ hasField = true;
308
+ }
309
+ if (params.host !== undefined) {
310
+ body.host = validateHost(params.host);
311
+ hasField = true;
312
+ }
313
+ if (params.auth !== undefined) {
314
+ body.auth = buildAuth(params.auth, true);
315
+ hasField = true;
316
+ }
317
+ const enabledRaw = params.enabledForChats !== undefined ? params.enabledForChats : params.enabled_for_chats;
318
+ if (enabledRaw !== undefined) {
319
+ if (typeof enabledRaw !== "boolean") {
320
+ throw badReq("enabledForChats must be a boolean.", "enabled_for_chats");
321
+ }
322
+ body.enabledForChats = enabledRaw;
323
+ hasField = true;
324
+ }
325
+ if (!hasField) {
326
+ throw badReq("At least one field must be provided to update a custom API.");
327
+ }
328
+ const raw = await this.http.call(() => this.api.updateCustomApi({ customApiId, customApiUpdate: body }), { idempotent: false });
329
+ return infoFromModel(raw);
330
+ }
331
+ async delete(customApiId, opts = {}) {
332
+ if (typeof customApiId !== "string" || !customApiId.trim()) {
333
+ throw badReq("customApiId must be a non-empty string.", "custom_api_id");
334
+ }
335
+ if (!opts.force) {
336
+ const info = await this.get(customApiId);
337
+ if (info.agents.length > 0) {
338
+ const ids = info.agents.map((a) => a.id).filter(Boolean).join(", ");
339
+ throw new CoreAPIError(`Custom API ${JSON.stringify(info.name)} (${info.id}) is attached to ${info.agents.length} agent(s)${ids ? ` (${ids})` : ""}; unbind it first or pass { force: true }.`, { status: 409, code: "custom_api_in_use", param: "custom_api_id" });
340
+ }
341
+ }
342
+ await this.http.call(() => this.api.deleteCustomApi({ customApiId }), { idempotent: true });
343
+ }
344
+ async listForAgent(agentId) {
345
+ if (typeof agentId !== "string" || !agentId.trim()) {
346
+ throw badReq("agentId must be a non-empty string.", "agent_id");
347
+ }
348
+ const resp = await this.http.call(() => this.api.listAgentCustomApis({ agentId }), { idempotent: true });
349
+ const d = asRecord(resp);
350
+ const items = Array.isArray(d["data"]) ? d["data"] : [];
351
+ return items.map((item) => {
352
+ var _a, _b;
353
+ const r = asRecord(item);
354
+ return {
355
+ id: String((_a = r["id"]) !== null && _a !== void 0 ? _a : ""),
356
+ name: String((_b = r["name"]) !== null && _b !== void 0 ? _b : ""),
357
+ host: r["host"] !== undefined && r["host"] !== null ? String(r["host"]) : null,
358
+ };
359
+ });
360
+ }
361
+ async bind(agentId, customApiId) {
362
+ if (typeof agentId !== "string" || !agentId.trim()) {
363
+ throw badReq("agentId must be a non-empty string.", "agent_id");
364
+ }
365
+ if (typeof customApiId !== "string" || !customApiId.trim()) {
366
+ throw badReq("customApiId must be a non-empty string.", "custom_api_id");
367
+ }
368
+ await this.http.call(() => this.api.bindCustomApi({ agentId, bindCustomApiBody: { customApiId } }), { idempotent: true });
369
+ }
370
+ async unbind(agentId, customApiId) {
371
+ if (typeof agentId !== "string" || !agentId.trim()) {
372
+ throw badReq("agentId must be a non-empty string.", "agent_id");
373
+ }
374
+ if (typeof customApiId !== "string" || !customApiId.trim()) {
375
+ throw badReq("customApiId must be a non-empty string.", "custom_api_id");
376
+ }
377
+ await this.http.call(() => this.api.unbindCustomApi({ agentId, customApiId }), { idempotent: true });
378
+ }
379
+ async resolveRefs(refs, paramPrefix = "sarvam_config.custom_apis") {
380
+ var _a, _b;
381
+ const validated = validateCustomApiRefs([...refs], paramPrefix);
382
+ if (validated.length === 0)
383
+ return [];
384
+ const catalog = await this.list();
385
+ const byId = new Map();
386
+ const byName = new Map();
387
+ for (const c of catalog) {
388
+ byId.set(c.id, c);
389
+ const list = (_a = byName.get(c.name)) !== null && _a !== void 0 ? _a : [];
390
+ list.push(c);
391
+ byName.set(c.name, list);
392
+ }
393
+ const resolved = [];
394
+ const seen = new Set();
395
+ for (let idx = 0; idx < validated.length; idx++) {
396
+ const ref = validated[idx];
397
+ const param = `${paramPrefix}[${idx}]`;
398
+ let match = byId.get(ref);
399
+ if (!match) {
400
+ const nameMatches = (_b = byName.get(ref)) !== null && _b !== void 0 ? _b : [];
401
+ if (nameMatches.length === 1) {
402
+ match = nameMatches[0];
403
+ }
404
+ else if (nameMatches.length > 1) {
405
+ const ids = nameMatches.map((m) => m.id).join(", ");
406
+ throw new CoreAPIError(`Custom API name ${JSON.stringify(ref)} matches multiple custom APIs (${ids}); pass the custom API ID instead.`, { status: 409, code: "ambiguous_custom_api", param });
407
+ }
408
+ else {
409
+ throw new CoreAPIError(`Custom API ${JSON.stringify(ref)} was not found. Create it with client.sarvam.customApis.create(...) or check client.sarvam.customApis.list().`, { status: 404, code: "custom_api_not_found", param });
410
+ }
411
+ }
412
+ if (!seen.has(match.id)) {
413
+ seen.add(match.id);
414
+ resolved.push(match);
415
+ }
416
+ }
417
+ return resolved;
418
+ }
419
+ }
@@ -13,7 +13,7 @@ export const REFUSALS = [
13
13
  "path": "environment.vault_ids",
14
14
  "param": "environment.vault_ids",
15
15
  "reason": "OpenAI vaults are not supported",
16
- "hint": "Configure agent apps or custom APIs via sarvam_config={'apps': [...]}.",
16
+ "hint": "Configure agent apps via sarvam_config={'apps': [...]} or custom APIs via sarvam_config={'custom_apis': [...]}.",
17
17
  "needs": null,
18
18
  "feature": "openai.environment.vault_ids"
19
19
  },
@@ -3,6 +3,7 @@ import { SessionUpdateQueue } from "../core/sessions.js";
3
3
  import { ToolResultStore } from "../core/toolResults.js";
4
4
  import { ListenerRegistry } from "../core/turns.js";
5
5
  import { AgentsResource } from "./resources/agents.js";
6
+ import { SarvamResource } from "./resources/sarvam.js";
6
7
  import { SessionsResource } from "./resources/sessions.js";
7
8
  import type { AgentSessionEventStream } from "./stream.js";
8
9
  import type { AgentSession, RawResponse, RequestOptions } from "./types.js";
@@ -44,11 +45,13 @@ export interface RawResponseClient {
44
45
  readonly beta: {
45
46
  readonly agents: RawResponseAgentsResource;
46
47
  };
48
+ readonly sarvam: RawResponseProxy<SarvamResource>;
47
49
  }
48
50
  export declare class OpenAI {
49
51
  readonly beta: {
50
52
  readonly agents: AgentsResource;
51
53
  };
54
+ readonly sarvam: SarvamResource;
52
55
  private readonly initOpts;
53
56
  private readonly http;
54
57
  private readonly listenerRegistry;
@@ -1,5 +1,6 @@
1
1
  /** OpenAI drop-in client (client.beta.agents...) backed by compat/core. */
2
2
  import { Agents } from "../core/agents.js";
3
+ import { CustomApis } from "../core/customApis.js";
3
4
  import { CoreAPIError } from "../core/errors.js";
4
5
  import { AttachmentUploadCache } from "../core/files.js";
5
6
  import { DEFAULT_MAX_RETRIES, DEFAULT_TIMEOUT_MS, Http } from "../core/http.js";
@@ -10,6 +11,7 @@ import { ListenerRegistry, Turns } from "../core/turns.js";
10
11
  import { toOpenAIError } from "./errors.js";
11
12
  import { AgentsResource } from "./resources/agents.js";
12
13
  import { EventsResource, ItemsResource } from "./resources/events.js";
14
+ import { SarvamResource } from "./resources/sarvam.js";
13
15
  import { SessionsResource } from "./resources/sessions.js";
14
16
  function makeRawProxy(target, http) {
15
17
  return new Proxy(target, {
@@ -63,7 +65,8 @@ export class OpenAI {
63
65
  strict: opts.strictModels,
64
66
  provider: "openai",
65
67
  });
66
- const agentsCore = new Agents(this.http, models);
68
+ const customApisCore = new CustomApis(this.http);
69
+ const agentsCore = new Agents(this.http, models, customApisCore);
67
70
  this.sessionUpdateQueue = (_c = opts._sharedSessionQueue) !== null && _c !== void 0 ? _c : new SessionUpdateQueue();
68
71
  const sessionsCore = new Sessions(this.http, { provider: "openai", updateQueue: this.sessionUpdateQueue });
69
72
  this.listenerRegistry = (_d = opts._sharedRegistry) !== null && _d !== void 0 ? _d : new ListenerRegistry();
@@ -83,6 +86,7 @@ export class OpenAI {
83
86
  const sessionsRes = new SessionsResource(this.http, agentsCore, sessionsCore, turnsCore, eventsRes, itemsRes);
84
87
  const agentsRes = new AgentsResource(this.http, agentsCore, sessionsRes);
85
88
  this.beta = { agents: agentsRes };
89
+ this.sarvam = new SarvamResource(this.http, customApisCore);
86
90
  }
87
91
  get withRawResponse() {
88
92
  return makeRawProxy(this, this.http);
@@ -1,4 +1,5 @@
1
1
  /** OpenAI Hosted Agents API drop-in compatibility module. */
2
+ export type { CustomApiInfo, CustomApiAttachedAgent, CustomApiAgentEntry, CustomApiAuthInput, CustomApiHeaderInput, CustomApiCreateParams, CustomApiUpdateParams, } from "../core/customApis.js";
2
3
  export { SarvamCompatWarning } from "../core/warnings.js";
3
4
  export { OpenAIError, APIError, APIConnectionError, APITimeoutError, APIUserAbortError, APIStatusError, BadRequestError, UnsupportedFeatureError, AuthenticationError, PermissionDeniedError, NotFoundError, ConflictError, UnprocessableEntityError, RateLimitError, InternalServerError, } from "./errors.js";
4
5
  export { NOT_GIVEN, NotGiven } from "./types.js";
@@ -1,4 +1,3 @@
1
- /** OpenAI Hosted Agents API drop-in compatibility module. */
2
1
  export { SarvamCompatWarning } from "../core/warnings.js";
3
2
  export { OpenAIError, APIError, APIConnectionError, APITimeoutError, APIUserAbortError, APIStatusError, BadRequestError, UnsupportedFeatureError, AuthenticationError, PermissionDeniedError, NotFoundError, ConflictError, UnprocessableEntityError, RateLimitError, InternalServerError, } from "./errors.js";
4
3
  export { NOT_GIVEN, NotGiven } from "./types.js";
@@ -366,6 +366,13 @@ export function recordToAgent(rec) {
366
366
  const multiAgent = spec.multiAgentEnabled !== null && spec.multiAgentEnabled !== undefined
367
367
  ? { enabled: spec.multiAgentEnabled }
368
368
  : null;
369
+ const sarvamInfo = { model: rec.sarvamModel, version: rec.version };
370
+ if (rec.customApis.length > 0) {
371
+ sarvamInfo["custom_apis"] = rec.customApis.map((c) => ({ ...c }));
372
+ }
373
+ if (rec.unmanagedCustomApis.length > 0) {
374
+ sarvamInfo["unmanaged_custom_apis"] = rec.unmanagedCustomApis.map((c) => ({ ...c }));
375
+ }
369
376
  return {
370
377
  id: rec.id,
371
378
  object: "agent",
@@ -379,7 +386,7 @@ export function recordToAgent(rec) {
379
386
  tool_choice: (_f = spec.toolChoice) !== null && _f !== void 0 ? _f : null,
380
387
  multi_agent: multiAgent,
381
388
  metadata: { ...spec.metadata },
382
- sarvam: { model: rec.sarvamModel, version: rec.version },
389
+ sarvam: sarvamInfo,
383
390
  };
384
391
  }
385
392
  export class RefusedResource {
@@ -0,0 +1,26 @@
1
+ /** Sarvam-specific helper namespace (client.sarvam.customApis). */
2
+ import { CustomApis, type CustomApiAgentEntry, type CustomApiCreateParams, type CustomApiInfo, type CustomApiUpdateParams } from "../../core/customApis.js";
3
+ import { Http } from "../../core/http.js";
4
+ import type { RequestOptions } from "../types.js";
5
+ export declare class CustomApisResource {
6
+ private readonly http;
7
+ private readonly core;
8
+ constructor(http: Http, core: CustomApis);
9
+ list(opts?: {
10
+ q?: string;
11
+ }, options?: RequestOptions): Promise<CustomApiInfo[]>;
12
+ get(customApiId: string, options?: RequestOptions): Promise<CustomApiInfo>;
13
+ retrieve(customApiId: string, options?: RequestOptions): Promise<CustomApiInfo>;
14
+ create(params: CustomApiCreateParams, options?: RequestOptions): Promise<CustomApiInfo>;
15
+ update(customApiId: string, params: CustomApiUpdateParams, options?: RequestOptions): Promise<CustomApiInfo>;
16
+ delete(customApiId: string, opts?: {
17
+ force?: boolean;
18
+ }, options?: RequestOptions): Promise<void>;
19
+ listForAgent(agentId: string, options?: RequestOptions): Promise<CustomApiAgentEntry[]>;
20
+ bind(agentId: string, customApiId: string, options?: RequestOptions): Promise<void>;
21
+ unbind(agentId: string, customApiId: string, options?: RequestOptions): Promise<void>;
22
+ }
23
+ export declare class SarvamResource {
24
+ readonly customApis: CustomApisResource;
25
+ constructor(http: Http, customApis: CustomApis);
26
+ }
@@ -0,0 +1,51 @@
1
+ import { wrapCoreErrors } from "../errors.js";
2
+ function toPerCallOpts(options) {
3
+ if (!options)
4
+ return {};
5
+ return {
6
+ timeout: options.timeout,
7
+ maxRetries: options.maxRetries,
8
+ headers: options.headers,
9
+ query: options.query,
10
+ signal: options.signal,
11
+ idempotencyKey: options.idempotencyKey,
12
+ };
13
+ }
14
+ export class CustomApisResource {
15
+ constructor(http, core) {
16
+ this.http = http;
17
+ this.core = core;
18
+ }
19
+ async list(opts = {}, options) {
20
+ return wrapCoreErrors(() => this.http.withRequestOptions(toPerCallOpts(options), () => this.core.list(opts)));
21
+ }
22
+ async get(customApiId, options) {
23
+ return wrapCoreErrors(() => this.http.withRequestOptions(toPerCallOpts(options), () => this.core.get(customApiId)));
24
+ }
25
+ async retrieve(customApiId, options) {
26
+ return this.get(customApiId, options);
27
+ }
28
+ async create(params, options) {
29
+ return wrapCoreErrors(() => this.http.withRequestOptions(toPerCallOpts(options), () => this.core.create(params)));
30
+ }
31
+ async update(customApiId, params, options) {
32
+ return wrapCoreErrors(() => this.http.withRequestOptions(toPerCallOpts(options), () => this.core.update(customApiId, params)));
33
+ }
34
+ async delete(customApiId, opts = {}, options) {
35
+ await wrapCoreErrors(() => this.http.withRequestOptions(toPerCallOpts(options), () => this.core.delete(customApiId, opts)));
36
+ }
37
+ async listForAgent(agentId, options) {
38
+ return wrapCoreErrors(() => this.http.withRequestOptions(toPerCallOpts(options), () => this.core.listForAgent(agentId)));
39
+ }
40
+ async bind(agentId, customApiId, options) {
41
+ await wrapCoreErrors(() => this.http.withRequestOptions(toPerCallOpts(options), () => this.core.bind(agentId, customApiId)));
42
+ }
43
+ async unbind(agentId, customApiId, options) {
44
+ await wrapCoreErrors(() => this.http.withRequestOptions(toPerCallOpts(options), () => this.core.unbind(agentId, customApiId)));
45
+ }
46
+ }
47
+ export class SarvamResource {
48
+ constructor(http, customApis) {
49
+ this.customApis = new CustomApisResource(http, customApis);
50
+ }
51
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "sarvam-agents-client",
3
- "version": "0.5.3",
3
+ "version": "0.5.4",
4
4
  "description": "Client for the Sarvam Agents API: chat with an agent, exchange files with it, and set it up from your own code.",
5
5
  "author": "Sarvam AI <support@sarvam.ai>",
6
6
  "license": "MIT",