sarvam-agents-client 0.2.3 → 0.3.1
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 +16 -1
- package/dist/apis/AgentsApi.d.ts +4 -4
- package/dist/apis/AgentsApi.js +4 -4
- package/dist/apis/AppsApi.d.ts +1 -0
- package/dist/apis/AppsApi.js +3 -0
- package/dist/apis/FunctionToolsApi.d.ts +33 -0
- package/dist/apis/FunctionToolsApi.js +65 -0
- package/dist/apis/QueueApi.d.ts +1 -0
- package/dist/apis/QueueApi.js +3 -0
- package/dist/apis/ResponsesApi.d.ts +2 -0
- package/dist/apis/ResponsesApi.js +6 -0
- package/dist/apis/index.d.ts +1 -0
- package/dist/apis/index.js +1 -0
- package/dist/compose/agent.d.ts +26 -6
- package/dist/compose/agent.js +84 -7
- package/dist/compose/deploy.d.ts +3 -2
- package/dist/compose/errors.d.ts +22 -1
- package/dist/compose/errors.js +21 -1
- package/dist/compose/events.d.ts +38 -0
- package/dist/compose/events.js +59 -2
- package/dist/compose/functionTool.d.ts +101 -0
- package/dist/compose/functionTool.js +420 -0
- package/dist/compose/index.d.ts +7 -3
- package/dist/compose/index.js +3 -1
- package/dist/compose/output.d.ts +40 -0
- package/dist/compose/output.js +476 -0
- package/dist/compose/run.d.ts +44 -15
- package/dist/compose/run.js +164 -21
- package/dist/compose/runState.d.ts +28 -2
- package/dist/compose/runState.js +30 -0
- package/dist/compose/settingsTransport.d.ts +23 -3
- package/dist/compose/settingsTransport.js +295 -3
- package/dist/compose/transport.d.ts +21 -3
- package/dist/esm/apis/AgentsApi.d.ts +4 -4
- package/dist/esm/apis/AgentsApi.js +4 -4
- package/dist/esm/apis/AppsApi.d.ts +1 -0
- package/dist/esm/apis/AppsApi.js +3 -0
- package/dist/esm/apis/FunctionToolsApi.d.ts +33 -0
- package/dist/esm/apis/FunctionToolsApi.js +61 -0
- package/dist/esm/apis/QueueApi.d.ts +1 -0
- package/dist/esm/apis/QueueApi.js +3 -0
- package/dist/esm/apis/ResponsesApi.d.ts +2 -0
- package/dist/esm/apis/ResponsesApi.js +6 -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 +26 -6
- package/dist/esm/compose/agent.js +84 -7
- package/dist/esm/compose/deploy.d.ts +3 -2
- package/dist/esm/compose/errors.d.ts +22 -1
- package/dist/esm/compose/errors.js +21 -1
- package/dist/esm/compose/events.d.ts +38 -0
- package/dist/esm/compose/events.js +58 -2
- package/dist/esm/compose/functionTool.d.ts +101 -0
- package/dist/esm/compose/functionTool.js +406 -0
- package/dist/esm/compose/index.d.ts +7 -3
- package/dist/esm/compose/index.js +1 -0
- package/dist/esm/compose/output.d.ts +40 -0
- package/dist/esm/compose/output.js +466 -0
- package/dist/esm/compose/run.d.ts +44 -15
- package/dist/esm/compose/run.js +165 -22
- package/dist/esm/compose/runState.d.ts +28 -2
- package/dist/esm/compose/runState.js +31 -1
- package/dist/esm/compose/settingsTransport.d.ts +23 -3
- package/dist/esm/compose/settingsTransport.js +298 -7
- package/dist/esm/compose/transport.d.ts +21 -3
- package/dist/esm/models/AgentConversationDetail.d.ts +7 -0
- package/dist/esm/models/AgentConversationDetail.js +3 -0
- package/dist/esm/models/AppResource.d.ts +29 -0
- package/dist/esm/models/AppResource.js +16 -0
- package/dist/esm/models/AppToolsResponse.d.ts +3 -4
- package/dist/esm/models/AppToolsResponse.js +3 -2
- package/dist/esm/models/AppView.d.ts +48 -0
- package/dist/esm/models/AppView.js +23 -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/McpSecurityAppealView.d.ts +50 -0
- package/dist/esm/models/McpSecurityAppealView.js +47 -0
- package/dist/esm/models/McpSecurityView.d.ts +105 -0
- package/dist/esm/models/McpSecurityView.js +66 -0
- package/dist/esm/models/MessagesResponse.d.ts +6 -0
- package/dist/esm/models/MessagesResponse.js +2 -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 +40 -0
- package/dist/esm/models/ResponseDetail.js +12 -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 +6 -0
- package/dist/esm/models/index.js +6 -0
- package/dist/esm/streaming.d.ts +14 -2
- package/dist/esm/streaming.js +26 -4
- package/dist/models/AgentConversationDetail.d.ts +7 -0
- package/dist/models/AgentConversationDetail.js +3 -0
- package/dist/models/AppResource.d.ts +29 -0
- package/dist/models/AppResource.js +17 -1
- package/dist/models/AppToolsResponse.d.ts +3 -4
- package/dist/models/AppToolsResponse.js +3 -2
- package/dist/models/AppView.d.ts +48 -0
- package/dist/models/AppView.js +24 -1
- 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/McpSecurityAppealView.d.ts +50 -0
- package/dist/models/McpSecurityAppealView.js +54 -0
- package/dist/models/McpSecurityView.d.ts +105 -0
- package/dist/models/McpSecurityView.js +73 -0
- package/dist/models/MessagesResponse.d.ts +6 -0
- package/dist/models/MessagesResponse.js +2 -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 +40 -0
- package/dist/models/ResponseDetail.js +12 -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 +6 -0
- package/dist/models/index.js +6 -0
- package/dist/streaming.d.ts +14 -2
- package/dist/streaming.js +27 -4
- package/package.json +4 -3
- package/src/apis/AgentsApi.ts +4 -4
- package/src/apis/AppsApi.ts +5 -0
- package/src/apis/FunctionToolsApi.ts +102 -0
- package/src/apis/QueueApi.ts +5 -0
- package/src/apis/ResponsesApi.ts +10 -0
- package/src/apis/index.ts +1 -0
- package/src/compose/agent.ts +108 -15
- package/src/compose/deploy.ts +6 -5
- package/src/compose/errors.ts +35 -2
- package/src/compose/events.ts +79 -1
- package/src/compose/functionTool.ts +441 -0
- package/src/compose/index.ts +7 -3
- package/src/compose/output.ts +436 -0
- package/src/compose/run.ts +208 -39
- package/src/compose/runState.ts +46 -6
- package/src/compose/settingsTransport.ts +297 -10
- package/src/compose/transport.ts +27 -3
- package/src/models/AgentConversationDetail.ts +15 -0
- package/src/models/AppResource.ts +42 -0
- package/src/models/AppToolsResponse.ts +11 -4
- package/src/models/AppView.ts +73 -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/McpSecurityAppealView.ts +89 -0
- package/src/models/McpSecurityView.ts +169 -0
- package/src/models/MessagesResponse.ts +8 -0
- package/src/models/QueueMessageInput.ts +28 -0
- package/src/models/RequiredAction.ts +128 -0
- package/src/models/ResponseDetail.ts +48 -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 +6 -0
- package/src/streaming.ts +39 -3
package/dist/esm/compose/run.js
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import { FetchError } from "../runtime.js";
|
|
2
2
|
import { agentIdFor, getDefaultClient, resolveTransport } from "./deploy.js";
|
|
3
|
-
import { NotSupportedError, RunError, UserError } from "./errors.js";
|
|
3
|
+
import { ModelBehaviorError, NotSupportedError, RunError, UserError } from "./errors.js";
|
|
4
|
+
import { CallsCancelled, runCalls } from "./functionTool.js";
|
|
5
|
+
import { parseOutput } from "./output.js";
|
|
4
6
|
import { RunState } from "./runState.js";
|
|
5
7
|
const MAX_RECONNECTS = 3;
|
|
6
8
|
/** The abort reason ResponseStream (src/streaming.ts) uses when a stream goes quiet. */
|
|
@@ -25,6 +27,10 @@ export class RunResult {
|
|
|
25
27
|
this.interruptions = outcome.interruptions;
|
|
26
28
|
this.stopReason = outcome.stopReason;
|
|
27
29
|
this.conversationId = outcome.conversationId;
|
|
30
|
+
this.outputCitations = outcome.outputCitations;
|
|
31
|
+
this.outputNote = outcome.outputNote;
|
|
32
|
+
this.outputSkipped = outcome.outputSkipped;
|
|
33
|
+
this.outputMode = outcome.outputMode;
|
|
28
34
|
}
|
|
29
35
|
/** A RunState to answer the interruptions and continue; throws UserError when the run has no conversation. */
|
|
30
36
|
get state() {
|
|
@@ -96,19 +102,28 @@ class Stopper {
|
|
|
96
102
|
}
|
|
97
103
|
}
|
|
98
104
|
class Loop {
|
|
99
|
-
constructor(transport, onClarify, emit, signal, onConversation) {
|
|
105
|
+
constructor(transport, onClarify, emit, signal, onConversation, functions = new Map(), raiseErrors = false) {
|
|
100
106
|
this.transport = transport;
|
|
101
107
|
this.onClarify = onClarify;
|
|
102
108
|
this.emit = emit;
|
|
103
109
|
this.signal = signal;
|
|
104
110
|
this.onConversation = onConversation;
|
|
111
|
+
this.functions = functions;
|
|
112
|
+
this.raiseErrors = raiseErrors;
|
|
105
113
|
this.conversationId = null;
|
|
106
114
|
this.items = [];
|
|
107
115
|
this.stopReason = undefined;
|
|
116
|
+
/** The turn's structured output (`data-output` / `data-output-error`), when the agent has an `outputType`. */
|
|
117
|
+
this.output = undefined;
|
|
108
118
|
// Text of the current segment, per text block. Kept per block so a resumed stream, which replays from the start
|
|
109
119
|
// of the block it dropped in, doesn't repeat text.
|
|
110
120
|
this.blocks = [];
|
|
111
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;
|
|
112
127
|
}
|
|
113
128
|
get text() {
|
|
114
129
|
return this.blocks.map(([, parts]) => parts.join("")).join("");
|
|
@@ -186,14 +201,17 @@ class Loop {
|
|
|
186
201
|
start(agentId, conversationId, input) {
|
|
187
202
|
return this.open(() => this.transport.startTurn(agentId, conversationId, input, this.signal));
|
|
188
203
|
}
|
|
189
|
-
/** 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. */
|
|
190
205
|
async consume(stream) {
|
|
191
|
-
let
|
|
206
|
+
let pause = null;
|
|
192
207
|
let reconnects = 0;
|
|
193
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;
|
|
194
211
|
for (;;) {
|
|
195
212
|
let finished = false;
|
|
196
213
|
const current = stream;
|
|
214
|
+
this.replaying = current.replay === true;
|
|
197
215
|
const onAbort = () => current.close();
|
|
198
216
|
this.signal.addEventListener("abort", onAbort, { once: true });
|
|
199
217
|
try {
|
|
@@ -207,8 +225,22 @@ class Loop {
|
|
|
207
225
|
finished = true;
|
|
208
226
|
break;
|
|
209
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;
|
|
210
242
|
if (this.handle(event))
|
|
211
|
-
|
|
243
|
+
pause = event;
|
|
212
244
|
}
|
|
213
245
|
}
|
|
214
246
|
catch (err) {
|
|
@@ -225,7 +257,7 @@ class Loop {
|
|
|
225
257
|
if (this.signal.aborted)
|
|
226
258
|
throw new Cancelled();
|
|
227
259
|
if (finished)
|
|
228
|
-
return
|
|
260
|
+
return pause;
|
|
229
261
|
const responseId = current.responseId;
|
|
230
262
|
const lastEventId = current.lastEventId;
|
|
231
263
|
if (reconnects >= MAX_RECONNECTS || this.conversationId === null) {
|
|
@@ -240,7 +272,7 @@ class Loop {
|
|
|
240
272
|
stream = await this.open(() => this.transport.resume(conversationId, responseId, lastEventId, this.signal));
|
|
241
273
|
}
|
|
242
274
|
}
|
|
243
|
-
/** 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. */
|
|
244
276
|
handle(event) {
|
|
245
277
|
switch (event.kind) {
|
|
246
278
|
case "turn_failed":
|
|
@@ -252,28 +284,33 @@ class Loop {
|
|
|
252
284
|
case "turn_limit":
|
|
253
285
|
this.stopReason = STOP_REASONS[event.capKind];
|
|
254
286
|
return false;
|
|
287
|
+
case "output":
|
|
288
|
+
case "output_error":
|
|
289
|
+
this.output = event;
|
|
290
|
+
return false;
|
|
255
291
|
case "text_start":
|
|
256
292
|
case "text_end":
|
|
257
293
|
this.onText(event);
|
|
258
294
|
return false;
|
|
259
295
|
case "text_delta":
|
|
260
296
|
this.onText(event);
|
|
261
|
-
this.
|
|
297
|
+
if (!this.replaying) {
|
|
298
|
+
this.emit({ type: "raw_model_stream_event", data: { type: "output_text_delta", delta: event.delta } });
|
|
299
|
+
}
|
|
262
300
|
return false;
|
|
263
301
|
case "reasoning_delta":
|
|
264
|
-
this.
|
|
302
|
+
if (!this.replaying) {
|
|
303
|
+
this.emit({ type: "raw_model_stream_event", data: { type: "reasoning_delta", delta: event.delta } });
|
|
304
|
+
}
|
|
265
305
|
return false;
|
|
266
306
|
default:
|
|
267
307
|
break;
|
|
268
308
|
}
|
|
269
309
|
this.items.push(event);
|
|
270
|
-
if (event.kind === "tool_called" || event.kind === "tool_output") {
|
|
310
|
+
if ((event.kind === "tool_called" || event.kind === "tool_output") && !this.replaying) {
|
|
271
311
|
this.emit({ type: "run_item_stream_event", name: event.kind, item: event });
|
|
272
312
|
}
|
|
273
|
-
|
|
274
|
-
throw new NotSupportedError("function tools are not supported yet");
|
|
275
|
-
}
|
|
276
|
-
return event.kind === "clarify_requested";
|
|
313
|
+
return event.kind === "clarify_requested" || event.kind === "function_calls_requested";
|
|
277
314
|
}
|
|
278
315
|
async ask(questions) {
|
|
279
316
|
const handler = this.onClarify;
|
|
@@ -284,13 +321,51 @@ class Loop {
|
|
|
284
321
|
}
|
|
285
322
|
return answers;
|
|
286
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
|
+
}
|
|
287
335
|
answer(requestId, answers) {
|
|
336
|
+
this.markAnswered(requestId);
|
|
288
337
|
const conversationId = this.conversationId;
|
|
289
338
|
if (conversationId === null)
|
|
290
339
|
throw new RunError("stream_lost", "no conversation to answer the question in");
|
|
291
340
|
return this.open(() => this.transport.answerClarify(conversationId, requestId, answers, this.signal));
|
|
292
341
|
}
|
|
293
|
-
/** 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. */
|
|
294
369
|
async drive(stream) {
|
|
295
370
|
for (;;) {
|
|
296
371
|
const clarify = await this.consume(stream);
|
|
@@ -298,6 +373,10 @@ class Loop {
|
|
|
298
373
|
this.emit({ type: "run_item_stream_event", name: "message_output_created", item: this.text });
|
|
299
374
|
return null;
|
|
300
375
|
}
|
|
376
|
+
if (clarify.kind === "function_calls_requested") {
|
|
377
|
+
stream = await this.answerFunctions(clarify);
|
|
378
|
+
continue;
|
|
379
|
+
}
|
|
301
380
|
if (this.onClarify === undefined) {
|
|
302
381
|
return { kind: "clarify", requestId: clarify.requestId, payload: { questions: clarify.questions.slice() } };
|
|
303
382
|
}
|
|
@@ -306,7 +385,6 @@ class Loop {
|
|
|
306
385
|
const answers = await this.ask(clarify.questions);
|
|
307
386
|
if (this.signal.aborted)
|
|
308
387
|
throw new Cancelled();
|
|
309
|
-
this.resetText();
|
|
310
388
|
stream = await this.answer(clarify.requestId, answers);
|
|
311
389
|
}
|
|
312
390
|
}
|
|
@@ -314,9 +392,31 @@ class Loop {
|
|
|
314
392
|
async answerPending(state) {
|
|
315
393
|
this.conversationId = state.conversationId;
|
|
316
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
|
+
}
|
|
317
404
|
for (let n = 0; n < state.pending.length; n++) {
|
|
318
405
|
const item = state.pending[n];
|
|
319
|
-
|
|
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);
|
|
320
420
|
if (interruption !== null)
|
|
321
421
|
return [interruption, ...state.pending.slice(n + 1)];
|
|
322
422
|
}
|
|
@@ -333,7 +433,10 @@ function checkMaxTurns(opts) {
|
|
|
333
433
|
function checkInput(input) {
|
|
334
434
|
if (input instanceof RunState) {
|
|
335
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
|
|
336
438
|
if (item.kind !== "clarify") {
|
|
439
|
+
// fromString keeps kinds it doesn't know, so this is reachable at runtime.
|
|
337
440
|
throw new NotSupportedError(`resuming "${item.kind}" interruptions is not supported yet`);
|
|
338
441
|
}
|
|
339
442
|
if (!Object.prototype.hasOwnProperty.call(input.answers, item.requestId)) {
|
|
@@ -366,14 +469,25 @@ function link(signal, controller) {
|
|
|
366
469
|
signal.addEventListener("abort", onAbort, { once: true });
|
|
367
470
|
return () => signal.removeEventListener("abort", onAbort);
|
|
368
471
|
}
|
|
472
|
+
/** `finalOutput` for an agent with an `outputType`: the parsed value, or undefined when the turn produced none
|
|
473
|
+
* (`outputSkipped` says why). A mismatch throws `ModelBehaviorError`. */
|
|
474
|
+
function structuredOutput(outputType, event) {
|
|
475
|
+
if ((event === null || event === void 0 ? void 0 : event.kind) === "output_error")
|
|
476
|
+
throw new ModelBehaviorError(event.rawText, event.errors, event.note);
|
|
477
|
+
if ((event === null || event === void 0 ? void 0 : event.kind) === "output" && event.output !== null && event.output !== undefined) {
|
|
478
|
+
return parseOutput(outputType, event.output, event.note);
|
|
479
|
+
}
|
|
480
|
+
return undefined;
|
|
481
|
+
}
|
|
369
482
|
async function execute(p, controller, emit) {
|
|
370
|
-
var _a, _b;
|
|
483
|
+
var _a, _b, _c, _d, _e, _f, _g, _h, _j;
|
|
371
484
|
const signal = controller.signal;
|
|
372
485
|
const unlink = link(p.opts.signal, controller);
|
|
373
486
|
const stopper = new Stopper(p.transport, signal);
|
|
374
487
|
const onAbort = () => stopper.send();
|
|
375
488
|
signal.addEventListener("abort", onAbort, { once: true });
|
|
376
|
-
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);
|
|
377
491
|
let interruptions = [];
|
|
378
492
|
let cancelled = false;
|
|
379
493
|
const fallbackConversation = p.input instanceof RunState ? p.input.conversationId : p.opts.conversationId;
|
|
@@ -385,7 +499,7 @@ async function execute(p, controller, emit) {
|
|
|
385
499
|
}
|
|
386
500
|
else {
|
|
387
501
|
const agentId = await raceAbort(agentIdFor(p.agent, p.transport, p.owner), signal);
|
|
388
|
-
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);
|
|
389
503
|
const interruption = await loop.drive(stream);
|
|
390
504
|
interruptions = interruption ? [interruption] : [];
|
|
391
505
|
}
|
|
@@ -403,14 +517,34 @@ async function execute(p, controller, emit) {
|
|
|
403
517
|
}
|
|
404
518
|
cancelled = cancelled || signal.aborted;
|
|
405
519
|
const text = loop.text;
|
|
520
|
+
const outputType = p.agent.outputType;
|
|
521
|
+
let finalOutput;
|
|
522
|
+
if (interruptions.length || cancelled)
|
|
523
|
+
finalOutput = undefined;
|
|
524
|
+
else if (outputType !== undefined) {
|
|
525
|
+
try {
|
|
526
|
+
finalOutput = structuredOutput(outputType, loop.output);
|
|
527
|
+
}
|
|
528
|
+
catch (err) {
|
|
529
|
+
if (err instanceof ModelBehaviorError)
|
|
530
|
+
err.conversationId = (_c = loop.conversationId) !== null && _c !== void 0 ? _c : fallbackConversation;
|
|
531
|
+
throw err;
|
|
532
|
+
}
|
|
533
|
+
}
|
|
534
|
+
else
|
|
535
|
+
finalOutput = text;
|
|
406
536
|
return {
|
|
407
|
-
finalOutput
|
|
537
|
+
finalOutput,
|
|
408
538
|
outputText: text,
|
|
409
539
|
newItems: loop.items,
|
|
410
540
|
interruptions,
|
|
411
541
|
stopReason: loop.stopReason,
|
|
412
|
-
conversationId: (
|
|
542
|
+
conversationId: (_d = loop.conversationId) !== null && _d !== void 0 ? _d : fallbackConversation,
|
|
413
543
|
cancelled,
|
|
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,
|
|
414
548
|
};
|
|
415
549
|
}
|
|
416
550
|
// -- streaming ---------------------------------------------------------------------------------------------------
|
|
@@ -426,6 +560,11 @@ export class StreamedRunResult {
|
|
|
426
560
|
this.stopReason = undefined;
|
|
427
561
|
this.conversationId = undefined;
|
|
428
562
|
this.cancelled = false;
|
|
563
|
+
/** As on `RunResult`; read after `completed` settles. */
|
|
564
|
+
this.outputCitations = [];
|
|
565
|
+
this.outputNote = undefined;
|
|
566
|
+
this.outputSkipped = undefined;
|
|
567
|
+
this.outputMode = undefined;
|
|
429
568
|
this.queue = [];
|
|
430
569
|
this.waiters = [];
|
|
431
570
|
this.done = false;
|
|
@@ -441,6 +580,10 @@ export class StreamedRunResult {
|
|
|
441
580
|
this.stopReason = outcome.stopReason;
|
|
442
581
|
this.conversationId = outcome.conversationId;
|
|
443
582
|
this.cancelled = outcome.cancelled;
|
|
583
|
+
this.outputCitations = outcome.outputCitations;
|
|
584
|
+
this.outputNote = outcome.outputNote;
|
|
585
|
+
this.outputSkipped = outcome.outputSkipped;
|
|
586
|
+
this.outputMode = outcome.outputMode;
|
|
444
587
|
this.end();
|
|
445
588
|
}, (error) => {
|
|
446
589
|
this.failure = { error };
|
|
@@ -1,13 +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
|
+
import type { OutputType } from "./output.js";
|
|
4
|
+
import type { Configuration } from "../runtime.js";
|
|
3
5
|
import type { ClarifyQuestion } from "./events.js";
|
|
4
|
-
|
|
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 = {
|
|
5
14
|
kind: "clarify";
|
|
6
15
|
requestId: string;
|
|
7
16
|
payload: {
|
|
8
17
|
questions: ClarifyQuestion[];
|
|
9
18
|
};
|
|
10
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
|
+
};
|
|
11
29
|
export declare class RunState {
|
|
12
30
|
readonly conversationId: string;
|
|
13
31
|
readonly pending: Interruption[];
|
|
@@ -17,10 +35,18 @@ export declare class RunState {
|
|
|
17
35
|
readonly transportKind: string;
|
|
18
36
|
/** @internal Use `result.state` or `RunState.fromString`. */
|
|
19
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>;
|
|
20
46
|
/** Record the answers to a pending interruption; `run(agent, state)` sends them. */
|
|
21
47
|
answer(item: Interruption, answers: Record<string, unknown>): void;
|
|
22
48
|
/** JSON in the format Python's `RunState.to_json()` writes. */
|
|
23
49
|
toString(): string;
|
|
24
50
|
/** Read a state written by `toString()` (or by Python's `to_json()`). */
|
|
25
|
-
static fromString(agent: Agent
|
|
51
|
+
static fromString(agent: Agent<OutputType | undefined>, s: string): Promise<RunState>;
|
|
26
52
|
}
|
|
@@ -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,6 +1,16 @@
|
|
|
1
1
|
import type { Configuration } from "../runtime.js";
|
|
2
2
|
import type { Agent } from "./agent.js";
|
|
3
|
-
import type {
|
|
3
|
+
import type { OutputType } from "./output.js";
|
|
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;
|
|
4
14
|
export declare class SettingsTransport implements Transport {
|
|
5
15
|
private readonly config;
|
|
6
16
|
readonly kind: "settings";
|
|
@@ -10,13 +20,23 @@ export declare class SettingsTransport implements Transport {
|
|
|
10
20
|
constructor(config: Configuration);
|
|
11
21
|
findAgents(sdkName: string): Promise<RemoteAgent[]>;
|
|
12
22
|
readAgent(agentId: string): Promise<RemoteAgent>;
|
|
13
|
-
createAgent(agent: Agent): Promise<RemoteAgent>;
|
|
14
|
-
updateAgent(agentId: string, agent: Agent): Promise<RemoteAgent>;
|
|
23
|
+
createAgent(agent: Agent<OutputType | undefined>): Promise<RemoteAgent>;
|
|
24
|
+
updateAgent(agentId: string, agent: Agent<OutputType | undefined>): Promise<RemoteAgent>;
|
|
15
25
|
deleteAgent(agentId: string): Promise<void>;
|
|
16
26
|
startTurn(agentId: string, conversationId: string | null, text: string, signal?: AbortSignal): Promise<TurnStream>;
|
|
17
27
|
answerClarify(conversationId: string, requestId: string, answers: Record<string, unknown>, signal?: AbortSignal): Promise<TurnStream>;
|
|
18
28
|
resume(conversationId: string, responseId: string, lastEventId: string | null, signal?: AbortSignal): Promise<TurnStream>;
|
|
19
29
|
stop(conversationId: string): Promise<void>;
|
|
30
|
+
postFunctionResults(conversationId: string, requestId: string, results: FunctionResult[], signal?: AbortSignal): Promise<TurnStream>;
|
|
31
|
+
/** The turn after a request someone already answered, as a replay of it from its start (the run skips up to the
|
|
32
|
+
* answered request): the running response by reconnecting without a cursor, else the conversation's last reply
|
|
33
|
+
* as stored. A turn that paused again ends on its new request, unanswered. */
|
|
34
|
+
follow(conversationId: string, signal?: AbortSignal): Promise<TurnStream>;
|
|
35
|
+
/** `follow`, after a 409 expired / already_answered for `requestId`: a turn not yet picked up again (no active
|
|
36
|
+
* response, and the last reply still ends on that request) is read again every second, up to 30 times; then
|
|
37
|
+
* RunError(reason). An abort ends the wait. */
|
|
38
|
+
private followAfter;
|
|
39
|
+
pending(conversationId: string): Promise<PendingFunctionCalls[]>;
|
|
20
40
|
/** Put back what updateAgent overwrote; a failing restore must not mask the original error. */
|
|
21
41
|
private restore;
|
|
22
42
|
private instructions;
|