sarvam-agents-client 0.3.0 → 0.3.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/README.md +98 -1
- package/dist/apis/FunctionToolsApi.d.ts +33 -0
- package/dist/apis/FunctionToolsApi.js +65 -0
- package/dist/apis/index.d.ts +1 -0
- package/dist/apis/index.js +1 -0
- package/dist/compose/agent.d.ts +20 -3
- package/dist/compose/agent.js +84 -7
- package/dist/compose/errors.d.ts +5 -1
- package/dist/compose/errors.js +4 -1
- package/dist/compose/events.d.ts +4 -0
- package/dist/compose/events.js +34 -0
- package/dist/compose/functionTool.d.ts +101 -0
- package/dist/compose/functionTool.js +420 -0
- package/dist/compose/index.d.ts +6 -2
- package/dist/compose/index.js +3 -1
- package/dist/compose/output.d.ts +11 -0
- package/dist/compose/output.js +32 -7
- package/dist/compose/run.d.ts +5 -1
- package/dist/compose/run.js +118 -25
- package/dist/compose/runState.d.ts +26 -1
- package/dist/compose/runState.js +30 -0
- package/dist/compose/settingsTransport.d.ts +28 -1
- package/dist/compose/settingsTransport.js +389 -7
- package/dist/compose/transport.d.ts +18 -1
- package/dist/compose/webhook.d.ts +19 -0
- package/dist/compose/webhook.js +184 -0
- package/dist/esm/apis/FunctionToolsApi.d.ts +33 -0
- package/dist/esm/apis/FunctionToolsApi.js +61 -0
- package/dist/esm/apis/index.d.ts +1 -0
- package/dist/esm/apis/index.js +1 -0
- package/dist/esm/compose/agent.d.ts +20 -3
- package/dist/esm/compose/agent.js +84 -7
- package/dist/esm/compose/errors.d.ts +5 -1
- package/dist/esm/compose/errors.js +4 -1
- package/dist/esm/compose/events.d.ts +4 -0
- package/dist/esm/compose/events.js +33 -0
- package/dist/esm/compose/functionTool.d.ts +101 -0
- package/dist/esm/compose/functionTool.js +406 -0
- package/dist/esm/compose/index.d.ts +6 -2
- package/dist/esm/compose/index.js +1 -0
- package/dist/esm/compose/output.d.ts +11 -0
- package/dist/esm/compose/output.js +30 -9
- package/dist/esm/compose/run.d.ts +5 -1
- package/dist/esm/compose/run.js +118 -25
- package/dist/esm/compose/runState.d.ts +26 -1
- package/dist/esm/compose/runState.js +31 -1
- package/dist/esm/compose/settingsTransport.d.ts +28 -1
- package/dist/esm/compose/settingsTransport.js +392 -11
- package/dist/esm/compose/transport.d.ts +18 -1
- package/dist/esm/compose/webhook.d.ts +19 -0
- package/dist/esm/compose/webhook.js +177 -0
- package/dist/esm/models/AgentConversationDetail.d.ts +7 -0
- package/dist/esm/models/AgentConversationDetail.js +3 -0
- package/dist/esm/models/ClarifyBody.d.ts +6 -0
- package/dist/esm/models/ClarifyBody.js +2 -0
- package/dist/esm/models/ConversationDetail.d.ts +7 -0
- package/dist/esm/models/ConversationDetail.js +3 -0
- package/dist/esm/models/ErrorDetail.d.ts +1 -0
- package/dist/esm/models/ErrorDetail.js +2 -1
- package/dist/esm/models/FunctionResultBody.d.ts +44 -0
- package/dist/esm/models/FunctionResultBody.js +49 -0
- package/dist/esm/models/QueueMessageInput.d.ts +23 -0
- package/dist/esm/models/QueueMessageInput.js +14 -0
- package/dist/esm/models/RequiredAction.d.ts +77 -0
- package/dist/esm/models/RequiredAction.js +69 -0
- package/dist/esm/models/ResponseDetail.d.ts +8 -0
- package/dist/esm/models/ResponseDetail.js +2 -0
- package/dist/esm/models/ResponseInput.d.ts +23 -0
- package/dist/esm/models/ResponseInput.js +14 -0
- package/dist/esm/models/ToolResults200Response.d.ts +38 -0
- package/dist/esm/models/ToolResults200Response.js +47 -0
- package/dist/esm/models/ToolResultsBody.d.ts +39 -0
- package/dist/esm/models/ToolResultsBody.js +48 -0
- package/dist/esm/models/index.d.ts +4 -0
- package/dist/esm/models/index.js +4 -0
- package/dist/esm/streaming.d.ts +14 -2
- package/dist/esm/streaming.js +26 -4
- package/dist/esm/webhooks.d.ts +203 -0
- package/dist/esm/webhooks.js +215 -0
- package/dist/models/AgentConversationDetail.d.ts +7 -0
- package/dist/models/AgentConversationDetail.js +3 -0
- package/dist/models/ClarifyBody.d.ts +6 -0
- package/dist/models/ClarifyBody.js +2 -0
- package/dist/models/ConversationDetail.d.ts +7 -0
- package/dist/models/ConversationDetail.js +3 -0
- package/dist/models/ErrorDetail.d.ts +1 -0
- package/dist/models/ErrorDetail.js +2 -1
- package/dist/models/FunctionResultBody.d.ts +44 -0
- package/dist/models/FunctionResultBody.js +56 -0
- package/dist/models/QueueMessageInput.d.ts +23 -0
- package/dist/models/QueueMessageInput.js +15 -1
- package/dist/models/RequiredAction.d.ts +77 -0
- package/dist/models/RequiredAction.js +77 -0
- package/dist/models/ResponseDetail.d.ts +8 -0
- package/dist/models/ResponseDetail.js +2 -0
- package/dist/models/ResponseInput.d.ts +23 -0
- package/dist/models/ResponseInput.js +15 -0
- package/dist/models/ToolResults200Response.d.ts +38 -0
- package/dist/models/ToolResults200Response.js +54 -0
- package/dist/models/ToolResultsBody.d.ts +39 -0
- package/dist/models/ToolResultsBody.js +55 -0
- package/dist/models/index.d.ts +4 -0
- package/dist/models/index.js +4 -0
- package/dist/streaming.d.ts +14 -2
- package/dist/streaming.js +27 -4
- package/dist/webhooks.d.ts +203 -0
- package/dist/webhooks.js +224 -0
- package/package.json +9 -1
- package/src/apis/FunctionToolsApi.ts +102 -0
- package/src/apis/index.ts +1 -0
- package/src/compose/agent.ts +96 -9
- package/src/compose/errors.ts +7 -1
- package/src/compose/events.ts +30 -0
- package/src/compose/functionTool.ts +441 -0
- package/src/compose/index.ts +6 -2
- package/src/compose/output.ts +30 -9
- package/src/compose/run.ts +115 -18
- package/src/compose/runState.ts +44 -5
- package/src/compose/settingsTransport.ts +379 -8
- package/src/compose/transport.ts +24 -1
- package/src/compose/webhook.ts +181 -0
- package/src/models/AgentConversationDetail.ts +15 -0
- package/src/models/ClarifyBody.ts +8 -0
- package/src/models/ConversationDetail.ts +15 -0
- package/src/models/ErrorDetail.ts +2 -1
- package/src/models/FunctionResultBody.ts +83 -0
- package/src/models/QueueMessageInput.ts +28 -0
- package/src/models/RequiredAction.ts +128 -0
- package/src/models/ResponseDetail.ts +8 -0
- package/src/models/ResponseInput.ts +30 -0
- package/src/models/ToolResults200Response.ts +75 -0
- package/src/models/ToolResultsBody.ts +83 -0
- package/src/models/index.ts +4 -0
- package/src/streaming.ts +39 -3
- package/src/webhooks.ts +390 -0
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
/** run(): deploy the agent, drive one turn through a Transport, handle clarify questions, dropped
|
|
1
|
+
/** run(): deploy the agent, drive one turn through a Transport, run function tools, handle clarify questions, dropped
|
|
2
|
+
* streams and cancel. */
|
|
2
3
|
import type { Configuration } from "../runtime.js";
|
|
3
4
|
import type { Agent } from "./agent.js";
|
|
4
5
|
import type { ClarifyQuestion, Event, OutputCitation } from "./events.js";
|
|
@@ -16,6 +17,9 @@ export interface RunOptions {
|
|
|
16
17
|
signal?: AbortSignal;
|
|
17
18
|
/** Answers clarify questions; without it a question ends the run with an interruption. */
|
|
18
19
|
onClarify?: ClarifyHandler;
|
|
20
|
+
/** Throw an error thrown by a function tool's `execute` instead of sending it to the model (for tests). The turn
|
|
21
|
+
* then stays paused on the server; `RunState.fromSession` continues it. */
|
|
22
|
+
raiseErrors?: boolean;
|
|
19
23
|
/** Not supported: the server caps turns per agent; set `new Agent({ limits: { maxTurns } })`. */
|
|
20
24
|
maxTurns?: never;
|
|
21
25
|
}
|
package/dist/esm/compose/run.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { FetchError } from "../runtime.js";
|
|
2
2
|
import { agentIdFor, getDefaultClient, resolveTransport } from "./deploy.js";
|
|
3
3
|
import { ModelBehaviorError, NotSupportedError, RunError, UserError } from "./errors.js";
|
|
4
|
+
import { CallsCancelled, runCalls } from "./functionTool.js";
|
|
4
5
|
import { parseOutput } from "./output.js";
|
|
5
6
|
import { RunState } from "./runState.js";
|
|
6
7
|
const MAX_RECONNECTS = 3;
|
|
@@ -101,12 +102,14 @@ class Stopper {
|
|
|
101
102
|
}
|
|
102
103
|
}
|
|
103
104
|
class Loop {
|
|
104
|
-
constructor(transport, onClarify, emit, signal, onConversation) {
|
|
105
|
+
constructor(transport, onClarify, emit, signal, onConversation, functions = new Map(), raiseErrors = false) {
|
|
105
106
|
this.transport = transport;
|
|
106
107
|
this.onClarify = onClarify;
|
|
107
108
|
this.emit = emit;
|
|
108
109
|
this.signal = signal;
|
|
109
110
|
this.onConversation = onConversation;
|
|
111
|
+
this.functions = functions;
|
|
112
|
+
this.raiseErrors = raiseErrors;
|
|
110
113
|
this.conversationId = null;
|
|
111
114
|
this.items = [];
|
|
112
115
|
this.stopReason = undefined;
|
|
@@ -116,6 +119,11 @@ class Loop {
|
|
|
116
119
|
// of the block it dropped in, doesn't repeat text.
|
|
117
120
|
this.blocks = [];
|
|
118
121
|
this.openBlock = null;
|
|
122
|
+
/** Requests this run has answered. A stream read without a cursor (a duplicate post's reconnect, a resume before
|
|
123
|
+
* any event id) replays the turn from its start, these requests too: one is a marker, not a pause. */
|
|
124
|
+
this.answered = new Set();
|
|
125
|
+
/** A full-turn replay repeats what this run already showed: emit nothing until it passes an answered request. */
|
|
126
|
+
this.replaying = false;
|
|
119
127
|
}
|
|
120
128
|
get text() {
|
|
121
129
|
return this.blocks.map(([, parts]) => parts.join("")).join("");
|
|
@@ -193,14 +201,17 @@ class Loop {
|
|
|
193
201
|
start(agentId, conversationId, input) {
|
|
194
202
|
return this.open(() => this.transport.startTurn(agentId, conversationId, input, this.signal));
|
|
195
203
|
}
|
|
196
|
-
/** Read one turn segment to turn_finished, resuming dropped streams; return
|
|
204
|
+
/** Read one turn segment to turn_finished, resuming dropped streams; return what it paused on, if anything. */
|
|
197
205
|
async consume(stream) {
|
|
198
|
-
let
|
|
206
|
+
let pause = null;
|
|
199
207
|
let reconnects = 0;
|
|
200
208
|
const itemsAtStart = this.items.length;
|
|
209
|
+
// The last pause read is one this run answered (kept across a resume, which goes on from where it was).
|
|
210
|
+
let afterAnswered = false;
|
|
201
211
|
for (;;) {
|
|
202
212
|
let finished = false;
|
|
203
213
|
const current = stream;
|
|
214
|
+
this.replaying = current.replay === true;
|
|
204
215
|
const onAbort = () => current.close();
|
|
205
216
|
this.signal.addEventListener("abort", onAbort, { once: true });
|
|
206
217
|
try {
|
|
@@ -214,8 +225,22 @@ class Loop {
|
|
|
214
225
|
finished = true;
|
|
215
226
|
break;
|
|
216
227
|
}
|
|
228
|
+
if ((event.kind === "clarify_requested" || event.kind === "function_calls_requested")
|
|
229
|
+
&& this.answered.has(event.requestId)) {
|
|
230
|
+
// Replayed up to a pause this run already answered: what came before it is not new.
|
|
231
|
+
this.items.length = itemsAtStart;
|
|
232
|
+
this.pastAnswered();
|
|
233
|
+
this.replaying = false;
|
|
234
|
+
afterAnswered = true;
|
|
235
|
+
continue;
|
|
236
|
+
}
|
|
237
|
+
if (event.kind === "clarify_requested" || event.kind === "function_calls_requested")
|
|
238
|
+
afterAnswered = false;
|
|
239
|
+
// The skip of a pause this run answered (a replay): not the turn's.
|
|
240
|
+
if (afterAnswered && event.kind === "output" && event.skipped === "paused")
|
|
241
|
+
continue;
|
|
217
242
|
if (this.handle(event))
|
|
218
|
-
|
|
243
|
+
pause = event;
|
|
219
244
|
}
|
|
220
245
|
}
|
|
221
246
|
catch (err) {
|
|
@@ -232,7 +257,7 @@ class Loop {
|
|
|
232
257
|
if (this.signal.aborted)
|
|
233
258
|
throw new Cancelled();
|
|
234
259
|
if (finished)
|
|
235
|
-
return
|
|
260
|
+
return pause;
|
|
236
261
|
const responseId = current.responseId;
|
|
237
262
|
const lastEventId = current.lastEventId;
|
|
238
263
|
if (reconnects >= MAX_RECONNECTS || this.conversationId === null) {
|
|
@@ -247,7 +272,7 @@ class Loop {
|
|
|
247
272
|
stream = await this.open(() => this.transport.resume(conversationId, responseId, lastEventId, this.signal));
|
|
248
273
|
}
|
|
249
274
|
}
|
|
250
|
-
/** Handle one event other than turn_finished; returns true for a clarify request. */
|
|
275
|
+
/** Handle one event other than turn_finished; returns true for a clarify or function-call request. */
|
|
251
276
|
handle(event) {
|
|
252
277
|
switch (event.kind) {
|
|
253
278
|
case "turn_failed":
|
|
@@ -269,22 +294,23 @@ class Loop {
|
|
|
269
294
|
return false;
|
|
270
295
|
case "text_delta":
|
|
271
296
|
this.onText(event);
|
|
272
|
-
this.
|
|
297
|
+
if (!this.replaying) {
|
|
298
|
+
this.emit({ type: "raw_model_stream_event", data: { type: "output_text_delta", delta: event.delta } });
|
|
299
|
+
}
|
|
273
300
|
return false;
|
|
274
301
|
case "reasoning_delta":
|
|
275
|
-
this.
|
|
302
|
+
if (!this.replaying) {
|
|
303
|
+
this.emit({ type: "raw_model_stream_event", data: { type: "reasoning_delta", delta: event.delta } });
|
|
304
|
+
}
|
|
276
305
|
return false;
|
|
277
306
|
default:
|
|
278
307
|
break;
|
|
279
308
|
}
|
|
280
309
|
this.items.push(event);
|
|
281
|
-
if (event.kind === "tool_called" || event.kind === "tool_output") {
|
|
310
|
+
if ((event.kind === "tool_called" || event.kind === "tool_output") && !this.replaying) {
|
|
282
311
|
this.emit({ type: "run_item_stream_event", name: event.kind, item: event });
|
|
283
312
|
}
|
|
284
|
-
|
|
285
|
-
throw new NotSupportedError("function tools are not supported yet");
|
|
286
|
-
}
|
|
287
|
-
return event.kind === "clarify_requested";
|
|
313
|
+
return event.kind === "clarify_requested" || event.kind === "function_calls_requested";
|
|
288
314
|
}
|
|
289
315
|
async ask(questions) {
|
|
290
316
|
const handler = this.onClarify;
|
|
@@ -295,13 +321,51 @@ class Loop {
|
|
|
295
321
|
}
|
|
296
322
|
return answers;
|
|
297
323
|
}
|
|
324
|
+
/** Past a pause this run answers: its text and its `outputSkipped: "paused"` belong to the paused segment, and the
|
|
325
|
+
* continuation (or its replay) says what the turn's own are. */
|
|
326
|
+
pastAnswered() {
|
|
327
|
+
this.resetText();
|
|
328
|
+
this.output = undefined;
|
|
329
|
+
}
|
|
330
|
+
/** Mark `requestId` answered by this run, before its answer is sent. */
|
|
331
|
+
markAnswered(requestId) {
|
|
332
|
+
this.answered.add(requestId);
|
|
333
|
+
this.pastAnswered();
|
|
334
|
+
}
|
|
298
335
|
answer(requestId, answers) {
|
|
336
|
+
this.markAnswered(requestId);
|
|
299
337
|
const conversationId = this.conversationId;
|
|
300
338
|
if (conversationId === null)
|
|
301
339
|
throw new RunError("stream_lost", "no conversation to answer the question in");
|
|
302
340
|
return this.open(() => this.transport.answerClarify(conversationId, requestId, answers, this.signal));
|
|
303
341
|
}
|
|
304
|
-
/** Run
|
|
342
|
+
/** Run the request's calls here and post their results; the returned stream continues the turn. */
|
|
343
|
+
async answerFunctions(request) {
|
|
344
|
+
const conversationId = this.conversationId;
|
|
345
|
+
if (conversationId === null)
|
|
346
|
+
throw new RunError("stream_lost", "no conversation to answer the function calls in");
|
|
347
|
+
const transport = this.transport;
|
|
348
|
+
if (transport.postFunctionResults === undefined) {
|
|
349
|
+
throw new NotSupportedError("this transport cannot post function results");
|
|
350
|
+
}
|
|
351
|
+
let results;
|
|
352
|
+
try {
|
|
353
|
+
// Raced against the signal: an execute that never settles must not keep a cancelled run alive.
|
|
354
|
+
results = await raceAbort(runCalls(this.functions, request.calls, { signal: this.signal, raiseErrors: this.raiseErrors }), this.signal);
|
|
355
|
+
}
|
|
356
|
+
catch (err) {
|
|
357
|
+
if (err instanceof CallsCancelled)
|
|
358
|
+
throw new Cancelled();
|
|
359
|
+
throw err;
|
|
360
|
+
}
|
|
361
|
+
if (this.signal.aborted)
|
|
362
|
+
throw new Cancelled();
|
|
363
|
+
this.markAnswered(request.requestId);
|
|
364
|
+
const post = transport.postFunctionResults.bind(transport);
|
|
365
|
+
return this.open(() => post(conversationId, request.requestId, results, this.signal));
|
|
366
|
+
}
|
|
367
|
+
/** Run to completion, running function calls and answering questions with onClarify; return an Interruption if a
|
|
368
|
+
* question has no handler. */
|
|
305
369
|
async drive(stream) {
|
|
306
370
|
for (;;) {
|
|
307
371
|
const clarify = await this.consume(stream);
|
|
@@ -309,6 +373,10 @@ class Loop {
|
|
|
309
373
|
this.emit({ type: "run_item_stream_event", name: "message_output_created", item: this.text });
|
|
310
374
|
return null;
|
|
311
375
|
}
|
|
376
|
+
if (clarify.kind === "function_calls_requested") {
|
|
377
|
+
stream = await this.answerFunctions(clarify);
|
|
378
|
+
continue;
|
|
379
|
+
}
|
|
312
380
|
if (this.onClarify === undefined) {
|
|
313
381
|
return { kind: "clarify", requestId: clarify.requestId, payload: { questions: clarify.questions.slice() } };
|
|
314
382
|
}
|
|
@@ -317,7 +385,6 @@ class Loop {
|
|
|
317
385
|
const answers = await this.ask(clarify.questions);
|
|
318
386
|
if (this.signal.aborted)
|
|
319
387
|
throw new Cancelled();
|
|
320
|
-
this.resetText();
|
|
321
388
|
stream = await this.answer(clarify.requestId, answers);
|
|
322
389
|
}
|
|
323
390
|
}
|
|
@@ -325,9 +392,31 @@ class Loop {
|
|
|
325
392
|
async answerPending(state) {
|
|
326
393
|
this.conversationId = state.conversationId;
|
|
327
394
|
this.onConversation(state.conversationId);
|
|
395
|
+
// A saved state can be stale: another process may have answered its calls since. Run only what the server still
|
|
396
|
+
// waits on, so no function's side effects happen twice.
|
|
397
|
+
const transport = this.transport;
|
|
398
|
+
let waiting = null;
|
|
399
|
+
if (state.pending.some((item) => item.kind === "function_call")
|
|
400
|
+
&& transport.pending !== undefined && transport.follow !== undefined) {
|
|
401
|
+
const live = await raceAbort(transport.pending(state.conversationId), this.signal);
|
|
402
|
+
waiting = new Set(live.map((request) => request.requestId));
|
|
403
|
+
}
|
|
328
404
|
for (let n = 0; n < state.pending.length; n++) {
|
|
329
405
|
const item = state.pending[n];
|
|
330
|
-
|
|
406
|
+
let stream;
|
|
407
|
+
if (item.kind === "function_call" && waiting !== null && !waiting.has(item.requestId)) {
|
|
408
|
+
this.markAnswered(item.requestId);
|
|
409
|
+
const follow = transport.follow.bind(transport);
|
|
410
|
+
stream = await this.open(() => follow(state.conversationId, this.signal));
|
|
411
|
+
}
|
|
412
|
+
else
|
|
413
|
+
stream = item.kind === "function_call"
|
|
414
|
+
? await this.answerFunctions({
|
|
415
|
+
requestId: item.requestId,
|
|
416
|
+
calls: item.payload.calls.map((c) => ({ callId: c.call_id, name: c.name, arguments: { ...c.arguments } })),
|
|
417
|
+
})
|
|
418
|
+
: await this.answer(item.requestId, state.answers[item.requestId]);
|
|
419
|
+
const interruption = await this.drive(stream);
|
|
331
420
|
if (interruption !== null)
|
|
332
421
|
return [interruption, ...state.pending.slice(n + 1)];
|
|
333
422
|
}
|
|
@@ -344,7 +433,10 @@ function checkMaxTurns(opts) {
|
|
|
344
433
|
function checkInput(input) {
|
|
345
434
|
if (input instanceof RunState) {
|
|
346
435
|
for (const item of input.pending) {
|
|
436
|
+
if (item.kind === "function_call")
|
|
437
|
+
continue; // run here when the state is resumed; nothing to answer
|
|
347
438
|
if (item.kind !== "clarify") {
|
|
439
|
+
// fromString keeps kinds it doesn't know, so this is reachable at runtime.
|
|
348
440
|
throw new NotSupportedError(`resuming "${item.kind}" interruptions is not supported yet`);
|
|
349
441
|
}
|
|
350
442
|
if (!Object.prototype.hasOwnProperty.call(input.answers, item.requestId)) {
|
|
@@ -388,13 +480,14 @@ function structuredOutput(outputType, event) {
|
|
|
388
480
|
return undefined;
|
|
389
481
|
}
|
|
390
482
|
async function execute(p, controller, emit) {
|
|
391
|
-
var _a, _b, _c, _d, _e, _f, _g, _h;
|
|
483
|
+
var _a, _b, _c, _d, _e, _f, _g, _h, _j;
|
|
392
484
|
const signal = controller.signal;
|
|
393
485
|
const unlink = link(p.opts.signal, controller);
|
|
394
486
|
const stopper = new Stopper(p.transport, signal);
|
|
395
487
|
const onAbort = () => stopper.send();
|
|
396
488
|
signal.addEventListener("abort", onAbort, { once: true });
|
|
397
|
-
const
|
|
489
|
+
const functions = new Map(p.agent.functionTools.map((t) => [t.name, t]));
|
|
490
|
+
const loop = new Loop(p.transport, p.opts.onClarify, emit, signal, (c) => stopper.onConversation(c), functions, (_a = p.opts.raiseErrors) !== null && _a !== void 0 ? _a : false);
|
|
398
491
|
let interruptions = [];
|
|
399
492
|
let cancelled = false;
|
|
400
493
|
const fallbackConversation = p.input instanceof RunState ? p.input.conversationId : p.opts.conversationId;
|
|
@@ -406,7 +499,7 @@ async function execute(p, controller, emit) {
|
|
|
406
499
|
}
|
|
407
500
|
else {
|
|
408
501
|
const agentId = await raceAbort(agentIdFor(p.agent, p.transport, p.owner), signal);
|
|
409
|
-
const stream = await loop.start(agentId, (
|
|
502
|
+
const stream = await loop.start(agentId, (_b = p.opts.conversationId) !== null && _b !== void 0 ? _b : null, p.input);
|
|
410
503
|
const interruption = await loop.drive(stream);
|
|
411
504
|
interruptions = interruption ? [interruption] : [];
|
|
412
505
|
}
|
|
@@ -434,7 +527,7 @@ async function execute(p, controller, emit) {
|
|
|
434
527
|
}
|
|
435
528
|
catch (err) {
|
|
436
529
|
if (err instanceof ModelBehaviorError)
|
|
437
|
-
err.conversationId = (
|
|
530
|
+
err.conversationId = (_c = loop.conversationId) !== null && _c !== void 0 ? _c : fallbackConversation;
|
|
438
531
|
throw err;
|
|
439
532
|
}
|
|
440
533
|
}
|
|
@@ -446,12 +539,12 @@ async function execute(p, controller, emit) {
|
|
|
446
539
|
newItems: loop.items,
|
|
447
540
|
interruptions,
|
|
448
541
|
stopReason: loop.stopReason,
|
|
449
|
-
conversationId: (
|
|
542
|
+
conversationId: (_d = loop.conversationId) !== null && _d !== void 0 ? _d : fallbackConversation,
|
|
450
543
|
cancelled,
|
|
451
|
-
outputCitations: ((
|
|
452
|
-
outputNote: (
|
|
453
|
-
outputSkipped: ((
|
|
454
|
-
outputMode: ((
|
|
544
|
+
outputCitations: ((_e = loop.output) === null || _e === void 0 ? void 0 : _e.kind) === "output" ? ((_f = loop.output.citations) !== null && _f !== void 0 ? _f : []).slice() : [],
|
|
545
|
+
outputNote: (_g = loop.output) === null || _g === void 0 ? void 0 : _g.note,
|
|
546
|
+
outputSkipped: ((_h = loop.output) === null || _h === void 0 ? void 0 : _h.kind) === "output" ? loop.output.skipped : undefined,
|
|
547
|
+
outputMode: ((_j = loop.output) === null || _j === void 0 ? void 0 : _j.kind) === "output" ? loop.output.mode : undefined,
|
|
455
548
|
};
|
|
456
549
|
}
|
|
457
550
|
// -- streaming ---------------------------------------------------------------------------------------------------
|
|
@@ -1,14 +1,31 @@
|
|
|
1
1
|
/** RunState: what a paused run needs to continue (conversation, pending interruptions and the caller's answers). */
|
|
2
2
|
import type { Agent } from "./agent.js";
|
|
3
3
|
import type { OutputType } from "./output.js";
|
|
4
|
+
import type { Configuration } from "../runtime.js";
|
|
4
5
|
import type { ClarifyQuestion } from "./events.js";
|
|
5
|
-
|
|
6
|
+
import type { Transport } from "./transport.js";
|
|
7
|
+
/** One function call waiting on this process, in the JSON shape Python's `RunState` uses. */
|
|
8
|
+
export interface PendingFunctionCall {
|
|
9
|
+
call_id: string;
|
|
10
|
+
name: string;
|
|
11
|
+
arguments: Record<string, unknown>;
|
|
12
|
+
}
|
|
13
|
+
export type Interruption = {
|
|
6
14
|
kind: "clarify";
|
|
7
15
|
requestId: string;
|
|
8
16
|
payload: {
|
|
9
17
|
questions: ClarifyQuestion[];
|
|
10
18
|
};
|
|
11
19
|
}
|
|
20
|
+
/** Calls a stopped process left waiting (`RunState.fromSession`); `run(agent, state)` runs them. */
|
|
21
|
+
| {
|
|
22
|
+
kind: "function_call";
|
|
23
|
+
requestId: string;
|
|
24
|
+
payload: {
|
|
25
|
+
calls: PendingFunctionCall[];
|
|
26
|
+
expires_at: string | null;
|
|
27
|
+
};
|
|
28
|
+
};
|
|
12
29
|
export declare class RunState {
|
|
13
30
|
readonly conversationId: string;
|
|
14
31
|
readonly pending: Interruption[];
|
|
@@ -18,6 +35,14 @@ export declare class RunState {
|
|
|
18
35
|
readonly transportKind: string;
|
|
19
36
|
/** @internal Use `result.state` or `RunState.fromString`. */
|
|
20
37
|
constructor(conversationId: string, pending: Interruption[], answers?: Record<string, Record<string, unknown>>, transportKind?: string);
|
|
38
|
+
/**
|
|
39
|
+
* What the conversation is waiting on, read from the server: the function calls of a run whose process stopped
|
|
40
|
+
* before answering them. `run(agent, state)` then runs them here and continues the turn.
|
|
41
|
+
*/
|
|
42
|
+
static fromSession(conversationId: string, opts?: {
|
|
43
|
+
client?: Configuration;
|
|
44
|
+
transport?: Transport;
|
|
45
|
+
}): Promise<RunState>;
|
|
21
46
|
/** Record the answers to a pending interruption; `run(agent, state)` sends them. */
|
|
22
47
|
answer(item: Interruption, answers: Record<string, unknown>): void;
|
|
23
48
|
/** JSON in the format Python's `RunState.to_json()` writes. */
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { UserError } from "./errors.js";
|
|
1
|
+
import { NotSupportedError, UserError } from "./errors.js";
|
|
2
2
|
const STATE_VERSION = 1;
|
|
3
3
|
function isObject(v) {
|
|
4
4
|
return typeof v === "object" && v !== null && !Array.isArray(v);
|
|
@@ -11,11 +11,41 @@ export class RunState {
|
|
|
11
11
|
this.answers = answers;
|
|
12
12
|
this.transportKind = transportKind;
|
|
13
13
|
}
|
|
14
|
+
/**
|
|
15
|
+
* What the conversation is waiting on, read from the server: the function calls of a run whose process stopped
|
|
16
|
+
* before answering them. `run(agent, state)` then runs them here and continues the turn.
|
|
17
|
+
*/
|
|
18
|
+
static async fromSession(conversationId, opts = {}) {
|
|
19
|
+
const { resolveTransport } = await import("./deploy.js"); // deploy imports run, which imports this module
|
|
20
|
+
const transport = resolveTransport(opts.client, opts.transport);
|
|
21
|
+
if (typeof conversationId !== "string" || conversationId === "") {
|
|
22
|
+
throw new UserError("fromSession needs a conversation id (a previous result.conversationId)");
|
|
23
|
+
}
|
|
24
|
+
if (transport.pending === undefined) {
|
|
25
|
+
throw new NotSupportedError("this transport cannot list pending function calls");
|
|
26
|
+
}
|
|
27
|
+
const pending = (await transport.pending(conversationId)).map((r) => {
|
|
28
|
+
var _a;
|
|
29
|
+
return ({
|
|
30
|
+
kind: "function_call",
|
|
31
|
+
requestId: r.requestId,
|
|
32
|
+
payload: {
|
|
33
|
+
calls: r.calls.map((c) => ({ call_id: c.callId, name: c.name, arguments: { ...c.arguments } })),
|
|
34
|
+
expires_at: (_a = r.expiresAt) !== null && _a !== void 0 ? _a : null,
|
|
35
|
+
},
|
|
36
|
+
});
|
|
37
|
+
});
|
|
38
|
+
return new RunState(conversationId, pending, {});
|
|
39
|
+
}
|
|
14
40
|
/** Record the answers to a pending interruption; `run(agent, state)` sends them. */
|
|
15
41
|
answer(item, answers) {
|
|
16
42
|
if (!this.pending.some((p) => p.requestId === item.requestId)) {
|
|
17
43
|
throw new UserError(`no pending item with request id "${item.requestId}"`);
|
|
18
44
|
}
|
|
45
|
+
if (item.kind === "function_call") {
|
|
46
|
+
throw new UserError("function calls are answered by running the agent's function tools: pass this state to " +
|
|
47
|
+
"run() with the agent");
|
|
48
|
+
}
|
|
19
49
|
this.answers[item.requestId] = { ...answers };
|
|
20
50
|
}
|
|
21
51
|
/** JSON in the format Python's `RunState.to_json()` writes. */
|
|
@@ -1,23 +1,50 @@
|
|
|
1
1
|
import type { Configuration } from "../runtime.js";
|
|
2
2
|
import type { Agent } from "./agent.js";
|
|
3
3
|
import type { OutputType } from "./output.js";
|
|
4
|
-
import type {
|
|
4
|
+
import type { FunctionResult } from "./functionTool.js";
|
|
5
|
+
import type { PendingFunctionCalls, RemoteAgent, Transport, TurnStream } from "./transport.js";
|
|
6
|
+
/** After a 409 expired or already_answered the server goes on with the turn; chat_service may still be picking that
|
|
7
|
+
* continuation up. The conversation is read again every `followPollMs.value` ms, at most FOLLOW_POLLS times. Mutable
|
|
8
|
+
* for tests; not exported from the compose root. */
|
|
9
|
+
export declare const followPollMs: {
|
|
10
|
+
value: number;
|
|
11
|
+
};
|
|
12
|
+
/** The `Idempotency-Key` for answering `requestId`: the same for every post of it, from any process. */
|
|
13
|
+
export declare function idempotencyKey(requestId: string): string;
|
|
5
14
|
export declare class SettingsTransport implements Transport {
|
|
6
15
|
private readonly config;
|
|
7
16
|
readonly kind: "settings";
|
|
8
17
|
private readonly agents;
|
|
9
18
|
private readonly conversations;
|
|
10
19
|
private readonly responses;
|
|
20
|
+
private readonly customApis;
|
|
11
21
|
constructor(config: Configuration);
|
|
12
22
|
findAgents(sdkName: string): Promise<RemoteAgent[]>;
|
|
13
23
|
readAgent(agentId: string): Promise<RemoteAgent>;
|
|
14
24
|
createAgent(agent: Agent<OutputType | undefined>): Promise<RemoteAgent>;
|
|
25
|
+
/** The caller's Custom APIs the webhooks name, to bind to a new agent: one entry per name that matches exactly
|
|
26
|
+
* one, and a sentence per name that matches none or several (left to the server, which refuses it only when it
|
|
27
|
+
* checks credentials). */
|
|
28
|
+
private webhookCredentials;
|
|
29
|
+
/** The ids of the caller's own Custom APIs named exactly `name` (`q` also matches substrings and hosts). */
|
|
30
|
+
private customApiIds;
|
|
31
|
+
private bind;
|
|
15
32
|
updateAgent(agentId: string, agent: Agent<OutputType | undefined>): Promise<RemoteAgent>;
|
|
16
33
|
deleteAgent(agentId: string): Promise<void>;
|
|
17
34
|
startTurn(agentId: string, conversationId: string | null, text: string, signal?: AbortSignal): Promise<TurnStream>;
|
|
18
35
|
answerClarify(conversationId: string, requestId: string, answers: Record<string, unknown>, signal?: AbortSignal): Promise<TurnStream>;
|
|
19
36
|
resume(conversationId: string, responseId: string, lastEventId: string | null, signal?: AbortSignal): Promise<TurnStream>;
|
|
20
37
|
stop(conversationId: string): Promise<void>;
|
|
38
|
+
postFunctionResults(conversationId: string, requestId: string, results: FunctionResult[], signal?: AbortSignal): Promise<TurnStream>;
|
|
39
|
+
/** The turn after a request someone already answered, as a replay of it from its start (the run skips up to the
|
|
40
|
+
* answered request): the running response by reconnecting without a cursor, else the conversation's last reply
|
|
41
|
+
* as stored. A turn that paused again ends on its new request, unanswered. */
|
|
42
|
+
follow(conversationId: string, signal?: AbortSignal): Promise<TurnStream>;
|
|
43
|
+
/** `follow`, after a 409 expired / already_answered for `requestId`: a turn not yet picked up again (no active
|
|
44
|
+
* response, and the last reply still ends on that request) is read again every second, up to 30 times; then
|
|
45
|
+
* RunError(reason). An abort ends the wait. */
|
|
46
|
+
private followAfter;
|
|
47
|
+
pending(conversationId: string): Promise<PendingFunctionCalls[]>;
|
|
21
48
|
/** Put back what updateAgent overwrote; a failing restore must not mask the original error. */
|
|
22
49
|
private restore;
|
|
23
50
|
private instructions;
|