sarvam-agents-client 0.5.2 → 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 (174) hide show
  1. package/README.md +52 -29
  2. package/dist/apis/AgentsApi.d.ts +96 -11
  3. package/dist/apis/AgentsApi.js +229 -9
  4. package/dist/apis/ConversationsApi.d.ts +5 -2
  5. package/dist/apis/ConversationsApi.js +7 -2
  6. package/dist/client.d.ts +3 -2
  7. package/dist/client.js +2 -1
  8. package/dist/compat/core/agents.d.ts +6 -1
  9. package/dist/compat/core/agents.js +237 -27
  10. package/dist/compat/core/customApis.d.ts +76 -0
  11. package/dist/compat/core/customApis.js +424 -0
  12. package/dist/compat/core/data.js +1 -1
  13. package/dist/compat/openai/client.d.ts +3 -0
  14. package/dist/compat/openai/client.js +5 -1
  15. package/dist/compat/openai/index.d.ts +1 -0
  16. package/dist/compat/openai/index.js +0 -1
  17. package/dist/compat/openai/resources/agents.js +8 -1
  18. package/dist/compat/openai/resources/sarvam.d.ts +26 -0
  19. package/dist/compat/openai/resources/sarvam.js +56 -0
  20. package/dist/compose/deploy.d.ts +14 -3
  21. package/dist/compose/deploy.js +60 -7
  22. package/dist/compose/errors.d.ts +4 -0
  23. package/dist/compose/errors.js +6 -1
  24. package/dist/compose/settingsTransport.d.ts +18 -13
  25. package/dist/compose/settingsTransport.js +78 -130
  26. package/dist/compose/transport.d.ts +12 -2
  27. package/dist/compose/webhook.d.ts +10 -13
  28. package/dist/compose/webhook.js +48 -45
  29. package/dist/compose/webhookSecrets.d.ts +79 -49
  30. package/dist/compose/webhookSecrets.js +244 -195
  31. package/dist/esm/apis/AgentsApi.d.ts +96 -11
  32. package/dist/esm/apis/AgentsApi.js +230 -10
  33. package/dist/esm/apis/ConversationsApi.d.ts +5 -2
  34. package/dist/esm/apis/ConversationsApi.js +7 -2
  35. package/dist/esm/client.d.ts +3 -2
  36. package/dist/esm/client.js +2 -1
  37. package/dist/esm/compat/core/agents.d.ts +6 -1
  38. package/dist/esm/compat/core/agents.js +237 -27
  39. package/dist/esm/compat/core/customApis.d.ts +76 -0
  40. package/dist/esm/compat/core/customApis.js +419 -0
  41. package/dist/esm/compat/core/data.js +1 -1
  42. package/dist/esm/compat/openai/client.d.ts +3 -0
  43. package/dist/esm/compat/openai/client.js +5 -1
  44. package/dist/esm/compat/openai/index.d.ts +1 -0
  45. package/dist/esm/compat/openai/index.js +0 -1
  46. package/dist/esm/compat/openai/resources/agents.js +8 -1
  47. package/dist/esm/compat/openai/resources/sarvam.d.ts +26 -0
  48. package/dist/esm/compat/openai/resources/sarvam.js +51 -0
  49. package/dist/esm/compose/deploy.d.ts +14 -3
  50. package/dist/esm/compose/deploy.js +60 -7
  51. package/dist/esm/compose/errors.d.ts +4 -0
  52. package/dist/esm/compose/errors.js +4 -0
  53. package/dist/esm/compose/settingsTransport.d.ts +18 -13
  54. package/dist/esm/compose/settingsTransport.js +80 -132
  55. package/dist/esm/compose/transport.d.ts +12 -2
  56. package/dist/esm/compose/webhook.d.ts +10 -13
  57. package/dist/esm/compose/webhook.js +45 -42
  58. package/dist/esm/compose/webhookSecrets.d.ts +79 -49
  59. package/dist/esm/compose/webhookSecrets.js +241 -193
  60. package/dist/esm/index.d.ts +2 -1
  61. package/dist/esm/index.js +2 -1
  62. package/dist/esm/models/AgentConversationDetail.d.ts +12 -0
  63. package/dist/esm/models/AgentConversationDetail.js +4 -0
  64. package/dist/esm/models/AgentConversationView.d.ts +12 -0
  65. package/dist/esm/models/AgentConversationView.js +4 -0
  66. package/dist/esm/models/AgentResource.d.ts +7 -0
  67. package/dist/esm/models/AgentResource.js +3 -0
  68. package/dist/esm/models/AgentVersionSavedResource.d.ts +65 -0
  69. package/dist/esm/models/AgentVersionSavedResource.js +60 -0
  70. package/dist/esm/models/AgentWebhookList.d.ts +33 -0
  71. package/dist/esm/models/AgentWebhookList.js +44 -0
  72. package/dist/esm/models/AgentWebhookView.d.ts +76 -0
  73. package/dist/esm/models/AgentWebhookView.js +70 -0
  74. package/dist/esm/models/ConversationDetail.d.ts +6 -0
  75. package/dist/esm/models/ConversationDetail.js +2 -0
  76. package/dist/esm/models/ConversationView.d.ts +6 -0
  77. package/dist/esm/models/ConversationView.js +2 -0
  78. package/dist/esm/models/ErrorDetailItem.d.ts +3 -0
  79. package/dist/esm/models/FileNodeView.d.ts +7 -0
  80. package/dist/esm/models/FileNodeView.js +3 -0
  81. package/dist/esm/models/QueueMessageInput.d.ts +6 -0
  82. package/dist/esm/models/QueueMessageInput.js +2 -0
  83. package/dist/esm/models/RotatedWebhookSecretView.d.ts +58 -0
  84. package/dist/esm/models/RotatedWebhookSecretView.js +61 -0
  85. package/dist/esm/models/SaveWarningView.d.ts +44 -0
  86. package/dist/esm/models/SaveWarningView.js +51 -0
  87. package/dist/esm/models/ShareSkippedResource.d.ts +41 -0
  88. package/dist/esm/models/ShareSkippedResource.js +47 -0
  89. package/dist/esm/models/WebhookSecretPutBody.d.ts +32 -0
  90. package/dist/esm/models/WebhookSecretPutBody.js +43 -0
  91. package/dist/esm/models/WebhookSecretStateView.d.ts +52 -0
  92. package/dist/esm/models/WebhookSecretStateView.js +56 -0
  93. package/dist/esm/models/WebhookSecretValueView.d.ts +32 -0
  94. package/dist/esm/models/WebhookSecretValueView.js +44 -0
  95. package/dist/esm/models/WebhookWarning.d.ts +44 -0
  96. package/dist/esm/models/WebhookWarning.js +51 -0
  97. package/dist/esm/models/index.d.ts +10 -0
  98. package/dist/esm/models/index.js +10 -0
  99. package/dist/index.d.ts +2 -1
  100. package/dist/index.js +4 -1
  101. package/dist/models/AgentConversationDetail.d.ts +12 -0
  102. package/dist/models/AgentConversationDetail.js +4 -0
  103. package/dist/models/AgentConversationView.d.ts +12 -0
  104. package/dist/models/AgentConversationView.js +4 -0
  105. package/dist/models/AgentResource.d.ts +7 -0
  106. package/dist/models/AgentResource.js +3 -0
  107. package/dist/models/AgentVersionSavedResource.d.ts +65 -0
  108. package/dist/models/AgentVersionSavedResource.js +67 -0
  109. package/dist/models/AgentWebhookList.d.ts +33 -0
  110. package/dist/models/AgentWebhookList.js +51 -0
  111. package/dist/models/AgentWebhookView.d.ts +76 -0
  112. package/dist/models/AgentWebhookView.js +78 -0
  113. package/dist/models/ConversationDetail.d.ts +6 -0
  114. package/dist/models/ConversationDetail.js +2 -0
  115. package/dist/models/ConversationView.d.ts +6 -0
  116. package/dist/models/ConversationView.js +2 -0
  117. package/dist/models/ErrorDetailItem.d.ts +3 -0
  118. package/dist/models/FileNodeView.d.ts +7 -0
  119. package/dist/models/FileNodeView.js +3 -0
  120. package/dist/models/QueueMessageInput.d.ts +6 -0
  121. package/dist/models/QueueMessageInput.js +2 -0
  122. package/dist/models/RotatedWebhookSecretView.d.ts +58 -0
  123. package/dist/models/RotatedWebhookSecretView.js +69 -0
  124. package/dist/models/SaveWarningView.d.ts +44 -0
  125. package/dist/models/SaveWarningView.js +58 -0
  126. package/dist/models/ShareSkippedResource.d.ts +41 -0
  127. package/dist/models/ShareSkippedResource.js +54 -0
  128. package/dist/models/WebhookSecretPutBody.d.ts +32 -0
  129. package/dist/models/WebhookSecretPutBody.js +50 -0
  130. package/dist/models/WebhookSecretStateView.d.ts +52 -0
  131. package/dist/models/WebhookSecretStateView.js +64 -0
  132. package/dist/models/WebhookSecretValueView.d.ts +32 -0
  133. package/dist/models/WebhookSecretValueView.js +51 -0
  134. package/dist/models/WebhookWarning.d.ts +44 -0
  135. package/dist/models/WebhookWarning.js +58 -0
  136. package/dist/models/index.d.ts +10 -0
  137. package/dist/models/index.js +10 -0
  138. package/package.json +1 -1
  139. package/src/apis/AgentsApi.ts +366 -11
  140. package/src/apis/ConversationsApi.ts +9 -2
  141. package/src/client.ts +3 -2
  142. package/src/compat/core/agents.ts +265 -36
  143. package/src/compat/core/customApis.ts +506 -0
  144. package/src/compat/core/data.ts +1 -1
  145. package/src/compat/openai/client.ts +7 -1
  146. package/src/compat/openai/index.ts +9 -0
  147. package/src/compat/openai/resources/agents.ts +9 -1
  148. package/src/compat/openai/resources/sarvam.ts +94 -0
  149. package/src/compose/deploy.ts +71 -10
  150. package/src/compose/errors.ts +4 -0
  151. package/src/compose/settingsTransport.ts +78 -131
  152. package/src/compose/transport.ts +10 -2
  153. package/src/compose/webhook.ts +49 -45
  154. package/src/compose/webhookSecrets.ts +227 -179
  155. package/src/index.ts +2 -1
  156. package/src/models/AgentConversationDetail.ts +16 -0
  157. package/src/models/AgentConversationView.ts +16 -0
  158. package/src/models/AgentResource.ts +15 -0
  159. package/src/models/AgentVersionSavedResource.ts +119 -0
  160. package/src/models/AgentWebhookList.ts +74 -0
  161. package/src/models/AgentWebhookView.ts +129 -0
  162. package/src/models/ConversationDetail.ts +8 -0
  163. package/src/models/ConversationView.ts +8 -0
  164. package/src/models/ErrorDetailItem.ts +3 -0
  165. package/src/models/FileNodeView.ts +16 -0
  166. package/src/models/QueueMessageInput.ts +8 -0
  167. package/src/models/RotatedWebhookSecretView.ts +103 -0
  168. package/src/models/SaveWarningView.ts +84 -0
  169. package/src/models/ShareSkippedResource.ts +78 -0
  170. package/src/models/WebhookSecretPutBody.ts +66 -0
  171. package/src/models/WebhookSecretStateView.ts +94 -0
  172. package/src/models/WebhookSecretValueView.ts +66 -0
  173. package/src/models/WebhookWarning.ts +84 -0
  174. package/src/models/index.ts +10 -0
