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.
Files changed (178) hide show
  1. package/README.md +16 -1
  2. package/dist/apis/AgentsApi.d.ts +4 -4
  3. package/dist/apis/AgentsApi.js +4 -4
  4. package/dist/apis/AppsApi.d.ts +1 -0
  5. package/dist/apis/AppsApi.js +3 -0
  6. package/dist/apis/FunctionToolsApi.d.ts +33 -0
  7. package/dist/apis/FunctionToolsApi.js +65 -0
  8. package/dist/apis/QueueApi.d.ts +1 -0
  9. package/dist/apis/QueueApi.js +3 -0
  10. package/dist/apis/ResponsesApi.d.ts +2 -0
  11. package/dist/apis/ResponsesApi.js +6 -0
  12. package/dist/apis/index.d.ts +1 -0
  13. package/dist/apis/index.js +1 -0
  14. package/dist/compose/agent.d.ts +26 -6
  15. package/dist/compose/agent.js +84 -7
  16. package/dist/compose/deploy.d.ts +3 -2
  17. package/dist/compose/errors.d.ts +22 -1
  18. package/dist/compose/errors.js +21 -1
  19. package/dist/compose/events.d.ts +38 -0
  20. package/dist/compose/events.js +59 -2
  21. package/dist/compose/functionTool.d.ts +101 -0
  22. package/dist/compose/functionTool.js +420 -0
  23. package/dist/compose/index.d.ts +7 -3
  24. package/dist/compose/index.js +3 -1
  25. package/dist/compose/output.d.ts +40 -0
  26. package/dist/compose/output.js +476 -0
  27. package/dist/compose/run.d.ts +44 -15
  28. package/dist/compose/run.js +164 -21
  29. package/dist/compose/runState.d.ts +28 -2
  30. package/dist/compose/runState.js +30 -0
  31. package/dist/compose/settingsTransport.d.ts +23 -3
  32. package/dist/compose/settingsTransport.js +295 -3
  33. package/dist/compose/transport.d.ts +21 -3
  34. package/dist/esm/apis/AgentsApi.d.ts +4 -4
  35. package/dist/esm/apis/AgentsApi.js +4 -4
  36. package/dist/esm/apis/AppsApi.d.ts +1 -0
  37. package/dist/esm/apis/AppsApi.js +3 -0
  38. package/dist/esm/apis/FunctionToolsApi.d.ts +33 -0
  39. package/dist/esm/apis/FunctionToolsApi.js +61 -0
  40. package/dist/esm/apis/QueueApi.d.ts +1 -0
  41. package/dist/esm/apis/QueueApi.js +3 -0
  42. package/dist/esm/apis/ResponsesApi.d.ts +2 -0
  43. package/dist/esm/apis/ResponsesApi.js +6 -0
  44. package/dist/esm/apis/index.d.ts +1 -0
  45. package/dist/esm/apis/index.js +1 -0
  46. package/dist/esm/compose/agent.d.ts +26 -6
  47. package/dist/esm/compose/agent.js +84 -7
  48. package/dist/esm/compose/deploy.d.ts +3 -2
  49. package/dist/esm/compose/errors.d.ts +22 -1
  50. package/dist/esm/compose/errors.js +21 -1
  51. package/dist/esm/compose/events.d.ts +38 -0
  52. package/dist/esm/compose/events.js +58 -2
  53. package/dist/esm/compose/functionTool.d.ts +101 -0
  54. package/dist/esm/compose/functionTool.js +406 -0
  55. package/dist/esm/compose/index.d.ts +7 -3
  56. package/dist/esm/compose/index.js +1 -0
  57. package/dist/esm/compose/output.d.ts +40 -0
  58. package/dist/esm/compose/output.js +466 -0
  59. package/dist/esm/compose/run.d.ts +44 -15
  60. package/dist/esm/compose/run.js +165 -22
  61. package/dist/esm/compose/runState.d.ts +28 -2
  62. package/dist/esm/compose/runState.js +31 -1
  63. package/dist/esm/compose/settingsTransport.d.ts +23 -3
  64. package/dist/esm/compose/settingsTransport.js +298 -7
  65. package/dist/esm/compose/transport.d.ts +21 -3
  66. package/dist/esm/models/AgentConversationDetail.d.ts +7 -0
  67. package/dist/esm/models/AgentConversationDetail.js +3 -0
  68. package/dist/esm/models/AppResource.d.ts +29 -0
  69. package/dist/esm/models/AppResource.js +16 -0
  70. package/dist/esm/models/AppToolsResponse.d.ts +3 -4
  71. package/dist/esm/models/AppToolsResponse.js +3 -2
  72. package/dist/esm/models/AppView.d.ts +48 -0
  73. package/dist/esm/models/AppView.js +23 -0
  74. package/dist/esm/models/ClarifyBody.d.ts +6 -0
  75. package/dist/esm/models/ClarifyBody.js +2 -0
  76. package/dist/esm/models/ConversationDetail.d.ts +7 -0
  77. package/dist/esm/models/ConversationDetail.js +3 -0
  78. package/dist/esm/models/ErrorDetail.d.ts +1 -0
  79. package/dist/esm/models/ErrorDetail.js +2 -1
  80. package/dist/esm/models/FunctionResultBody.d.ts +44 -0
  81. package/dist/esm/models/FunctionResultBody.js +49 -0
  82. package/dist/esm/models/McpSecurityAppealView.d.ts +50 -0
  83. package/dist/esm/models/McpSecurityAppealView.js +47 -0
  84. package/dist/esm/models/McpSecurityView.d.ts +105 -0
  85. package/dist/esm/models/McpSecurityView.js +66 -0
  86. package/dist/esm/models/MessagesResponse.d.ts +6 -0
  87. package/dist/esm/models/MessagesResponse.js +2 -0
  88. package/dist/esm/models/QueueMessageInput.d.ts +23 -0
  89. package/dist/esm/models/QueueMessageInput.js +14 -0
  90. package/dist/esm/models/RequiredAction.d.ts +77 -0
  91. package/dist/esm/models/RequiredAction.js +69 -0
  92. package/dist/esm/models/ResponseDetail.d.ts +40 -0
  93. package/dist/esm/models/ResponseDetail.js +12 -0
  94. package/dist/esm/models/ResponseInput.d.ts +23 -0
  95. package/dist/esm/models/ResponseInput.js +14 -0
  96. package/dist/esm/models/ToolResults200Response.d.ts +38 -0
  97. package/dist/esm/models/ToolResults200Response.js +47 -0
  98. package/dist/esm/models/ToolResultsBody.d.ts +39 -0
  99. package/dist/esm/models/ToolResultsBody.js +48 -0
  100. package/dist/esm/models/index.d.ts +6 -0
  101. package/dist/esm/models/index.js +6 -0
  102. package/dist/esm/streaming.d.ts +14 -2
  103. package/dist/esm/streaming.js +26 -4
  104. package/dist/models/AgentConversationDetail.d.ts +7 -0
  105. package/dist/models/AgentConversationDetail.js +3 -0
  106. package/dist/models/AppResource.d.ts +29 -0
  107. package/dist/models/AppResource.js +17 -1
  108. package/dist/models/AppToolsResponse.d.ts +3 -4
  109. package/dist/models/AppToolsResponse.js +3 -2
  110. package/dist/models/AppView.d.ts +48 -0
  111. package/dist/models/AppView.js +24 -1
  112. package/dist/models/ClarifyBody.d.ts +6 -0
  113. package/dist/models/ClarifyBody.js +2 -0
  114. package/dist/models/ConversationDetail.d.ts +7 -0
  115. package/dist/models/ConversationDetail.js +3 -0
  116. package/dist/models/ErrorDetail.d.ts +1 -0
  117. package/dist/models/ErrorDetail.js +2 -1
  118. package/dist/models/FunctionResultBody.d.ts +44 -0
  119. package/dist/models/FunctionResultBody.js +56 -0
  120. package/dist/models/McpSecurityAppealView.d.ts +50 -0
  121. package/dist/models/McpSecurityAppealView.js +54 -0
  122. package/dist/models/McpSecurityView.d.ts +105 -0
  123. package/dist/models/McpSecurityView.js +73 -0
  124. package/dist/models/MessagesResponse.d.ts +6 -0
  125. package/dist/models/MessagesResponse.js +2 -0
  126. package/dist/models/QueueMessageInput.d.ts +23 -0
  127. package/dist/models/QueueMessageInput.js +15 -1
  128. package/dist/models/RequiredAction.d.ts +77 -0
  129. package/dist/models/RequiredAction.js +77 -0
  130. package/dist/models/ResponseDetail.d.ts +40 -0
  131. package/dist/models/ResponseDetail.js +12 -0
  132. package/dist/models/ResponseInput.d.ts +23 -0
  133. package/dist/models/ResponseInput.js +15 -0
  134. package/dist/models/ToolResults200Response.d.ts +38 -0
  135. package/dist/models/ToolResults200Response.js +54 -0
  136. package/dist/models/ToolResultsBody.d.ts +39 -0
  137. package/dist/models/ToolResultsBody.js +55 -0
  138. package/dist/models/index.d.ts +6 -0
  139. package/dist/models/index.js +6 -0
  140. package/dist/streaming.d.ts +14 -2
  141. package/dist/streaming.js +27 -4
  142. package/package.json +4 -3
  143. package/src/apis/AgentsApi.ts +4 -4
  144. package/src/apis/AppsApi.ts +5 -0
  145. package/src/apis/FunctionToolsApi.ts +102 -0
  146. package/src/apis/QueueApi.ts +5 -0
  147. package/src/apis/ResponsesApi.ts +10 -0
  148. package/src/apis/index.ts +1 -0
  149. package/src/compose/agent.ts +108 -15
  150. package/src/compose/deploy.ts +6 -5
  151. package/src/compose/errors.ts +35 -2
  152. package/src/compose/events.ts +79 -1
  153. package/src/compose/functionTool.ts +441 -0
  154. package/src/compose/index.ts +7 -3
  155. package/src/compose/output.ts +436 -0
  156. package/src/compose/run.ts +208 -39
  157. package/src/compose/runState.ts +46 -6
  158. package/src/compose/settingsTransport.ts +297 -10
  159. package/src/compose/transport.ts +27 -3
  160. package/src/models/AgentConversationDetail.ts +15 -0
  161. package/src/models/AppResource.ts +42 -0
  162. package/src/models/AppToolsResponse.ts +11 -4
  163. package/src/models/AppView.ts +73 -0
  164. package/src/models/ClarifyBody.ts +8 -0
  165. package/src/models/ConversationDetail.ts +15 -0
  166. package/src/models/ErrorDetail.ts +2 -1
  167. package/src/models/FunctionResultBody.ts +83 -0
  168. package/src/models/McpSecurityAppealView.ts +89 -0
  169. package/src/models/McpSecurityView.ts +169 -0
  170. package/src/models/MessagesResponse.ts +8 -0
  171. package/src/models/QueueMessageInput.ts +28 -0
  172. package/src/models/RequiredAction.ts +128 -0
  173. package/src/models/ResponseDetail.ts +48 -0
  174. package/src/models/ResponseInput.ts +30 -0
  175. package/src/models/ToolResults200Response.ts +75 -0
  176. package/src/models/ToolResultsBody.ts +83 -0
  177. package/src/models/index.ts +6 -0
  178. package/src/streaming.ts +39 -3
