sarvam-agents-client 0.5.0 → 0.5.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (151) hide show
  1. package/dist/compat/core/agents.d.ts +53 -0
  2. package/dist/compat/core/agents.js +338 -0
  3. package/dist/compat/core/data.d.ts +10 -0
  4. package/dist/compat/core/data.js +275 -0
  5. package/dist/compat/core/errors.d.ts +37 -0
  6. package/dist/compat/core/errors.js +155 -0
  7. package/dist/compat/core/events.d.ts +107 -0
  8. package/dist/compat/core/events.js +160 -0
  9. package/dist/compat/core/files.d.ts +65 -0
  10. package/dist/compat/core/files.js +851 -0
  11. package/dist/compat/core/history.d.ts +9 -0
  12. package/dist/compat/core/history.js +112 -0
  13. package/dist/compat/core/http.d.ts +112 -0
  14. package/dist/compat/core/http.js +753 -0
  15. package/dist/compat/core/ids.d.ts +4 -0
  16. package/dist/compat/core/ids.js +36 -0
  17. package/dist/compat/core/index.d.ts +14 -0
  18. package/dist/compat/core/index.js +30 -0
  19. package/dist/compat/core/models.d.ts +20 -0
  20. package/dist/compat/core/models.js +75 -0
  21. package/dist/compat/core/paging.d.ts +14 -0
  22. package/dist/compat/core/paging.js +124 -0
  23. package/dist/compat/core/refusals.d.ts +9 -0
  24. package/dist/compat/core/refusals.js +25 -0
  25. package/dist/compat/core/sessions.d.ts +65 -0
  26. package/dist/compat/core/sessions.js +317 -0
  27. package/dist/compat/core/toolResults.d.ts +43 -0
  28. package/dist/compat/core/toolResults.js +208 -0
  29. package/dist/compat/core/turns.d.ts +104 -0
  30. package/dist/compat/core/turns.js +504 -0
  31. package/dist/compat/core/warnings.d.ts +6 -0
  32. package/dist/compat/core/warnings.js +26 -0
  33. package/dist/compat/index.d.ts +3 -0
  34. package/dist/compat/index.js +9 -0
  35. package/dist/compat/openai/client.d.ts +62 -0
  36. package/dist/compat/openai/client.js +108 -0
  37. package/dist/compat/openai/errors.d.ts +72 -0
  38. package/dist/compat/openai/errors.js +150 -0
  39. package/dist/compat/openai/index.d.ts +14 -0
  40. package/dist/compat/openai/index.js +42 -0
  41. package/dist/compat/openai/pages.d.ts +19 -0
  42. package/dist/compat/openai/pages.js +39 -0
  43. package/dist/compat/openai/resources/agents.d.ts +36 -0
  44. package/dist/compat/openai/resources/agents.js +549 -0
  45. package/dist/compat/openai/resources/events.d.ts +23 -0
  46. package/dist/compat/openai/resources/events.js +485 -0
  47. package/dist/compat/openai/resources/sessions.d.ts +33 -0
  48. package/dist/compat/openai/resources/sessions.js +283 -0
  49. package/dist/compat/openai/stream.d.ts +40 -0
  50. package/dist/compat/openai/stream.js +585 -0
  51. package/dist/compat/openai/types.d.ts +125 -0
  52. package/dist/compat/openai/types.js +98 -0
  53. package/dist/compose/agent.d.ts +2 -0
  54. package/dist/compose/agent.js +27 -0
  55. package/dist/compose/functionTool.d.ts +2 -0
  56. package/dist/compose/functionTool.js +46 -0
  57. package/dist/compose/output.d.ts +2 -0
  58. package/dist/compose/output.js +15 -7
  59. package/dist/esm/compat/core/agents.d.ts +53 -0
  60. package/dist/esm/compat/core/agents.js +334 -0
  61. package/dist/esm/compat/core/data.d.ts +10 -0
  62. package/dist/esm/compat/core/data.js +272 -0
  63. package/dist/esm/compat/core/errors.d.ts +37 -0
  64. package/dist/esm/compat/core/errors.js +146 -0
  65. package/dist/esm/compat/core/events.d.ts +107 -0
  66. package/dist/esm/compat/core/events.js +156 -0
  67. package/dist/esm/compat/core/files.d.ts +65 -0
  68. package/dist/esm/compat/core/files.js +829 -0
  69. package/dist/esm/compat/core/history.d.ts +9 -0
  70. package/dist/esm/compat/core/history.js +109 -0
  71. package/dist/esm/compat/core/http.d.ts +112 -0
  72. package/dist/esm/compat/core/http.js +746 -0
  73. package/dist/esm/compat/core/ids.d.ts +4 -0
  74. package/dist/esm/compat/core/ids.js +30 -0
  75. package/dist/esm/compat/core/index.d.ts +14 -0
  76. package/dist/esm/compat/core/index.js +14 -0
  77. package/dist/esm/compat/core/models.d.ts +20 -0
  78. package/dist/esm/compat/core/models.js +71 -0
  79. package/dist/esm/compat/core/paging.d.ts +14 -0
  80. package/dist/esm/compat/core/paging.js +118 -0
  81. package/dist/esm/compat/core/refusals.d.ts +9 -0
  82. package/dist/esm/compat/core/refusals.js +21 -0
  83. package/dist/esm/compat/core/sessions.d.ts +65 -0
  84. package/dist/esm/compat/core/sessions.js +312 -0
  85. package/dist/esm/compat/core/toolResults.d.ts +43 -0
  86. package/dist/esm/compat/core/toolResults.js +203 -0
  87. package/dist/esm/compat/core/turns.d.ts +104 -0
  88. package/dist/esm/compat/core/turns.js +497 -0
  89. package/dist/esm/compat/core/warnings.d.ts +6 -0
  90. package/dist/esm/compat/core/warnings.js +20 -0
  91. package/dist/esm/compat/index.d.ts +3 -0
  92. package/dist/esm/compat/index.js +3 -0
  93. package/dist/esm/compat/openai/client.d.ts +62 -0
  94. package/dist/esm/compat/openai/client.js +104 -0
  95. package/dist/esm/compat/openai/errors.d.ts +72 -0
  96. package/dist/esm/compat/openai/errors.js +130 -0
  97. package/dist/esm/compat/openai/index.d.ts +14 -0
  98. package/dist/esm/compat/openai/index.js +17 -0
  99. package/dist/esm/compat/openai/pages.d.ts +19 -0
  100. package/dist/esm/compat/openai/pages.js +35 -0
  101. package/dist/esm/compat/openai/resources/agents.d.ts +36 -0
  102. package/dist/esm/compat/openai/resources/agents.js +540 -0
  103. package/dist/esm/compat/openai/resources/events.d.ts +23 -0
  104. package/dist/esm/compat/openai/resources/events.js +479 -0
  105. package/dist/esm/compat/openai/resources/sessions.d.ts +33 -0
  106. package/dist/esm/compat/openai/resources/sessions.js +278 -0
  107. package/dist/esm/compat/openai/stream.d.ts +40 -0
  108. package/dist/esm/compat/openai/stream.js +579 -0
  109. package/dist/esm/compat/openai/types.d.ts +125 -0
  110. package/dist/esm/compat/openai/types.js +91 -0
  111. package/dist/esm/compose/agent.d.ts +2 -0
  112. package/dist/esm/compose/agent.js +28 -2
  113. package/dist/esm/compose/functionTool.d.ts +2 -0
  114. package/dist/esm/compose/functionTool.js +45 -0
  115. package/dist/esm/compose/output.d.ts +2 -0
  116. package/dist/esm/compose/output.js +14 -7
  117. package/dist/esm/index.d.ts +2 -0
  118. package/dist/esm/index.js +2 -0
  119. package/dist/index.d.ts +2 -0
  120. package/dist/index.js +5 -1
  121. package/package.json +53 -11
  122. package/src/compat/core/agents.ts +437 -0
  123. package/src/compat/core/data.ts +283 -0
  124. package/src/compat/core/errors.ts +162 -0
  125. package/src/compat/core/events.ts +198 -0
  126. package/src/compat/core/files.ts +913 -0
  127. package/src/compat/core/history.ts +116 -0
  128. package/src/compat/core/http.ts +827 -0
  129. package/src/compat/core/ids.ts +35 -0
  130. package/src/compat/core/index.ts +14 -0
  131. package/src/compat/core/models.ts +85 -0
  132. package/src/compat/core/paging.ts +119 -0
  133. package/src/compat/core/refusals.ts +31 -0
  134. package/src/compat/core/sessions.ts +358 -0
  135. package/src/compat/core/toolResults.ts +235 -0
  136. package/src/compat/core/turns.ts +622 -0
  137. package/src/compat/core/warnings.ts +23 -0
  138. package/src/compat/index.ts +3 -0
  139. package/src/compat/openai/client.ts +177 -0
  140. package/src/compat/openai/errors.ts +165 -0
  141. package/src/compat/openai/index.ts +65 -0
  142. package/src/compat/openai/pages.ts +55 -0
  143. package/src/compat/openai/resources/agents.ts +603 -0
  144. package/src/compat/openai/resources/events.ts +523 -0
  145. package/src/compat/openai/resources/sessions.ts +369 -0
  146. package/src/compat/openai/stream.ts +599 -0
  147. package/src/compat/openai/types.ts +217 -0
  148. package/src/compose/agent.ts +30 -3
  149. package/src/compose/functionTool.ts +44 -0
  150. package/src/compose/output.ts +14 -8
  151. package/src/index.ts +3 -0