@@ -0,0 +1,506 @@
1
+ /** Core Custom APIs service: CRUD, validation, resolution, and agent bindings. */
2
+ import { CustomAPIsApi } from "../../apis/CustomAPIsApi.js";
3
+ import type { Auth } from "../../models/Auth.js";
4
+ import type { CustomApiCreate } from "../../models/CustomApiCreate.js";
5
+ import type { CustomApiHeader } from "../../models/CustomApiHeader.js";
6
+ import type { CustomApiUpdate } from "../../models/CustomApiUpdate.js";
7
+ import type { CustomApiUpdateAuth } from "../../models/CustomApiUpdateAuth.js";
8
+ import { CoreAPIError } from "./errors.js";
9
+ import { Http } from "./http.js";
10
+
11
+ const PAGE_LIMIT = 100;
12
+ const MAX_PAGES = 50;
13
+ const MAX_NAME_LEN = 256;
14
+ const MAX_DESC_LEN = 200;
15
+ const MAX_HOST_LEN = 253;
16
+ const MAX_SECRET_LEN = 8192;
17
+ const MAX_HEADERS = 16;
18
+
19
+ export interface CustomApiAttachedAgent {
20
+ readonly id: string;
21
+ readonly name: string;
22
+ }
23
+
24
+ export interface CustomApiAgentEntry {
25
+ readonly id: string;
26
+ readonly name: string;
27
+ readonly host: string | null;
28
+ }
29
+
30
+ export interface CustomApiInfo {
31
+ readonly id: string;
32
+ readonly name: string;
33
+ readonly description: string;
34
+ readonly host: string;
35
+ readonly authType: string;
36
+ readonly headerNames: readonly string[];
37
+ readonly enabledForChats: boolean;
38
+ readonly agents: readonly CustomApiAttachedAgent[];
39
+ readonly createdAt: string;
40
+ readonly credentialsUpdatedAt: string;
41
+ readonly enabledForChatsError: string | null;
42
+ }
43
+
44
+ export interface CustomApiHeaderInput {
45
+ name: string;
46
+ value?: string | null;
47
+ previousName?: string | null;
48
+ previous_name?: string | null;
49
+ }
50
+
51
+ export type CustomApiAuthInput =
52
+ | { type: "bearer"; token: string }
53
+ | { type: "basic"; username: string; password: string }
54
+ | { type: "headers"; headers: CustomApiHeaderInput[] | Record<string, string | null> };
55
+
56
+ export interface CustomApiCreateParams {
57
+ name: string;
58
+ host: string;
59
+ auth: CustomApiAuthInput;
60
+ description?: string | null;
61
+ enabledForChats?: boolean;
62
+ enabled_for_chats?: boolean;
63
+ }
64
+
65
+ export interface CustomApiUpdateParams {
66
+ name?: string;
67
+ description?: string | null;
68
+ host?: string;
69
+ auth?: CustomApiAuthInput;
70
+ enabledForChats?: boolean;
71
+ enabled_for_chats?: boolean;
72
+ }
73
+
74
+ function isObj(v: unknown): v is Record<string, unknown> {
75
+ return v !== null && typeof v === "object" && !Array.isArray(v);
76
+ }
77
+
78
+ function asRecord(v: unknown): Record<string, unknown> {
79
+ return isObj(v) ? v : {};
80
+ }
81
+
82
+ function isoStr(v: unknown): string {
83
+ if (v instanceof Date) return v.toISOString();
84
+ if (typeof v === "string") return v;
85
+ return "";
86
+ }
87
+
88
+ function badReq(message: string, param?: string, code = "invalid_request_error"): CoreAPIError {
89
+ return new CoreAPIError(message, { status: 400, code, param: param ?? null });
90
+ }
91
+
92
+ function infoFromModel(raw: unknown): CustomApiInfo {
93
+ const d = asRecord(raw);
94
+ const agentsRaw = Array.isArray(d["agents"]) ? d["agents"] : [];
95
+ const agents: CustomApiAttachedAgent[] = agentsRaw.map((a) => {
96
+ const ar = asRecord(a);
97
+ return Object.freeze({ id: String(ar["id"] ?? ""), name: String(ar["name"] ?? "") });
98
+ });
99
+ const headerNamesRaw = Array.isArray(d["headerNames"])
100
+ ? d["headerNames"]
101
+ : (Array.isArray(d["header_names"]) ? d["header_names"] : []);
102
+ const enabledRaw = "enabledForChats" in d
103
+ ? d["enabledForChats"]
104
+ : ("enabled_for_chats" in d ? d["enabled_for_chats"] : true);
105
+ const errRaw = d["enabledForChatsError"] ?? d["enabled_for_chats_error"];
106
+ return Object.freeze({
107
+ id: String(d["id"] ?? ""),
108
+ name: String(d["name"] ?? ""),
109
+ description: String(d["description"] ?? ""),
110
+ host: String(d["host"] ?? ""),
111
+ authType: String(d["authType"] ?? d["auth_type"] ?? ""),
112
+ headerNames: Object.freeze(headerNamesRaw.map((h) => String(h))),
113
+ enabledForChats: Boolean(enabledRaw),
114
+ agents: Object.freeze(agents),
115
+ createdAt: isoStr(d["createdAt"] ?? d["created_at"]),
116
+ credentialsUpdatedAt: isoStr(d["credentialsUpdatedAt"] ?? d["credentials_updated_at"]),
117
+ enabledForChatsError: errRaw !== undefined && errRaw !== null ? String(errRaw) : null,
118
+ });
119
+ }
120
+
121
+ function validateName(name: unknown, param = "name"): string {
122
+ if (typeof name !== "string" || !name.trim()) {
123
+ throw badReq("name must be a non-empty string.", param);
124
+ }
125
+ if (name.length > MAX_NAME_LEN) {
126
+ throw badReq(`name must be at most ${MAX_NAME_LEN} characters.`, param);
127
+ }
128
+ return name;
129
+ }
130
+
131
+ function validateDescription(description: unknown, param = "description"): string | null {
132
+ if (description === undefined || description === null) return null;
133
+ if (typeof description !== "string") {
134
+ throw badReq("description must be a string or null.", param);
135
+ }
136
+ if (description.length > MAX_DESC_LEN) {
137
+ throw badReq(`description must be at most ${MAX_DESC_LEN} characters.`, param);
138
+ }
139
+ return description;
140
+ }
141
+
142
+ function validateHost(host: unknown, param = "host"): string {
143
+ if (typeof host !== "string" || !host.trim()) {
144
+ throw badReq("host must be a non-empty hostname (for example 'api.acme.com').", param);
145
+ }
146
+ const trimmed = host.trim();
147
+ if (trimmed.length > MAX_HOST_LEN) {
148
+ throw badReq(`host must be at most ${MAX_HOST_LEN} characters.`, param);
149
+ }
150
+ if (trimmed.includes("://")) {
151
+ throw badReq("host must be a bare hostname without scheme (for example 'api.acme.com', not a full URL).", param);
152
+ }
153
+ if (/\s/.test(trimmed) || trimmed.includes("/") || trimmed.includes("?") || trimmed.includes("#")) {
154
+ throw badReq("host must be a bare hostname without path, query, or whitespace.", param);
155
+ }
156
+ return trimmed;
157
+ }
158
+
159
+ function buildAuth(auth: unknown, forUpdate: boolean, param = "auth"): Auth {
160
+ if (!isObj(auth)) {
161
+ throw badReq("auth must be an object with type 'bearer', 'basic', or 'headers'.", param);
162
+ }
163
+ const atype = auth["type"];
164
+ if (atype === "bearer") {
165
+ const extra = Object.keys(auth).filter((k) => k !== "type" && k !== "token");
166
+ if (extra.length > 0) {
167
+ throw badReq(`Unknown bearer auth key ${JSON.stringify(extra[0])}.`, `${param}.${extra[0]}`);
168
+ }
169
+ const token = auth["token"];
170
+ if (typeof token !== "string" || !token) {
171
+ throw badReq("bearer auth requires a non-empty token string.", `${param}.token`);
172
+ }
173
+ if (token.length > MAX_SECRET_LEN) {
174
+ throw badReq(`bearer token exceeds maximum length of ${MAX_SECRET_LEN}.`, `${param}.token`);
175
+ }
176
+ return { type: "bearer", token };
177
+ }
178
+
179
+ if (atype === "basic") {
180
+ const extra = Object.keys(auth).filter((k) => k !== "type" && k !== "username" && k !== "password");
181
+ if (extra.length > 0) {
182
+ throw badReq(`Unknown basic auth key ${JSON.stringify(extra[0])}.`, `${param}.${extra[0]}`);
183
+ }
184
+ const username = auth["username"];
185
+ const password = auth["password"];
186
+ if (typeof username !== "string" || !username) {
187
+ throw badReq("basic auth requires a non-empty username string.", `${param}.username`);
188
+ }
189
+ if (typeof password !== "string" || !password) {
190
+ throw badReq("basic auth requires a non-empty password string.", `${param}.password`);
191
+ }
192
+ if (password.length > MAX_SECRET_LEN) {
193
+ throw badReq(`basic password exceeds maximum length of ${MAX_SECRET_LEN}.`, `${param}.password`);
194
+ }
195
+ return { type: "basic", username, password };
196
+ }
197
+
198
+ if (atype === "headers") {
199
+ const extra = Object.keys(auth).filter((k) => k !== "type" && k !== "headers");
200
+ if (extra.length > 0) {
201
+ throw badReq(`Unknown headers auth key ${JSON.stringify(extra[0])}.`, `${param}.${extra[0]}`);
202
+ }
203
+ const rawHeaders = auth["headers"];
204
+ const parsed: CustomApiHeader[] = [];
205
+ if (isObj(rawHeaders)) {
206
+ for (const [k, v] of Object.entries(rawHeaders)) {
207
+ if (typeof k !== "string" || !k.trim()) {
208
+ throw badReq("Header name must be a non-empty string.", `${param}.headers`);
209
+ }
210
+ if (v === null || v === undefined) {
211
+ if (!forUpdate) {
212
+ throw badReq(`Header ${JSON.stringify(k)} requires a non-empty value on create.`, `${param}.headers`);
213
+ }
214
+ parsed.push({ name: k });
215
+ } else if (typeof v !== "string" || !v) {
216
+ throw badReq(`Header ${JSON.stringify(k)} value must be a non-empty string.`, `${param}.headers`);
217
+ } else if (v.length > MAX_SECRET_LEN) {
218
+ throw badReq(`Header ${JSON.stringify(k)} value exceeds maximum length of ${MAX_SECRET_LEN}.`, `${param}.headers`);
219
+ } else {
220
+ parsed.push({ name: k, value: v });
221
+ }
222
+ }
223
+ } else if (Array.isArray(rawHeaders)) {
224
+ for (let i = 0; i < rawHeaders.length; i++) {
225
+ const item = rawHeaders[i];
226
+ const itemParam = `${param}.headers[${i}]`;
227
+ if (!isObj(item)) {
228
+ throw badReq("Each header entry must be an object with 'name' and 'value'.", itemParam);
229
+ }
230
+ const badKeys = Object.keys(item).filter(
231
+ (k) => k !== "name" && k !== "value" && k !== "previousName" && k !== "previous_name",
232
+ );
233
+ if (badKeys.length > 0) {
234
+ throw badReq(`Unknown header key ${JSON.stringify(badKeys[0])}.`, `${itemParam}.${badKeys[0]}`);
235
+ }
236
+ const hname = item["name"];
237
+ if (typeof hname !== "string" || !hname.trim()) {
238
+ throw badReq("Header name must be a non-empty string.", `${itemParam}.name`);
239
+ }
240
+ const hval = item["value"];
241
+ const prevName = "previousName" in item ? item["previousName"] : item["previous_name"];
242
+ if (prevName !== undefined && prevName !== null && (typeof prevName !== "string" || !prevName.trim())) {
243
+ throw badReq("previousName must be a non-empty string or null.", `${itemParam}.previousName`);
244
+ }
245
+ if (hval === undefined || hval === null) {
246
+ if (!forUpdate) {
247
+ throw badReq(`Header ${JSON.stringify(hname)} requires a non-empty value on create.`, `${itemParam}.value`);
248
+ }
249
+ const entry: CustomApiHeader = { name: hname };
250
+ if (typeof prevName === "string") entry.previousName = prevName;
251
+ parsed.push(entry);
252
+ } else {
253
+ if (typeof hval !== "string" || !hval) {
254
+ throw badReq(`Header ${JSON.stringify(hname)} value must be a non-empty string.`, `${itemParam}.value`);
255
+ }
256
+ if (hval.length > MAX_SECRET_LEN) {
257
+ throw badReq(`Header ${JSON.stringify(hname)} value exceeds maximum length of ${MAX_SECRET_LEN}.`, `${itemParam}.value`);
258
+ }
259
+ const entry: CustomApiHeader = { name: hname, value: hval };
260
+ if (typeof prevName === "string") entry.previousName = prevName;
261
+ parsed.push(entry);
262
+ }
263
+ }
264
+ } else {
265
+ throw badReq("headers auth requires 'headers' as a non-empty list or name->value mapping.", `${param}.headers`);
266
+ }
267
+ if (parsed.length === 0 || parsed.length > MAX_HEADERS) {
268
+ throw badReq(`headers auth requires between 1 and ${MAX_HEADERS} headers.`, `${param}.headers`);
269
+ }
270
+ return { type: "headers", headers: parsed };
271
+ }
272
+
273
+ throw badReq("auth.type must be 'bearer', 'basic', or 'headers'.", `${param}.type`);
274
+ }
275
+
276
+ export function validateCustomApiRefs(refs: unknown, param = "sarvam_config.custom_apis"): string[] {
277
+ if (!Array.isArray(refs)) {
278
+ throw badReq("sarvam_config.custom_apis must be a list of custom API IDs or names.", param);
279
+ }
280
+ const out: string[] = [];
281
+ for (let i = 0; i < refs.length; i++) {
282
+ const ref = refs[i];
283
+ if (typeof ref !== "string" || !ref.trim()) {
284
+ throw badReq("Each entry in sarvam_config.custom_apis must be a non-empty string.", `${param}[${i}]`);
285
+ }
286
+ out.push(ref.trim());
287
+ }
288
+ return out;
289
+ }
290
+
291
+ export class CustomApis {
292
+ private readonly api: CustomAPIsApi;
293
+
294
+ constructor(private readonly http: Http) {
295
+ this.api = new CustomAPIsApi(http.sdkConfig);
296
+ }
297
+
298
+ async list(opts: { q?: string } = {}): Promise<CustomApiInfo[]> {
299
+ const rows: CustomApiInfo[] = [];
300
+ const seenIds = new Set<string>();
301
+ let offset = 0;
302
+ for (let pages = 0; pages < MAX_PAGES; pages += 1) {
303
+ const off = offset;
304
+ const page = await this.http.call(
305
+ () => this.api.listCustomApis({
306
+ ...(opts.q !== undefined ? { q: opts.q } : {}),
307
+ limit: PAGE_LIMIT,
308
+ offset: off,
309
+ }),
310
+ { idempotent: true },
311
+ );
312
+ const d = asRecord(page);
313
+ const items = Array.isArray(d["data"]) ? d["data"] : [];
314
+ for (const item of items) {
315
+ const info = infoFromModel(item);
316
+ if (info.id && seenIds.has(info.id)) continue;
317
+ if (info.id) seenIds.add(info.id);
318
+ rows.push(info);
319
+ }
320
+ const hasMore = Boolean(d["hasMore"]);
321
+ if (items.length === 0 || !hasMore) break;
322
+ offset += items.length;
323
+ }
324
+ return rows;
325
+ }
326
+
327
+ async get(customApiId: string): Promise<CustomApiInfo> {
328
+ if (typeof customApiId !== "string" || !customApiId.trim()) {
329
+ throw badReq("customApiId must be a non-empty string.", "custom_api_id");
330
+ }
331
+ const raw = await this.http.call(() => this.api.getCustomApi({ customApiId }), { idempotent: true });
332
+ return infoFromModel(raw);
333
+ }
334
+
335
+ async retrieve(customApiId: string): Promise<CustomApiInfo> {
336
+ return this.get(customApiId);
337
+ }
338
+
339
+ async create(params: CustomApiCreateParams): Promise<CustomApiInfo> {
340
+ if (!isObj(params)) {
341
+ throw badReq("create params must be an object.");
342
+ }
343
+ const name = validateName(params.name);
344
+ const host = validateHost(params.host);
345
+ const description = validateDescription(params.description);
346
+ const auth = buildAuth(params.auth, false);
347
+ const enabledRaw = params.enabledForChats !== undefined ? params.enabledForChats : params.enabled_for_chats;
348
+ const enabledForChats = enabledRaw === undefined ? true : enabledRaw;
349
+ if (typeof enabledForChats !== "boolean") {
350
+ throw badReq("enabledForChats must be a boolean.", "enabled_for_chats");
351
+ }
352
+ const body: CustomApiCreate = {
353
+ name,
354
+ host,
355
+ auth,
356
+ enabledForChats,
357
+ ...(description !== null ? { description } : {}),
358
+ };
359
+ const raw = await this.http.call(() => this.api.createCustomApi({ customApiCreate: body }), { idempotent: false });
360
+ return infoFromModel(raw);
361
+ }
362
+
363
+ async update(customApiId: string, params: CustomApiUpdateParams): Promise<CustomApiInfo> {
364
+ if (typeof customApiId !== "string" || !customApiId.trim()) {
365
+ throw badReq("customApiId must be a non-empty string.", "custom_api_id");
366
+ }
367
+ if (!isObj(params)) {
368
+ throw badReq("update params must be an object.");
369
+ }
370
+ const body: CustomApiUpdate = {};
371
+ let hasField = false;
372
+ if (params.name !== undefined) {
373
+ body.name = validateName(params.name);
374
+ hasField = true;
375
+ }
376
+ if (params.description !== undefined) {
377
+ body.description = validateDescription(params.description);
378
+ hasField = true;
379
+ }
380
+ if (params.host !== undefined) {
381
+ body.host = validateHost(params.host);
382
+ hasField = true;
383
+ }
384
+ if (params.auth !== undefined) {
385
+ body.auth = buildAuth(params.auth, true) as CustomApiUpdateAuth;
386
+ hasField = true;
387
+ }
388
+ const enabledRaw = params.enabledForChats !== undefined ? params.enabledForChats : params.enabled_for_chats;
389
+ if (enabledRaw !== undefined) {
390
+ if (typeof enabledRaw !== "boolean") {
391
+ throw badReq("enabledForChats must be a boolean.", "enabled_for_chats");
392
+ }
393
+ body.enabledForChats = enabledRaw;
394
+ hasField = true;
395
+ }
396
+ if (!hasField) {
397
+ throw badReq("At least one field must be provided to update a custom API.");
398
+ }
399
+ const raw = await this.http.call(
400
+ () => this.api.updateCustomApi({ customApiId, customApiUpdate: body }),
401
+ { idempotent: false },
402
+ );
403
+ return infoFromModel(raw);
404
+ }
405
+
406
+ async delete(customApiId: string, opts: { force?: boolean } = {}): Promise<void> {
407
+ if (typeof customApiId !== "string" || !customApiId.trim()) {
408
+ throw badReq("customApiId must be a non-empty string.", "custom_api_id");
409
+ }
410
+ if (!opts.force) {
411
+ const info = await this.get(customApiId);
412
+ if (info.agents.length > 0) {
413
+ const ids = info.agents.map((a) => a.id).filter(Boolean).join(", ");
414
+ throw new CoreAPIError(
415
+ `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 }.`,
416
+ { status: 409, code: "custom_api_in_use", param: "custom_api_id" },
417
+ );
418
+ }
419
+ }
420
+ await this.http.call(() => this.api.deleteCustomApi({ customApiId }), { idempotent: true });
421
+ }
422
+
423
+ async listForAgent(agentId: string): Promise<CustomApiAgentEntry[]> {
424
+ if (typeof agentId !== "string" || !agentId.trim()) {
425
+ throw badReq("agentId must be a non-empty string.", "agent_id");
426
+ }
427
+ const resp = await this.http.call(() => this.api.listAgentCustomApis({ agentId }), { idempotent: true });
428
+ const d = asRecord(resp);
429
+ const items = Array.isArray(d["data"]) ? d["data"] : [];
430
+ return items.map((item) => {
431
+ const r = asRecord(item);
432
+ return {
433
+ id: String(r["id"] ?? ""),
434
+ name: String(r["name"] ?? ""),
435
+ host: r["host"] !== undefined && r["host"] !== null ? String(r["host"]) : null,
436
+ };
437
+ });
438
+ }
439
+
440
+ async bind(agentId: string, customApiId: string): Promise<void> {
441
+ if (typeof agentId !== "string" || !agentId.trim()) {
442
+ throw badReq("agentId must be a non-empty string.", "agent_id");
443
+ }
444
+ if (typeof customApiId !== "string" || !customApiId.trim()) {
445
+ throw badReq("customApiId must be a non-empty string.", "custom_api_id");
446
+ }
447
+ await this.http.call(
448
+ () => this.api.bindCustomApi({ agentId, bindCustomApiBody: { customApiId } }),
449
+ { idempotent: true },
450
+ );
451
+ }
452
+
453
+ async unbind(agentId: string, customApiId: string): Promise<void> {
454
+ if (typeof agentId !== "string" || !agentId.trim()) {
455
+ throw badReq("agentId must be a non-empty string.", "agent_id");
456
+ }
457
+ if (typeof customApiId !== "string" || !customApiId.trim()) {
458
+ throw badReq("customApiId must be a non-empty string.", "custom_api_id");
459
+ }
460
+ await this.http.call(() => this.api.unbindCustomApi({ agentId, customApiId }), { idempotent: true });
461
+ }
462
+
463
+ async resolveRefs(refs: readonly string[], paramPrefix = "sarvam_config.custom_apis"): Promise<CustomApiInfo[]> {
464
+ const validated = validateCustomApiRefs([...refs], paramPrefix);
465
+ if (validated.length === 0) return [];
466
+ const catalog = await this.list();
467
+ const byId = new Map<string, CustomApiInfo>();
468
+ const byName = new Map<string, CustomApiInfo[]>();
469
+ for (const c of catalog) {
470
+ byId.set(c.id, c);
471
+ const list = byName.get(c.name) ?? [];
472
+ list.push(c);
473
+ byName.set(c.name, list);
474
+ }
475
+
476
+ const resolved: CustomApiInfo[] = [];
477
+ const seen = new Set<string>();
478
+ for (let idx = 0; idx < validated.length; idx++) {
479
+ const ref = validated[idx];
480
+ const param = `${paramPrefix}[${idx}]`;
481
+ let match = byId.get(ref);
482
+ if (!match) {
483
+ const nameMatches = byName.get(ref) ?? [];
484
+ if (nameMatches.length === 1) {
485
+ match = nameMatches[0];
486
+ } else if (nameMatches.length > 1) {
487
+ const ids = nameMatches.map((m) => m.id).join(", ");
488
+ throw new CoreAPIError(
489
+ `Custom API name ${JSON.stringify(ref)} matches multiple custom APIs (${ids}); pass the custom API ID instead.`,
490
+ { status: 409, code: "ambiguous_custom_api", param },
491
+ );
492
+ } else {
493
+ throw new CoreAPIError(
494
+ `Custom API ${JSON.stringify(ref)} was not found. Create it with client.sarvam.customApis.create(...) or check client.sarvam.customApis.list().`,
495
+ { status: 404, code: "custom_api_not_found", param },
496
+ );
497
+ }
498
+ }
499
+ if (!seen.has(match.id)) {
500
+ seen.add(match.id);
501
+ resolved.push(match);
502
+ }
503
+ }
504
+ return resolved;
505
+ }
506
+ }
@@ -24,7 +24,7 @@ export const REFUSALS: readonly RefusalSpec[] = [
24
24
  "path": "environment.vault_ids",
25
25
  "param": "environment.vault_ids",
26
26
  "reason": "OpenAI vaults are not supported",
27
- "hint": "Configure agent apps or custom APIs via sarvam_config={'apps': [...]}.",
27
+ "hint": "Configure agent apps via sarvam_config={'apps': [...]} or custom APIs via sarvam_config={'custom_apis': [...]}.",
28
28
  "needs": null,
29
29
  "feature": "openai.environment.vault_ids"
30
30
  },
