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,7 +1,9 @@
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 type { Agent } from "./agent.js";
4
- import type { ClarifyQuestion, Event } from "./events.js";
5
+ import type { ClarifyQuestion, Event, OutputCitation } from "./events.js";
6
+ import type { OutputType, ResolvedOutput } from "./output.js";
5
7
  import { RunState } from "./runState.js";
6
8
  import type { Interruption } from "./runState.js";
7
9
  import type { Transport } from "./transport.js";
@@ -15,6 +17,9 @@ export interface RunOptions {
15
17
  signal?: AbortSignal;
16
18
  /** Answers clarify questions; without it a question ends the run with an interruption. */
17
19
  onClarify?: ClarifyHandler;
20
+ /** Throw an error thrown by a function tool's `execute` instead of sending it to the model (for tests). The turn
21
+ * then stays paused on the server; `RunState.fromSession` continues it. */
22
+ raiseErrors?: boolean;
18
23
  /** Not supported: the server caps turns per agent; set `new Agent({ limits: { maxTurns } })`. */
19
24
  maxTurns?: never;
20
25
  }
@@ -31,40 +36,59 @@ export type RunStreamEvent = {
31
36
  };
32
37
  /** Why the run ended early: the `limits` field whose cap the server hit. */
33
38
  export type StopReason = "max_turns" | "max_tool_calls" | "max_tokens";