@@ -0,0 +1,523 @@
1
+ /** OpenAI beta.agents.sessions.events and beta.agents.sessions.items resources. */
2
+ import { CoreAPIError } from "../../core/errors.js";
3
+ import {
4
+ ARTIFACT_URI_PREFIX,
5
+ decodeBase64Bytes,
6
+ inferMimeFromFilename,
7
+ isOpenAIFileId,
8
+ MAX_ATTACHMENTS_PER_MESSAGE,
9
+ MAX_TOTAL_ATTACHMENT_BYTES,
10
+ normalizeMime,
11
+ parseDataUri,
12
+ sanitizeFilename,
13
+ validateFileMime,
14
+ validateImageMime,
15
+ validateRemoteUrl,
16
+ verifyImageBytes,
17
+ } from "../../core/files.js";
18
+ import { history as loadHistory, type TurnRecord } from "../../core/history.js";
19
+ import { Http } from "../../core/http.js";
20
+ import { CursorPager } from "../../core/paging.js";
21
+ import { Sessions } from "../../core/sessions.js";
22
+ import { ToolResults } from "../../core/toolResults.js";
23
+ import { Turns, type Part } from "../../core/turns.js";
24
+ import { BadRequestError, wrapCoreErrors } from "../errors.js";
25
+ import { SyncCursorPage } from "../pages.js";
26
+ import { AgentSessionEventStream } from "../stream.js";
27
+ import { checkExtraParams, refuseOpenAI, type AgentSessionItem, type RequestOptions } from "../types.js";
28
+
29
+ function isObj(v: unknown): v is Record<string, unknown> {
30
+ return v !== null && typeof v === "object" && !Array.isArray(v);
31
+ }
32
+
33
+ function parseInputImage(block: Record<string, unknown>, path: string): Part {
34
+ if (block["detail"] !== undefined && block["detail"] !== null) {
35
+ refuseOpenAI("input.input_image.detail", { param: `${path}.detail` });
36
+ }
37
+
38
+ let rawUrl: unknown = block["image_url"];
39
+ if (isObj(rawUrl)) {
40
+ if (rawUrl["detail"] !== undefined && rawUrl["detail"] !== null) {
41
+ refuseOpenAI("input.input_image.detail", { param: `${path}.image_url.detail` });
42
+ }
43
+ rawUrl = rawUrl["url"];
44
+ }
45
+
46
+ const rawFileId = block["file_id"];
47
+ const hasUrl = rawUrl !== undefined && rawUrl !== null && rawUrl !== "";
48
+ const hasFileId = rawFileId !== undefined && rawFileId !== null && rawFileId !== "";
49
+ if (hasUrl === hasFileId) {
50
+ throw new BadRequestError(`${path} must specify exactly one of 'image_url' or 'file_id'.`, {
51
+ status: 400,
52
+ param: path,
53
+ });
54
+ }
55
+
56
+ const rawFilename = block["filename"];
57
+ if (rawFilename !== undefined && rawFilename !== null && typeof rawFilename !== "string") {
58
+ throw new BadRequestError(`${path}.filename must be a string.`, { status: 400, param: `${path}.filename` });
59
+ }
60
+ const filename = typeof rawFilename === "string" ? rawFilename : undefined;
61
+
62
+ if (hasFileId) {
63
+ const fidParam = `${path}.file_id`;
64
+ if (typeof rawFileId !== "string" || !rawFileId.trim()) {
65
+ throw new BadRequestError(`${path}.file_id must be a non-empty string.`, { status: 400, param: fidParam });
66
+ }
67
+ const fid = rawFileId.trim();
68
+ if (isOpenAIFileId(fid)) {
69
+ throw new BadRequestError(
70
+ `OpenAI file_id ${JSON.stringify(fid)} is not supported; pass a Sarvam artifact_id belonging to this session, ` +
71
+ "a base64 data: URI, or an http(s) image_url.",
72
+ { status: 400, param: fidParam },
73
+ );
74
+ }
75
+ return { type: "file_ref", fileId: fid, filename, kind: "image", param: fidParam };
76
+ }
77
+
78
+ const urlParam = `${path}.image_url`;
79
+ if (typeof rawUrl !== "string" || !rawUrl.trim()) {
80
+ throw new BadRequestError(`${path}.image_url must be a non-empty string.`, { status: 400, param: urlParam });
81
+ }
82
+ const trimmed = rawUrl.trim();
83
+ if (trimmed.startsWith(ARTIFACT_URI_PREFIX)) {
84
+ const aid = trimmed.slice(ARTIFACT_URI_PREFIX.length).trim();
85
+ if (!aid || isOpenAIFileId(aid)) {
86
+ throw new BadRequestError(
87
+ `Invalid artifact URI ${JSON.stringify(trimmed)}; pass an artifact://<artifact_id> belonging to this session.`,
88
+ { status: 400, param: urlParam },
89
+ );
90
+ }
91
+ return { type: "file_ref", fileId: aid, filename, kind: "image", param: urlParam };
92
+ }
93
+ try {
94
+ if (trimmed.startsWith("data:")) {
95
+ const { mime, data } = parseDataUri(trimmed, urlParam);
96
+ const validMime = validateImageMime(mime, urlParam);
97
+ const verifiedMime = verifyImageBytes(data, validMime, urlParam);
98
+ const fname = sanitizeFilename(filename, "image", verifiedMime);
99
+ return { type: "inline_file", data, mediaType: verifiedMime, filename: fname, kind: "image", param: urlParam };
100
+ }
101
+ const validUrl = validateRemoteUrl(trimmed, urlParam);
102
+ return { type: "remote_file", url: validUrl, kind: "image", filename, param: urlParam };
103
+ } catch (err) {
104
+ if (err instanceof CoreAPIError) {
105
+ throw new BadRequestError(err.message, { status: 400, param: err.param ?? urlParam });
106
+ }
107
+ throw err;
108
+ }
109
+ }
110
+
111
+ function parseInputFile(block: Record<string, unknown>, path: string): Part {
112
+ const rawData = block["file_data"];
113
+ const rawUrl = block["file_url"];
114
+ const rawFileId = block["file_id"];
115
+ const hasData = rawData !== undefined && rawData !== null && rawData !== "";
116
+ const hasUrl = rawUrl !== undefined && rawUrl !== null && rawUrl !== "";
117
+ const hasFileId = rawFileId !== undefined && rawFileId !== null && rawFileId !== "";
118
+ if (Number(hasData) + Number(hasUrl) + Number(hasFileId) !== 1) {
119
+ throw new BadRequestError(`${path} must specify exactly one of 'file_data', 'file_url', or 'file_id'.`, {
120
+ status: 400,
121
+ param: path,
122
+ });
123
+ }
124
+
125
+ const rawFilename = block["filename"];
126
+ if (rawFilename !== undefined && rawFilename !== null && typeof rawFilename !== "string") {
127
+ throw new BadRequestError(`${path}.filename must be a string.`, { status: 400, param: `${path}.filename` });
128
+ }
129
+ const filename = typeof rawFilename === "string" ? rawFilename : undefined;
130
+
131
+ const rawMime = block["media_type"] !== undefined ? block["media_type"] : block["mime_type"];
132
+ if (rawMime !== undefined && rawMime !== null && typeof rawMime !== "string") {
133
+ throw new BadRequestError(`${path}.media_type must be a string.`, { status: 400, param: `${path}.media_type` });
134
+ }
135
+ const mimeStr = typeof rawMime === "string" ? rawMime : undefined;
136
+
137
+ if (hasFileId) {
138
+ const fidParam = `${path}.file_id`;
139
+ if (typeof rawFileId !== "string" || !rawFileId.trim()) {
140
+ throw new BadRequestError(`${path}.file_id must be a non-empty string.`, { status: 400, param: fidParam });
141
+ }
142
+ const fid = rawFileId.trim();
143
+ if (isOpenAIFileId(fid)) {
144
+ throw new BadRequestError(
145
+ `OpenAI file_id ${JSON.stringify(fid)} is not supported; pass a Sarvam artifact_id belonging to this session, ` +
146
+ "file_data (base64), or an http(s) file_url.",
147
+ { status: 400, param: fidParam },
148
+ );
149
+ }
150
+ return {
151
+ type: "file_ref",
152
+ fileId: fid,
153
+ mediaType: normalizeMime(mimeStr) ?? undefined,
154
+ filename,
155
+ kind: "file",
156
+ param: fidParam,
157
+ };
158
+ }
159
+
160
+ if (hasUrl) {
161
+ const urlParam = `${path}.file_url`;
162
+ if (typeof rawUrl !== "string" || !rawUrl.trim()) {
163
+ throw new BadRequestError(`${path}.file_url must be a non-empty string.`, { status: 400, param: urlParam });
164
+ }
165
+ try {
166
+ const validUrl = validateRemoteUrl(rawUrl, urlParam);
167
+ const checkedMime = mimeStr ? validateFileMime(mimeStr, `${path}.media_type`) : undefined;
168
+ return { type: "remote_file", url: validUrl, kind: "file", filename, mediaType: checkedMime, param: urlParam };
169
+ } catch (err) {
170
+ if (err instanceof CoreAPIError) {
171
+ throw new BadRequestError(err.message, { status: 400, param: err.param ?? urlParam });
172
+ }
173
+ throw err;
174
+ }
175
+ }
176
+
177
+ const dataParam = `${path}.file_data`;
178
+ if (typeof rawData !== "string" || !rawData.trim()) {
179
+ throw new BadRequestError(`${path}.file_data must be a non-empty string.`, { status: 400, param: dataParam });
180
+ }
181
+ const trimmed = rawData.trim();
182
+ try {
183
+ let data: Uint8Array;
184
+ let validMime: string;
185
+ if (trimmed.startsWith("data:")) {
186
+ const parsed = parseDataUri(trimmed, dataParam);
187
+ data = parsed.data;
188
+ validMime = validateFileMime(normalizeMime(mimeStr) ?? parsed.mime, dataParam);
189
+ } else {
190
+ data = decodeBase64Bytes(trimmed, dataParam);
191
+ const chosen = normalizeMime(mimeStr) ?? inferMimeFromFilename(filename) ?? "application/octet-stream";
192
+ validMime = validateFileMime(chosen, dataParam);
193
+ }
194
+ const fname = sanitizeFilename(filename, "file", validMime);
195
+ return { type: "inline_file", data, mediaType: validMime, filename: fname, kind: "file", param: dataParam };
196
+ } catch (err) {
197
+ if (err instanceof CoreAPIError) {
198
+ throw new BadRequestError(err.message, { status: 400, param: err.param ?? dataParam });
199
+ }
200
+ throw err;
201
+ }
202
+ }
203
+
204
+ export function parseInputParts(rawInput: unknown): Part[] {
205
+ if (typeof rawInput === "string") return [{ type: "text", text: rawInput }];
206
+ if (!Array.isArray(rawInput)) {
207
+ throw new BadRequestError("input must be a string or an array of message objects.", { status: 400, param: "input" });
208
+ }
209
+ const parts: Part[] = [];
210
+ for (let i = 0; i < rawInput.length; i++) {
211
+ const entry = rawInput[i];
212
+ if (typeof entry === "string") {
213
+ parts.push({ type: "text", text: entry });
214
+ continue;
215
+ }
216
+ if (!isObj(entry)) {
217
+ throw new BadRequestError(`input[${i}] must be a string or message object.`, { status: 400, param: `input[${i}]` });
218
+ }
219
+ const content = entry["content"];
220
+ if (typeof content === "string") {
221
+ parts.push({ type: "text", text: content });
222
+ } else if (Array.isArray(content)) {
223
+ for (let j = 0; j < content.length; j++) {
224
+ const block = content[j];
225
+ const blockPath = `input[${i}].content[${j}]`;
226
+ if (!isObj(block)) {
227
+ throw new BadRequestError(`${blockPath} must be an object.`, {
228
+ status: 400,
229
+ param: blockPath,
230
+ });
231
+ }
232
+ const btype = block["type"];
233
+ if (btype === "input_text" || btype === "text") {
234
+ parts.push({ type: "text", text: String(block["text"] ?? "") });
235
+ } else if (btype === "input_image") {
236
+ parts.push(parseInputImage(block, blockPath));
237
+ } else if (btype === "input_file") {
238
+ parts.push(parseInputFile(block, blockPath));
239
+ } else {
240
+ refuseOpenAI(`input.${String(btype)}`, { reason: "unsupported input content part", param: "input" });
241
+ }
242
+ }
243
+ } else {
244
+ throw new BadRequestError(`input[${i}].content must be a string or array of content parts.`, {
245
+ status: 400,
246
+ param: `input[${i}].content`,
247
+ });
248
+ }
249
+ }
250
+ let attachmentCount = 0;
251
+ let inlineBytes = 0;
252
+ for (const p of parts) {
253
+ if (p.type !== "text") attachmentCount += 1;
254
+ if (p.type === "inline_file") inlineBytes += p.data.byteLength;
255
+ }
256
+ if (attachmentCount > MAX_ATTACHMENTS_PER_MESSAGE) {
257
+ throw new BadRequestError(
258
+ `A message can contain at most ${MAX_ATTACHMENTS_PER_MESSAGE} attachments (got ${attachmentCount}).`,
259
+ { status: 400, param: "input" },
260
+ );
261
+ }
262
+ if (inlineBytes > MAX_TOTAL_ATTACHMENT_BYTES) {
263
+ throw new BadRequestError(
264
+ `Combined attachment size exceeds the maximum of ${Math.floor(MAX_TOTAL_ATTACHMENT_BYTES / (1024 * 1024))} MB per message.`,
265
+ { status: 400, param: "input" },
266
+ );
267
+ }
268
+ return parts;
269
+ }
270
+
271
+ function stringifyToolOutput(output: unknown): string {
272
+ if (typeof output === "string") return output;
273
+ if (Array.isArray(output)) {
274
+ return output
275
+ .map((item) => {
276
+ if (isObj(item) && (item["type"] === "input_text" || item["type"] === "output_text" || item["type"] === "text")) {
277
+ return String(item["text"] ?? "");
278
+ }
279
+ return JSON.stringify(item);
280
+ })
281
+ .join("\n");
282
+ }
283
+ return JSON.stringify(output);
284
+ }
285
+
286
+ function stringifyToolError(ev: Record<string, unknown>): string {
287
+ const errVal = ev["error"];
288
+ if (errVal !== undefined && errVal !== null && errVal !== "") {
289
+ return typeof errVal === "string" ? errVal : JSON.stringify(errVal);
290
+ }
291
+ const outVal = ev["output"];
292
+ if (outVal !== undefined && outVal !== null && outVal !== "") {
293
+ return stringifyToolOutput(outVal);
294
+ }
295
+ return "Tool execution failed";
296
+ }
297
+
298
+ type ParsedEventOp =
299
+ | { kind: "message"; parts: Part[] }
300
+ | { kind: "cancel" }
301
+ | { kind: "tool_result"; callId: string; text: string; isError: boolean }
302
+ | { kind: "clarify"; requestId: string; answers: Record<string, unknown> };
303
+
304
+ export class EventsResource {
305
+ constructor(
306
+ private readonly http: Http,
307
+ private readonly sessions: Sessions,
308
+ private readonly turns: Turns,
309
+ private readonly toolResults: ToolResults,
310
+ ) {}
311
+
312
+ async create(sessionId: string, params: Record<string, unknown> = {}, options?: RequestOptions): Promise<void> {
313
+ const { sarvamConfig: extraSarvam, reqOpts } = checkExtraParams(
314
+ params,
315
+ new Set(["events", "idempotency_key", "sarvam_config"]),
316
+ options,
317
+ );
318
+ const ext: Record<string, unknown> = {
319
+ ...(isObj(params["sarvam_config"]) ? params["sarvam_config"] : {}),
320
+ ...extraSarvam,
321
+ };
322
+ const baseKey = typeof params["idempotency_key"] === "string"
323
+ ? params["idempotency_key"]
324
+ : options?.idempotencyKey;
325
+
326
+ if (!Array.isArray(params["events"])) {
327
+ throw new BadRequestError("events must be an array.", { status: 400, param: "events" });
328
+ }
329
+ const rawEvents = params["events"] as unknown[];
330
+
331
+ // Validate and parse all events before issuing any HTTP request.
332
+ const ops: ParsedEventOp[] = [];
333
+ for (let i = 0; i < rawEvents.length; i++) {
334
+ const ev = rawEvents[i];
335
+ if (!isObj(ev)) {
336
+ throw new BadRequestError(`events[${i}] must be an object.`, { status: 400, param: `events[${i}]` });
337
+ }
338
+ const etype = ev["type"];
339
+ if (etype === "agent.session.input.message") {
340
+ ops.push({ kind: "message", parts: parseInputParts(ev["input"]) });
341
+ } else if (etype === "agent.session.input.cancel") {
342
+ ops.push({ kind: "cancel" });
343
+ } else if (etype === "agent.session.input.tool_result") {
344
+ const callId = String(ev["call_id"] ?? "");
345
+ const success = ev["success"] !== undefined ? ev["success"] : true;
346
+ if (success === false) {
347
+ ops.push({ kind: "tool_result", callId, text: stringifyToolError(ev), isError: true });
348
+ } else {
349
+ ops.push({ kind: "tool_result", callId, text: stringifyToolOutput(ev["output"] ?? ""), isError: false });
350
+ }
351
+ } else if (etype === "sarvam.input.clarify_answer") {
352
+ ops.push({
353
+ kind: "clarify",
354
+ requestId: String(ev["request_id"] ?? ""),
355
+ answers: isObj(ev["answers"]) ? ev["answers"] : {},
356
+ });
357
+ } else {
358
+ refuseOpenAI(`events[type=${String(etype)}]`, {
359
+ reason: "unsupported input event type",
360
+ param: "events",
361
+ });
362
+ }
363
+ }
364
+
365
+ const multi = ops.length > 1;
366
+ const keyFor = (idx: number): string | undefined => {
367
+ if (baseKey === undefined) return undefined;
368
+ return multi ? `${baseKey}:${idx}` : baseKey;
369
+ };
370
+
371
+ await wrapCoreErrors(() =>
372
+ this.http.withRequestOptions(reqOpts, async () => {
373
+ for (let idx = 0; idx < ops.length; idx++) {
374
+ const op = ops[idx];
375
+ const key = keyFor(idx);
376
+ if (op.kind === "message") {
377
+ const rec = await this.sessions.ensureNotArchived(sessionId);
378
+ if (ext["queue"]) {
379
+ await this.turns.steer(sessionId, rec.agentId || null, op.parts, { key, delivery: "queue" });
380
+ } else if (rec.status === "running") {
381
+ await this.turns.steer(sessionId, rec.agentId || null, op.parts, { key, delivery: "now" });
382
+ } else {
383
+ await this.turns.send(sessionId, rec.agentId || null, op.parts, { key });
384
+ }
385
+ } else if (op.kind === "cancel") {
386
+ await this.turns.stop(sessionId);
387
+ } else if (op.kind === "tool_result") {
388
+ await this.toolResults.submit(sessionId, op.callId, op.text, { isError: op.isError, key });
389
+ } else if (op.kind === "clarify") {
390
+ await this.turns.answerClarify(sessionId, op.requestId, op.answers);
391
+ }
392
+ }
393
+ }),
394
+ );
395
+ }
396
+
397
+ stream(sessionId: string, params: Record<string, unknown> = {}, options?: RequestOptions): AgentSessionEventStream {
398
+ const { reqOpts } = checkExtraParams(params, new Set(["poll_timeout", "pollTimeout"]), options);
399
+ const pollTimeoutRaw = params["poll_timeout"] ?? params["pollTimeout"];
400
+ const pollTimeoutMs = typeof pollTimeoutRaw === "number" && Number.isFinite(pollTimeoutRaw)
401
+ ? pollTimeoutRaw
402
+ : undefined;
403
+ const listener = this.turns.listen(sessionId, { pollTimeoutMs, reqOpts });
404
+ const stream = new AgentSessionEventStream(sessionId, { listener });
405
+ if (options?.signal) {
406
+ if (options.signal.aborted) stream.controller.abort(options.signal.reason);
407
+ else options.signal.addEventListener("abort", () => stream.controller.abort(options.signal!.reason), { once: true });
408
+ }
409
+ return stream;
410
+ }
411
+ }
412
+
413
+ function recordsToItems(records: TurnRecord[]): AgentSessionItem[] {
414
+ const items: AgentSessionItem[] = [];
415
+ for (const rec of records) {
416
+ for (const ev of rec.events) {
417
+ if (ev.kind === "text_done") {
418
+ if (rec.role === "user") {
419
+ const blocks: Record<string, unknown>[] = [];
420
+ const atts = ev.attachments ?? [];
421
+ if (ev.text || atts.length === 0) {
422
+ blocks.push({ type: "input_text", text: ev.text });
423
+ }
424
+ for (const att of atts) {
425
+ if ((att.mediaType || "").toLowerCase().startsWith("image/")) {
426
+ blocks.push({ type: "input_image", image_url: `${ARTIFACT_URI_PREFIX}${att.fileId}` });
427
+ } else {
428
+ blocks.push({ type: "input_file", file_id: att.fileId, filename: att.filename });
429
+ }
430
+ }
431
+ items.push({
432
+ id: ev.itemId,
433
+ type: "message",
434
+ role: rec.role,
435
+ status: "completed",
436
+ content: blocks,
437
+ });
438
+ } else {
439
+ items.push({
440
+ id: ev.itemId,
441
+ type: "message",
442
+ role: rec.role,
443
+ status: "completed",
444
+ content: [{ type: "output_text", text: ev.text }],
445
+ });
446
+ }
447
+ } else if (ev.kind === "tool_called") {
448
+ const itype = ev.name === "web_search" ? "web_search_call" : "sarvam.tool_call";
449
+ items.push({
450
+ id: ev.itemId,
451
+ type: itype,
452
+ call_id: ev.callId,
453
+ name: ev.name,
454
+ input: ev.input,
455
+ status: "completed",
456
+ });
457
+ } else if (ev.kind === "tool_output") {
458
+ // Matches stream item_id and type.
459
+ items.push({
460
+ id: `${ev.itemId}:output`,
461
+ type: "sarvam.tool_output",
462
+ call_id: ev.callId,
463
+ output: ev.output,
464
+ status: "completed",
465
+ });
466
+ } else if (ev.kind === "function_calls_requested") {
467
+ for (let i = 0; i < ev.calls.length; i++) {
468
+ const call = ev.calls[i];
469
+ const iid = i < ev.itemIds.length ? ev.itemIds[i] : `${rec.responseId || "turn"}:fn:${i}`;
470
+ items.push({
471
+ id: iid,
472
+ type: "function_call",
473
+ call_id: call.callId,
474
+ name: call.name,
475
+ arguments: JSON.stringify(call.arguments),
476
+ status: "completed",
477
+ });
478
+ }
479
+ }
480
+ }
481
+ }
482
+ return items;
483
+ }
484
+
485
+ export class ItemsResource {
486
+ constructor(private readonly http: Http) {}
487
+
488
+ private async pageFromCached(
489
+ descItems: AgentSessionItem[],
490
+ opts: { after?: string; limit: number; order: string },
491
+ ): Promise<SyncCursorPage<AgentSessionItem>> {
492
+ const pager = new CursorPager<AgentSessionItem>(
493
+ async (off, lim) => {
494
+ const slice = descItems.slice(off, off + lim);
495
+ return [slice, off + lim < descItems.length];
496
+ },
497
+ (it) => it.id,
498
+ );
499
+ const [items, hasMore] = await wrapCoreErrors(() => pager.page(opts));
500
+ return new SyncCursorPage<AgentSessionItem>(
501
+ {
502
+ data: items,
503
+ hasMore,
504
+ firstId: items.length > 0 ? items[0].id : null,
505
+ lastId: items.length > 0 ? items[items.length - 1].id : null,
506
+ },
507
+ (nextAfter) => this.pageFromCached(descItems, { ...opts, after: nextAfter }),
508
+ );
509
+ }
510
+
511
+ async list(sessionId: string, params: Record<string, unknown> = {}, options?: RequestOptions): Promise<SyncCursorPage<AgentSessionItem>> {
512
+ const { reqOpts } = checkExtraParams(params, new Set(["after", "limit", "order"]), options);
513
+ const limit = params["limit"] !== undefined ? (params["limit"] as number) : 20;
514
+ const order = params["order"] !== undefined ? String(params["order"]) : "asc";
515
+ const after = typeof params["after"] === "string" ? params["after"] : undefined;
516
+
517
+ const allRecords = await wrapCoreErrors(() =>
518
+ this.http.withRequestOptions(reqOpts, () => loadHistory(this.http, sessionId)),
519
+ );
520
+ const descItems = recordsToItems(allRecords).reverse();
521
+ return this.pageFromCached(descItems, { limit, order, after });
522
+ }
523
+ }