@@ -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
  import type { AgentSessionEventStream } from "./stream.js";
15
17
  import type { AgentSession, RawResponse, RequestOptions } from "./types.js";
@@ -67,6 +69,7 @@ export interface RawResponseClient {
67
69
  readonly beta: {
68
70
  readonly agents: RawResponseAgentsResource;
69
71
  };
72
+ readonly sarvam: RawResponseProxy<SarvamResource>;
70
73
  }
71
74
 
72
75
  function makeRawProxy(target: object, http: Http): unknown {
@@ -95,6 +98,7 @@ function makeRawProxy(target: object, http: Http): unknown {
95
98
 
96
99
  export class OpenAI {
97
100
  readonly beta: { readonly agents: AgentsResource };
101
+ readonly sarvam: SarvamResource;
98
102
  private readonly initOpts: OpenAIOptions;
99
103
  private readonly http: Http;
100
104
  private readonly listenerRegistry: ListenerRegistry;
@@ -132,7 +136,8 @@ export class OpenAI {
132
136
  strict: opts.strictModels,
133
137
  provider: "openai",
134
138
  });
135
- const agentsCore = new Agents(this.http, models);
139
+ const customApisCore = new CustomApis(this.http);
140
+ const agentsCore = new Agents(this.http, models, customApisCore);
136
141
  this.sessionUpdateQueue = opts._sharedSessionQueue ?? new SessionUpdateQueue();
137
142
  const sessionsCore = new Sessions(this.http, { provider: "openai", updateQueue: this.sessionUpdateQueue });
138
143
  this.listenerRegistry = opts._sharedRegistry ?? new ListenerRegistry();
@@ -153,6 +158,7 @@ export class OpenAI {
153
158
  const sessionsRes = new SessionsResource(this.http, agentsCore, sessionsCore, turnsCore, eventsRes, itemsRes);
154
159
  const agentsRes = new AgentsResource(this.http, agentsCore, sessionsRes);
155
160
  this.beta = { agents: agentsRes };
161
+ this.sarvam = new SarvamResource(this.http, customApisCore);
156
162
  }
157
163
 
158
164
  get withRawResponse(): RawResponseClient {
@@ -1,4 +1,13 @@
1
1
  /** OpenAI Hosted Agents API drop-in compatibility module. */
2
+ export type {
3
+ CustomApiInfo,
4
+ CustomApiAttachedAgent,
5
+ CustomApiAgentEntry,
6
+ CustomApiAuthInput,
7
+ CustomApiHeaderInput,
8
+ CustomApiCreateParams,
9
+ CustomApiUpdateParams,
10
+ } from "../core/customApis.js";
2
11
  export { SarvamCompatWarning } from "../core/warnings.js";
3
12
  export {
4
13
  OpenAIError,
@@ -388,6 +388,14 @@ export function recordToAgent(rec: AgentRecord): Agent {
388
388
  ? { enabled: spec.multiAgentEnabled }
389
389
  : null;
390
390
 
391
+ const sarvamInfo: Record<string, unknown> = { model: rec.sarvamModel, version: rec.version };
392
+ if (rec.customApis.length > 0) {
393
+ sarvamInfo["custom_apis"] = rec.customApis.map((c) => ({ ...c }));
394
+ }
395
+ if (rec.unmanagedCustomApis.length > 0) {
396
+ sarvamInfo["unmanaged_custom_apis"] = rec.unmanagedCustomApis.map((c) => ({ ...c }));
397
+ }
398
+
391
399
  return {
392
400
  id: rec.id,
393
401
  object: "agent",
@@ -401,7 +409,7 @@ export function recordToAgent(rec: AgentRecord): Agent {
401
409
  tool_choice: spec.toolChoice ?? null,
402
410
  multi_agent: multiAgent,
403
411
  metadata: { ...spec.metadata },
404
- sarvam: { model: rec.sarvamModel, version: rec.version },
412
+ sarvam: sarvamInfo,
405
413
  };
406
414
  }
407
415