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