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
@@ -2,6 +2,13 @@ import { NotSupportedError, UserError } from "./errors.js";
2
2
  import { settingsFingerprint } from "./fingerprint.js";
3
3
  import { BUILTIN_NAMES, checkWebSearchOptions } from "./builtins.js";
4
4
  import { BuiltinTool } from "./tools.js";
5
+ import {
6
+ DEFAULT_FUNCTION_TIMEOUT_SECONDS, FUNCTION_TIMEOUT_RANGE, FUNCTIONS_MAX, FUNCTIONS_TOTAL_MAX_BYTES, compactBytes,
7
+ functionToolSettings, isBuiltFunctionTool, isFunctionTool, tool,
8
+ } from "./functionTool.js";
9
+ import type { FunctionTool, FunctionToolOptions } from "./functionTool.js";
10
+ import { checkOutputType, outputSchema } from "./output.js";
11
+ import type { OutputType } from "./output.js";
5
12
 
6
13
  const SLUG = /^[a-z0-9][a-z0-9-]{0,63}$/;
7
14
  const REASONING = ["off", "none", "low", "medium", "high", "xhigh", "max"];
@@ -21,7 +28,10 @@ export interface Limits {
21
28
  maxTokensPerTurn?: number;
22
29
  }
23
30
 
24
- export interface AgentOptions {
31
+ /** An entry of `Agent` `tools`: a built-in (`sandbox()`, `webSearchTool()`, ...) or a function tool (`tool()`). */
32
+ export type AgentTool = BuiltinTool | FunctionTool;
33
+
34
+ export interface AgentOptions<TOutput extends OutputType | undefined = undefined> {
25
35
  name: string;
26
36
  instructions?: string;
27
37
  model?: string;
@@ -29,10 +39,15 @@ export interface AgentOptions {
29
39
  endpoint?: string;
30
40
  modelSettings?: ModelSettings;
31
41
  fallbackModels?: string[];
32
- /** Exact list of built-ins to keep on; omit to keep the server default (all on). */
33
- tools?: BuiltinTool[];
42
+ /** Exact list of what the agent may use: built-ins (the unlisted ones are turned off) and function tools (agent.json
43
+ * `functions`). Omit to keep the server default (every built-in on, no functions). */
44
+ tools?: AgentTool[];
45
+ /** Seconds (10 to 3000, default 600) the server waits for this process to answer a function call (`function_timeout_seconds`). */
46
+ functionTimeoutSeconds?: number;
34
47
  limits?: Limits;
35
48
  metadata?: Record<string, string>;
49
+ /** The shape of the final answer: `{ type: "json_schema", schema }` or a zod schema. `finalOutput` follows it. */
50
+ outputType?: TOutput;
36
51
  }
37
52
 
38
53
  function deepFreeze<T>(value: T): T {
@@ -56,7 +71,7 @@ function isFiniteNumber(n: unknown): boolean {
56
71
  }
57
72
 
58
73
  /** Runs on the raw options, before the JSON clone turns NaN/Infinity into null. */
59
- function checkNumbers(opts: AgentOptions): void {
74
+ function checkNumbers(opts: AgentOptions<OutputType | undefined>): void {
60
75
  const ms = opts.modelSettings;
61
76
  if (ms !== undefined && ms !== null) {
62
77
  if (ms.temperature !== undefined && !(isFiniteNumber(ms.temperature) && ms.temperature >= 0 && ms.temperature <= 2)) {
@@ -91,8 +106,8 @@ function dropNulls<T extends object>(value: T | null | undefined): T | undefined
91
106
  }
92
107
 
93
108
  /** JS callers spreading JSON configs pass null for unset fields; null means unset everywhere (like Python's None). */
94
- function normalize(raw: AgentOptions): AgentOptions {
95
- const opts = dropNulls(raw) as AgentOptions;
109
+ function normalize<T extends OutputType | undefined>(raw: AgentOptions<T>): AgentOptions<T> {
110
+ const opts = dropNulls(raw) as AgentOptions<T>;
96
111
  if (opts.modelSettings !== undefined) opts.modelSettings = dropNulls(opts.modelSettings);
97
112
  if (opts.limits !== undefined) opts.limits = dropNulls(opts.limits);
98
113
  return opts;
@@ -104,23 +119,38 @@ const LIMIT_KEYS: [keyof Limits, string][] = [
104
119
  ["maxTokensPerTurn", "max_tokens_per_turn"],
105
120
  ];
106
121
 
107
- export class Agent {
122
+ /** An agent with any output type: use it for helpers that accept every agent (plain `Agent` means a text agent). */
123
+ export type AnyAgent = Agent<OutputType | undefined>;
124
+
125
+ export class Agent<TOutput extends OutputType | undefined = undefined> {
108
126
  readonly name: string;
109
127
  readonly instructions: string;
110
128
  readonly model?: string;
111
129
  readonly endpoint?: string;
112
130
  readonly modelSettings?: ModelSettings;
113
131
  readonly fallbackModels?: string[];
114
- readonly tools?: readonly BuiltinTool[];
132
+ /** Built-ins and function tools, in the order given. */
133
+ readonly tools?: readonly AgentTool[];
134
+ readonly functionTimeoutSeconds?: number;
115
135
  readonly limits?: Limits;
116
136
  readonly metadata?: Record<string, string>;
137
+ /** Kept by reference and not frozen: a zod schema must stay usable. Non-enumerable, so deepFreeze skips it. */
138
+ declare readonly outputType: TOutput;
117
139
 
118
- constructor(rawOpts: AgentOptions) {
140
+ constructor(rawOpts: AgentOptions<TOutput>) {
119
141
  const opts = normalize(rawOpts);
120
- for (const tool of opts.tools ?? []) {
142
+ for (const tool of (opts.tools ?? []) as unknown[]) {
121
143
  if (tool instanceof Agent) {
122
144
  throw new NotSupportedError("sub-agents in tools are not supported yet (field: tools)");
123
145
  }
146
+ if (typeof tool === "function") {
147
+ throw new UserError(`tools: ${tool.name || "a function"} is not a tool; wrap it with tool({ name, description, ` +
148
+ "parameters, execute })");
149
+ }
150
+ if (tool === null || typeof tool !== "object" || Array.isArray(tool)) {
151
+ throw new UserError(`tools: ${JSON.stringify(tool)} is not a tool; list built-ins (sandbox(), webSearchTool(), ...) ` +
152
+ "and tool() function tools");
153
+ }
124
154
  }
125
155
  checkNumbers(opts);
126
156
  this.name = opts.name;
@@ -129,9 +159,18 @@ export class Agent {
129
159
  this.endpoint = opts.endpoint;
130
160
  this.modelSettings = clone(opts.modelSettings);
131
161
  this.fallbackModels = clone(opts.fallbackModels);
132
- this.tools = clone(opts.tools);
162
+ // A function tool is kept by reference (it holds execute and maybe a zod schema); an object literal of that shape
163
+ // goes through tool().
164
+ this.tools = opts.tools === undefined ? undefined
165
+ : opts.tools.map((t): AgentTool => {
166
+ if (isBuiltFunctionTool(t)) return t;
167
+ if (isFunctionTool(t)) return tool(t as unknown as FunctionToolOptions);
168
+ return clone(t);
169
+ });
170
+ this.functionTimeoutSeconds = opts.functionTimeoutSeconds;
133
171
  this.limits = clone(opts.limits);
134
172
  this.metadata = clone(opts.metadata);
173
+ Object.defineProperty(this, "outputType", { value: opts.outputType, enumerable: false, writable: false });
135
174
  this.check();
136
175
  deepFreeze(this);
137
176
  }
@@ -140,6 +179,10 @@ export class Agent {
140
179
  if (typeof this.name !== "string" || !SLUG.test(this.name)) {
141
180
  throw new UserError(`name: ${JSON.stringify(this.name)} must match ${SLUG.source}`);
142
181
  }
182
+ if (this.outputType !== undefined) {
183
+ checkOutputType(this.outputType);
184
+ outputSchema(this.outputType as OutputType); // refuse what the server would, before anything is sent
185
+ }
143
186
  for (const [key, value] of [["model", this.model], ["endpoint", this.endpoint]] as [string, unknown][]) {
144
187
  if (value !== undefined && (typeof value !== "string" || value === "")) {
145
188
  throw new UserError(`${key}: must be a non-empty string`);
@@ -182,7 +225,7 @@ export class Agent {
182
225
  throw new UserError(`metadata: keys starting with 'sdk_' are reserved (${bad.join(", ")})`);
183
226
  }
184
227
  }
185
- const names = (this.tools ?? []).map((t) => t.name);
228
+ const names = this.builtinTools.map((t) => t.name);
186
229
  for (const n of names) {
187
230
  if ((BUILTIN_NAMES as readonly string[]).indexOf(n) === -1) {
188
231
  throw new UserError(`tools: unknown built-in tool ${JSON.stringify(n)} (known: ${BUILTIN_NAMES.join(", ")})`);
@@ -192,7 +235,7 @@ export class Agent {
192
235
  if (dupes.length > 0) {
193
236
  throw new UserError(`tools: duplicate built-in tool(s): ${dupes.join(", ")}`);
194
237
  }
195
- for (const t of this.tools ?? []) {
238
+ for (const t of this.builtinTools) {
196
239
  if (t.options === undefined || Object.keys(t.options).length === 0) continue;
197
240
  if (t.name !== "web_search") throw new UserError(`tools: ${t.name} takes no options`);
198
241
  checkWebSearchOptions(t.options);
@@ -200,6 +243,49 @@ export class Agent {
200
243
  if (names.indexOf("code_mode") !== -1 && names.indexOf("sandbox") === -1) {
201
244
  throw new UserError("tools: codeMode needs sandbox; add sandbox() to tools");
202
245
  }
246
+ this.checkFunctions();
247
+ }
248
+
249
+ private checkFunctions(): void {
250
+ const functions = this.functionTools;
251
+ if (functions.length > FUNCTIONS_MAX) {
252
+ throw new UserError(`tools: at most ${FUNCTIONS_MAX} function tools (got ${functions.length})`);
253
+ }
254
+ const names = functions.map((t) => t.name);
255
+ const dupes = Array.from(new Set(names.filter((n, i) => names.indexOf(n) !== i))).sort();
256
+ if (dupes.length > 0) throw new UserError(`tools: duplicate function tool(s): ${dupes.join(", ")}`);
257
+ const total = functions.reduce((sum, t) => sum + compactBytes(functionToolSettings(t)), 0);
258
+ if (total > FUNCTIONS_TOTAL_MAX_BYTES) {
259
+ throw new UserError(`tools: function tools are ${Math.ceil(total / 1024)} KB together (names, descriptions and ` +
260
+ "parameters); the server allows 64 KB, because every model call carries them");
261
+ }
262
+ const timeout = this.functionTimeoutSeconds;
263
+ if (timeout !== undefined) {
264
+ const [low, high] = FUNCTION_TIMEOUT_RANGE;
265
+ if (typeof timeout !== "number" || !Number.isInteger(timeout) || timeout < low || timeout > high) {
266
+ throw new UserError(`functionTimeoutSeconds: must be a whole number of seconds from ${low} to ${high}`);
267
+ }
268
+ }
269
+ // A call still running when the server's deadline passes is answered too late (409 expired) and the run fails;
270
+ // one that times out here first goes to the model as a failed result in time.
271
+ const deadline = timeout ?? DEFAULT_FUNCTION_TIMEOUT_SECONDS;
272
+ for (const t of functions) {
273
+ if (t.timeoutMs >= deadline * 1000) {
274
+ throw new UserError(`${t.name}: timeoutMs=${t.timeoutMs} (${t.timeoutMs / 1000}s) must be shorter than the ` +
275
+ `agent's functionTimeoutSeconds (${deadline}s${timeout === undefined ? ", the server default" : ""}); ` +
276
+ "lower the tool's timeoutMs or raise functionTimeoutSeconds");
277
+ }
278
+ }
279
+ }
280
+
281
+ /** The built-in tools in `tools`, in order. */
282
+ get builtinTools(): readonly BuiltinTool[] {
283
+ return (this.tools ?? []).filter((t) => !isFunctionTool(t)) as BuiltinTool[];
284
+ }
285
+
286
+ /** The function tools in `tools`, in order. */
287
+ get functionTools(): readonly FunctionTool[] {
288
+ return (this.tools ?? []).filter(isFunctionTool);
203
289
  }
204
290
 
205
291
  private baseSettings(): Record<string, unknown> {
@@ -226,15 +312,22 @@ export class Agent {
226
312
  if (Object.keys(limits).length > 0) out["limits"] = limits;
227
313
  }
228
314
  if (this.tools !== undefined) {
229
- // Built-ins are on by default, so an exact list writes every unlisted one as off.
315
+ // Built-ins are on by default, so an exact list writes every unlisted one as off (function tools included:
316
+ // tools: [tool(...)] means that function and no built-in).
317
+ const builtins = this.builtinTools;
230
318
  const tools: Record<string, unknown> = {};
231
319
  for (const n of BUILTIN_NAMES) {
232
- const t = this.tools.find((x) => x.name === n);
320
+ const t = builtins.find((x) => x.name === n);
233
321
  tools[n] = t === undefined ? false
234
322
  : t.options !== undefined && Object.keys(t.options).length > 0 ? clone(t.options) : true;
235
323
  }
236
324
  out["builtin_tools"] = tools;
325
+ // Never an empty list: that would change every existing agent's fingerprint.
326
+ const functions = this.functionTools;
327
+ if (functions.length > 0) out["functions"] = functions.map(functionToolSettings);
237
328
  }
329
+ if (this.functionTimeoutSeconds !== undefined) out["function_timeout_seconds"] = this.functionTimeoutSeconds;
330
+ if (this.outputType !== undefined) out["output_schema"] = outputSchema(this.outputType as OutputType);
238
331
  return out;
239
332
  }
240
333
 
@@ -1,6 +1,7 @@
1
1
  /** deploy()/undeploy(): upsert a hosted agent by name, with fingerprint-based drift detection, and the deploy cache. */
2
2
  import type { Configuration } from "../runtime.js";
3
3
  import type { Agent } from "./agent.js";
4
+ import type { OutputType } from "./output.js";
4
5
  import { DriftError, DuplicateAgentsError, UserError } from "./errors.js";
5
6
  import { canonicalJson, fingerprintBody, settingsFingerprint } from "./fingerprint.js";
6
7
  import { SettingsTransport } from "./settingsTransport.js";
@@ -37,7 +38,7 @@ function storedHash(remote: RemoteAgent): string | undefined {
37
38
  return typeof h === "string" ? h : undefined;
38
39
  }
39
40
 
40
- function changedFields(remote: RemoteAgent, agent: Agent): string[] {
41
+ function changedFields(remote: RemoteAgent, agent: Agent<OutputType | undefined>): string[] {
41
42
  const want = fingerprintBody(agent.toSettings());
42
43
  const have = fingerprintBody(remote.settings);
43
44
  const keys: string[] = [];
@@ -53,7 +54,7 @@ function changedFields(remote: RemoteAgent, agent: Agent): string[] {
53
54
  return keys;
54
55
  }
55
56
 
56
- async function update(transport: Transport, remote: RemoteAgent, agent: Agent, strict: boolean): Promise<Deployment> {
57
+ async function update(transport: Transport, remote: RemoteAgent, agent: Agent<OutputType | undefined>, strict: boolean): Promise<Deployment> {
57
58
  const stored = storedHash(remote);
58
59
  if (stored !== undefined && settingsFingerprint(remote.instructions, remote.settings) !== stored) {
59
60
  const changed = changedFields(remote, agent);
@@ -68,7 +69,7 @@ async function update(transport: Transport, remote: RemoteAgent, agent: Agent, s
68
69
  return { agentId: remote.agentId, action: "updated" };
69
70
  }
70
71
 
71
- async function deployWith(agent: Agent, transport: Transport, strict: boolean, adopt?: string): Promise<Deployment> {
72
+ async function deployWith(agent: Agent<OutputType | undefined>, transport: Transport, strict: boolean, adopt?: string): Promise<Deployment> {
72
73
  const found = await transport.findAgents(agent.name);
73
74
  if (adopt !== undefined) {
74
75
  const target = await transport.readAgent(adopt);
@@ -90,7 +91,7 @@ async function deployWith(agent: Agent, transport: Transport, strict: boolean, a
90
91
  }
91
92
 
92
93
  export async function deploy(
93
- agent: Agent,
94
+ agent: Agent<OutputType | undefined>,
94
95
  opts: { client?: Configuration; transport?: Transport; strict?: boolean; adopt?: string } = {},
95
96
  ): Promise<Deployment> {
96
97
  const transport = resolveTransport(opts.client, opts.transport);
@@ -148,7 +149,7 @@ export function forget(name: string): void {
148
149
  * Keyed by name, as the server is: a variant with the same name redeploys, chained after any in-flight deploy so
149
150
  * deploys of one name never overlap.
150
151
  */
151
- export function agentIdFor(agent: Agent, transport: Transport, owner: object): Promise<string> {
152
+ export function agentIdFor(agent: Agent<OutputType | undefined>, transport: Transport, owner: object): Promise<string> {
152
153
  const hash = agent.specHash();
153
154
  let owners = cache.get(agent.name);
154
155
  if (!owners) {
@@ -19,7 +19,34 @@ export class UserError extends AgentsError {
19
19
  }
20
20
  }
21
21
 
22
- export class ModelBehaviorError extends AgentsError {}
22
+ /** Where a `ModelBehaviorError` came from: the server's check, or the `outputType`'s own `parse`. */
23
+ export type ModelBehaviorErrorSource = "server" | "local_parse";
24
+
25
+ /**
26
+ * The agent's answer didn't match its `outputType`. `source` says where: `"server"` (no answer matched the schema
27
+ * after the server's retry; `rawText` is the model's last attempt) or `"local_parse"` (the server accepted the answer
28
+ * but the `outputType`'s `parse` refused it, for example a zod refinement; `rawText` is the server's JSON,
29
+ * re-serialised).
30
+ */
31
+ export class ModelBehaviorError extends AgentsError {
32
+ readonly rawText: string;
33
+ readonly errors: string[];
34
+ /** The server's `outputNote`: the turn's size-refused `final_answer` was not the answer. */
35
+ readonly note: string | undefined;
36
+ readonly source: ModelBehaviorErrorSource;
37
+ /** The run's conversation, set when a run rejects with this, so the caller can continue it (`conversationId`) or
38
+ * fetch its `ResponseDetail`. */
39
+ conversationId: string | undefined = undefined;
40
+
41
+ constructor(rawText = "", errors: string[] = [], note?: string, source: ModelBehaviorErrorSource = "server") {
42
+ const prefix = source === "server" ? "model output rejected" : "model output rejected by outputType";
43
+ super(errors.length ? `${prefix}: ` + errors.join("; ") : rawText);
44
+ this.rawText = rawText;
45
+ this.errors = errors.slice();
46
+ this.note = note;
47
+ this.source = source;
48
+ }
49
+ }
23
50
 
24
51
  export class MaxTurnsExceededError extends AgentsError {}
25
52
 
@@ -35,9 +62,15 @@ export class NotSupportedError extends AgentsError {}
35
62
 
36
63
  export class RunError extends AgentsError {
37
64
  readonly code: string;
38
- constructor(code: string, message: string) {
65
+ /** The HTTP status when a request was refused (for example 409 on a function-results post). */
66
+ readonly status?: number;
67
+ /** The server's `error.details[0]` (for example `toolCallIds` or `maxBytes`); `{}` when none. */
68
+ readonly details: Record<string, unknown>;
69
+ constructor(code: string, message: string, status?: number, details?: Record<string, unknown>) {
39
70
  super(`${code}: ${message}`);
40
71
  this.code = code;
72
+ if (status !== undefined) this.status = status;
73
+ this.details = { ...(details ?? {}) };
41
74
  }
42
75
  }
43
76
 
@@ -14,6 +14,15 @@ export interface FunctionCallRequest {
14
14
  arguments: Record<string, unknown>;
15
15
  }
16
16
 
17
+ /** A source the structured output cited: the server's citation-manifest entry, passed through as sent. */
18
+ export interface OutputCitation {
19
+ cite_id: string;
20
+ type?: string;
21
+ url?: string;
22
+ title?: string;
23
+ [key: string]: unknown;
24
+ }
25
+
17
26
  export type Event =
18
27
  | { kind: "text_start"; id: string }
19
28
  | { kind: "text_delta"; delta: string; id?: string }
@@ -24,6 +33,27 @@ export type Event =
24
33
  | { kind: "clarify_requested"; requestId: string; questions: ClarifyQuestion[] }
25
34
  | { kind: "function_calls_requested"; requestId: string; calls: FunctionCallRequest[]; expiresAt?: string }
26
35
  | { kind: "stopped"; reason: string }
36
+ /** The turn's structured output (`data-output`); `output` is null and `skipped` says why when the turn ended
37
+ * without one: `limit`, `budget`, `paused` or `suppressed` (a cron turn that ended `[SILENT]`), passed through as
38
+ * sent, so a newer server's value arrives unchanged. */
39
+ | {
40
+ kind: "output";
41
+ output: unknown;
42
+ skipped?: string;
43
+ /** How the server produced it (`tool_in_loop`, `tool_oversize`, `forced_tool`, `native`, `prompted`), passed
44
+ * through as sent. `tool_oversize`: the model's `final_answer` was too large for the tool loop and the server
45
+ * validated it afterwards. */
46
+ mode?: string;
47
+ /** The sources `output` cited, first citation first; absent when it cited none. `output` itself carries no
48
+ * `[cite:...]` markers. */
49
+ citations?: OutputCitation[];
50
+ /** Set when the turn's `final_answer` was refused for size and was not the answer: `oversize_answer_invalid`
51
+ * (it did not validate) or `oversize_answer_dropped` (too large to check), so `output` came from the model's
52
+ * later text. */
53
+ note?: string;
54
+ }
55
+ /** No answer matched the agent's output schema (`data-output-error`); `note` as on `output`. */
56
+ | { kind: "output_error"; errors: string[]; rawText: string; note?: string }
27
57
  /** An agent.json limit ended the turn (`data-turn-limit`); the wrap-up answer still follows. `capKind` is the
28
58
  * server's cap name: `max_turns`, `tool_calls` or `tokens`. `limit` is the agent.json `limits` key that set it
29
59
  * (`max_turns`, `max_tool_calls_per_turn` or `max_tokens_per_turn`) and `value` the configured number; both are
@@ -127,8 +157,56 @@ function map(chunk: Record<string, unknown>): Event | null {
127
157
  return { kind: "turn_failed", code: str(chunk["code"], "turn_failed"), message: text(chunk["errorText"]) };
128
158
  case "finish":
129
159
  return { kind: "turn_finished", reason: str(chunk["finishReason"], "stop") };
160
+ case "data-output": {
161
+ const ev: Event = { kind: "output", output: data["output"] ?? null };
162
+ if (typeof data["skipped"] === "string" && data["skipped"]) ev.skipped = data["skipped"];
163
+ if (typeof data["mode"] === "string" && data["mode"]) ev.mode = data["mode"];
164
+ const citations = Array.isArray(data["citations"]) ? data["citations"].filter(isObject) : [];
165
+ if (citations.length) ev.citations = citations as OutputCitation[];
166
+ if (typeof data["note"] === "string" && data["note"]) ev.note = data["note"];
167
+ return ev;
168
+ }
169
+ case "data-output-error": {
170
+ const errors = data["errors"];
171
+ const ev: Event = {
172
+ kind: "output_error",
173
+ errors: Array.isArray(errors) ? errors.map(String) : typeof errors === "string" ? [errors] : [],
174
+ rawText: text(data["rawText"]),
175
+ };
176
+ if (typeof data["note"] === "string" && data["note"]) ev.note = data["note"];
177
+ return ev;
178
+ }
130
179
  default:
131
- // data-output and data-output-error are unknown until structured output lands.
132
180
  return { kind: "unknown", chunk };
133
181
  }
134
182
  }
183
+
184
+ /** A stored UIMessage (`GET /v1/conversations/{id}` `messages`) as the stream chunks that would have produced it,
185
+ * ending with `finish`, so a finished turn can be read like a live one. Text parts become one text block each, tool
186
+ * parts a call and (when they have one) its output, `data-*` parts pass through; reasoning is dropped. */
187
+ export function chunksFromUiMessage(message: unknown): Record<string, unknown>[] {
188
+ const chunks: Record<string, unknown>[] = [];
189
+ const parts = isObject(message) && Array.isArray(message["parts"]) ? message["parts"] : [];
190
+ parts.forEach((part: unknown, n: number) => {
191
+ if (!isObject(part)) return;
192
+ const kind = typeof part["type"] === "string" ? part["type"] : "";
193
+ if (kind === "text") {
194
+ const id = `msg-text-${n}`;
195
+ chunks.push({ type: "text-start", id }, { type: "text-delta", id, delta: String(part["text"] ?? "") },
196
+ { type: "text-end", id });
197
+ } else if (kind === "dynamic-tool" || kind.startsWith("tool-")) {
198
+ const name = part["toolName"] ?? (kind.startsWith("tool-") ? kind.slice("tool-".length) : "");
199
+ const toolCallId = part["toolCallId"] ?? "";
200
+ chunks.push({ type: "tool-input-available", toolCallId, toolName: name, input: part["input"] });
201
+ if (part["state"] === "output-available") {
202
+ chunks.push({ type: "tool-output-available", toolCallId, output: part["output"] });
203
+ } else if (part["state"] === "output-error") {
204
+ chunks.push({ type: "tool-output-available", toolCallId, output: { error: part["errorText"] ?? "" } });
205
+ }
206
+ } else if (kind.startsWith("data-")) {
207
+ chunks.push({ type: kind, id: part["id"], data: part["data"] });
208
+ }
209
+ });
210
+ chunks.push({ type: "finish", finishReason: "stop" });
211
+ return chunks;
212
+ }