34
- interface Outcome {
35
- finalOutput: string | undefined;
39
+ interface Outcome<T = string> {
40
+ finalOutput: T | undefined;
36
41
  outputText: string;
37
42
  newItems: Event[];
38
43
  interruptions: Interruption[];
39
44
  stopReason: StopReason | undefined;
40
45
  conversationId: string | undefined;
41
46
  cancelled: boolean;
47
+ outputCitations: OutputCitation[];
48
+ outputNote: string | undefined;
49
+ outputSkipped: string | undefined;
50
+ outputMode: string | undefined;
42
51
  }
43
- export declare class RunResult {
44
- readonly finalOutput: string | undefined;
52
+ export declare class RunResult<T = string> {
53
+ /** The reply text, or the parsed structured output when the agent has an `outputType`. */
54
+ readonly finalOutput: T | undefined;
45
55
  readonly outputText: string;
46
56
  readonly newItems: Event[];
47
57
  readonly interruptions: Interruption[];
48
- /** Set when an agent.json limit ended the turn; `finalOutput` still holds the wrap-up answer. */
58
+ /** Set when one of the agent's own `limits` ended the turn (the server sent `data-turn-limit`); `finalOutput`
59
+ * still holds the wrap-up answer. A default server cap leaves it undefined. */
49
60
  readonly stopReason: StopReason | undefined;
50
61
  readonly conversationId: string | undefined;
62
+ /** The sources the structured output cited: the server's citation-manifest entries, first citation first. */
63
+ readonly outputCitations: OutputCitation[];
64
+ /** `oversize_answer_invalid` / `oversize_answer_dropped` when the turn's `final_answer` was refused for size and
65
+ * was not the answer, so the output came from the model's later text. */
66
+ readonly outputNote: string | undefined;
67
+ /** Why an agent with an `outputType` has no structured output (`finalOutput` is undefined): `limit` (a turn cap
68
+ * ended the turn; `stopReason` names it only when the agent's own `limits` set it), `budget` (the seat budget ran
69
+ * out before the answer was formatted), `paused` (the turn stopped on a question) or `suppressed` (a scheduled
70
+ * turn ended silently). Passed through as sent; undefined when there is output. */
71
+ readonly outputSkipped: string | undefined;
72
+ /** How the server produced the structured output (`tool_in_loop`, `tool_oversize`, `forced_tool`, `native`,
73
+ * `prompted`), passed through as sent; undefined when there is none. */
74
+ readonly outputMode: string | undefined;
51
75
  /** @internal */
52
- constructor(outcome: Outcome);
76
+ constructor(outcome: Outcome<T>);
53
77
  /** A RunState to answer the interruptions and continue; throws UserError when the run has no conversation. */
54
78
  get state(): RunState;
55
79
  }
56
80
  interface Prepared {
57
- agent: Agent;
81
+ agent: Agent<OutputType | undefined>;
58
82
  input: string | RunState;
59
83
  opts: RunOptions;
60
84
  transport: Transport;
61
85
  owner: object;
62
86
  }
63
87
  /** Returned by `run(..., { stream: true })`. Iterate it once (or use `toTextStream()`); leaving early cancels. */
64
- export declare class StreamedRunResult implements AsyncIterable<RunStreamEvent> {
88
+ export declare class StreamedRunResult<T = string> implements AsyncIterable<RunStreamEvent> {
65
89
  /** Settles when the run ends; rejects with the run's error. */
66
90
  readonly completed: Promise<void>;
67
- finalOutput: string | undefined;
91
+ finalOutput: T | undefined;
68
92
  outputText: string;
69
93
  newItems: Event[];
70
94
  interruptions: Interruption[];
@@ -72,6 +96,11 @@ export declare class StreamedRunResult implements AsyncIterable<RunStreamEvent>
72
96
  stopReason: StopReason | undefined;
73
97
  conversationId: string | undefined;
74
98
  cancelled: boolean;
99
+ /** As on `RunResult`; read after `completed` settles. */
100
+ outputCitations: OutputCitation[];
101
+ outputNote: string | undefined;
102
+ outputSkipped: string | undefined;
103
+ outputMode: string | undefined;
75
104
  private readonly queue;
76
105
  private waiters;
77
106
  private done;
@@ -98,10 +127,10 @@ export declare class StreamedRunResult implements AsyncIterable<RunStreamEvent>
98
127
  * Run `agent` on `input` (a message, or a RunState holding answers), deploying it first if this owner has not
99
128
  * deployed this exact definition. With `stream: true`, resolves at once with a StreamedRunResult.
100
129
  */
101
- export declare function run(agent: Agent, input: string | RunState, opts: RunOptions & {
130
+ export declare function run<O extends OutputType | undefined = undefined>(agent: Agent<O>, input: string | RunState, opts: RunOptions & {
102
131
  stream: true;
103
- }): Promise<StreamedRunResult>;
104
- export declare function run(agent: Agent, input: string | RunState, opts?: RunOptions & {
132
+ }): Promise<StreamedRunResult<ResolvedOutput<O>>>;
133
+ export declare function run<O extends OutputType | undefined = undefined>(agent: Agent<O>, input: string | RunState, opts?: RunOptions & {
105
134
  stream?: false;
106
- }): Promise<RunResult>;
135
+ }): Promise<RunResult<ResolvedOutput<O>>>;
107
136
  export {};
@@ -5,6 +5,8 @@ exports.run = run;
5
5
  const runtime_js_1 = require("../runtime.js");
6
6
  const deploy_js_1 = require("./deploy.js");
7
7
  const errors_js_1 = require("./errors.js");
8
+ const functionTool_js_1 = require("./functionTool.js");
9
+ const output_js_1 = require("./output.js");
8
10
  const runState_js_1 = require("./runState.js");
9
11
  const MAX_RECONNECTS = 3;
10
12
  /** The abort reason ResponseStream (src/streaming.ts) uses when a stream goes quiet. */
@@ -29,6 +31,10 @@ class RunResult {
29
31
  this.interruptions = outcome.interruptions;
30
32
  this.stopReason = outcome.stopReason;
31
33
  this.conversationId = outcome.conversationId;
34
+ this.outputCitations = outcome.outputCitations;
35
+ this.outputNote = outcome.outputNote;
36
+ this.outputSkipped = outcome.outputSkipped;
37
+ this.outputMode = outcome.outputMode;
32
38
  }
33
39
  /** A RunState to answer the interruptions and continue; throws UserError when the run has no conversation. */
34
40
  get state() {
@@ -101,19 +107,28 @@ class Stopper {
101
107
  }
102
108
  }
103
109
  class Loop {
104
- constructor(transport, onClarify, emit, signal, onConversation) {
110
+ constructor(transport, onClarify, emit, signal, onConversation, functions = new Map(), raiseErrors = false) {
105
111
  this.transport = transport;
106
112
  this.onClarify = onClarify;
107
113
  this.emit = emit;
108
114
  this.signal = signal;
109
115
  this.onConversation = onConversation;
116
+ this.functions = functions;
117
+ this.raiseErrors = raiseErrors;
110
118
  this.conversationId = null;
111
119
  this.items = [];
112
120
  this.stopReason = undefined;
121
+ /** The turn's structured output (`data-output` / `data-output-error`), when the agent has an `outputType`. */
122
+ this.output = undefined;
113
123
  // Text of the current segment, per text block. Kept per block so a resumed stream, which replays from the start
114
124
  // of the block it dropped in, doesn't repeat text.
115
125
  this.blocks = [];
116
126
  this.openBlock = null;
127
+ /** Requests this run has answered. A stream read without a cursor (a duplicate post's reconnect, a resume before
128
+ * any event id) replays the turn from its start, these requests too: one is a marker, not a pause. */
129
+ this.answered = new Set();
130
+ /** A full-turn replay repeats what this run already showed: emit nothing until it passes an answered request. */
131
+ this.replaying = false;
117
132
  }
118
133
  get text() {
119
134
  return this.blocks.map(([, parts]) => parts.join("")).join("");
@@ -191,14 +206,17 @@ class Loop {
191
206
  start(agentId, conversationId, input) {
192
207
  return this.open(() => this.transport.startTurn(agentId, conversationId, input, this.signal));
193
208
  }
194
- /** Read one turn segment to turn_finished, resuming dropped streams; return an unanswered question. */
209
+ /** Read one turn segment to turn_finished, resuming dropped streams; return what it paused on, if anything. */
195
210
  async consume(stream) {
196
- let clarify = null;
211
+ let pause = null;
197
212
  let reconnects = 0;
198
213
  const itemsAtStart = this.items.length;
214
+ // The last pause read is one this run answered (kept across a resume, which goes on from where it was).
215
+ let afterAnswered = false;
199
216
  for (;;) {
200
217
  let finished = false;
201
218
  const current = stream;
219
+ this.replaying = current.replay === true;
202
220
  const onAbort = () => current.close();
203
221
  this.signal.addEventListener("abort", onAbort, { once: true });
204
222
  try {
@@ -212,8 +230,22 @@ class Loop {
212
230
  finished = true;
213
231
  break;
214
232
  }
233
+ if ((event.kind === "clarify_requested" || event.kind === "function_calls_requested")
234
+ && this.answered.has(event.requestId)) {
235
+ // Replayed up to a pause this run already answered: what came before it is not new.
236
+ this.items.length = itemsAtStart;
237
+ this.pastAnswered();
238
+ this.replaying = false;
239
+ afterAnswered = true;
240
+ continue;
241
+ }
242
+ if (event.kind === "clarify_requested" || event.kind === "function_calls_requested")
243
+ afterAnswered = false;
244
+ // The skip of a pause this run answered (a replay): not the turn's.
245
+ if (afterAnswered && event.kind === "output" && event.skipped === "paused")
246
+ continue;
215
247
  if (this.handle(event))
216
- clarify = event;
248
+ pause = event;
217
249
  }
218
250
  }
219
251
  catch (err) {
@@ -230,7 +262,7 @@ class Loop {
230
262
  if (this.signal.aborted)
231
263
  throw new Cancelled();
232
264
  if (finished)
233
- return clarify;
265
+ return pause;
234
266
  const responseId = current.responseId;
235
267
  const lastEventId = current.lastEventId;
236
268
  if (reconnects >= MAX_RECONNECTS || this.conversationId === null) {
@@ -245,7 +277,7 @@ class Loop {
245
277
  stream = await this.open(() => this.transport.resume(conversationId, responseId, lastEventId, this.signal));
246
278
  }
247
279
  }
248
- /** Handle one event other than turn_finished; returns true for a clarify request. */
280
+ /** Handle one event other than turn_finished; returns true for a clarify or function-call request. */
249
281
  handle(event) {
250
282
  switch (event.kind) {
251
283
  case "turn_failed":
@@ -257,28 +289,33 @@ class Loop {
257
289
  case "turn_limit":
258
290
  this.stopReason = STOP_REASONS[event.capKind];
259
291
  return false;
292
+ case "output":
293
+ case "output_error":
294
+ this.output = event;
295
+ return false;
260
296
  case "text_start":
261
297
  case "text_end":
262
298
  this.onText(event);
263
299
  return false;
264
300
  case "text_delta":
265
301
  this.onText(event);
266
- this.emit({ type: "raw_model_stream_event", data: { type: "output_text_delta", delta: event.delta } });
302
+ if (!this.replaying) {
303
+ this.emit({ type: "raw_model_stream_event", data: { type: "output_text_delta", delta: event.delta } });
304
+ }
267
305
  return false;
268
306
  case "reasoning_delta":
269
- this.emit({ type: "raw_model_stream_event", data: { type: "reasoning_delta", delta: event.delta } });
307
+ if (!this.replaying) {
308
+ this.emit({ type: "raw_model_stream_event", data: { type: "reasoning_delta", delta: event.delta } });
309
+ }
270
310
  return false;
271
311
  default:
272
312
  break;
273
313
  }
274
314
  this.items.push(event);
275
- if (event.kind === "tool_called" || event.kind === "tool_output") {
315
+ if ((event.kind === "tool_called" || event.kind === "tool_output") && !this.replaying) {
276
316
  this.emit({ type: "run_item_stream_event", name: event.kind, item: event });
277
317
  }
278
- else if (event.kind === "function_calls_requested") {
279
- throw new errors_js_1.NotSupportedError("function tools are not supported yet");
280
- }
281
- return event.kind === "clarify_requested";
318
+ return event.kind === "clarify_requested" || event.kind === "function_calls_requested";
282
319
  }
283
320
  async ask(questions) {
284
321
  const handler = this.onClarify;
@@ -289,13 +326,51 @@ class Loop {
289
326
  }
290
327
  return answers;
291
328
  }
329
+ /** Past a pause this run answers: its text and its `outputSkipped: "paused"` belong to the paused segment, and the
330
+ * continuation (or its replay) says what the turn's own are. */
331
+ pastAnswered() {
332
+ this.resetText();
333
+ this.output = undefined;
334
+ }
335
+ /** Mark `requestId` answered by this run, before its answer is sent. */
336
+ markAnswered(requestId) {
337
+ this.answered.add(requestId);
338
+ this.pastAnswered();
339
+ }
292
340
  answer(requestId, answers) {
341
+ this.markAnswered(requestId);
293
342
  const conversationId = this.conversationId;
294
343
  if (conversationId === null)
295
344
  throw new errors_js_1.RunError("stream_lost", "no conversation to answer the question in");
296
345
  return this.open(() => this.transport.answerClarify(conversationId, requestId, answers, this.signal));
297
346
  }
298
- /** Run to completion, answering questions with onClarify; return an Interruption if there is no handler. */
347
+ /** Run the request's calls here and post their results; the returned stream continues the turn. */
348
+ async answerFunctions(request) {
349
+ const conversationId = this.conversationId;
350
+ if (conversationId === null)
351
+ throw new errors_js_1.RunError("stream_lost", "no conversation to answer the function calls in");
352
+ const transport = this.transport;
353
+ if (transport.postFunctionResults === undefined) {
354
+ throw new errors_js_1.NotSupportedError("this transport cannot post function results");
355
+ }
356
+ let results;
357
+ try {
358
+ // Raced against the signal: an execute that never settles must not keep a cancelled run alive.
359
+ results = await raceAbort((0, functionTool_js_1.runCalls)(this.functions, request.calls, { signal: this.signal, raiseErrors: this.raiseErrors }), this.signal);
360
+ }
361
+ catch (err) {
362
+ if (err instanceof functionTool_js_1.CallsCancelled)
363
+ throw new Cancelled();
364
+ throw err;
365
+ }
366
+ if (this.signal.aborted)
367
+ throw new Cancelled();
368
+ this.markAnswered(request.requestId);
369
+ const post = transport.postFunctionResults.bind(transport);
370
+ return this.open(() => post(conversationId, request.requestId, results, this.signal));
371
+ }
372
+ /** Run to completion, running function calls and answering questions with onClarify; return an Interruption if a
373
+ * question has no handler. */
299
374
  async drive(stream) {
300
375
  for (;;) {
301
376
  const clarify = await this.consume(stream);
@@ -303,6 +378,10 @@ class Loop {
303
378
  this.emit({ type: "run_item_stream_event", name: "message_output_created", item: this.text });
304
379
  return null;
305
380
  }
381
+ if (clarify.kind === "function_calls_requested") {
382
+ stream = await this.answerFunctions(clarify);
383
+ continue;
384
+ }
306
385
  if (this.onClarify === undefined) {
307
386
  return { kind: "clarify", requestId: clarify.requestId, payload: { questions: clarify.questions.slice() } };
308
387
  }
@@ -311,7 +390,6 @@ class Loop {
311
390
  const answers = await this.ask(clarify.questions);
312
391
  if (this.signal.aborted)
313
392
  throw new Cancelled();
314
- this.resetText();
315
393
  stream = await this.answer(clarify.requestId, answers);
316
394
  }
317
395
  }
@@ -319,9 +397,31 @@ class Loop {
319
397
  async answerPending(state) {
320
398
  this.conversationId = state.conversationId;
321
399
  this.onConversation(state.conversationId);
400
+ // A saved state can be stale: another process may have answered its calls since. Run only what the server still
401
+ // waits on, so no function's side effects happen twice.
402
+ const transport = this.transport;
403
+ let waiting = null;
404
+ if (state.pending.some((item) => item.kind === "function_call")
405
+ && transport.pending !== undefined && transport.follow !== undefined) {
406
+ const live = await raceAbort(transport.pending(state.conversationId), this.signal);
407
+ waiting = new Set(live.map((request) => request.requestId));
408
+ }
322
409
  for (let n = 0; n < state.pending.length; n++) {
323
410
  const item = state.pending[n];
324
- const interruption = await this.drive(await this.answer(item.requestId, state.answers[item.requestId]));
411
+ let stream;
412
+ if (item.kind === "function_call" && waiting !== null && !waiting.has(item.requestId)) {
413
+ this.markAnswered(item.requestId);
414
+ const follow = transport.follow.bind(transport);
415
+ stream = await this.open(() => follow(state.conversationId, this.signal));
416
+ }
417
+ else
418
+ stream = item.kind === "function_call"
419
+ ? await this.answerFunctions({
420
+ requestId: item.requestId,
421
+ calls: item.payload.calls.map((c) => ({ callId: c.call_id, name: c.name, arguments: { ...c.arguments } })),
422
+ })
423
+ : await this.answer(item.requestId, state.answers[item.requestId]);
424
+ const interruption = await this.drive(stream);
325
425
  if (interruption !== null)
326
426
  return [interruption, ...state.pending.slice(n + 1)];
327
427
  }
@@ -338,7 +438,10 @@ function checkMaxTurns(opts) {
338
438
  function checkInput(input) {
339
439
  if (input instanceof runState_js_1.RunState) {
340
440
  for (const item of input.pending) {
441
+ if (item.kind === "function_call")
442
+ continue; // run here when the state is resumed; nothing to answer
341
443
  if (item.kind !== "clarify") {
444
+ // fromString keeps kinds it doesn't know, so this is reachable at runtime.
342
445
  throw new errors_js_1.NotSupportedError(`resuming "${item.kind}" interruptions is not supported yet`);
343
446
  }
344
447
  if (!Object.prototype.hasOwnProperty.call(input.answers, item.requestId)) {
@@ -371,14 +474,25 @@ function link(signal, controller) {
371
474
  signal.addEventListener("abort", onAbort, { once: true });
372
475
  return () => signal.removeEventListener("abort", onAbort);
373
476
  }
477
+ /** `finalOutput` for an agent with an `outputType`: the parsed value, or undefined when the turn produced none
478
+ * (`outputSkipped` says why). A mismatch throws `ModelBehaviorError`. */
479
+ function structuredOutput(outputType, event) {
480
+ if ((event === null || event === void 0 ? void 0 : event.kind) === "output_error")
481
+ throw new errors_js_1.ModelBehaviorError(event.rawText, event.errors, event.note);
482
+ if ((event === null || event === void 0 ? void 0 : event.kind) === "output" && event.output !== null && event.output !== undefined) {
483
+ return (0, output_js_1.parseOutput)(outputType, event.output, event.note);
484
+ }
485
+ return undefined;
486
+ }
374
487
  async function execute(p, controller, emit) {
375
- var _a, _b;
488
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j;
376
489
  const signal = controller.signal;
377
490
  const unlink = link(p.opts.signal, controller);
378
491
  const stopper = new Stopper(p.transport, signal);
379
492
  const onAbort = () => stopper.send();
380
493
  signal.addEventListener("abort", onAbort, { once: true });
381
- const loop = new Loop(p.transport, p.opts.onClarify, emit, signal, (c) => stopper.onConversation(c));
494
+ const functions = new Map(p.agent.functionTools.map((t) => [t.name, t]));
495
+ 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);
382
496
  let interruptions = [];
383
497
  let cancelled = false;
384
498
  const fallbackConversation = p.input instanceof runState_js_1.RunState ? p.input.conversationId : p.opts.conversationId;
@@ -390,7 +504,7 @@ async function execute(p, controller, emit) {
390
504
  }
391
505
  else {
392
506
  const agentId = await raceAbort((0, deploy_js_1.agentIdFor)(p.agent, p.transport, p.owner), signal);
393
- const stream = await loop.start(agentId, (_a = p.opts.conversationId) !== null && _a !== void 0 ? _a : null, p.input);
507
+ const stream = await loop.start(agentId, (_b = p.opts.conversationId) !== null && _b !== void 0 ? _b : null, p.input);
394
508
  const interruption = await loop.drive(stream);
395
509
  interruptions = interruption ? [interruption] : [];
396
510
  }
@@ -408,14 +522,34 @@ async function execute(p, controller, emit) {
408
522
  }
409
523
  cancelled = cancelled || signal.aborted;
410
524
  const text = loop.text;
525
+ const outputType = p.agent.outputType;
526
+ let finalOutput;
527
+ if (interruptions.length || cancelled)
528
+ finalOutput = undefined;
529
+ else if (outputType !== undefined) {
530
+ try {
531
+ finalOutput = structuredOutput(outputType, loop.output);
532
+ }
533
+ catch (err) {
534
+ if (err instanceof errors_js_1.ModelBehaviorError)
535
+ err.conversationId = (_c = loop.conversationId) !== null && _c !== void 0 ? _c : fallbackConversation;
536
+ throw err;
537
+ }
538
+ }
539
+ else
540
+ finalOutput = text;
411
541
  return {
412
- finalOutput: interruptions.length || cancelled ? undefined : text,
542
+ finalOutput,
413
543
  outputText: text,
414
544
  newItems: loop.items,
415
545
  interruptions,
416
546
  stopReason: loop.stopReason,
417
- conversationId: (_b = loop.conversationId) !== null && _b !== void 0 ? _b : fallbackConversation,
547
+ conversationId: (_d = loop.conversationId) !== null && _d !== void 0 ? _d : fallbackConversation,
418
548
  cancelled,
549
+ outputCitations: ((_e = loop.output) === null || _e === void 0 ? void 0 : _e.kind) === "output" ? ((_f = loop.output.citations) !== null && _f !== void 0 ? _f : []).slice() : [],
550
+ outputNote: (_g = loop.output) === null || _g === void 0 ? void 0 : _g.note,
551
+ outputSkipped: ((_h = loop.output) === null || _h === void 0 ? void 0 : _h.kind) === "output" ? loop.output.skipped : undefined,
552
+ outputMode: ((_j = loop.output) === null || _j === void 0 ? void 0 : _j.kind) === "output" ? loop.output.mode : undefined,
419
553
  };
420
554
  }
421
555
  // -- streaming ---------------------------------------------------------------------------------------------------
@@ -431,6 +565,11 @@ class StreamedRunResult {
431
565
  this.stopReason = undefined;
432
566
  this.conversationId = undefined;
433
567
  this.cancelled = false;
568
+ /** As on `RunResult`; read after `completed` settles. */
569
+ this.outputCitations = [];
570
+ this.outputNote = undefined;
571
+ this.outputSkipped = undefined;
572
+ this.outputMode = undefined;
434
573
  this.queue = [];
435
574
  this.waiters = [];
436
575
  this.done = false;
@@ -446,6 +585,10 @@ class StreamedRunResult {
446
585
  this.stopReason = outcome.stopReason;
447
586
  this.conversationId = outcome.conversationId;
448
587
  this.cancelled = outcome.cancelled;
588
+ this.outputCitations = outcome.outputCitations;
589
+ this.outputNote = outcome.outputNote;
590
+ this.outputSkipped = outcome.outputSkipped;
591
+ this.outputMode = outcome.outputMode;
449
592
  this.end();
450
593
  }, (error) => {
451
594
  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
- export interface Interruption {
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, s: string): Promise<RunState>;
51
+ static fromString(agent: Agent<OutputType | undefined>, s: string): Promise<RunState>;
26
52
  }
@@ -14,11 +14,41 @@ class RunState {
14
14
  this.answers = answers;
15
15
  this.transportKind = transportKind;
16
16
  }
17
+ /**
18
+ * What the conversation is waiting on, read from the server: the function calls of a run whose process stopped
19
+ * before answering them. `run(agent, state)` then runs them here and continues the turn.
20
+ */
21
+ static async fromSession(conversationId, opts = {}) {
22
+ const { resolveTransport } = await Promise.resolve().then(() => require("./deploy.js")); // deploy imports run, which imports this module
23
+ const transport = resolveTransport(opts.client, opts.transport);
24
+ if (typeof conversationId !== "string" || conversationId === "") {
25
+ throw new errors_js_1.UserError("fromSession needs a conversation id (a previous result.conversationId)");
26
+ }
27
+ if (transport.pending === undefined) {
28
+ throw new errors_js_1.NotSupportedError("this transport cannot list pending function calls");
29
+ }
30
+ const pending = (await transport.pending(conversationId)).map((r) => {
31
+ var _a;
32
+ return ({
33
+ kind: "function_call",
34
+ requestId: r.requestId,
35
+ payload: {
36
+ calls: r.calls.map((c) => ({ call_id: c.callId, name: c.name, arguments: { ...c.arguments } })),
37
+ expires_at: (_a = r.expiresAt) !== null && _a !== void 0 ? _a : null,
38
+ },
39
+ });
40
+ });
41
+ return new RunState(conversationId, pending, {});
42
+ }
17
43
  /** Record the answers to a pending interruption; `run(agent, state)` sends them. */
18
44
  answer(item, answers) {
19
45
  if (!this.pending.some((p) => p.requestId === item.requestId)) {
20
46
  throw new errors_js_1.UserError(`no pending item with request id "${item.requestId}"`);
21
47
  }
48
+ if (item.kind === "function_call") {
49
+ throw new errors_js_1.UserError("function calls are answered by running the agent's function tools: pass this state to " +
50
+ "run() with the agent");
51
+ }
22
52
  this.answers[item.requestId] = { ...answers };
23
53
  }
24
54
  /** 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 { RemoteAgent, Transport, TurnStream } from "./transport.js";
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;