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,497 @@
1
+ /** Core Turns service: send, steer, stop, clarify, and in-process/cross-process stream follow. */
2
+ import { createHash } from "node:crypto";
3
+ import { QueueApi } from "../../apis/QueueApi.js";
4
+ import { ResponsesApi } from "../../apis/ResponsesApi.js";
5
+ import { answerClarify, reconnect, streamResponse } from "../../streaming.js";
6
+ import { CoreAPIError, CoreTimeoutError } from "./errors.js";
7
+ import { TurnEvents } from "./events.js";
8
+ import { ACCEPTED_IMAGE_MIMES, AttachmentUploadCache, deleteArtifactBestEffort, fetchRemoteFile, listSessionArtifacts, makeFileMessagePart, MAX_ATTACHMENTS_PER_MESSAGE, MAX_TOTAL_ATTACHMENT_BYTES, normalizeMime, uploadArtifact, } from "./files.js";
9
+ import { refuse } from "./refusals.js";
10
+ const NO_ACTIVE_CODES = new Set([
11
+ "NO_ACTIVE_TURN",
12
+ "no_active_turn",
13
+ "no_active_response",
14
+ "NO_ACTIVE_RESPONSE",
15
+ ]);
16
+ const UNITERATED_TTL_MS = 60000;
17
+ export const DEFAULT_POLL_TIMEOUT_MS = 300000;
18
+ export async function prefetchRemoteParts(http, parts) {
19
+ var _a;
20
+ let attachmentCount = 0;
21
+ let usedBytes = 0;
22
+ for (const p of parts) {
23
+ if (p.type !== "text")
24
+ attachmentCount += 1;
25
+ if (p.type === "inline_file")
26
+ usedBytes += p.data.byteLength;
27
+ }
28
+ if (attachmentCount > MAX_ATTACHMENTS_PER_MESSAGE) {
29
+ throw new CoreAPIError(`A message can contain at most ${MAX_ATTACHMENTS_PER_MESSAGE} attachments (got ${attachmentCount}).`, { status: 400, code: "invalid_request_error", param: "input" });
30
+ }
31
+ if (usedBytes > MAX_TOTAL_ATTACHMENT_BYTES) {
32
+ throw new CoreAPIError(`Combined attachment size exceeds the maximum of ${Math.floor(MAX_TOTAL_ATTACHMENT_BYTES / (1024 * 1024))} MB per message.`, { status: 400, code: "invalid_request_error", param: "input" });
33
+ }
34
+ if (!parts.some((p) => p.type === "remote_file"))
35
+ return parts;
36
+ const out = [];
37
+ for (const p of parts) {
38
+ if (p.type === "remote_file") {
39
+ const remainingBudget = MAX_TOTAL_ATTACHMENT_BYTES - usedBytes;
40
+ if (remainingBudget <= 0) {
41
+ throw new CoreAPIError(`Combined attachment size exceeds the maximum of ${Math.floor(MAX_TOTAL_ATTACHMENT_BYTES / (1024 * 1024))} MB per message.`, { status: 400, code: "invalid_request_error", param: (_a = p.param) !== null && _a !== void 0 ? _a : "input" });
42
+ }
43
+ const fetched = await fetchRemoteFile(http, p.url, {
44
+ kind: p.kind,
45
+ filename: p.filename,
46
+ mediaType: p.mediaType,
47
+ param: p.param,
48
+ maxBytes: remainingBudget,
49
+ });
50
+ usedBytes += fetched.data.byteLength;
51
+ out.push({
52
+ type: "inline_file",
53
+ data: fetched.data,
54
+ mediaType: fetched.mediaType,
55
+ filename: fetched.filename,
56
+ kind: p.kind,
57
+ param: p.param,
58
+ });
59
+ }
60
+ else {
61
+ out.push(p);
62
+ }
63
+ }
64
+ return out;
65
+ }
66
+ async function resolveMessageParts(http, sessionId, parts, provider = "openai", opts = {}) {
67
+ var _a, _b, _c, _d;
68
+ // Guard: verify every file_id belongs to this session BEFORE downloading remote URLs or uploading anything.
69
+ const hasRefs = parts.some((p) => p.type === "file_ref");
70
+ const sessionArtifacts = hasRefs ? await listSessionArtifacts(http, sessionId) : new Map();
71
+ for (const p of parts) {
72
+ if (p.type === "file_ref") {
73
+ const found = sessionArtifacts.get(p.fileId);
74
+ if (!found) {
75
+ throw new CoreAPIError(`file_id ${JSON.stringify(p.fileId)} does not belong to session ${JSON.stringify(sessionId)}. ` +
76
+ "Panja artifacts are scoped to a single session; pass an artifact_id from this session or provide inline data/URL instead.", { status: 400, code: "invalid_request_error", param: (_a = p.param) !== null && _a !== void 0 ? _a : "file_id" });
77
+ }
78
+ if (p.kind === "image") {
79
+ const norm = normalizeMime(found.mediaType);
80
+ if (!norm || !ACCEPTED_IMAGE_MIMES.has(norm)) {
81
+ const accepted = Array.from(ACCEPTED_IMAGE_MIMES).sort().join(", ");
82
+ throw new CoreAPIError(`file_id ${JSON.stringify(p.fileId)} has media type ${JSON.stringify(found.mediaType)}, which is not a supported image type (${accepted}).`, { status: 400, code: "invalid_request_error", param: (_b = p.param) !== null && _b !== void 0 ? _b : "file_id" });
83
+ }
84
+ }
85
+ }
86
+ }
87
+ const prepared = await prefetchRemoteParts(http, parts);
88
+ const out = [];
89
+ const newlyUploaded = [];
90
+ try {
91
+ for (let idx = 0; idx < prepared.length; idx++) {
92
+ const p = prepared[idx];
93
+ if (p.type === "text") {
94
+ out.push({ type: "text", text: p.text });
95
+ }
96
+ else if (p.type === "inline_file") {
97
+ const sha = createHash("sha256").update(p.data).digest("hex");
98
+ const cached = opts.idempotencyKey && opts.uploadCache
99
+ ? opts.uploadCache.get(sessionId, opts.idempotencyKey, idx, sha)
100
+ : undefined;
101
+ if (cached) {
102
+ out.push(makeFileMessagePart(cached.artifactId, cached.filename, cached.mediaType));
103
+ continue;
104
+ }
105
+ const uploaded = await uploadArtifact(http, sessionId, p.data, {
106
+ filename: p.filename,
107
+ mediaType: p.mediaType,
108
+ });
109
+ let cacheEntry;
110
+ if (opts.idempotencyKey && opts.uploadCache) {
111
+ cacheEntry = [sessionId, opts.idempotencyKey, idx, sha];
112
+ opts.uploadCache.put(sessionId, opts.idempotencyKey, idx, sha, uploaded);
113
+ }
114
+ newlyUploaded.push({ artifactId: uploaded.artifactId, cacheEntry });
115
+ out.push(makeFileMessagePart(uploaded.artifactId, uploaded.filename, uploaded.mediaType));
116
+ }
117
+ else if (p.type === "file_ref") {
118
+ const found = sessionArtifacts.get(p.fileId);
119
+ out.push(makeFileMessagePart(found.artifactId, (_c = p.filename) !== null && _c !== void 0 ? _c : found.filename, (_d = p.mediaType) !== null && _d !== void 0 ? _d : found.mediaType));
120
+ }
121
+ else {
122
+ refuse(provider, "input", { reason: "unsupported input part" });
123
+ }
124
+ }
125
+ }
126
+ catch (err) {
127
+ for (const item of newlyUploaded) {
128
+ await deleteArtifactBestEffort(http, sessionId, item.artifactId);
129
+ if (item.cacheEntry && opts.uploadCache) {
130
+ opts.uploadCache.evict(...item.cacheEntry);
131
+ }
132
+ }
133
+ throw err;
134
+ }
135
+ return { msgParts: out, newlyUploaded };
136
+ }
137
+ const WeakRefImpl = globalThis.WeakRef;
138
+ const FinalizationRegistryImpl = globalThis.FinalizationRegistry;
139
+ const listenerFinalizer = FinalizationRegistryImpl
140
+ ? new FinalizationRegistryImpl((streams) => {
141
+ for (const s of streams) {
142
+ try {
143
+ s.close();
144
+ }
145
+ catch ( /* ignore */_a) { /* ignore */ }
146
+ }
147
+ })
148
+ : null;
149
+ function makeRef(listener) {
150
+ return WeakRefImpl ? new WeakRefImpl(listener) : { deref: () => listener };
151
+ }
152
+ export class ListenerRegistry {
153
+ constructor() {
154
+ this.listeners = new Map();
155
+ }
156
+ register(sessionId, listener) {
157
+ var _a;
158
+ const list = (_a = this.listeners.get(sessionId)) !== null && _a !== void 0 ? _a : [];
159
+ list.push(makeRef(listener));
160
+ this.listeners.set(sessionId, list);
161
+ }
162
+ unregister(sessionId, listener) {
163
+ const list = this.listeners.get(sessionId);
164
+ if (!list)
165
+ return;
166
+ const kept = list.filter((ref) => {
167
+ const target = ref.deref();
168
+ return target !== undefined && target !== listener;
169
+ });
170
+ if (kept.length > 0)
171
+ this.listeners.set(sessionId, kept);
172
+ else
173
+ this.listeners.delete(sessionId);
174
+ }
175
+ liveListeners(sessionId) {
176
+ const refs = this.listeners.get(sessionId);
177
+ if (!refs)
178
+ return [];
179
+ const live = [];
180
+ const kept = [];
181
+ for (const r of refs) {
182
+ const obj = r.deref();
183
+ if (obj && !obj.isClosed) {
184
+ live.push(obj);
185
+ kept.push(r);
186
+ }
187
+ }
188
+ if (kept.length > 0)
189
+ this.listeners.set(sessionId, kept);
190
+ else
191
+ this.listeners.delete(sessionId);
192
+ return live;
193
+ }
194
+ handoffOrClose(sessionId, stream) {
195
+ const listeners = this.liveListeners(sessionId);
196
+ // Priority 1: listeners already actively iterating.
197
+ for (const l of listeners) {
198
+ if (l.isIterating && l.handoff(stream))
199
+ return true;
200
+ }
201
+ // Priority 2: newest non-abandoned uniterated listener without an already-queued stream.
202
+ const now = Date.now();
203
+ const uniterated = listeners.filter((l) => !l.isIterating);
204
+ const abandoned = [];
205
+ let chosen = null;
206
+ for (let i = uniterated.length - 1; i >= 0; i--) {
207
+ const l = uniterated[i];
208
+ if (l.hasQueuedStream || now - l.createdAt > UNITERATED_TTL_MS) {
209
+ abandoned.push(l);
210
+ continue;
211
+ }
212
+ if (!chosen && l.handoff(stream)) {
213
+ chosen = l;
214
+ }
215
+ }
216
+ for (const dead of abandoned)
217
+ dead.close();
218
+ if (chosen)
219
+ return true;
220
+ stream.close();
221
+ return false;
222
+ }
223
+ }
224
+ export class Listener {
225
+ constructor(sessionId, turns, pollIntervalMs, maxPolls, pollTimeoutMs, initialStream, reqOpts) {
226
+ this.sessionId = sessionId;
227
+ this.turns = turns;
228
+ this.pollIntervalMs = pollIntervalMs;
229
+ this.maxPolls = maxPolls;
230
+ this.pollTimeoutMs = pollTimeoutMs;
231
+ this.reqOpts = reqOpts;
232
+ this.turnEnded = false;
233
+ this.createdAt = Date.now();
234
+ this.closed = false;
235
+ this.iterating = false;
236
+ this.queue = [];
237
+ this.waitResolve = null;
238
+ this.activeStream = null;
239
+ if (initialStream)
240
+ this.queue.push(initialStream);
241
+ listenerFinalizer === null || listenerFinalizer === void 0 ? void 0 : listenerFinalizer.register(this, this.queue, this);
242
+ }
243
+ get isClosed() {
244
+ return this.closed;
245
+ }
246
+ get isIterating() {
247
+ return this.iterating;
248
+ }
249
+ get hasQueuedStream() {
250
+ return this.queue.length > 0 || this.activeStream !== null;
251
+ }
252
+ handoff(stream) {
253
+ if (this.closed)
254
+ return false;
255
+ if (this.waitResolve) {
256
+ const r = this.waitResolve;
257
+ this.waitResolve = null;
258
+ r(stream);
259
+ return true;
260
+ }
261
+ this.queue.push(stream);
262
+ return true;
263
+ }
264
+ close() {
265
+ if (this.closed)
266
+ return;
267
+ this.closed = true;
268
+ listenerFinalizer === null || listenerFinalizer === void 0 ? void 0 : listenerFinalizer.unregister(this);
269
+ this.turns._registry.unregister(this.sessionId, this);
270
+ if (this.activeStream) {
271
+ try {
272
+ this.activeStream.close();
273
+ }
274
+ catch ( /* ignore */_a) { /* ignore */ }
275
+ this.activeStream = null;
276
+ }
277
+ while (this.queue.length > 0) {
278
+ const s = this.queue.shift();
279
+ try {
280
+ s.close();
281
+ }
282
+ catch ( /* ignore */_b) { /* ignore */ }
283
+ }
284
+ if (this.waitResolve) {
285
+ const r = this.waitResolve;
286
+ this.waitResolve = null;
287
+ r(null);
288
+ }
289
+ }
290
+ async *consume(stream) {
291
+ var _a;
292
+ if (this.closed) {
293
+ stream.close();
294
+ return;
295
+ }
296
+ this.activeStream = stream;
297
+ const machine = new TurnEvents((_a = stream.responseId) !== null && _a !== void 0 ? _a : "");
298
+ try {
299
+ for await (const chunk of stream) {
300
+ if (this.closed)
301
+ return;
302
+ for (const ev of machine.feed(chunk)) {
303
+ if (ev.kind === "turn_finished" ||
304
+ ev.kind === "turn_failed" ||
305
+ ev.kind === "stopped" ||
306
+ ev.kind === "function_calls_requested" ||
307
+ ev.kind === "clarify_requested") {
308
+ this.turnEnded = true;
309
+ }
310
+ yield ev;
311
+ }
312
+ }
313
+ }
314
+ finally {
315
+ if (this.activeStream === stream)
316
+ this.activeStream = null;
317
+ try {
318
+ stream.close();
319
+ }
320
+ catch ( /* ignore */_b) { /* ignore */ }
321
+ }
322
+ }
323
+ async *drainQueued(first) {
324
+ let cur = first;
325
+ while (cur && !this.closed) {
326
+ yield* this.consume(cur);
327
+ cur = this.queue.shift();
328
+ }
329
+ }
330
+ async *[Symbol.asyncIterator]() {
331
+ this.iterating = true;
332
+ try {
333
+ const first = this.queue.shift();
334
+ if (first) {
335
+ yield* this.drainQueued(first);
336
+ return;
337
+ }
338
+ let polls = 0;
339
+ let delayMs = this.pollIntervalMs;
340
+ let elapsedMs = 0;
341
+ const startWall = Date.now();
342
+ while (!this.closed) {
343
+ const queued = this.queue.shift();
344
+ if (queued) {
345
+ yield* this.drainQueued(queued);
346
+ return;
347
+ }
348
+ const rec = await this.turns._http.withRequestOptions(this.reqOpts, () => this.turns._sessions.retrieve(this.sessionId));
349
+ // Re-check handoff that may have arrived while retrieve() was in flight.
350
+ const queuedAfter = this.queue.shift();
351
+ if (queuedAfter) {
352
+ yield* this.drainQueued(queuedAfter);
353
+ return;
354
+ }
355
+ if (rec.activeResponseId) {
356
+ const rid = rec.activeResponseId;
357
+ const stream = await this.turns._http.withRequestOptions(this.reqOpts, () => this.turns._http.call(() => reconnect(this.turns._http.sdkConfig, this.sessionId, rid), { idempotent: false }));
358
+ yield* this.drainQueued(stream);
359
+ return;
360
+ }
361
+ const wallElapsed = Date.now() - startWall;
362
+ if (polls >= this.maxPolls || Math.max(elapsedMs, wallElapsed) >= this.pollTimeoutMs) {
363
+ throw new CoreTimeoutError(`Timed out waiting for a turn to start on session ${this.sessionId}.`);
364
+ }
365
+ polls += 1;
366
+ const handed = await new Promise((resolve) => {
367
+ const timer = setTimeout(() => {
368
+ if (this.waitResolve === done)
369
+ this.waitResolve = null;
370
+ resolve(null);
371
+ }, delayMs);
372
+ const done = (s) => {
373
+ clearTimeout(timer);
374
+ resolve(s);
375
+ };
376
+ this.waitResolve = done;
377
+ });
378
+ if (handed) {
379
+ yield* this.drainQueued(handed);
380
+ return;
381
+ }
382
+ elapsedMs += delayMs;
383
+ delayMs = Math.min(Math.round(delayMs * 1.5), 5000);
384
+ }
385
+ }
386
+ finally {
387
+ this.close();
388
+ }
389
+ }
390
+ }
391
+ export class Turns {
392
+ constructor(_http, _sessions, opts = {}) {
393
+ var _a, _b, _c, _d;
394
+ this._http = _http;
395
+ this._sessions = _sessions;
396
+ this.queueApi = new QueueApi(_http.sdkConfig);
397
+ this.responsesApi = new ResponsesApi(_http.sdkConfig);
398
+ this.pollIntervalMs = (_a = opts.pollIntervalMs) !== null && _a !== void 0 ? _a : 1000;
399
+ this.provider = (_b = opts.provider) !== null && _b !== void 0 ? _b : "openai";
400
+ this._registry = (_c = opts.registry) !== null && _c !== void 0 ? _c : new ListenerRegistry();
401
+ this.uploadCache = (_d = opts.uploadCache) !== null && _d !== void 0 ? _d : new AttachmentUploadCache();
402
+ }
403
+ handoffOrClose(sessionId, stream) {
404
+ return this._registry.handoffOrClose(sessionId, stream);
405
+ }
406
+ listen(sessionId, opts = {}) {
407
+ var _a, _b;
408
+ const listener = new Listener(sessionId, this, this.pollIntervalMs, (_a = opts.maxPolls) !== null && _a !== void 0 ? _a : 300, (_b = opts.pollTimeoutMs) !== null && _b !== void 0 ? _b : DEFAULT_POLL_TIMEOUT_MS, opts.initialStream, opts.reqOpts);
409
+ this._registry.register(sessionId, listener);
410
+ return listener;
411
+ }
412
+ async resolveParts(sessionId, parts, opts = {}) {
413
+ const { msgParts } = await resolveMessageParts(this._http, sessionId, parts, this.provider, {
414
+ idempotencyKey: opts.key,
415
+ uploadCache: this.uploadCache,
416
+ });
417
+ return msgParts;
418
+ }
419
+ async sendMessageParts(sessionId, agentId, msgParts, opts) {
420
+ const stream = await this._http.call(() => streamResponse(this._http.sdkConfig, {
421
+ id: sessionId,
422
+ agentId: agentId !== null && agentId !== void 0 ? agentId : undefined,
423
+ message: { id: opts.msgId, role: "user", parts: msgParts },
424
+ }), { idempotent: false });
425
+ if (opts.returnStream)
426
+ return stream;
427
+ this.handoffOrClose(sessionId, stream);
428
+ return null;
429
+ }
430
+ async send(sessionId, agentId, parts, opts = {}) {
431
+ var _a;
432
+ const msgId = (_a = opts.key) !== null && _a !== void 0 ? _a : this._http.newIdempotencyKey();
433
+ const { msgParts, newlyUploaded } = await resolveMessageParts(this._http, sessionId, parts, this.provider, {
434
+ idempotencyKey: opts.key,
435
+ uploadCache: this.uploadCache,
436
+ });
437
+ try {
438
+ return await this.sendMessageParts(sessionId, agentId, msgParts, { msgId, returnStream: opts.returnStream });
439
+ }
440
+ catch (err) {
441
+ if (err instanceof CoreAPIError && err.status !== null && err.status >= 400 && err.status < 500) {
442
+ for (const item of newlyUploaded) {
443
+ await deleteArtifactBestEffort(this._http, sessionId, item.artifactId);
444
+ if (item.cacheEntry)
445
+ this.uploadCache.evict(...item.cacheEntry);
446
+ }
447
+ }
448
+ throw err;
449
+ }
450
+ }
451
+ async steer(sessionId, agentId, parts, opts = {}) {
452
+ var _a, _b, _c;
453
+ const msgId = (_a = opts.key) !== null && _a !== void 0 ? _a : this._http.newIdempotencyKey();
454
+ const delivery = (_b = opts.delivery) !== null && _b !== void 0 ? _b : "now";
455
+ const { msgParts, newlyUploaded } = await resolveMessageParts(this._http, sessionId, parts, this.provider, {
456
+ idempotencyKey: opts.key,
457
+ uploadCache: this.uploadCache,
458
+ });
459
+ try {
460
+ await this._http.call(() => this.queueApi.queueMessage({
461
+ conversationId: sessionId,
462
+ queueMessageInput: {
463
+ message: { id: msgId, role: "user", parts: msgParts },
464
+ delivery,
465
+ agentId: agentId !== null && agentId !== void 0 ? agentId : undefined,
466
+ },
467
+ }), { idempotent: false });
468
+ }
469
+ catch (err) {
470
+ // Fall back to starting a new turn only when Panja rejects with a no-active-turn error.
471
+ // Reuse already-resolved msgParts so inline files are never uploaded twice.
472
+ // A 202 queued response (even with reason=no_active_turn) means Panja already accepted
473
+ // and queued the message, so we must not double-post to /v1/responses.
474
+ if (err instanceof CoreAPIError &&
475
+ (err.status === 404 || err.status === 409) &&
476
+ NO_ACTIVE_CODES.has((_c = err.code) !== null && _c !== void 0 ? _c : "")) {
477
+ await this.sendMessageParts(sessionId, agentId, msgParts, { msgId });
478
+ return;
479
+ }
480
+ if (err instanceof CoreAPIError && err.status !== null && err.status >= 400 && err.status < 500) {
481
+ for (const item of newlyUploaded) {
482
+ await deleteArtifactBestEffort(this._http, sessionId, item.artifactId);
483
+ if (item.cacheEntry)
484
+ this.uploadCache.evict(...item.cacheEntry);
485
+ }
486
+ }
487
+ throw err;
488
+ }
489
+ }
490
+ async stop(sessionId) {
491
+ await this._http.call(() => this.responsesApi.stopResponse({ conversationId: sessionId }), { idempotent: true });
492
+ }
493
+ async answerClarify(sessionId, requestId, answers) {
494
+ const stream = await this._http.call(() => answerClarify(this._http.sdkConfig, sessionId, { requestId, answers }), { idempotent: false });
495
+ this.handoffOrClose(sessionId, stream);
496
+ }
497
+ }
@@ -0,0 +1,6 @@
1
+ /** Once-per-process compatibility warnings. */
2
+ export declare class SarvamCompatWarning extends Error {
3
+ constructor(message: string);
4
+ }
5
+ export declare function warnOnce(code: string, message: string): void;
6
+ export declare function resetWarningsForTest(): void;
@@ -0,0 +1,20 @@
1
+ /** Once-per-process compatibility warnings. */
2
+ export class SarvamCompatWarning extends Error {
3
+ constructor(message) {
4
+ super(message);
5
+ this.name = "SarvamCompatWarning";
6
+ Object.setPrototypeOf(this, new.target.prototype);
7
+ }
8
+ }
9
+ const emitted = new Set();
10
+ export function warnOnce(code, message) {
11
+ if (emitted.has(code))
12
+ return;
13
+ emitted.add(code);
14
+ if (typeof process !== "undefined" && typeof process.emitWarning === "function") {
15
+ process.emitWarning(message, { type: "SarvamCompatWarning", code });
16
+ }
17
+ }
18
+ export function resetWarningsForTest() {
19
+ emitted.clear();
20
+ }
@@ -0,0 +1,3 @@
1
+ /** Drop-in compatibility entry point (OpenAI Hosted Agents API). */
2
+ export { OpenAI, SarvamAgents, type OpenAIOptions, type SarvamAgentsOptions } from "./openai/index.js";
3
+ export { default } from "./openai/index.js";
@@ -0,0 +1,3 @@
1
+ /** Drop-in compatibility entry point (OpenAI Hosted Agents API). */
2
+ export { OpenAI, SarvamAgents } from "./openai/index.js";
3
+ export { default } from "./openai/index.js";
@@ -0,0 +1,62 @@
1
+ import { AttachmentUploadCache } from "../core/files.js";
2
+ import { SessionUpdateQueue } from "../core/sessions.js";
3
+ import { ToolResultStore } from "../core/toolResults.js";
4
+ import { ListenerRegistry } from "../core/turns.js";
5
+ import { AgentsResource } from "./resources/agents.js";
6
+ import { SessionsResource } from "./resources/sessions.js";
7
+ import type { AgentSessionEventStream } from "./stream.js";
8
+ import type { AgentSession, RawResponse, RequestOptions } from "./types.js";
9
+ export interface OpenAIOptions {
10
+ apiKey?: string;
11
+ baseURL?: string;
12
+ timeout?: number;
13
+ maxRetries?: number;
14
+ defaultHeaders?: Record<string, string>;
15
+ defaultQuery?: Record<string, string>;
16
+ modelMap?: Record<string, string>;
17
+ strictModels?: boolean;
18
+ allowPrivateRemoteUrls?: boolean;
19
+ fetch?: typeof globalThis.fetch;
20
+ _sleep?: (ms: number) => Promise<void>;
21
+ _pollIntervalMs?: number;
22
+ _resolveHost?: (host: string) => Promise<string[]>;
23
+ _sharedRegistry?: ListenerRegistry;
24
+ _sharedToolStore?: ToolResultStore;
25
+ _sharedSessionQueue?: SessionUpdateQueue;
26
+ _sharedUploadCache?: AttachmentUploadCache;
27
+ }
28
+ export type RawResponseProxy<T> = {
29
+ readonly [K in keyof T]: T[K] extends (...args: infer A) => Promise<infer R> ? (...args: A) => Promise<RawResponse<R>> : T[K] extends (...args: infer A) => infer R ? (...args: A) => Promise<RawResponse<R>> : T[K] extends object ? RawResponseProxy<T[K]> : T[K];
30
+ };
31
+ export interface RawResponseSessionsResource extends Omit<RawResponseProxy<SessionsResource>, "create"> {
32
+ create(params: Record<string, unknown> & {
33
+ stream: true;
34
+ }, options?: RequestOptions): Promise<RawResponse<AgentSessionEventStream>>;
35
+ create(params: Record<string, unknown> & {
36
+ stream?: false;
37
+ }, options?: RequestOptions): Promise<RawResponse<AgentSession>>;
38
+ create(params?: Record<string, unknown>, options?: RequestOptions): Promise<RawResponse<AgentSession | AgentSessionEventStream>>;
39
+ }
40
+ export interface RawResponseAgentsResource extends Omit<RawResponseProxy<AgentsResource>, "sessions"> {
41
+ readonly sessions: RawResponseSessionsResource;
42
+ }
43
+ export interface RawResponseClient {
44
+ readonly beta: {
45
+ readonly agents: RawResponseAgentsResource;
46
+ };
47
+ }
48
+ export declare class OpenAI {
49
+ readonly beta: {
50
+ readonly agents: AgentsResource;
51
+ };
52
+ private readonly initOpts;
53
+ private readonly http;
54
+ private readonly listenerRegistry;
55
+ private readonly toolResultStore;
56
+ private readonly sessionUpdateQueue;
57
+ private readonly uploadCache;
58
+ constructor(opts?: OpenAIOptions);
59
+ get withRawResponse(): RawResponseClient;
60
+ withOptions(overrides: Partial<OpenAIOptions>): OpenAI;
61
+ close(): void;
62
+ }