@@ -1,10 +1,15 @@
1
- /** run(): deploy the agent, drive one turn through a Transport, handle clarify questions, dropped streams and cancel. */
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
- import { NotSupportedError, RunError, UserError } from "./errors.js";
7
- import type { ClarifyQuestion, Event } from "./events.js";
7
+ import { ModelBehaviorError, NotSupportedError, RunError, UserError } from "./errors.js";
8
+ import type { ClarifyQuestion, Event, OutputCitation } from "./events.js";
9
+ import { CallsCancelled, runCalls } from "./functionTool.js";
10
+ import type { FunctionTool } from "./functionTool.js";
11
+ import { parseOutput } from "./output.js";
12
+ import type { OutputType, ResolvedOutput } from "./output.js";
8
13
  import { RunState } from "./runState.js";
9
14
  import type { Interruption } from "./runState.js";
10
15
  import type { Transport, TurnStream } from "./transport.js";
@@ -26,6 +31,9 @@ export interface RunOptions {
26
31
  signal?: AbortSignal;
27
32
  /** Answers clarify questions; without it a question ends the run with an interruption. */
28
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;
29
37
  /** Not supported: the server caps turns per agent; set `new Agent({ limits: { maxTurns } })`. */
30
38
  maxTurns?: never;
31
39
  }
