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
package/src/compose/run.ts
CHANGED
|
@@ -1,10 +1,13 @@
|
|
|
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 { FetchError } from "../runtime.js";
|
|
4
5
|
import type { Agent } from "./agent.js";
|
|
5
6
|
import { agentIdFor, getDefaultClient, resolveTransport } from "./deploy.js";
|
|
6
7
|
import { ModelBehaviorError, NotSupportedError, RunError, UserError } from "./errors.js";
|
|
7
8
|
import type { ClarifyQuestion, Event, OutputCitation } from "./events.js";
|
|
9
|
+
import { CallsCancelled, runCalls } from "./functionTool.js";
|
|
10
|
+
import type { FunctionTool } from "./functionTool.js";
|
|
8
11
|
import { parseOutput } from "./output.js";
|
|
9
12
|
import type { OutputType, ResolvedOutput } from "./output.js";
|
|
10
13
|
import { RunState } from "./runState.js";
|
|
@@ -28,6 +31,9 @@ export interface RunOptions {
|
|
|
28
31
|
signal?: AbortSignal;
|
|
29
32
|
/** Answers clarify questions; without it a question ends the run with an interruption. */
|
|
30
33
|
onClarify?: ClarifyHandler;
|
|
34
|
+
/** Throw an error thrown by a function tool's `execute` instead of sending it to the model (for tests). The turn
|
|
35
|
+
* then stays paused on the server; `RunState.fromSession` continues it. */
|
|
36
|
+
raiseErrors?: boolean;
|
|
31
37
|
/** Not supported: the server caps turns per agent; set `new Agent({ limits: { maxTurns } })`. */
|
|
32
38
|
maxTurns?: never;
|
|
33
39
|
}
|
|
@@ -37,6 +43,8 @@ export type RunStreamEvent =
|
|
|
37
43
|
| { type: "run_item_stream_event"; name: "tool_called" | "tool_output" | "message_output_created"; item: unknown };
|
|
38
44
|
|
|
39
45
|
type ClarifyEvent = Extract<Event, { kind: "clarify_requested" }>;
|
|
46
|
+
type FunctionCallsEvent = Extract<Event, { kind: "function_calls_requested" }>;
|
|
47
|
+
type PauseEvent = ClarifyEvent | FunctionCallsEvent;
|
|
40
48
|
type Emit = (event: RunStreamEvent) => void;
|
|
41
49
|
|
|
42
50
|
/** Why the run ended early: the `limits` field whose cap the server hit. */
|
|
@@ -193,6 +201,11 @@ class Loop {
|
|
|
193
201
|
// of the block it dropped in, doesn't repeat text.
|
|
194
202
|
private blocks: [string | null, string[]][] = [];
|
|
195
203
|
private openBlock: string | null = null;
|
|
204
|
+
/** Requests this run has answered. A stream read without a cursor (a duplicate post's reconnect, a resume before
|
|
205
|
+
* any event id) replays the turn from its start, these requests too: one is a marker, not a pause. */
|
|
206
|
+
private readonly answered = new Set<string>();
|
|
207
|
+
/** A full-turn replay repeats what this run already showed: emit nothing until it passes an answered request. */
|
|
208
|
+
private replaying = false;
|
|
196
209
|
|
|
197
210
|
constructor(
|
|
198
211
|
private readonly transport: Transport,
|
|
@@ -200,6 +213,8 @@ class Loop {
|
|
|
200
213
|
private readonly emit: Emit,
|
|
201
214
|
private readonly signal: AbortSignal,
|
|
202
215
|
private readonly onConversation: (conversationId: string) => void,
|
|
216
|
+
private readonly functions: ReadonlyMap<string, FunctionTool> = new Map(),
|
|
217
|
+
private readonly raiseErrors = false,
|
|
203
218
|
) {}
|
|
204
219
|
|
|
205
220
|
get text(): string {
|
|
@@ -274,14 +289,17 @@ class Loop {
|
|
|
274
289
|
return this.open(() => this.transport.startTurn(agentId, conversationId, input, this.signal));
|
|
275
290
|
}
|
|
276
291
|
|
|
277
|
-
/** Read one turn segment to turn_finished, resuming dropped streams; return
|
|
278
|
-
private async consume(stream: TurnStream): Promise<
|
|
279
|
-
let
|
|
292
|
+
/** Read one turn segment to turn_finished, resuming dropped streams; return what it paused on, if anything. */
|
|
293
|
+
private async consume(stream: TurnStream): Promise<PauseEvent | null> {
|
|
294
|
+
let pause: PauseEvent | null = null;
|
|
280
295
|
let reconnects = 0;
|
|
281
296
|
const itemsAtStart = this.items.length;
|
|
297
|
+
// The last pause read is one this run answered (kept across a resume, which goes on from where it was).
|
|
298
|
+
let afterAnswered = false;
|
|
282
299
|
for (;;) {
|
|
283
300
|
let finished = false;
|
|
284
301
|
const current = stream;
|
|
302
|
+
this.replaying = current.replay === true;
|
|
285
303
|
const onAbort = () => current.close();
|
|
286
304
|
this.signal.addEventListener("abort", onAbort, { once: true });
|
|
287
305
|
try {
|
|
@@ -294,7 +312,19 @@ class Loop {
|
|
|
294
312
|
finished = true;
|
|
295
313
|
break;
|
|
296
314
|
}
|
|
297
|
-
if (
|
|
315
|
+
if ((event.kind === "clarify_requested" || event.kind === "function_calls_requested")
|
|
316
|
+
&& this.answered.has(event.requestId)) {
|
|
317
|
+
// Replayed up to a pause this run already answered: what came before it is not new.
|
|
318
|
+
this.items.length = itemsAtStart;
|
|
319
|
+
this.pastAnswered();
|
|
320
|
+
this.replaying = false;
|
|
321
|
+
afterAnswered = true;
|
|
322
|
+
continue;
|
|
323
|
+
}
|
|
324
|
+
if (event.kind === "clarify_requested" || event.kind === "function_calls_requested") afterAnswered = false;
|
|
325
|
+
// The skip of a pause this run answered (a replay): not the turn's.
|
|
326
|
+
if (afterAnswered && event.kind === "output" && event.skipped === "paused") continue;
|
|
327
|
+
if (this.handle(event)) pause = event as PauseEvent;
|
|
298
328
|
}
|
|
299
329
|
} catch (err) {
|
|
300
330
|
if (err instanceof Cancelled || this.signal.aborted) throw new Cancelled();
|
|
@@ -305,7 +335,7 @@ class Loop {
|
|
|
305
335
|
current.close();
|
|
306
336
|
}
|
|
307
337
|
if (this.signal.aborted) throw new Cancelled();
|
|
308
|
-
if (finished) return
|
|
338
|
+
if (finished) return pause;
|
|
309
339
|
const responseId = current.responseId;
|
|
310
340
|
const lastEventId = current.lastEventId;
|
|
311
341
|
if (reconnects >= MAX_RECONNECTS || this.conversationId === null) {
|
|
@@ -321,7 +351,7 @@ class Loop {
|
|
|
321
351
|
}
|
|
322
352
|
}
|
|
323
353
|
|
|
324
|
-
/** Handle one event other than turn_finished; returns true for a clarify request. */
|
|
354
|
+
/** Handle one event other than turn_finished; returns true for a clarify or function-call request. */
|
|
325
355
|
private handle(event: Event): boolean {
|
|
326
356
|
switch (event.kind) {
|
|
327
357
|
case "turn_failed":
|
|
@@ -342,21 +372,23 @@ class Loop {
|
|
|
342
372
|
return false;
|
|
343
373
|
case "text_delta":
|
|
344
374
|
this.onText(event);
|
|
345
|
-
this.
|
|
375
|
+
if (!this.replaying) {
|
|
376
|
+
this.emit({ type: "raw_model_stream_event", data: { type: "output_text_delta", delta: event.delta } });
|
|
377
|
+
}
|
|
346
378
|
return false;
|
|
347
379
|
case "reasoning_delta":
|
|
348
|
-
this.
|
|
380
|
+
if (!this.replaying) {
|
|
381
|
+
this.emit({ type: "raw_model_stream_event", data: { type: "reasoning_delta", delta: event.delta } });
|
|
382
|
+
}
|
|
349
383
|
return false;
|
|
350
384
|
default:
|
|
351
385
|
break;
|
|
352
386
|
}
|
|
353
387
|
this.items.push(event);
|
|
354
|
-
if (event.kind === "tool_called" || event.kind === "tool_output") {
|
|
388
|
+
if ((event.kind === "tool_called" || event.kind === "tool_output") && !this.replaying) {
|
|
355
389
|
this.emit({ type: "run_item_stream_event", name: event.kind, item: event });
|
|
356
|
-
} else if (event.kind === "function_calls_requested") {
|
|
357
|
-
throw new NotSupportedError("function tools are not supported yet");
|
|
358
390
|
}
|
|
359
|
-
return event.kind === "clarify_requested";
|
|
391
|
+
return event.kind === "clarify_requested" || event.kind === "function_calls_requested";
|
|
360
392
|
}
|
|
361
393
|
|
|
362
394
|
private async ask(questions: ClarifyQuestion[]): Promise<Record<string, unknown>> {
|
|
@@ -369,13 +401,51 @@ class Loop {
|
|
|
369
401
|
return answers as Record<string, unknown>;
|
|
370
402
|
}
|
|
371
403
|
|
|
404
|
+
/** Past a pause this run answers: its text and its `outputSkipped: "paused"` belong to the paused segment, and the
|
|
405
|
+
* continuation (or its replay) says what the turn's own are. */
|
|
406
|
+
private pastAnswered(): void {
|
|
407
|
+
this.resetText();
|
|
408
|
+
this.output = undefined;
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
/** Mark `requestId` answered by this run, before its answer is sent. */
|
|
412
|
+
private markAnswered(requestId: string): void {
|
|
413
|
+
this.answered.add(requestId);
|
|
414
|
+
this.pastAnswered();
|
|
415
|
+
}
|
|
416
|
+
|
|
372
417
|
private answer(requestId: string, answers: Record<string, unknown>): Promise<TurnStream> {
|
|
418
|
+
this.markAnswered(requestId);
|
|
373
419
|
const conversationId = this.conversationId;
|
|
374
420
|
if (conversationId === null) throw new RunError("stream_lost", "no conversation to answer the question in");
|
|
375
421
|
return this.open(() => this.transport.answerClarify(conversationId, requestId, answers, this.signal));
|
|
376
422
|
}
|
|
377
423
|
|
|
378
|
-
/** Run
|
|
424
|
+
/** Run the request's calls here and post their results; the returned stream continues the turn. */
|
|
425
|
+
private async answerFunctions(request: { requestId: string; calls: FunctionCallsEvent["calls"] }): Promise<TurnStream> {
|
|
426
|
+
const conversationId = this.conversationId;
|
|
427
|
+
if (conversationId === null) throw new RunError("stream_lost", "no conversation to answer the function calls in");
|
|
428
|
+
const transport = this.transport;
|
|
429
|
+
if (transport.postFunctionResults === undefined) {
|
|
430
|
+
throw new NotSupportedError("this transport cannot post function results");
|
|
431
|
+
}
|
|
432
|
+
let results;
|
|
433
|
+
try {
|
|
434
|
+
// Raced against the signal: an execute that never settles must not keep a cancelled run alive.
|
|
435
|
+
results = await raceAbort(runCalls(this.functions, request.calls, { signal: this.signal, raiseErrors: this.raiseErrors }),
|
|
436
|
+
this.signal);
|
|
437
|
+
} catch (err) {
|
|
438
|
+
if (err instanceof CallsCancelled) throw new Cancelled();
|
|
439
|
+
throw err;
|
|
440
|
+
}
|
|
441
|
+
if (this.signal.aborted) throw new Cancelled();
|
|
442
|
+
this.markAnswered(request.requestId);
|
|
443
|
+
const post = transport.postFunctionResults.bind(transport);
|
|
444
|
+
return this.open(() => post(conversationId, request.requestId, results, this.signal));
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
/** Run to completion, running function calls and answering questions with onClarify; return an Interruption if a
|
|
448
|
+
* question has no handler. */
|
|
379
449
|
async drive(stream: TurnStream): Promise<Interruption | null> {
|
|
380
450
|
for (;;) {
|
|
381
451
|
const clarify = await this.consume(stream);
|
|
@@ -383,13 +453,16 @@ class Loop {
|
|
|
383
453
|
this.emit({ type: "run_item_stream_event", name: "message_output_created", item: this.text });
|
|
384
454
|
return null;
|
|
385
455
|
}
|
|
456
|
+
if (clarify.kind === "function_calls_requested") {
|
|
457
|
+
stream = await this.answerFunctions(clarify);
|
|
458
|
+
continue;
|
|
459
|
+
}
|
|
386
460
|
if (this.onClarify === undefined) {
|
|
387
461
|
return { kind: "clarify", requestId: clarify.requestId, payload: { questions: clarify.questions.slice() } };
|
|
388
462
|
}
|
|
389
463
|
if (this.signal.aborted) throw new Cancelled();
|
|
390
464
|
const answers = await this.ask(clarify.questions);
|
|
391
465
|
if (this.signal.aborted) throw new Cancelled();
|
|
392
|
-
this.resetText();
|
|
393
466
|
stream = await this.answer(clarify.requestId, answers);
|
|
394
467
|
}
|
|
395
468
|
}
|
|
@@ -398,9 +471,29 @@ class Loop {
|
|
|
398
471
|
async answerPending(state: RunState): Promise<Interruption[]> {
|
|
399
472
|
this.conversationId = state.conversationId;
|
|
400
473
|
this.onConversation(state.conversationId);
|
|
474
|
+
// A saved state can be stale: another process may have answered its calls since. Run only what the server still
|
|
475
|
+
// waits on, so no function's side effects happen twice.
|
|
476
|
+
const transport = this.transport;
|
|
477
|
+
let waiting: Set<string> | null = null;
|
|
478
|
+
if (state.pending.some((item) => item.kind === "function_call")
|
|
479
|
+
&& transport.pending !== undefined && transport.follow !== undefined) {
|
|
480
|
+
const live = await raceAbort(transport.pending(state.conversationId), this.signal);
|
|
481
|
+
waiting = new Set(live.map((request) => request.requestId));
|
|
482
|
+
}
|
|
401
483
|
for (let n = 0; n < state.pending.length; n++) {
|
|
402
484
|
const item = state.pending[n];
|
|
403
|
-
|
|
485
|
+
let stream: TurnStream;
|
|
486
|
+
if (item.kind === "function_call" && waiting !== null && !waiting.has(item.requestId)) {
|
|
487
|
+
this.markAnswered(item.requestId);
|
|
488
|
+
const follow = (transport.follow as NonNullable<Transport["follow"]>).bind(transport);
|
|
489
|
+
stream = await this.open(() => follow(state.conversationId, this.signal));
|
|
490
|
+
} else stream = item.kind === "function_call"
|
|
491
|
+
? await this.answerFunctions({
|
|
492
|
+
requestId: item.requestId,
|
|
493
|
+
calls: item.payload.calls.map((c) => ({ callId: c.call_id, name: c.name, arguments: { ...c.arguments } })),
|
|
494
|
+
})
|
|
495
|
+
: await this.answer(item.requestId, state.answers[item.requestId]);
|
|
496
|
+
const interruption = await this.drive(stream);
|
|
404
497
|
if (interruption !== null) return [interruption, ...state.pending.slice(n + 1)];
|
|
405
498
|
}
|
|
406
499
|
return [];
|
|
@@ -421,8 +514,10 @@ function checkMaxTurns(opts: { maxTurns?: unknown }): void {
|
|
|
421
514
|
function checkInput(input: unknown): void {
|
|
422
515
|
if (input instanceof RunState) {
|
|
423
516
|
for (const item of input.pending) {
|
|
517
|
+
if (item.kind === "function_call") continue; // run here when the state is resumed; nothing to answer
|
|
424
518
|
if (item.kind !== "clarify") {
|
|
425
|
-
|
|
519
|
+
// fromString keeps kinds it doesn't know, so this is reachable at runtime.
|
|
520
|
+
throw new NotSupportedError(`resuming "${(item as { kind: string }).kind}" interruptions is not supported yet`);
|
|
426
521
|
}
|
|
427
522
|
if (!Object.prototype.hasOwnProperty.call(input.answers, item.requestId)) {
|
|
428
523
|
throw new UserError(`pending clarify "${item.requestId}" has no answer: call state.answer(item, {...})`);
|
|
@@ -478,7 +573,9 @@ async function execute(p: Prepared, controller: AbortController, emit: Emit): Pr
|
|
|
478
573
|
const stopper = new Stopper(p.transport, signal);
|
|
479
574
|
const onAbort = () => stopper.send();
|
|
480
575
|
signal.addEventListener("abort", onAbort, { once: true });
|
|
481
|
-
const
|
|
576
|
+
const functions = new Map(p.agent.functionTools.map((t): [string, FunctionTool] => [t.name, t]));
|
|
577
|
+
const loop = new Loop(p.transport, p.opts.onClarify, emit, signal, (c) => stopper.onConversation(c), functions,
|
|
578
|
+
p.opts.raiseErrors ?? false);
|
|
482
579
|
let interruptions: Interruption[] = [];
|
|
483
580
|
let cancelled = false;
|
|
484
581
|
const fallbackConversation = p.input instanceof RunState ? p.input.conversationId : p.opts.conversationId;
|
package/src/compose/runState.ts
CHANGED
|
@@ -1,17 +1,25 @@
|
|
|
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 {
|
|
4
|
+
import type { Configuration } from "../runtime.js";
|
|
5
|
+
import { NotSupportedError, UserError } from "./errors.js";
|
|
5
6
|
import type { ClarifyQuestion } from "./events.js";
|
|
7
|
+
import type { Transport } from "./transport.js";
|
|
6
8
|
|
|
7
9
|
const STATE_VERSION = 1;
|
|
8
10
|
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
11
|
+
/** One function call waiting on this process, in the JSON shape Python's `RunState` uses. */
|
|
12
|
+
export interface PendingFunctionCall {
|
|
13
|
+
call_id: string;
|
|
14
|
+
name: string;
|
|
15
|
+
arguments: Record<string, unknown>;
|
|
13
16
|
}
|
|
14
17
|
|
|
18
|
+
export type Interruption =
|
|
19
|
+
| { kind: "clarify"; requestId: string; payload: { questions: ClarifyQuestion[] } }
|
|
20
|
+
/** Calls a stopped process left waiting (`RunState.fromSession`); `run(agent, state)` runs them. */
|
|
21
|
+
| { kind: "function_call"; requestId: string; payload: { calls: PendingFunctionCall[]; expires_at: string | null } };
|
|
22
|
+
|
|
15
23
|
function isObject(v: unknown): v is Record<string, unknown> {
|
|
16
24
|
return typeof v === "object" && v !== null && !Array.isArray(v);
|
|
17
25
|
}
|
|
@@ -37,11 +45,42 @@ export class RunState {
|
|
|
37
45
|
this.transportKind = transportKind;
|
|
38
46
|
}
|
|
39
47
|
|
|
48
|
+
/**
|
|
49
|
+
* What the conversation is waiting on, read from the server: the function calls of a run whose process stopped
|
|
50
|
+
* before answering them. `run(agent, state)` then runs them here and continues the turn.
|
|
51
|
+
*/
|
|
52
|
+
static async fromSession(
|
|
53
|
+
conversationId: string,
|
|
54
|
+
opts: { client?: Configuration; transport?: Transport } = {},
|
|
55
|
+
): Promise<RunState> {
|
|
56
|
+
const { resolveTransport } = await import("./deploy.js"); // deploy imports run, which imports this module
|
|
57
|
+
const transport = resolveTransport(opts.client, opts.transport);
|
|
58
|
+
if (typeof conversationId !== "string" || conversationId === "") {
|
|
59
|
+
throw new UserError("fromSession needs a conversation id (a previous result.conversationId)");
|
|
60
|
+
}
|
|
61
|
+
if (transport.pending === undefined) {
|
|
62
|
+
throw new NotSupportedError("this transport cannot list pending function calls");
|
|
63
|
+
}
|
|
64
|
+
const pending = (await transport.pending(conversationId)).map((r): Interruption => ({
|
|
65
|
+
kind: "function_call",
|
|
66
|
+
requestId: r.requestId,
|
|
67
|
+
payload: {
|
|
68
|
+
calls: r.calls.map((c) => ({ call_id: c.callId, name: c.name, arguments: { ...c.arguments } })),
|
|
69
|
+
expires_at: r.expiresAt ?? null,
|
|
70
|
+
},
|
|
71
|
+
}));
|
|
72
|
+
return new RunState(conversationId, pending, {});
|
|
73
|
+
}
|
|
74
|
+
|
|
40
75
|
/** Record the answers to a pending interruption; `run(agent, state)` sends them. */
|
|
41
76
|
answer(item: Interruption, answers: Record<string, unknown>): void {
|
|
42
77
|
if (!this.pending.some((p) => p.requestId === item.requestId)) {
|
|
43
78
|
throw new UserError(`no pending item with request id "${item.requestId}"`);
|
|
44
79
|
}
|
|
80
|
+
if (item.kind === "function_call") {
|
|
81
|
+
throw new UserError("function calls are answered by running the agent's function tools: pass this state to " +
|
|
82
|
+
"run() with the agent");
|
|
83
|
+
}
|
|
45
84
|
this.answers[item.requestId] = { ...answers };
|
|
46
85
|
}
|
|
47
86
|
|