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