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,317 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.Sessions = exports.SessionUpdateQueue = void 0;
|
|
4
|
+
/** Core Sessions service: neutral SessionRecord <-> Panja API conversations. */
|
|
5
|
+
const ConversationsApi_js_1 = require("../../apis/ConversationsApi.js");
|
|
6
|
+
const errors_js_1 = require("./errors.js");
|
|
7
|
+
function isObj(v) {
|
|
8
|
+
return v !== null && typeof v === "object" && !Array.isArray(v);
|
|
9
|
+
}
|
|
10
|
+
function clone(v) {
|
|
11
|
+
return JSON.parse(JSON.stringify(v));
|
|
12
|
+
}
|
|
13
|
+
function iso(v) {
|
|
14
|
+
if (v instanceof Date)
|
|
15
|
+
return v.toISOString();
|
|
16
|
+
if (typeof v === "string" && v)
|
|
17
|
+
return v;
|
|
18
|
+
return new Date().toISOString();
|
|
19
|
+
}
|
|
20
|
+
function extractCompat(rawMeta) {
|
|
21
|
+
if (!isObj(rawMeta))
|
|
22
|
+
return { metadata: {}, title: null, archived: false };
|
|
23
|
+
const compat = rawMeta["sdk_compat"];
|
|
24
|
+
if (isObj(compat)) {
|
|
25
|
+
const um = isObj(compat["metadata"]) ? compat["metadata"] : {};
|
|
26
|
+
const out = {};
|
|
27
|
+
for (const [k, v] of Object.entries(um))
|
|
28
|
+
out[k] = String(v);
|
|
29
|
+
const title = typeof compat["title"] === "string" ? compat["title"] : null;
|
|
30
|
+
const archived = Boolean(compat["archived"]);
|
|
31
|
+
return { metadata: out, title, archived };
|
|
32
|
+
}
|
|
33
|
+
const out = {};
|
|
34
|
+
for (const [k, v] of Object.entries(rawMeta)) {
|
|
35
|
+
if (k !== "sdk_compat" && typeof v === "string")
|
|
36
|
+
out[k] = v;
|
|
37
|
+
}
|
|
38
|
+
return { metadata: out, title: null, archived: false };
|
|
39
|
+
}
|
|
40
|
+
function parseRequiredActions(actions, responseId) {
|
|
41
|
+
var _a, _b, _c, _d, _e, _f, _g;
|
|
42
|
+
if (!Array.isArray(actions) || actions.length === 0)
|
|
43
|
+
return [];
|
|
44
|
+
const fnGroups = new Map();
|
|
45
|
+
const clarifySteps = [];
|
|
46
|
+
for (const a of actions) {
|
|
47
|
+
if (!isObj(a))
|
|
48
|
+
continue;
|
|
49
|
+
const aType = String((_a = a["type"]) !== null && _a !== void 0 ? _a : "function_call");
|
|
50
|
+
const reqId = String((_c = (_b = a["requestId"]) !== null && _b !== void 0 ? _b : a["request_id"]) !== null && _c !== void 0 ? _c : "");
|
|
51
|
+
if (aType === "clarify") {
|
|
52
|
+
const questions = Array.isArray(a["questions"]) ? a["questions"] : [];
|
|
53
|
+
clarifySteps.push({ requestId: reqId, responseId, kind: "clarify", calls: [], questions });
|
|
54
|
+
}
|
|
55
|
+
else {
|
|
56
|
+
const callId = String((_e = (_d = a["toolCallId"]) !== null && _d !== void 0 ? _d : a["tool_call_id"]) !== null && _e !== void 0 ? _e : "");
|
|
57
|
+
const name = String((_f = a["name"]) !== null && _f !== void 0 ? _f : "");
|
|
58
|
+
const args = isObj(a["arguments"]) ? a["arguments"] : {};
|
|
59
|
+
const list = (_g = fnGroups.get(reqId)) !== null && _g !== void 0 ? _g : [];
|
|
60
|
+
list.push({ callId, name, arguments: args });
|
|
61
|
+
fnGroups.set(reqId, list);
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
const steps = [];
|
|
65
|
+
for (const [requestId, calls] of fnGroups.entries()) {
|
|
66
|
+
steps.push({ requestId, responseId, kind: "function", calls, questions: [] });
|
|
67
|
+
}
|
|
68
|
+
steps.push(...clarifySteps);
|
|
69
|
+
return steps;
|
|
70
|
+
}
|
|
71
|
+
function detectPendingClarifyFromMessages(msgs, responseId) {
|
|
72
|
+
var _a, _b;
|
|
73
|
+
if (!Array.isArray(msgs) || msgs.length === 0)
|
|
74
|
+
return [];
|
|
75
|
+
const last = msgs[msgs.length - 1];
|
|
76
|
+
if (!isObj(last) || last["role"] !== "assistant")
|
|
77
|
+
return [];
|
|
78
|
+
const parts = last["parts"];
|
|
79
|
+
if (!Array.isArray(parts) || parts.length === 0)
|
|
80
|
+
return [];
|
|
81
|
+
let clarifyIdx = -1;
|
|
82
|
+
let clarifyPart = null;
|
|
83
|
+
for (let i = 0; i < parts.length; i++) {
|
|
84
|
+
const p = parts[i];
|
|
85
|
+
if (isObj(p) && p["type"] === "data-clarify-request") {
|
|
86
|
+
clarifyIdx = i;
|
|
87
|
+
clarifyPart = p;
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
if (!clarifyPart)
|
|
91
|
+
return [];
|
|
92
|
+
for (const p of parts.slice(clarifyIdx + 1)) {
|
|
93
|
+
if (!isObj(p))
|
|
94
|
+
continue;
|
|
95
|
+
const pt = p["type"];
|
|
96
|
+
if (pt === "reasoning" || pt === "step-start")
|
|
97
|
+
continue;
|
|
98
|
+
if (pt === "data-output" && isObj(p["data"]) && p["data"]["skipped"] === "paused")
|
|
99
|
+
continue;
|
|
100
|
+
return [];
|
|
101
|
+
}
|
|
102
|
+
const data = isObj(clarifyPart["data"]) ? clarifyPart["data"] : {};
|
|
103
|
+
const reqId = String((_b = (_a = data["requestId"]) !== null && _a !== void 0 ? _a : clarifyPart["id"]) !== null && _b !== void 0 ? _b : "");
|
|
104
|
+
const questions = Array.isArray(data["questions"]) ? data["questions"] : [];
|
|
105
|
+
return [{ requestId: reqId, responseId, kind: "clarify", calls: [], questions }];
|
|
106
|
+
}
|
|
107
|
+
function toRecord(conv) {
|
|
108
|
+
var _a, _b;
|
|
109
|
+
const c = (conv !== null && conv !== void 0 ? conv : {});
|
|
110
|
+
const rawMetadata = isObj(c["metadata"]) ? clone(c["metadata"]) : {};
|
|
111
|
+
const { metadata, title: compatTitle, archived } = extractCompat(rawMetadata);
|
|
112
|
+
const title = (typeof c["title"] === "string" && c["title"]) ? c["title"] : compatTitle;
|
|
113
|
+
const activeId = typeof c["activeResponseId"] === "string" && c["activeResponseId"] ? c["activeResponseId"] : null;
|
|
114
|
+
const agentIdRaw = (_a = c["targetAgentId"]) !== null && _a !== void 0 ? _a : c["targetId"];
|
|
115
|
+
const agentId = typeof agentIdRaw === "string" && agentIdRaw ? agentIdRaw : null;
|
|
116
|
+
let lastMsgId = activeId !== null && activeId !== void 0 ? activeId : "";
|
|
117
|
+
const msgs = c["messages"];
|
|
118
|
+
if (!lastMsgId && Array.isArray(msgs)) {
|
|
119
|
+
for (let i = msgs.length - 1; i >= 0; i--) {
|
|
120
|
+
const m = msgs[i];
|
|
121
|
+
if (isObj(m) && m["role"] === "assistant" && typeof m["id"] === "string") {
|
|
122
|
+
lastMsgId = m["id"];
|
|
123
|
+
break;
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
let required = parseRequiredActions(c["requiredActions"], lastMsgId);
|
|
128
|
+
if (required.length === 0) {
|
|
129
|
+
required = detectPendingClarifyFromMessages(msgs, lastMsgId);
|
|
130
|
+
}
|
|
131
|
+
const status = required.length > 0 ? "requires_action" : activeId ? "running" : "idle";
|
|
132
|
+
return {
|
|
133
|
+
id: String((_b = c["id"]) !== null && _b !== void 0 ? _b : ""),
|
|
134
|
+
agentId,
|
|
135
|
+
metadata,
|
|
136
|
+
title: title !== null && title !== void 0 ? title : null,
|
|
137
|
+
status,
|
|
138
|
+
activeResponseId: activeId,
|
|
139
|
+
required,
|
|
140
|
+
createdAt: iso(c["createdAt"]),
|
|
141
|
+
archived,
|
|
142
|
+
rawMetadata,
|
|
143
|
+
};
|
|
144
|
+
}
|
|
145
|
+
class SessionUpdateQueue {
|
|
146
|
+
constructor() {
|
|
147
|
+
this.tails = new Map();
|
|
148
|
+
}
|
|
149
|
+
async run(sessionId, fn) {
|
|
150
|
+
var _a;
|
|
151
|
+
const prev = (_a = this.tails.get(sessionId)) !== null && _a !== void 0 ? _a : Promise.resolve();
|
|
152
|
+
let release;
|
|
153
|
+
const gate = new Promise((resolve) => {
|
|
154
|
+
release = resolve;
|
|
155
|
+
});
|
|
156
|
+
const tail = prev.then(() => gate, () => gate);
|
|
157
|
+
this.tails.set(sessionId, tail);
|
|
158
|
+
await prev.catch(() => { });
|
|
159
|
+
try {
|
|
160
|
+
return await fn();
|
|
161
|
+
}
|
|
162
|
+
finally {
|
|
163
|
+
release();
|
|
164
|
+
if (this.tails.get(sessionId) === tail) {
|
|
165
|
+
this.tails.delete(sessionId);
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
exports.SessionUpdateQueue = SessionUpdateQueue;
|
|
171
|
+
class Sessions {
|
|
172
|
+
constructor(http, opts = {}) {
|
|
173
|
+
var _a, _b;
|
|
174
|
+
this.http = http;
|
|
175
|
+
this.api = new ConversationsApi_js_1.ConversationsApi(http.sdkConfig);
|
|
176
|
+
this.provider = (_a = opts.provider) !== null && _a !== void 0 ? _a : "openai";
|
|
177
|
+
this.updateQueue = (_b = opts.updateQueue) !== null && _b !== void 0 ? _b : new SessionUpdateQueue();
|
|
178
|
+
}
|
|
179
|
+
async create(opts) {
|
|
180
|
+
var _a, _b;
|
|
181
|
+
const sdkCompat = {
|
|
182
|
+
provider: (_a = opts.provider) !== null && _a !== void 0 ? _a : this.provider,
|
|
183
|
+
metadata: Object.fromEntries(Object.entries((_b = opts.metadata) !== null && _b !== void 0 ? _b : {}).map(([k, v]) => [k, String(v)])),
|
|
184
|
+
archived: false,
|
|
185
|
+
};
|
|
186
|
+
if (opts.title !== undefined)
|
|
187
|
+
sdkCompat["title"] = opts.title;
|
|
188
|
+
// POST /v1/conversations is not deduplicated server-side by Idempotency-Key; never auto-retry.
|
|
189
|
+
const conv = await this.http.call(() => this.api.createConversation({
|
|
190
|
+
createConversationBody: {
|
|
191
|
+
agentId: opts.agentId,
|
|
192
|
+
title: opts.title,
|
|
193
|
+
metadata: { sdk_compat: sdkCompat },
|
|
194
|
+
},
|
|
195
|
+
}), { idempotent: false });
|
|
196
|
+
return toRecord(conv);
|
|
197
|
+
}
|
|
198
|
+
async retrieve(sessionId) {
|
|
199
|
+
const conv = await this.http.call(() => this.api.getConversation({ conversationId: sessionId }), { idempotent: true });
|
|
200
|
+
return toRecord(conv);
|
|
201
|
+
}
|
|
202
|
+
async update(sessionId, opts) {
|
|
203
|
+
return this.updateQueue.run(sessionId, async () => {
|
|
204
|
+
const current = await this.retrieve(sessionId);
|
|
205
|
+
const merged = { ...current.metadata };
|
|
206
|
+
if (opts.metadata) {
|
|
207
|
+
for (const [k, v] of Object.entries(opts.metadata)) {
|
|
208
|
+
if (v === null)
|
|
209
|
+
delete merged[k];
|
|
210
|
+
else
|
|
211
|
+
merged[k] = String(v);
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
const newTitle = opts.title !== undefined ? opts.title : current.title;
|
|
215
|
+
const existingCompat = isObj(current.rawMetadata["sdk_compat"]) ? current.rawMetadata["sdk_compat"] : {};
|
|
216
|
+
const sdkCompat = {
|
|
217
|
+
provider: typeof existingCompat["provider"] === "string" ? existingCompat["provider"] : this.provider,
|
|
218
|
+
metadata: merged,
|
|
219
|
+
archived: current.archived,
|
|
220
|
+
};
|
|
221
|
+
if (newTitle !== null)
|
|
222
|
+
sdkCompat["title"] = newTitle;
|
|
223
|
+
const fullMeta = clone(current.rawMetadata);
|
|
224
|
+
fullMeta["sdk_compat"] = sdkCompat;
|
|
225
|
+
const conv = await this.http.call(() => this.api.updateConversation({
|
|
226
|
+
conversationId: sessionId,
|
|
227
|
+
updateConversationBody: {
|
|
228
|
+
title: newTitle !== null && newTitle !== void 0 ? newTitle : undefined,
|
|
229
|
+
metadata: fullMeta,
|
|
230
|
+
},
|
|
231
|
+
}), { idempotent: true });
|
|
232
|
+
return toRecord(conv);
|
|
233
|
+
});
|
|
234
|
+
}
|
|
235
|
+
async listCursor(opts = {}) {
|
|
236
|
+
var _a, _b, _c, _d;
|
|
237
|
+
const limit = (_a = opts.limit) !== null && _a !== void 0 ? _a : 20;
|
|
238
|
+
const matched = opts.buffered ? [...opts.buffered] : [];
|
|
239
|
+
const filtered = opts.agentId !== undefined || opts.metadata !== undefined;
|
|
240
|
+
const target = filtered ? limit + 1 : limit;
|
|
241
|
+
let cur = opts.cursor;
|
|
242
|
+
let nextCursor = (_b = opts.cursor) !== null && _b !== void 0 ? _b : null;
|
|
243
|
+
let moreOnServer = opts.cursor !== undefined;
|
|
244
|
+
let exhausted = opts.buffered !== undefined && opts.cursor === undefined;
|
|
245
|
+
while (matched.length < target && !exhausted) {
|
|
246
|
+
const c = cur;
|
|
247
|
+
const reqLimit = filtered ? 100 : Math.min(100, target - matched.length);
|
|
248
|
+
const page = await this.http.call(() => this.api.listConversations({ limit: reqLimit, cursor: c, sessionType: "api" }), { idempotent: true });
|
|
249
|
+
const items = (_c = page.data) !== null && _c !== void 0 ? _c : [];
|
|
250
|
+
nextCursor = (_d = page.nextCursor) !== null && _d !== void 0 ? _d : null;
|
|
251
|
+
moreOnServer = Boolean(page.hasMore || nextCursor);
|
|
252
|
+
for (const item of items) {
|
|
253
|
+
const rec = toRecord(item);
|
|
254
|
+
if (opts.agentId !== undefined && rec.agentId !== opts.agentId)
|
|
255
|
+
continue;
|
|
256
|
+
if (opts.metadata !== undefined) {
|
|
257
|
+
const ok = Object.entries(opts.metadata).every(([k, v]) => rec.metadata[k] === v);
|
|
258
|
+
if (!ok)
|
|
259
|
+
continue;
|
|
260
|
+
}
|
|
261
|
+
matched.push(rec);
|
|
262
|
+
}
|
|
263
|
+
if (items.length === 0 || !nextCursor) {
|
|
264
|
+
nextCursor = null;
|
|
265
|
+
moreOnServer = false;
|
|
266
|
+
exhausted = true;
|
|
267
|
+
break;
|
|
268
|
+
}
|
|
269
|
+
cur = nextCursor;
|
|
270
|
+
}
|
|
271
|
+
const pageItems = matched.slice(0, limit);
|
|
272
|
+
const leftover = matched.slice(limit);
|
|
273
|
+
const hasMore = leftover.length > 0 || (!filtered && moreOnServer && nextCursor !== null);
|
|
274
|
+
return { items: pageItems, nextCursor, hasMore, leftover };
|
|
275
|
+
}
|
|
276
|
+
async list(offset = 0, limit = 20, filters = {}) {
|
|
277
|
+
var _a, _b;
|
|
278
|
+
const matched = [];
|
|
279
|
+
let cursor;
|
|
280
|
+
const target = offset + limit + 1;
|
|
281
|
+
while (matched.length < target) {
|
|
282
|
+
const c = cursor;
|
|
283
|
+
const page = await this.http.call(() => this.api.listConversations({ limit: 100, cursor: c, sessionType: "api" }), { idempotent: true });
|
|
284
|
+
const items = (_a = page.data) !== null && _a !== void 0 ? _a : [];
|
|
285
|
+
for (const item of items) {
|
|
286
|
+
const rec = toRecord(item);
|
|
287
|
+
if (filters.agentId !== undefined && rec.agentId !== filters.agentId)
|
|
288
|
+
continue;
|
|
289
|
+
if (filters.metadata !== undefined) {
|
|
290
|
+
const ok = Object.entries(filters.metadata).every(([k, v]) => rec.metadata[k] === v);
|
|
291
|
+
if (!ok)
|
|
292
|
+
continue;
|
|
293
|
+
}
|
|
294
|
+
matched.push(rec);
|
|
295
|
+
}
|
|
296
|
+
const nextCursor = (_b = page.nextCursor) !== null && _b !== void 0 ? _b : undefined;
|
|
297
|
+
if (items.length === 0 || !nextCursor)
|
|
298
|
+
break;
|
|
299
|
+
cursor = nextCursor;
|
|
300
|
+
}
|
|
301
|
+
return [matched.slice(offset, offset + limit), matched.length > offset + limit];
|
|
302
|
+
}
|
|
303
|
+
async delete(sessionId) {
|
|
304
|
+
await this.http.call(() => this.api.deleteConversation({ conversationId: sessionId }), { idempotent: true });
|
|
305
|
+
}
|
|
306
|
+
async ensureNotArchived(sessionId) {
|
|
307
|
+
const rec = await this.retrieve(sessionId);
|
|
308
|
+
if (rec.archived) {
|
|
309
|
+
throw new errors_js_1.CoreAPIError(`Session ${sessionId} is archived and cannot accept new events.`, {
|
|
310
|
+
status: 400,
|
|
311
|
+
code: "invalid_request_error",
|
|
312
|
+
});
|
|
313
|
+
}
|
|
314
|
+
return rec;
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
exports.Sessions = Sessions;
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { Http } from "./http.js";
|
|
2
|
+
import { Sessions, type PendingStep } from "./sessions.js";
|
|
3
|
+
import { Turns } from "./turns.js";
|
|
4
|
+
export type SubmitOutcome = "held" | "posted" | "duplicate";
|
|
5
|
+
interface BufferedResult {
|
|
6
|
+
output: string;
|
|
7
|
+
isError: boolean;
|
|
8
|
+
}
|
|
9
|
+
interface StepBuffer {
|
|
10
|
+
step: PendingStep;
|
|
11
|
+
results: Map<string, BufferedResult>;
|
|
12
|
+
callKeys: Map<string, string[]>;
|
|
13
|
+
createdAt: number;
|
|
14
|
+
postFailed: boolean;
|
|
15
|
+
idemKey: string | null;
|
|
16
|
+
}
|
|
17
|
+
export declare class ToolResultStore {
|
|
18
|
+
readonly buffers: Map<string, StepBuffer>;
|
|
19
|
+
readonly callIndex: Map<string, string>;
|
|
20
|
+
readonly completed: Map<string, number>;
|
|
21
|
+
bufKey(sessionId: string, requestId: string): string;
|
|
22
|
+
callKey(sessionId: string, callId: string): string;
|
|
23
|
+
completedKey(sessionId: string, callId: string, key: string): string;
|
|
24
|
+
removeBuffer(key: string): void;
|
|
25
|
+
evictStale(): void;
|
|
26
|
+
markCompleted(sessionId: string, callIds: string[], keys: string[]): void;
|
|
27
|
+
isCompleted(sessionId: string, callId: string, key?: string): boolean;
|
|
28
|
+
}
|
|
29
|
+
export declare class ToolResults {
|
|
30
|
+
private readonly http;
|
|
31
|
+
private readonly sessions;
|
|
32
|
+
private readonly turns;
|
|
33
|
+
private readonly store;
|
|
34
|
+
constructor(http: Http, sessions: Sessions, turns: Turns, opts?: {
|
|
35
|
+
store?: ToolResultStore;
|
|
36
|
+
});
|
|
37
|
+
private findStep;
|
|
38
|
+
submit(sessionId: string, callId: string, output: string, opts?: {
|
|
39
|
+
isError?: boolean;
|
|
40
|
+
key?: string;
|
|
41
|
+
}): Promise<SubmitOutcome>;
|
|
42
|
+
}
|
|
43
|
+
export {};
|
|
@@ -0,0 +1,208 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.ToolResults = exports.ToolResultStore = void 0;
|
|
4
|
+
/** Per-step tool-result collector: buffers per-call results until a Panja step is complete. */
|
|
5
|
+
const node_crypto_1 = require("node:crypto");
|
|
6
|
+
const functionTool_js_1 = require("../../compose/functionTool.js");
|
|
7
|
+
const streaming_js_1 = require("../../streaming.js");
|
|
8
|
+
const errors_js_1 = require("./errors.js");
|
|
9
|
+
const BUFFER_TTL_MS = 3600000;
|
|
10
|
+
const MAX_BUFFERS = 1024;
|
|
11
|
+
function stepKey(requestId) {
|
|
12
|
+
return (0, node_crypto_1.createHash)("sha256").update(requestId, "utf8").digest("hex");
|
|
13
|
+
}
|
|
14
|
+
class ToolResultStore {
|
|
15
|
+
constructor() {
|
|
16
|
+
this.buffers = new Map();
|
|
17
|
+
this.callIndex = new Map();
|
|
18
|
+
this.completed = new Map();
|
|
19
|
+
}
|
|
20
|
+
bufKey(sessionId, requestId) {
|
|
21
|
+
return `${sessionId}::${requestId}`;
|
|
22
|
+
}
|
|
23
|
+
callKey(sessionId, callId) {
|
|
24
|
+
return `${sessionId}::${callId}`;
|
|
25
|
+
}
|
|
26
|
+
completedKey(sessionId, callId, key) {
|
|
27
|
+
return `${sessionId}::${callId}::${key}`;
|
|
28
|
+
}
|
|
29
|
+
removeBuffer(key) {
|
|
30
|
+
const buf = this.buffers.get(key);
|
|
31
|
+
if (!buf)
|
|
32
|
+
return;
|
|
33
|
+
this.buffers.delete(key);
|
|
34
|
+
const sid = key.slice(0, key.indexOf("::"));
|
|
35
|
+
for (const c of buf.step.calls) {
|
|
36
|
+
this.callIndex.delete(this.callKey(sid, c.callId));
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
evictStale() {
|
|
40
|
+
const now = Date.now();
|
|
41
|
+
for (const [k, b] of this.buffers.entries()) {
|
|
42
|
+
if (now - b.createdAt > BUFFER_TTL_MS)
|
|
43
|
+
this.removeBuffer(k);
|
|
44
|
+
}
|
|
45
|
+
while (this.buffers.size > MAX_BUFFERS) {
|
|
46
|
+
let oldestKey = null;
|
|
47
|
+
let oldestTs = Infinity;
|
|
48
|
+
for (const [k, b] of this.buffers.entries()) {
|
|
49
|
+
if (b.createdAt < oldestTs) {
|
|
50
|
+
oldestTs = b.createdAt;
|
|
51
|
+
oldestKey = k;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
if (!oldestKey)
|
|
55
|
+
break;
|
|
56
|
+
this.removeBuffer(oldestKey);
|
|
57
|
+
}
|
|
58
|
+
for (const [k, ts] of this.completed.entries()) {
|
|
59
|
+
if (now - ts > BUFFER_TTL_MS)
|
|
60
|
+
this.completed.delete(k);
|
|
61
|
+
}
|
|
62
|
+
while (this.completed.size > MAX_BUFFERS) {
|
|
63
|
+
const oldest = this.completed.keys().next().value;
|
|
64
|
+
if (oldest === undefined)
|
|
65
|
+
break;
|
|
66
|
+
this.completed.delete(oldest);
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
markCompleted(sessionId, callIds, keys) {
|
|
70
|
+
const now = Date.now();
|
|
71
|
+
for (const cid of callIds) {
|
|
72
|
+
for (const k of keys) {
|
|
73
|
+
if (k)
|
|
74
|
+
this.completed.set(this.completedKey(sessionId, cid, k), now);
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
isCompleted(sessionId, callId, key) {
|
|
79
|
+
if (!key)
|
|
80
|
+
return false;
|
|
81
|
+
const ck = this.completedKey(sessionId, callId, key);
|
|
82
|
+
const ts = this.completed.get(ck);
|
|
83
|
+
if (ts === undefined)
|
|
84
|
+
return false;
|
|
85
|
+
if (Date.now() - ts > BUFFER_TTL_MS) {
|
|
86
|
+
this.completed.delete(ck);
|
|
87
|
+
return false;
|
|
88
|
+
}
|
|
89
|
+
return true;
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
exports.ToolResultStore = ToolResultStore;
|
|
93
|
+
class ToolResults {
|
|
94
|
+
constructor(http, sessions, turns, opts = {}) {
|
|
95
|
+
var _a;
|
|
96
|
+
this.http = http;
|
|
97
|
+
this.sessions = sessions;
|
|
98
|
+
this.turns = turns;
|
|
99
|
+
this.store = (_a = opts.store) !== null && _a !== void 0 ? _a : new ToolResultStore();
|
|
100
|
+
}
|
|
101
|
+
async findStep(sessionId, callId) {
|
|
102
|
+
this.store.evictStale();
|
|
103
|
+
const existingKey = this.store.callIndex.get(this.store.callKey(sessionId, callId));
|
|
104
|
+
if (existingKey) {
|
|
105
|
+
const existing = this.store.buffers.get(existingKey);
|
|
106
|
+
if (existing)
|
|
107
|
+
return existing;
|
|
108
|
+
}
|
|
109
|
+
const rec = await this.sessions.retrieve(sessionId);
|
|
110
|
+
for (const step of rec.required) {
|
|
111
|
+
if (step.kind === "function" && step.calls.some((c) => c.callId === callId)) {
|
|
112
|
+
const key = this.store.bufKey(sessionId, step.requestId);
|
|
113
|
+
let buf = this.store.buffers.get(key);
|
|
114
|
+
if (!buf) {
|
|
115
|
+
buf = { step, results: new Map(), callKeys: new Map(), createdAt: Date.now(), postFailed: false, idemKey: null };
|
|
116
|
+
this.store.buffers.set(key, buf);
|
|
117
|
+
for (const c of step.calls) {
|
|
118
|
+
this.store.callIndex.set(this.store.callKey(sessionId, c.callId), key);
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
return buf;
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
return null;
|
|
125
|
+
}
|
|
126
|
+
async submit(sessionId, callId, output, opts = {}) {
|
|
127
|
+
var _a, _b;
|
|
128
|
+
this.store.evictStale();
|
|
129
|
+
if (this.store.isCompleted(sessionId, callId, opts.key)) {
|
|
130
|
+
return "duplicate";
|
|
131
|
+
}
|
|
132
|
+
const buf = await this.findStep(sessionId, callId);
|
|
133
|
+
if (!buf) {
|
|
134
|
+
if (this.store.isCompleted(sessionId, callId, opts.key)) {
|
|
135
|
+
return "duplicate";
|
|
136
|
+
}
|
|
137
|
+
throw new errors_js_1.CoreAPIError(`No pending function call with id ${JSON.stringify(callId)} in session ${sessionId}.`, {
|
|
138
|
+
status: 404,
|
|
139
|
+
code: "not_found",
|
|
140
|
+
param: callId,
|
|
141
|
+
});
|
|
142
|
+
}
|
|
143
|
+
if (buf.results.has(callId) && !buf.postFailed)
|
|
144
|
+
return "duplicate";
|
|
145
|
+
buf.results.set(callId, { output, isError: Boolean(opts.isError) });
|
|
146
|
+
if (opts.key) {
|
|
147
|
+
let seen = buf.callKeys.get(callId);
|
|
148
|
+
if (!seen) {
|
|
149
|
+
seen = [];
|
|
150
|
+
buf.callKeys.set(callId, seen);
|
|
151
|
+
}
|
|
152
|
+
if (!seen.includes(opts.key))
|
|
153
|
+
seen.push(opts.key);
|
|
154
|
+
}
|
|
155
|
+
const expectedIds = buf.step.calls.map((c) => c.callId);
|
|
156
|
+
if (!expectedIds.every((cid) => buf.results.has(cid)))
|
|
157
|
+
return "held";
|
|
158
|
+
const rawOutputs = expectedIds.map((cid) => buf.results.get(cid).output);
|
|
159
|
+
const flags = expectedIds.map((cid) => buf.results.get(cid).isError);
|
|
160
|
+
const truncated = (0, functionTool_js_1.fit)(rawOutputs);
|
|
161
|
+
const requestId = buf.step.requestId;
|
|
162
|
+
if (!buf.idemKey)
|
|
163
|
+
buf.idemKey = (_a = opts.key) !== null && _a !== void 0 ? _a : stepKey(requestId);
|
|
164
|
+
const idem = buf.idemKey;
|
|
165
|
+
try {
|
|
166
|
+
const stream = await this.http.call(() => (0, streaming_js_1.postToolResults)(this.http.sdkConfig, sessionId, {
|
|
167
|
+
requestId,
|
|
168
|
+
results: expectedIds.map((cid, i) => ({
|
|
169
|
+
toolCallId: cid,
|
|
170
|
+
output: truncated[i],
|
|
171
|
+
isError: flags[i],
|
|
172
|
+
})),
|
|
173
|
+
}, { idempotencyKey: idem }), { idempotent: true });
|
|
174
|
+
this.store.removeBuffer(this.store.bufKey(sessionId, requestId));
|
|
175
|
+
for (const cid of expectedIds) {
|
|
176
|
+
const cidKeys = [...((_b = buf.callKeys.get(cid)) !== null && _b !== void 0 ? _b : [])];
|
|
177
|
+
if (idem && !cidKeys.includes(idem))
|
|
178
|
+
cidKeys.push(idem);
|
|
179
|
+
if (opts.key && !cidKeys.includes(opts.key))
|
|
180
|
+
cidKeys.push(opts.key);
|
|
181
|
+
this.store.markCompleted(sessionId, [cid], cidKeys);
|
|
182
|
+
}
|
|
183
|
+
if (!stream.duplicate)
|
|
184
|
+
this.turns.handoffOrClose(sessionId, stream);
|
|
185
|
+
else
|
|
186
|
+
stream.close();
|
|
187
|
+
return "posted";
|
|
188
|
+
}
|
|
189
|
+
catch (err) {
|
|
190
|
+
if (err instanceof errors_js_1.CoreAPIError &&
|
|
191
|
+
err.status === 409 &&
|
|
192
|
+
(err.code === "expired" || err.code === "already_answered" || err.code === "stopped" || err.code === "ended")) {
|
|
193
|
+
this.store.removeBuffer(this.store.bufKey(sessionId, requestId));
|
|
194
|
+
throw new errors_js_1.CoreAPIError(`Tool call ${JSON.stringify(callId)} (${err.code}): ${err.message}`, {
|
|
195
|
+
status: 409,
|
|
196
|
+
code: err.code,
|
|
197
|
+
param: callId,
|
|
198
|
+
requestId: err.requestId,
|
|
199
|
+
body: err.body,
|
|
200
|
+
headers: err.headers,
|
|
201
|
+
});
|
|
202
|
+
}
|
|
203
|
+
buf.postFailed = true;
|
|
204
|
+
throw err;
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
exports.ToolResults = ToolResults;
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
import type { MessagePart } from "../../models/MessagePart.js";
|
|
2
|
+
import { type ResponseStream } from "../../streaming.js";
|
|
3
|
+
import { type TurnEvent } from "./events.js";
|
|
4
|
+
import { AttachmentUploadCache } from "./files.js";
|
|
5
|
+
import { Http, type PerCallRequestOptions } from "./http.js";
|
|
6
|
+
import { Sessions } from "./sessions.js";
|
|
7
|
+
export type Part = {
|
|
8
|
+
type: "text";
|
|
9
|
+
text: string;
|
|
10
|
+
} | {
|
|
11
|
+
type: "inline_file";
|
|
12
|
+
data: Uint8Array;
|
|
13
|
+
mediaType: string;
|
|
14
|
+
filename: string;
|
|
15
|
+
kind: "image" | "file";
|
|
16
|
+
param?: string;
|
|
17
|
+
} | {
|
|
18
|
+
type: "remote_file";
|
|
19
|
+
url: string;
|
|
20
|
+
kind: "image" | "file";
|
|
21
|
+
filename?: string;
|
|
22
|
+
mediaType?: string;
|
|
23
|
+
param?: string;
|
|
24
|
+
} | {
|
|
25
|
+
type: "file_ref";
|
|
26
|
+
fileId: string;
|
|
27
|
+
mediaType?: string;
|
|
28
|
+
filename?: string;
|
|
29
|
+
kind: "image" | "file";
|
|
30
|
+
param?: string;
|
|
31
|
+
};
|
|
32
|
+
export declare const DEFAULT_POLL_TIMEOUT_MS = 300000;
|
|
33
|
+
export declare function prefetchRemoteParts(http: Http, parts: Part[]): Promise<Part[]>;
|
|
34
|
+
export declare class ListenerRegistry {
|
|
35
|
+
private readonly listeners;
|
|
36
|
+
register(sessionId: string, listener: Listener): void;
|
|
37
|
+
unregister(sessionId: string, listener: Listener): void;
|
|
38
|
+
private liveListeners;
|
|
39
|
+
handoffOrClose(sessionId: string, stream: ResponseStream): boolean;
|
|
40
|
+
}
|
|
41
|
+
export declare class Listener implements AsyncIterable<TurnEvent> {
|
|
42
|
+
readonly sessionId: string;
|
|
43
|
+
private readonly turns;
|
|
44
|
+
private readonly pollIntervalMs;
|
|
45
|
+
private readonly maxPolls;
|
|
46
|
+
private readonly pollTimeoutMs;
|
|
47
|
+
private readonly reqOpts?;
|
|
48
|
+
turnEnded: boolean;
|
|
49
|
+
readonly createdAt: number;
|
|
50
|
+
private closed;
|
|
51
|
+
private iterating;
|
|
52
|
+
private readonly queue;
|
|
53
|
+
private waitResolve;
|
|
54
|
+
private activeStream;
|
|
55
|
+
constructor(sessionId: string, turns: Turns, pollIntervalMs: number, maxPolls: number, pollTimeoutMs: number, initialStream?: ResponseStream, reqOpts?: PerCallRequestOptions);
|
|
56
|
+
get isClosed(): boolean;
|
|
57
|
+
get isIterating(): boolean;
|
|
58
|
+
get hasQueuedStream(): boolean;
|
|
59
|
+
handoff(stream: ResponseStream): boolean;
|
|
60
|
+
close(): void;
|
|
61
|
+
private consume;
|
|
62
|
+
private drainQueued;
|
|
63
|
+
[Symbol.asyncIterator](): AsyncGenerator<TurnEvent, void, unknown>;
|
|
64
|
+
}
|
|
65
|
+
export declare class Turns {
|
|
66
|
+
readonly _http: Http;
|
|
67
|
+
readonly _sessions: Sessions;
|
|
68
|
+
readonly _registry: ListenerRegistry;
|
|
69
|
+
private readonly queueApi;
|
|
70
|
+
private readonly responsesApi;
|
|
71
|
+
private readonly pollIntervalMs;
|
|
72
|
+
private readonly provider;
|
|
73
|
+
private readonly uploadCache;
|
|
74
|
+
constructor(_http: Http, _sessions: Sessions, opts?: {
|
|
75
|
+
pollIntervalMs?: number;
|
|
76
|
+
provider?: string;
|
|
77
|
+
registry?: ListenerRegistry;
|
|
78
|
+
uploadCache?: AttachmentUploadCache;
|
|
79
|
+
});
|
|
80
|
+
handoffOrClose(sessionId: string, stream: ResponseStream): boolean;
|
|
81
|
+
listen(sessionId: string, opts?: {
|
|
82
|
+
maxPolls?: number;
|
|
83
|
+
pollTimeoutMs?: number;
|
|
84
|
+
initialStream?: ResponseStream;
|
|
85
|
+
reqOpts?: PerCallRequestOptions;
|
|
86
|
+
}): Listener;
|
|
87
|
+
resolveParts(sessionId: string, parts: Part[], opts?: {
|
|
88
|
+
key?: string;
|
|
89
|
+
}): Promise<MessagePart[]>;
|
|
90
|
+
sendMessageParts(sessionId: string, agentId: string | null, msgParts: MessagePart[], opts: {
|
|
91
|
+
msgId: string;
|
|
92
|
+
returnStream?: boolean;
|
|
93
|
+
}): Promise<ResponseStream | null>;
|
|
94
|
+
send(sessionId: string, agentId: string | null, parts: Part[], opts?: {
|
|
95
|
+
key?: string;
|
|
96
|
+
returnStream?: boolean;
|
|
97
|
+
}): Promise<ResponseStream | null>;
|
|
98
|
+
steer(sessionId: string, agentId: string | null, parts: Part[], opts?: {
|
|
99
|
+
key?: string;
|
|
100
|
+
delivery?: "now" | "queue";
|
|
101
|
+
}): Promise<void>;
|
|
102
|
+
stop(sessionId: string): Promise<void>;
|
|
103
|
+
answerClarify(sessionId: string, requestId: string, answers: Record<string, unknown>): Promise<void>;
|
|
104
|
+
}
|