@@ -35,6 +43,8 @@ export type RunStreamEvent =
35
43
  | { type: "run_item_stream_event"; name: "tool_called" | "tool_output" | "message_output_created"; item: unknown };
36
44
 
37
45
  type ClarifyEvent = Extract<Event, { kind: "clarify_requested" }>;
46
+ type FunctionCallsEvent = Extract<Event, { kind: "function_calls_requested" }>;
47
+ type PauseEvent = ClarifyEvent | FunctionCallsEvent;
38
48
  type Emit = (event: RunStreamEvent) => void;
39
49
 
40
50
  /** Why the run ended early: the `limits` field whose cap the server hit. */
@@ -47,14 +57,20 @@ const STOP_REASONS: Record<string, StopReason> = {
47
57
  tokens: "max_tokens",
48
58
  };
49
59
 
50
- interface Outcome {
51
- finalOutput: string | undefined;
60
+ type OutputEvent = Extract<Event, { kind: "output" | "output_error" }>;
61
+
62
+ interface Outcome<T = string> {
63
+ finalOutput: T | undefined;
52
64
  outputText: string;
53
65
  newItems: Event[];
54
66
  interruptions: Interruption[];
55
67
  stopReason: StopReason | undefined;
56
68
  conversationId: string | undefined;
57
69
  cancelled: boolean;
70
+ outputCitations: OutputCitation[];
71
+ outputNote: string | undefined;
72
+ outputSkipped: string | undefined;
73
+ outputMode: string | undefined;
58
74
  }
59
75
 
60
76
  function stateOf(conversationId: string | undefined, interruptions: Interruption[]): RunState {
@@ -62,23 +78,42 @@ function stateOf(conversationId: string | undefined, interruptions: Interruption
62
78
  return new RunState(conversationId, interruptions.slice(), {});
63
79
  }
64
80
 
65
- export class RunResult {
66
- readonly finalOutput: string | undefined;
81
+ export class RunResult<T = string> {
82
+ /** The reply text, or the parsed structured output when the agent has an `outputType`. */
83
+ readonly finalOutput: T | undefined;
67
84
  readonly outputText: string;
68
85
  readonly newItems: Event[];
69
86
  readonly interruptions: Interruption[];
70
- /** Set when an agent.json limit ended the turn; `finalOutput` still holds the wrap-up answer. */
87
+ /** Set when one of the agent's own `limits` ended the turn (the server sent `data-turn-limit`); `finalOutput`
88
+ * still holds the wrap-up answer. A default server cap leaves it undefined. */
71
89
  readonly stopReason: StopReason | undefined;
72
90
  readonly conversationId: string | undefined;
91
+ /** The sources the structured output cited: the server's citation-manifest entries, first citation first. */
92
+ readonly outputCitations: OutputCitation[];
93
+ /** `oversize_answer_invalid` / `oversize_answer_dropped` when the turn's `final_answer` was refused for size and
94
+ * was not the answer, so the output came from the model's later text. */
95
+ readonly outputNote: string | undefined;
96
+ /** Why an agent with an `outputType` has no structured output (`finalOutput` is undefined): `limit` (a turn cap
97
+ * ended the turn; `stopReason` names it only when the agent's own `limits` set it), `budget` (the seat budget ran
98
+ * out before the answer was formatted), `paused` (the turn stopped on a question) or `suppressed` (a scheduled
99
+ * turn ended silently). Passed through as sent; undefined when there is output. */
100
+ readonly outputSkipped: string | undefined;
101
+ /** How the server produced the structured output (`tool_in_loop`, `tool_oversize`, `forced_tool`, `native`,
102
+ * `prompted`), passed through as sent; undefined when there is none. */
103
+ readonly outputMode: string | undefined;
73
104
 
74
105
  /** @internal */
75
- constructor(outcome: Outcome) {
106
+ constructor(outcome: Outcome<T>) {
76
107
  this.finalOutput = outcome.finalOutput;
77
108
  this.outputText = outcome.outputText;
78
109
  this.newItems = outcome.newItems;
79
110
  this.interruptions = outcome.interruptions;
80
111
  this.stopReason = outcome.stopReason;
81
112
  this.conversationId = outcome.conversationId;
113
+ this.outputCitations = outcome.outputCitations;
114
+ this.outputNote = outcome.outputNote;
115
+ this.outputSkipped = outcome.outputSkipped;
116
+ this.outputMode = outcome.outputMode;
82
117
  }
83
118
 
84
119
  /** A RunState to answer the interruptions and continue; throws UserError when the run has no conversation. */
@@ -160,10 +195,17 @@ class Loop {
160
195
  conversationId: string | null = null;
161
196
  readonly items: Event[] = [];
162
197
  stopReason: StopReason | undefined = undefined;
198
+ /** The turn's structured output (`data-output` / `data-output-error`), when the agent has an `outputType`. */
199
+ output: OutputEvent | undefined = undefined;
163
200
  // Text of the current segment, per text block. Kept per block so a resumed stream, which replays from the start
164
201
  // of the block it dropped in, doesn't repeat text.
165
202
  private blocks: [string | null, string[]][] = [];
166
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;
167
209
 
168
210
  constructor(
169
211
  private readonly transport: Transport,
@@ -171,6 +213,8 @@ class Loop {
171
213
  private readonly emit: Emit,
172
214
  private readonly signal: AbortSignal,
173
215
  private readonly onConversation: (conversationId: string) => void,
216
+ private readonly functions: ReadonlyMap<string, FunctionTool> = new Map(),
217
+ private readonly raiseErrors = false,
174
218
  ) {}
175
219
 
176
220
  get text(): string {
@@ -245,14 +289,17 @@ class Loop {
245
289
  return this.open(() => this.transport.startTurn(agentId, conversationId, input, this.signal));
246
290
  }
247
291
 
248
- /** Read one turn segment to turn_finished, resuming dropped streams; return an unanswered question. */
249
- private async consume(stream: TurnStream): Promise<ClarifyEvent | null> {
250
- let clarify: ClarifyEvent | null = null;
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;
251
295
  let reconnects = 0;
252
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;
253
299
  for (;;) {
254
300
  let finished = false;
255
301
  const current = stream;
302
+ this.replaying = current.replay === true;
256
303
  const onAbort = () => current.close();
257
304
  this.signal.addEventListener("abort", onAbort, { once: true });
258
305
  try {
@@ -265,7 +312,19 @@ class Loop {
265
312
  finished = true;
266
313
  break;
267
314
  }
268
- if (this.handle(event)) clarify = event as ClarifyEvent;
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;
269
328
  }
270
329
  } catch (err) {
271
330
  if (err instanceof Cancelled || this.signal.aborted) throw new Cancelled();
@@ -276,7 +335,7 @@ class Loop {
276
335
  current.close();
277
336
  }
278
337
  if (this.signal.aborted) throw new Cancelled();
279
- if (finished) return clarify;
338
+ if (finished) return pause;
280
339
  const responseId = current.responseId;
281
340
  const lastEventId = current.lastEventId;
282
341
  if (reconnects >= MAX_RECONNECTS || this.conversationId === null) {
@@ -292,7 +351,7 @@ class Loop {
292
351
  }
293
352
  }
294
353
 
295
- /** 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. */
296
355
  private handle(event: Event): boolean {
297
356
  switch (event.kind) {
298
357
  case "turn_failed":
@@ -303,27 +362,33 @@ class Loop {
303
362
  case "turn_limit":
304
363
  this.stopReason = STOP_REASONS[event.capKind];
305
364
  return false;
365
+ case "output":
366
+ case "output_error":
367
+ this.output = event;
368
+ return false;
306
369
  case "text_start":
307
370
  case "text_end":
308
371
  this.onText(event);
309
372
  return false;
310
373
  case "text_delta":
311
374
  this.onText(event);
312
- this.emit({ type: "raw_model_stream_event", data: { type: "output_text_delta", delta: event.delta } });
375
+ if (!this.replaying) {
376
+ this.emit({ type: "raw_model_stream_event", data: { type: "output_text_delta", delta: event.delta } });
377
+ }
313
378
  return false;
314
379
  case "reasoning_delta":
315
- this.emit({ type: "raw_model_stream_event", data: { type: "reasoning_delta", delta: event.delta } });
380
+ if (!this.replaying) {
381
+ this.emit({ type: "raw_model_stream_event", data: { type: "reasoning_delta", delta: event.delta } });
382
+ }
316
383
  return false;
317
384
  default:
318
385
  break;
319
386
  }
320
387
  this.items.push(event);
321
- if (event.kind === "tool_called" || event.kind === "tool_output") {
388
+ if ((event.kind === "tool_called" || event.kind === "tool_output") && !this.replaying) {
322
389
  this.emit({ type: "run_item_stream_event", name: event.kind, item: event });
323
- } else if (event.kind === "function_calls_requested") {
324
- throw new NotSupportedError("function tools are not supported yet");
325
390
  }
326
- return event.kind === "clarify_requested";
391
+ return event.kind === "clarify_requested" || event.kind === "function_calls_requested";
327
392
  }
328
393
 
329
394
  private async ask(questions: ClarifyQuestion[]): Promise<Record<string, unknown>> {
@@ -336,13 +401,51 @@ class Loop {
336
401
  return answers as Record<string, unknown>;
337
402
  }
338
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
+
339
417
  private answer(requestId: string, answers: Record<string, unknown>): Promise<TurnStream> {
418
+ this.markAnswered(requestId);
340
419
  const conversationId = this.conversationId;
341
420
  if (conversationId === null) throw new RunError("stream_lost", "no conversation to answer the question in");
342
421
  return this.open(() => this.transport.answerClarify(conversationId, requestId, answers, this.signal));
343
422
  }
344
423
 
345
- /** Run to completion, answering questions with onClarify; return an Interruption if there is no handler. */
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. */
346
449
  async drive(stream: TurnStream): Promise<Interruption | null> {
347
450
  for (;;) {
348
451
  const clarify = await this.consume(stream);
@@ -350,13 +453,16 @@ class Loop {
350
453
  this.emit({ type: "run_item_stream_event", name: "message_output_created", item: this.text });
351
454
  return null;
352
455
  }
456
+ if (clarify.kind === "function_calls_requested") {
457
+ stream = await this.answerFunctions(clarify);
458
+ continue;
459
+ }
353
460
  if (this.onClarify === undefined) {
354
461
  return { kind: "clarify", requestId: clarify.requestId, payload: { questions: clarify.questions.slice() } };
355
462
  }
356
463
  if (this.signal.aborted) throw new Cancelled();
357
464
  const answers = await this.ask(clarify.questions);
358
465
  if (this.signal.aborted) throw new Cancelled();
359
- this.resetText();
360
466
  stream = await this.answer(clarify.requestId, answers);
361
467
  }
362
468
  }
@@ -365,9 +471,29 @@ class Loop {
365
471
  async answerPending(state: RunState): Promise<Interruption[]> {
366
472
  this.conversationId = state.conversationId;
367
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
+ }
368
483
  for (let n = 0; n < state.pending.length; n++) {
369
484
  const item = state.pending[n];
370
- const interruption = await this.drive(await this.answer(item.requestId, state.answers[item.requestId]));
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);
371
497
  if (interruption !== null) return [interruption, ...state.pending.slice(n + 1)];
372
498
  }
373
499
  return [];
@@ -388,8 +514,10 @@ function checkMaxTurns(opts: { maxTurns?: unknown }): void {
388
514
  function checkInput(input: unknown): void {
389
515
  if (input instanceof RunState) {
390
516
  for (const item of input.pending) {
517
+ if (item.kind === "function_call") continue; // run here when the state is resumed; nothing to answer
391
518
  if (item.kind !== "clarify") {
392
- throw new NotSupportedError(`resuming "${item.kind}" interruptions is not supported yet`);
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`);
393
521
  }
394
522
  if (!Object.prototype.hasOwnProperty.call(input.answers, item.requestId)) {
395
523
  throw new UserError(`pending clarify "${item.requestId}" has no answer: call state.answer(item, {...})`);
@@ -401,14 +529,14 @@ function checkInput(input: unknown): void {
401
529
  }
402
530
 
403
531
  interface Prepared {
404
- agent: Agent;
532
+ agent: Agent<OutputType | undefined>;
405
533
  input: string | RunState;
406
534
  opts: RunOptions;
407
535
  transport: Transport;
408
536
  owner: object;
409
537
  }
410
538
 
411
- function prepare(agent: Agent, input: string | RunState, opts: RunOptions): Prepared {
539
+ function prepare(agent: Agent<OutputType | undefined>, input: string | RunState, opts: RunOptions): Prepared {
412
540
  checkMaxTurns(opts);
413
541
  checkInput(input);
414
542
  const transport = resolveTransport(opts.client, opts.transport);
@@ -429,13 +557,25 @@ function link(signal: AbortSignal | undefined, controller: AbortController): ()
429
557
  return () => signal.removeEventListener("abort", onAbort);
430
558
  }
431
559
 
432
- async function execute(p: Prepared, controller: AbortController, emit: Emit): Promise<Outcome> {
560
+ /** `finalOutput` for an agent with an `outputType`: the parsed value, or undefined when the turn produced none
561
+ * (`outputSkipped` says why). A mismatch throws `ModelBehaviorError`. */
562
+ function structuredOutput(outputType: OutputType, event: OutputEvent | undefined): unknown {
563
+ if (event?.kind === "output_error") throw new ModelBehaviorError(event.rawText, event.errors, event.note);
564
+ if (event?.kind === "output" && event.output !== null && event.output !== undefined) {
565
+ return parseOutput(outputType, event.output, event.note);
566
+ }
567
+ return undefined;
568
+ }
569
+
570
+ async function execute(p: Prepared, controller: AbortController, emit: Emit): Promise<Outcome<unknown>> {
433
571
  const signal = controller.signal;
434
572
  const unlink = link(p.opts.signal, controller);
435
573
  const stopper = new Stopper(p.transport, signal);
436
574
  const onAbort = () => stopper.send();
437
575
  signal.addEventListener("abort", onAbort, { once: true });
438
- const loop = new Loop(p.transport, p.opts.onClarify, emit, signal, (c) => stopper.onConversation(c));
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);
439
579
  let interruptions: Interruption[] = [];
440
580
  let cancelled = false;
441
581
  const fallbackConversation = p.input instanceof RunState ? p.input.conversationId : p.opts.conversationId;
@@ -460,24 +600,40 @@ async function execute(p: Prepared, controller: AbortController, emit: Emit): Pr
460
600
  }
461
601
  cancelled = cancelled || signal.aborted;
462
602
  const text = loop.text;
603
+ const outputType = p.agent.outputType;
604
+ let finalOutput: unknown;
605
+ if (interruptions.length || cancelled) finalOutput = undefined;
606
+ else if (outputType !== undefined) {
607
+ try {
608
+ finalOutput = structuredOutput(outputType, loop.output);
609
+ } catch (err) {
610
+ if (err instanceof ModelBehaviorError) err.conversationId = loop.conversationId ?? fallbackConversation;
611
+ throw err;
612
+ }
613
+ }
614
+ else finalOutput = text;
463
615
  return {
464
- finalOutput: interruptions.length || cancelled ? undefined : text,
616
+ finalOutput,
465
617
  outputText: text,
466
618
  newItems: loop.items,
467
619
  interruptions,
468
620
  stopReason: loop.stopReason,
469
621
  conversationId: loop.conversationId ?? fallbackConversation,
470
622
  cancelled,
623
+ outputCitations: loop.output?.kind === "output" ? (loop.output.citations ?? []).slice() : [],
624
+ outputNote: loop.output?.note,
625
+ outputSkipped: loop.output?.kind === "output" ? loop.output.skipped : undefined,
626
+ outputMode: loop.output?.kind === "output" ? loop.output.mode : undefined,
471
627
  };
472
628
  }
473
629
 
474
630
  // -- streaming ---------------------------------------------------------------------------------------------------
475
631
 
476
632
  /** Returned by `run(..., { stream: true })`. Iterate it once (or use `toTextStream()`); leaving early cancels. */
477
- export class StreamedRunResult implements AsyncIterable<RunStreamEvent> {
633
+ export class StreamedRunResult<T = string> implements AsyncIterable<RunStreamEvent> {
478
634
  /** Settles when the run ends; rejects with the run's error. */
479
635
  readonly completed: Promise<void>;
480
- finalOutput: string | undefined = undefined;
636
+ finalOutput: T | undefined = undefined;
481
637
  outputText = "";
482
638
  newItems: Event[] = [];
483
639
  interruptions: Interruption[] = [];
@@ -485,6 +641,11 @@ export class StreamedRunResult implements AsyncIterable<RunStreamEvent> {
485
641
  stopReason: StopReason | undefined = undefined;
486
642
  conversationId: string | undefined = undefined;
487
643
  cancelled = false;
644
+ /** As on `RunResult`; read after `completed` settles. */
645
+ outputCitations: OutputCitation[] = [];
646
+ outputNote: string | undefined = undefined;
647
+ outputSkipped: string | undefined = undefined;
648
+ outputMode: string | undefined = undefined;
488
649
 
489
650
  private readonly queue: RunStreamEvent[] = [];
490
651
  private waiters: (() => void)[] = [];
@@ -499,13 +660,17 @@ export class StreamedRunResult implements AsyncIterable<RunStreamEvent> {
499
660
  this.conversationId = prepared.input instanceof RunState ? prepared.input.conversationId : prepared.opts.conversationId;
500
661
  this.completed = execute(prepared, this.controller, (e) => this.push(e)).then(
501
662
  (outcome) => {
502
- this.finalOutput = outcome.finalOutput;
663
+ this.finalOutput = outcome.finalOutput as T | undefined;
503
664
  this.outputText = outcome.outputText;
504
665
  this.newItems = outcome.newItems;
505
666
  this.interruptions = outcome.interruptions;
506
667
  this.stopReason = outcome.stopReason;
507
668
  this.conversationId = outcome.conversationId;
508
669
  this.cancelled = outcome.cancelled;
670
+ this.outputCitations = outcome.outputCitations;
671
+ this.outputNote = outcome.outputNote;
672
+ this.outputSkipped = outcome.outputSkipped;
673
+ this.outputMode = outcome.outputMode;
509
674
  this.end();
510
675
  },
511
676
  (error) => {
@@ -610,14 +775,18 @@ export class StreamedRunResult implements AsyncIterable<RunStreamEvent> {
610
775
  * Run `agent` on `input` (a message, or a RunState holding answers), deploying it first if this owner has not
611
776
  * deployed this exact definition. With `stream: true`, resolves at once with a StreamedRunResult.
612
777
  */
613
- export function run(agent: Agent, input: string | RunState, opts: RunOptions & { stream: true }): Promise<StreamedRunResult>;
614
- export function run(agent: Agent, input: string | RunState, opts?: RunOptions & { stream?: false }): Promise<RunResult>;
778
+ export function run<O extends OutputType | undefined = undefined>(
779
+ agent: Agent<O>, input: string | RunState, opts: RunOptions & { stream: true },
780
+ ): Promise<StreamedRunResult<ResolvedOutput<O>>>;
781
+ export function run<O extends OutputType | undefined = undefined>(
782
+ agent: Agent<O>, input: string | RunState, opts?: RunOptions & { stream?: false },
783
+ ): Promise<RunResult<ResolvedOutput<O>>>;
615
784
  export async function run(
616
- agent: Agent,
785
+ agent: Agent<OutputType | undefined>,
617
786
  input: string | RunState,
618
787
  opts: RunOptions & { stream?: boolean } = {},
619
- ): Promise<RunResult | StreamedRunResult> {
788
+ ): Promise<RunResult<unknown> | StreamedRunResult<unknown>> {
620
789
  const prepared = prepare(agent, input, opts);
621
- if (opts.stream) return new StreamedRunResult(prepared);
622
- return new RunResult(await execute(prepared, new AbortController(), () => undefined));
790
+ if (opts.stream) return new StreamedRunResult<unknown>(prepared);
791
+ return new RunResult<unknown>(await execute(prepared, new AbortController(), () => undefined));
623
792
  }
@@ -1,16 +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
- import { UserError } from "./errors.js";
3
+ import type { OutputType } from "./output.js";
4
+ import type { Configuration } from "../runtime.js";
5
+ import { NotSupportedError, UserError } from "./errors.js";
4
6
  import type { ClarifyQuestion } from "./events.js";
7
+ import type { Transport } from "./transport.js";
5
8
 
6
9
  const STATE_VERSION = 1;
7
10
 
8
- export interface Interruption {
9
- kind: "clarify";
10
- requestId: string;
11
- payload: { questions: ClarifyQuestion[] };
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>;
12
16
  }
13
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
+
14
23
  function isObject(v: unknown): v is Record<string, unknown> {
15
24
  return typeof v === "object" && v !== null && !Array.isArray(v);
16
25
  }
@@ -36,11 +45,42 @@ export class RunState {
36
45
  this.transportKind = transportKind;
37
46
  }
38
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
+
39
75
  /** Record the answers to a pending interruption; `run(agent, state)` sends them. */
40
76
  answer(item: Interruption, answers: Record<string, unknown>): void {
41
77
  if (!this.pending.some((p) => p.requestId === item.requestId)) {
42
78
  throw new UserError(`no pending item with request id "${item.requestId}"`);
43
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
+ }
44
84
  this.answers[item.requestId] = { ...answers };
45
85
  }
46
86
 
@@ -56,7 +96,7 @@ export class RunState {
56
96
  }
57
97
 
58
98
  /** Read a state written by `toString()` (or by Python's `to_json()`). */
59
- static async fromString(agent: Agent, s: string): Promise<RunState> {
99
+ static async fromString(agent: Agent<OutputType | undefined>, s: string): Promise<RunState> {
60
100
  void agent; // accepted for @openai/agents parity; the state holds no agent definition
61
101
  let data: unknown;
62
102
  try {