sarvam-agents-client 0.2.3 → 0.3.0

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 (101) hide show
  1. package/dist/apis/AgentsApi.d.ts +4 -4
  2. package/dist/apis/AgentsApi.js +4 -4
  3. package/dist/apis/AppsApi.d.ts +1 -0
  4. package/dist/apis/AppsApi.js +3 -0
  5. package/dist/apis/QueueApi.d.ts +1 -0
  6. package/dist/apis/QueueApi.js +3 -0
  7. package/dist/apis/ResponsesApi.d.ts +2 -0
  8. package/dist/apis/ResponsesApi.js +6 -0
  9. package/dist/compose/agent.d.ts +10 -3
  10. package/dist/compose/agent.js +8 -0
  11. package/dist/compose/deploy.d.ts +3 -2
  12. package/dist/compose/errors.d.ts +17 -0
  13. package/dist/compose/errors.js +17 -0
  14. package/dist/compose/events.d.ts +34 -0
  15. package/dist/compose/events.js +25 -2
  16. package/dist/compose/index.d.ts +2 -1
  17. package/dist/compose/output.d.ts +29 -0
  18. package/dist/compose/output.js +451 -0
  19. package/dist/compose/run.d.ts +39 -14
  20. package/dist/compose/run.js +53 -3
  21. package/dist/compose/runState.d.ts +2 -1
  22. package/dist/compose/settingsTransport.d.ts +3 -2
  23. package/dist/compose/transport.d.ts +3 -2
  24. package/dist/esm/apis/AgentsApi.d.ts +4 -4
  25. package/dist/esm/apis/AgentsApi.js +4 -4
  26. package/dist/esm/apis/AppsApi.d.ts +1 -0
  27. package/dist/esm/apis/AppsApi.js +3 -0
  28. package/dist/esm/apis/QueueApi.d.ts +1 -0
  29. package/dist/esm/apis/QueueApi.js +3 -0
  30. package/dist/esm/apis/ResponsesApi.d.ts +2 -0
  31. package/dist/esm/apis/ResponsesApi.js +6 -0
  32. package/dist/esm/compose/agent.d.ts +10 -3
  33. package/dist/esm/compose/agent.js +8 -0
  34. package/dist/esm/compose/deploy.d.ts +3 -2
  35. package/dist/esm/compose/errors.d.ts +17 -0
  36. package/dist/esm/compose/errors.js +17 -0
  37. package/dist/esm/compose/events.d.ts +34 -0
  38. package/dist/esm/compose/events.js +25 -2
  39. package/dist/esm/compose/index.d.ts +2 -1
  40. package/dist/esm/compose/output.d.ts +29 -0
  41. package/dist/esm/compose/output.js +445 -0
  42. package/dist/esm/compose/run.d.ts +39 -14
  43. package/dist/esm/compose/run.js +54 -4
  44. package/dist/esm/compose/runState.d.ts +2 -1
  45. package/dist/esm/compose/settingsTransport.d.ts +3 -2
  46. package/dist/esm/compose/transport.d.ts +3 -2
  47. package/dist/esm/models/AppResource.d.ts +29 -0
  48. package/dist/esm/models/AppResource.js +16 -0
  49. package/dist/esm/models/AppToolsResponse.d.ts +3 -4
  50. package/dist/esm/models/AppToolsResponse.js +3 -2
  51. package/dist/esm/models/AppView.d.ts +48 -0
  52. package/dist/esm/models/AppView.js +23 -0
  53. package/dist/esm/models/McpSecurityAppealView.d.ts +50 -0
  54. package/dist/esm/models/McpSecurityAppealView.js +47 -0
  55. package/dist/esm/models/McpSecurityView.d.ts +105 -0
  56. package/dist/esm/models/McpSecurityView.js +66 -0
  57. package/dist/esm/models/MessagesResponse.d.ts +6 -0
  58. package/dist/esm/models/MessagesResponse.js +2 -0
  59. package/dist/esm/models/ResponseDetail.d.ts +32 -0
  60. package/dist/esm/models/ResponseDetail.js +10 -0
  61. package/dist/esm/models/index.d.ts +2 -0
  62. package/dist/esm/models/index.js +2 -0
  63. package/dist/models/AppResource.d.ts +29 -0
  64. package/dist/models/AppResource.js +17 -1
  65. package/dist/models/AppToolsResponse.d.ts +3 -4
  66. package/dist/models/AppToolsResponse.js +3 -2
  67. package/dist/models/AppView.d.ts +48 -0
  68. package/dist/models/AppView.js +24 -1
  69. package/dist/models/McpSecurityAppealView.d.ts +50 -0
  70. package/dist/models/McpSecurityAppealView.js +54 -0
  71. package/dist/models/McpSecurityView.d.ts +105 -0
  72. package/dist/models/McpSecurityView.js +73 -0
  73. package/dist/models/MessagesResponse.d.ts +6 -0
  74. package/dist/models/MessagesResponse.js +2 -0
  75. package/dist/models/ResponseDetail.d.ts +32 -0
  76. package/dist/models/ResponseDetail.js +10 -0
  77. package/dist/models/index.d.ts +2 -0
  78. package/dist/models/index.js +2 -0
  79. package/package.json +4 -3
  80. package/src/apis/AgentsApi.ts +4 -4
  81. package/src/apis/AppsApi.ts +5 -0
  82. package/src/apis/QueueApi.ts +5 -0
  83. package/src/apis/ResponsesApi.ts +10 -0
  84. package/src/compose/agent.ts +21 -6
  85. package/src/compose/deploy.ts +6 -5
  86. package/src/compose/errors.ts +28 -1
  87. package/src/compose/events.ts +49 -1
  88. package/src/compose/index.ts +2 -1
  89. package/src/compose/output.ts +415 -0
  90. package/src/compose/run.ts +93 -21
  91. package/src/compose/runState.ts +2 -1
  92. package/src/compose/settingsTransport.ts +4 -3
  93. package/src/compose/transport.ts +3 -2
  94. package/src/models/AppResource.ts +42 -0
  95. package/src/models/AppToolsResponse.ts +11 -4
  96. package/src/models/AppView.ts +73 -0
  97. package/src/models/McpSecurityAppealView.ts +89 -0
  98. package/src/models/McpSecurityView.ts +169 -0
  99. package/src/models/MessagesResponse.ts +8 -0
  100. package/src/models/ResponseDetail.ts +40 -0
  101. package/src/models/index.ts +2 -0
@@ -0,0 +1,445 @@
1
+ /** `outputType` -> agent.json `output_schema` under the server's rules, and parsing the turn's output. */
2
+ import { ModelBehaviorError, NotSupportedError, UserError } from "./errors.js";
3
+ /** The only keywords the server accepts in output_schema: those whose cost per answer value is bounded (it validates
4
+ * the answer on its workflow thread). Anything else (`$ref`, `pattern`, `uniqueItems`, `contains`, `if`/`then`/`else`,
5
+ * `not`, `unevaluated*`, `dependent*`, `propertyNames`, `discriminator`...) is refused by name. */
6
+ const ALLOWED = new Set([
7
+ "type", "properties", "required", "additionalProperties", "items", "prefixItems", "anyOf", "oneOf", "allOf",
8
+ "enum", "const",
9
+ "minimum", "maximum", "exclusiveMinimum", "exclusiveMaximum", "multipleOf", "minLength", "maxLength",
10
+ "minItems", "maxItems", "minProperties", "maxProperties", "format",
11
+ "title", "description", "default", "examples", "deprecated", "readOnly", "writeOnly", "$comment",
12
+ ]);
13
+ /** Accepted on the root schema only. */
14
+ const ROOT_ONLY = new Set(["$schema", "$id"]);
15
+ /** The `$schema` values the server accepts (draft-04 to 2020-12), normalized as the server looks them up, and the
16
+ * dialect each names. No `$schema` is 2020-12. */
17
+ const DIALECTS = {
18
+ "http://json-schema.org/draft-04/schema": 4,
19
+ "http://json-schema.org/draft-06/schema": 6,
20
+ "http://json-schema.org/draft-07/schema": 7,
21
+ "https://json-schema.org/draft/2019-09/schema": 2019,
22
+ "https://json-schema.org/draft/2020-12/schema": 2020,
23
+ };
24
+ const LATEST_DIALECT = "https://json-schema.org/draft/2020-12/schema";
25
+ /** A refused keyword is named, never its value; a long one is cut. */
26
+ const KEYWORD_SHOWN_MAX = 40;
27
+ /** Keywords whose value maps property names to subschemas when inlining definitions. */
28
+ const NAME_MAPS = new Set(["properties", "$defs", "definitions", "dependentSchemas"]);
29
+ /** Keywords whose value is instance data, not schema. */
30
+ const DATA_KEYWORDS = new Set(["enum", "const", "default", "examples", "required"]);
31
+ /** The server counts the root as level 1 and every value, data included. */
32
+ const MAX_DEPTH = 32;
33
+ /** The server's default CLAW_AGENT_OUTPUT_SCHEMA_MAX_BYTES (compact JSON, UTF-8). */
34
+ const MAX_BYTES = 16384;
35
+ /** The server's MAX_SCHEMA_BRANCHES: anyOf/oneOf/allOf entries that may apply to one answer value. */
36
+ const MAX_BRANCHES = 12;
37
+ const BRANCH_LISTS = ["anyOf", "oneOf", "allOf"];
38
+ /** The server's MAX_ENUM_ENTRIES: enum entries summed over the whole schema; each is a scalar. */
39
+ const MAX_ENUM_ENTRIES = 256;
40
+ const SIMPLE_TYPES = new Set(["array", "boolean", "integer", "null", "number", "object", "string"]);
41
+ const COUNTS = new Set(["minLength", "maxLength", "minItems", "maxItems", "minProperties", "maxProperties"]);
42
+ function isObject(v) {
43
+ return v !== null && typeof v === "object" && !Array.isArray(v);
44
+ }
45
+ function isSchemaLike(v) {
46
+ return v !== null && typeof v === "object" &&
47
+ typeof v.parse === "function" &&
48
+ typeof v.toJSONSchema === "function";
49
+ }
50
+ function isJsonSchema(v) {
51
+ return isObject(v) && v["type"] === "json_schema" && isObject(v["schema"]);
52
+ }
53
+ export function checkOutputType(v) {
54
+ if (!isSchemaLike(v) && !isJsonSchema(v)) {
55
+ throw new NotSupportedError('outputType must be { type: "json_schema", schema } or a zod schema (anything with parse() and toJSONSchema())');
56
+ }
57
+ }
58
+ /** Replace each `$ref` to a definition with that definition, walking schema positions as the server does. */
59
+ function inline(node, defs, seen) {
60
+ if (Array.isArray(node))
61
+ return node.map((v) => inline(v, defs, seen));
62
+ if (!isObject(node))
63
+ return node;
64
+ const ref = node["$ref"];
65
+ for (const prefix of ["#/$defs/", "#/definitions/"]) {
66
+ if (typeof ref === "string" && ref.startsWith(prefix)) {
67
+ const name = ref.slice(prefix.length);
68
+ if (seen.has(name))
69
+ throw new UserError(`outputType: ${name} is recursive; the server accepts no references`);
70
+ if (!(name in defs))
71
+ throw new UserError(`outputType: ${ref} doesn't resolve`);
72
+ const rest = {};
73
+ for (const [k, v] of Object.entries(node))
74
+ if (k !== "$ref")
75
+ rest[k] = v;
76
+ const target = JSON.parse(JSON.stringify(defs[name]));
77
+ return inline({ ...target, ...rest }, defs, new Set([...seen, name]));
78
+ }
79
+ }
80
+ const out = {};
81
+ for (const [key, value] of Object.entries(node)) {
82
+ // z.record() writes propertyNames {type: "string"}, which every JSON key meets; the server refuses the keyword.
83
+ if (key === "propertyNames" && isObject(value) && Object.keys(value).length === 1 && value["type"] === "string")
84
+ continue;
85
+ // An OpenAPI annotation (as Pydantic writes for a tagged union): the oneOf beside it does the validating.
86
+ if (key === "discriminator" && isObject(value))
87
+ continue;
88
+ if (DATA_KEYWORDS.has(key))
89
+ out[key] = value;
90
+ else if (NAME_MAPS.has(key) && isObject(value)) {
91
+ const map = {};
92
+ for (const [name, child] of Object.entries(value))
93
+ map[name] = inline(child, defs, seen);
94
+ out[key] = map;
95
+ }
96
+ else
97
+ out[key] = inline(value, defs, seen);
98
+ }
99
+ return out;
100
+ }
101
+ /** Nesting depth of a JSON value, counted like the server: the root is 1. */
102
+ export function schemaDepth(node) {
103
+ let deepest = 0;
104
+ const stack = [[node, 1]];
105
+ while (stack.length) {
106
+ const [value, depth] = stack.pop();
107
+ deepest = Math.max(deepest, depth);
108
+ if (depth > MAX_DEPTH)
109
+ break;
110
+ if (Array.isArray(value))
111
+ for (const v of value)
112
+ stack.push([v, depth + 1]);
113
+ else if (isObject(value))
114
+ for (const v of Object.values(value))
115
+ stack.push([v, depth + 1]);
116
+ }
117
+ return deepest;
118
+ }
119
+ /** Subschemas of `node` that apply to the members of its value (each member gets at most one of them). */
120
+ function children(node) {
121
+ const out = [];
122
+ if (isObject(node["properties"]))
123
+ out.push(...Object.values(node["properties"]));
124
+ if (isObject(node["items"]))
125
+ out.push(node["items"]);
126
+ else if (Array.isArray(node["items"]))
127
+ out.push(...node["items"]); // the tuple form of drafts before 2020-12
128
+ if (isObject(node["additionalProperties"]))
129
+ out.push(node["additionalProperties"]);
130
+ if (Array.isArray(node["prefixItems"]))
131
+ out.push(...node["prefixItems"]);
132
+ return out;
133
+ }
134
+ /** Every schema position under `node`; property names and enum/const/default/examples values are data. */
135
+ function subschemas(node) {
136
+ const out = children(node);
137
+ for (const key of BRANCH_LISTS)
138
+ if (Array.isArray(node[key]))
139
+ out.push(...node[key]);
140
+ return out;
141
+ }
142
+ /** Most subschemas of `node` (itself included) that apply to one value, computed as the server does. */
143
+ function valueLoad(node) {
144
+ const sameValue = [];
145
+ const stack = [node];
146
+ while (stack.length) {
147
+ const each = stack.pop();
148
+ sameValue.push(each);
149
+ if (isObject(each))
150
+ for (const key of BRANCH_LISTS)
151
+ if (Array.isArray(each[key]))
152
+ stack.push(...each[key]);
153
+ }
154
+ let below = 0;
155
+ for (const each of sameValue) {
156
+ if (isObject(each))
157
+ below += Math.max(0, ...children(each).map(valueLoad));
158
+ }
159
+ return Math.max(sameValue.length, below);
160
+ }
161
+ function shown(keyword) {
162
+ return JSON.stringify(keyword.length > KEYWORD_SHOWN_MAX ? keyword.slice(0, KEYWORD_SHOWN_MAX) + "..." : keyword);
163
+ }
164
+ function isEnumScalar(v) {
165
+ return v === null || ["string", "number", "boolean"].includes(typeof v);
166
+ }
167
+ /** [why a keyword is refused or undefined, enum entries], walked as the server walks. */
168
+ function screen(schema) {
169
+ let enumEntries = 0;
170
+ const stack = [[schema, true]];
171
+ while (stack.length) {
172
+ const [node, isRoot] = stack.pop();
173
+ if (!isObject(node))
174
+ continue;
175
+ for (const key of Object.keys(node)) {
176
+ if (ROOT_ONLY.has(key) && !isRoot)
177
+ return [`uses ${shown(key)} below the root, which the server doesn't support`, 0];
178
+ if (!ALLOWED.has(key) && !ROOT_ONLY.has(key)) {
179
+ return [`uses ${shown(key)}, which the server doesn't support in output_schema (allowed: type, properties, ` +
180
+ "required, additionalProperties, items, prefixItems, anyOf, oneOf, allOf, enum, const, numeric/length/count " +
181
+ "limits, format and annotations)", 0];
182
+ }
183
+ }
184
+ const en = node["enum"];
185
+ if (Array.isArray(en)) {
186
+ if (!en.every(isEnumScalar)) {
187
+ return ["lists an object or array in enum, which the server doesn't support; enum may list only strings, " +
188
+ "numbers, booleans and null", 0];
189
+ }
190
+ enumEntries += en.length;
191
+ }
192
+ for (const child of subschemas(node))
193
+ stack.push([child, false]);
194
+ }
195
+ return [undefined, enumEntries];
196
+ }
197
+ /** `uri` normalized as the server's JSON Schema library looks dialects up (Python's `urlsplit(uri).geturl()`): the
198
+ * scheme lowercased and an empty query or fragment dropped. */
199
+ function dialectKey(uri) {
200
+ let out = uri.replace(/[\t\r\n]/g, "").replace(/^[\x00-\x20]+/, "");
201
+ const scheme = /^([A-Za-z][A-Za-z0-9+.-]*):/.exec(out);
202
+ if (scheme)
203
+ out = scheme[1].toLowerCase() + out.slice(scheme[1].length);
204
+ if (out.endsWith("#"))
205
+ out = out.slice(0, -1);
206
+ if (out.endsWith("?"))
207
+ out = out.slice(0, -1);
208
+ return out;
209
+ }
210
+ // -- the meta-schema check ---------------------------------------------------------------------------------------
211
+ // After the allowlist the server runs `validator_for(schema).check_schema(schema)`: the schema must be valid under its
212
+ // dialect's meta-schema. This checks the same rules for the allowlisted keywords (the only ones the screen lets
213
+ // through), per dialect, with the server's messages (which show values as Python writes them). Keywords a dialect does
214
+ // not define (`prefixItems` before 2020-12, `const` in draft-04...) are not checked, as the server does not check them.
215
+ /** `value` as the server's messages show it: Python's repr of the JSON value. */
216
+ function pyRepr(value) {
217
+ if (value === null)
218
+ return "None";
219
+ if (value === true)
220
+ return "True";
221
+ if (value === false)
222
+ return "False";
223
+ if (typeof value === "number")
224
+ return String(value);
225
+ if (typeof value === "string") {
226
+ const quote = value.includes("'") && !value.includes('"') ? '"' : "'";
227
+ const body = value.replace(/\\/g, "\\\\").replace(/\n/g, "\\n").replace(/\r/g, "\\r").replace(/\t/g, "\\t");
228
+ return quote + (quote === "'" ? body.replace(/'/g, "\\'") : body) + quote;
229
+ }
230
+ if (Array.isArray(value))
231
+ return "[" + value.map(pyRepr).join(", ") + "]";
232
+ if (isObject(value))
233
+ return "{" + Object.entries(value).map(([k, v]) => `${pyRepr(k)}: ${pyRepr(v)}`).join(", ") + "}";
234
+ return String(value);
235
+ }
236
+ function isNumber(v) {
237
+ return typeof v === "number";
238
+ }
239
+ /** A value's identity for uniqueness, as the server compares: `1` equals `1.0`, `true` is not `1`. */
240
+ function sameKey(v) {
241
+ if (Array.isArray(v))
242
+ return "[" + v.map(sameKey).join(",") + "]";
243
+ if (isObject(v))
244
+ return "{" + Object.keys(v).sort().map((k) => JSON.stringify(k) + ":" + sameKey(v[k])).join(",") + "}";
245
+ return JSON.stringify(v);
246
+ }
247
+ function unique(values) {
248
+ return new Set(values.map(sameKey)).size === values.length;
249
+ }
250
+ /** Why `schema` fails its dialect's meta-schema (allowlisted keywords only), or undefined. */
251
+ function metaProblem(schema, draft) {
252
+ const stack = [[schema, ""]];
253
+ while (stack.length) {
254
+ const [node, path] = stack.pop();
255
+ const found = nodeProblem(node, draft, stack, path);
256
+ if (found)
257
+ return found[0] + (found[1] ? ` (at ${found[1]})` : "");
258
+ }
259
+ return undefined;
260
+ }
261
+ /** [why, where] when one schema position is invalid; pushes its subschemas on `stack`. */
262
+ function nodeProblem(node, draft, stack, path) {
263
+ if (typeof node === "boolean" && draft > 4)
264
+ return undefined;
265
+ if (!isObject(node))
266
+ return [`${pyRepr(node)} is not of type ${draft === 4 ? "'object'" : "'object', 'boolean'"}`, path];
267
+ const at = (...parts) => [...(path ? [path] : []), ...parts.map(String)].join("/");
268
+ const notOfType = (v, t) => `${pyRepr(v)} is not of type '${t}'`;
269
+ const notUnderAny = (v) => `${pyRepr(v)} is not valid under any of the given schemas`;
270
+ const schemas = (key, value) => {
271
+ if (!Array.isArray(value))
272
+ return notOfType(value, "array");
273
+ if (!value.length)
274
+ return "[] should be non-empty";
275
+ value.forEach((child, n) => stack.push([child, at(key, n)]));
276
+ return undefined;
277
+ };
278
+ const strings = new Set(["format", "title", "description", "$schema"]);
279
+ if (draft > 4)
280
+ strings.add("$id");
281
+ if (draft > 6)
282
+ strings.add("$comment");
283
+ const flags = new Set();
284
+ if (draft > 6)
285
+ flags.add("readOnly");
286
+ if (draft > 7) {
287
+ flags.add("deprecated");
288
+ flags.add("writeOnly");
289
+ }
290
+ const problem = (key, value) => {
291
+ switch (key) {
292
+ case "type": {
293
+ const ok = typeof value === "string" ? SIMPLE_TYPES.has(value)
294
+ : Array.isArray(value) && value.length > 0 && value.every((t) => typeof t === "string" && SIMPLE_TYPES.has(t)) && unique(value);
295
+ return ok ? undefined : notUnderAny(value);
296
+ }
297
+ case "properties":
298
+ if (!isObject(value))
299
+ return notOfType(value, "object");
300
+ for (const [name, child] of Object.entries(value))
301
+ stack.push([child, at(key, name)]);
302
+ return undefined;
303
+ case "required":
304
+ if (!Array.isArray(value))
305
+ return notOfType(value, "array");
306
+ for (const each of value)
307
+ if (typeof each !== "string")
308
+ return notOfType(each, "string");
309
+ if (draft === 4 && !value.length)
310
+ return "[] should be non-empty";
311
+ return unique(value) ? undefined : `${pyRepr(value)} has non-unique elements`;
312
+ case "additionalProperties":
313
+ if (draft === 4 && typeof value !== "boolean" && !isObject(value))
314
+ return notUnderAny(value); // a flag or a schema
315
+ if (!(draft === 4 && typeof value === "boolean"))
316
+ stack.push([value, at(key)]);
317
+ return undefined;
318
+ case "items":
319
+ if (Array.isArray(value) && draft < 2020) { // the tuple form: a non-empty list of schemas
320
+ return value.length ? schemas(key, value) : notUnderAny(value);
321
+ }
322
+ if (draft < 2020 && !isObject(value) && !(draft > 4 && typeof value === "boolean"))
323
+ return notUnderAny(value);
324
+ stack.push([value, at(key)]);
325
+ return undefined;
326
+ case "prefixItems":
327
+ return draft === 2020 ? schemas(key, value) : undefined;
328
+ case "anyOf":
329
+ case "oneOf":
330
+ case "allOf":
331
+ return schemas(key, value);
332
+ case "enum":
333
+ if (!Array.isArray(value))
334
+ return notOfType(value, "array");
335
+ if (draft === 4 && !value.length)
336
+ return "[] should be non-empty";
337
+ if (draft === 4 && !unique(value))
338
+ return `${pyRepr(value)} has non-unique elements`;
339
+ return undefined;
340
+ case "minimum":
341
+ case "maximum":
342
+ return isNumber(value) ? undefined : notOfType(value, "number");
343
+ case "exclusiveMinimum":
344
+ case "exclusiveMaximum": {
345
+ if (draft > 4)
346
+ return isNumber(value) ? undefined : notOfType(value, "number");
347
+ // draft-04: a flag on minimum / maximum
348
+ if (typeof value !== "boolean")
349
+ return notOfType(value, "boolean");
350
+ const bound = key === "exclusiveMinimum" ? "minimum" : "maximum";
351
+ return bound in node ? undefined : `${pyRepr(bound)} is a dependency of ${pyRepr(key)}`;
352
+ }
353
+ case "multipleOf":
354
+ if (!isNumber(value))
355
+ return notOfType(value, "number");
356
+ return value > 0 ? undefined : `${pyRepr(value)} is less than or equal to the minimum of 0`;
357
+ case "examples":
358
+ return draft === 4 || Array.isArray(value) ? undefined : notOfType(value, "array");
359
+ default:
360
+ break;
361
+ }
362
+ if (COUNTS.has(key)) {
363
+ if (!isNumber(value) || !Number.isInteger(value))
364
+ return notOfType(value, "integer");
365
+ return value >= 0 ? undefined : `${pyRepr(value)} is less than the minimum of 0`;
366
+ }
367
+ if (strings.has(key)) {
368
+ if (typeof value !== "string")
369
+ return notOfType(value, "string");
370
+ if (key === "$id" && draft >= 2019 && value.slice(0, -1).includes("#")) { // at most an empty fragment
371
+ return `${pyRepr(value)} does not match '^[^#]*#?$'`;
372
+ }
373
+ return undefined;
374
+ }
375
+ if (flags.has(key))
376
+ return typeof value === "boolean" ? undefined : notOfType(value, "boolean");
377
+ return undefined; // default, const: any value; a keyword this dialect does not define: not checked
378
+ };
379
+ // Checked in sorted order so the reported problem does not depend on key order (as in Python).
380
+ for (const key of Object.keys(node).sort()) {
381
+ const found = problem(key, node[key]);
382
+ if (found !== undefined)
383
+ return [found, at(key)];
384
+ }
385
+ return undefined;
386
+ }
387
+ /** The output type's JSON Schema with definitions inlined, an OpenAPI `discriminator` and a no-op
388
+ * `propertyNames: {type: "string"}` dropped, and a root `$schema` naming 2020-12 (what zod writes, and the server's
389
+ * default) dropped; throws UserError on what the server refuses. Another `$schema` is kept, so the server reads the
390
+ * schema in the dialect it names, and must be draft-04 to 2020-12. A zod `.regex()`, `z.email()`, `z.uuid()`,
391
+ * `z.url()` or `z.iso.datetime()` becomes a `pattern`, which it refuses. */
392
+ export function outputSchema(outputType) {
393
+ const raw = JSON.parse(JSON.stringify(isSchemaLike(outputType) ? outputType.toJSONSchema() : outputType.schema));
394
+ const defs = { ...(isObject(raw["$defs"]) ? raw["$defs"] : {}), ...(isObject(raw["definitions"]) ? raw["definitions"] : {}) };
395
+ delete raw["$defs"];
396
+ delete raw["definitions"];
397
+ if (typeof raw["$schema"] === "string" && dialectKey(raw["$schema"]) === LATEST_DIALECT)
398
+ delete raw["$schema"];
399
+ const schema = inline(raw, defs, new Set());
400
+ if (schema["type"] !== "object")
401
+ throw new UserError("outputType: the schema's root must be an object");
402
+ const size = new TextEncoder().encode(JSON.stringify(schema)).length;
403
+ if (size > MAX_BYTES)
404
+ throw new UserError(`outputType: the schema is ${size} bytes; the server allows at most ${MAX_BYTES}`);
405
+ if (schemaDepth(schema) > MAX_DEPTH) {
406
+ throw new UserError(`outputType: the schema is nested too deeply (more than ${MAX_DEPTH} levels)`);
407
+ }
408
+ const named = schema["$schema"];
409
+ const draft = named === undefined ? 2020 : typeof named === "string" ? DIALECTS[dialectKey(named)] : undefined;
410
+ if (draft === undefined) {
411
+ throw new UserError("outputType: the schema names a $schema other than JSON Schema draft-04 to 2020-12");
412
+ }
413
+ const [refusal, enumEntries] = screen(schema);
414
+ if (refusal !== undefined)
415
+ throw new UserError(`outputType: the schema ${refusal}`);
416
+ const invalid = metaProblem(schema, draft);
417
+ if (invalid !== undefined)
418
+ throw new UserError(`outputType: the schema is not a valid JSON Schema: ${invalid}`);
419
+ if (valueLoad(schema) - 1 > MAX_BRANCHES) {
420
+ throw new UserError(`outputType: the schema applies more than ${MAX_BRANCHES} anyOf/oneOf/allOf entries to the same ` +
421
+ "value (nested ones and those of enclosing objects add up); merge alternatives");
422
+ }
423
+ if (enumEntries > MAX_ENUM_ENTRIES) {
424
+ throw new UserError(`outputType: the schema has more than ${MAX_ENUM_ENTRIES} enum entries in total; use a plain ` +
425
+ "type and list the values in the instructions instead");
426
+ }
427
+ return schema;
428
+ }
429
+ /** `data-output`'s JSON as the output type's value; a schema-like type's `parse` must accept it, or this throws
430
+ * `ModelBehaviorError` with `source: "local_parse"` and the server's `note`. */
431
+ export function parseOutput(outputType, output, note) {
432
+ var _a;
433
+ if (!isSchemaLike(outputType))
434
+ return output;
435
+ try {
436
+ return outputType.parse(output);
437
+ }
438
+ catch (err) {
439
+ const issues = err.issues;
440
+ const errors = Array.isArray(issues) && issues.length
441
+ ? issues.slice(0, 3).map((i) => { var _a, _b; return `${((_a = i.path) !== null && _a !== void 0 ? _a : []).join(".") || "$"}: ${(_b = i.message) !== null && _b !== void 0 ? _b : "invalid"}`; })
442
+ : [String((_a = err.message) !== null && _a !== void 0 ? _a : err)];
443
+ throw new ModelBehaviorError(JSON.stringify(output), errors, note, "local_parse");
444
+ }
445
+ }
@@ -1,7 +1,8 @@
1
1
  /** run(): deploy the agent, drive one turn through a Transport, handle clarify questions, dropped streams and cancel. */
2
2
  import type { Configuration } from "../runtime.js";
3
3
  import type { Agent } from "./agent.js";
4
- import type { ClarifyQuestion, Event } from "./events.js";
4
+ import type { ClarifyQuestion, Event, OutputCitation } from "./events.js";
5
+ import type { OutputType, ResolvedOutput } from "./output.js";
5
6
  import { RunState } from "./runState.js";
6
7
  import type { Interruption } from "./runState.js";
7
8
  import type { Transport } from "./transport.js";
@@ -31,40 +32,59 @@ export type RunStreamEvent = {
31
32
  };
32
33
  /** Why the run ended early: the `limits` field whose cap the server hit. */
33
34
  export type StopReason = "max_turns" | "max_tool_calls" | "max_tokens";
34
- interface Outcome {
35
- finalOutput: string | undefined;
35
+ interface Outcome<T = string> {
36
+ finalOutput: T | undefined;
36
37
  outputText: string;
37
38
  newItems: Event[];
38
39
  interruptions: Interruption[];
39
40
  stopReason: StopReason | undefined;
40
41
  conversationId: string | undefined;
41
42
  cancelled: boolean;
43
+ outputCitations: OutputCitation[];
44
+ outputNote: string | undefined;
45
+ outputSkipped: string | undefined;
46
+ outputMode: string | undefined;
42
47
  }
43
- export declare class RunResult {
44
- readonly finalOutput: string | undefined;
48
+ export declare class RunResult<T = string> {
49
+ /** The reply text, or the parsed structured output when the agent has an `outputType`. */
50
+ readonly finalOutput: T | undefined;
45
51
  readonly outputText: string;
46
52
  readonly newItems: Event[];
47
53
  readonly interruptions: Interruption[];
48
- /** Set when an agent.json limit ended the turn; `finalOutput` still holds the wrap-up answer. */
54
+ /** Set when one of the agent's own `limits` ended the turn (the server sent `data-turn-limit`); `finalOutput`
55
+ * still holds the wrap-up answer. A default server cap leaves it undefined. */
49
56
  readonly stopReason: StopReason | undefined;
50
57
  readonly conversationId: string | undefined;
58
+ /** The sources the structured output cited: the server's citation-manifest entries, first citation first. */
59
+ readonly outputCitations: OutputCitation[];
60
+ /** `oversize_answer_invalid` / `oversize_answer_dropped` when the turn's `final_answer` was refused for size and
61
+ * was not the answer, so the output came from the model's later text. */
62
+ readonly outputNote: string | undefined;
63
+ /** Why an agent with an `outputType` has no structured output (`finalOutput` is undefined): `limit` (a turn cap
64
+ * ended the turn; `stopReason` names it only when the agent's own `limits` set it), `budget` (the seat budget ran
65
+ * out before the answer was formatted), `paused` (the turn stopped on a question) or `suppressed` (a scheduled
66
+ * turn ended silently). Passed through as sent; undefined when there is output. */
67
+ readonly outputSkipped: string | undefined;
68
+ /** How the server produced the structured output (`tool_in_loop`, `tool_oversize`, `forced_tool`, `native`,
69
+ * `prompted`), passed through as sent; undefined when there is none. */
70
+ readonly outputMode: string | undefined;
51
71
  /** @internal */
52
- constructor(outcome: Outcome);
72
+ constructor(outcome: Outcome<T>);
53
73
  /** A RunState to answer the interruptions and continue; throws UserError when the run has no conversation. */
54
74
  get state(): RunState;
55
75
  }
56
76
  interface Prepared {
57
- agent: Agent;
77
+ agent: Agent<OutputType | undefined>;
58
78
  input: string | RunState;
59
79
  opts: RunOptions;
60
80
  transport: Transport;
61
81
  owner: object;
62
82
  }
63
83
  /** Returned by `run(..., { stream: true })`. Iterate it once (or use `toTextStream()`); leaving early cancels. */
64
- export declare class StreamedRunResult implements AsyncIterable<RunStreamEvent> {
84
+ export declare class StreamedRunResult<T = string> implements AsyncIterable<RunStreamEvent> {
65
85
  /** Settles when the run ends; rejects with the run's error. */
66
86
  readonly completed: Promise<void>;
67
- finalOutput: string | undefined;
87
+ finalOutput: T | undefined;
68
88
  outputText: string;
69
89
  newItems: Event[];
70
90
  interruptions: Interruption[];
@@ -72,6 +92,11 @@ export declare class StreamedRunResult implements AsyncIterable<RunStreamEvent>
72
92
  stopReason: StopReason | undefined;
73
93
  conversationId: string | undefined;
74
94
  cancelled: boolean;
95
+ /** As on `RunResult`; read after `completed` settles. */
96
+ outputCitations: OutputCitation[];
97
+ outputNote: string | undefined;
98
+ outputSkipped: string | undefined;
99
+ outputMode: string | undefined;
75
100
  private readonly queue;
76
101
  private waiters;
77
102
  private done;
@@ -98,10 +123,10 @@ export declare class StreamedRunResult implements AsyncIterable<RunStreamEvent>
98
123
  * Run `agent` on `input` (a message, or a RunState holding answers), deploying it first if this owner has not
99
124
  * deployed this exact definition. With `stream: true`, resolves at once with a StreamedRunResult.
100
125
  */
101
- export declare function run(agent: Agent, input: string | RunState, opts: RunOptions & {
126
+ export declare function run<O extends OutputType | undefined = undefined>(agent: Agent<O>, input: string | RunState, opts: RunOptions & {
102
127
  stream: true;
103
- }): Promise<StreamedRunResult>;
104
- export declare function run(agent: Agent, input: string | RunState, opts?: RunOptions & {
128
+ }): Promise<StreamedRunResult<ResolvedOutput<O>>>;
129
+ export declare function run<O extends OutputType | undefined = undefined>(agent: Agent<O>, input: string | RunState, opts?: RunOptions & {
105
130
  stream?: false;
106
- }): Promise<RunResult>;
131
+ }): Promise<RunResult<ResolvedOutput<O>>>;
107
132
  export {};
@@ -1,6 +1,7 @@
1
1
  import { FetchError } from "../runtime.js";
2
2
  import { agentIdFor, getDefaultClient, resolveTransport } from "./deploy.js";
3
- import { NotSupportedError, RunError, UserError } from "./errors.js";
3
+ import { ModelBehaviorError, NotSupportedError, RunError, UserError } from "./errors.js";
4
+ import { parseOutput } from "./output.js";
4
5
  import { RunState } from "./runState.js";
5
6
  const MAX_RECONNECTS = 3;
6
7
  /** The abort reason ResponseStream (src/streaming.ts) uses when a stream goes quiet. */
@@ -25,6 +26,10 @@ export class RunResult {
25
26
  this.interruptions = outcome.interruptions;
26
27
  this.stopReason = outcome.stopReason;
27
28
  this.conversationId = outcome.conversationId;
29
+ this.outputCitations = outcome.outputCitations;
30
+ this.outputNote = outcome.outputNote;
31
+ this.outputSkipped = outcome.outputSkipped;
32
+ this.outputMode = outcome.outputMode;
28
33
  }
29
34
  /** A RunState to answer the interruptions and continue; throws UserError when the run has no conversation. */
30
35
  get state() {
@@ -105,6 +110,8 @@ class Loop {
105
110
  this.conversationId = null;
106
111
  this.items = [];
107
112
  this.stopReason = undefined;
113
+ /** The turn's structured output (`data-output` / `data-output-error`), when the agent has an `outputType`. */
114
+ this.output = undefined;
108
115
  // Text of the current segment, per text block. Kept per block so a resumed stream, which replays from the start
109
116
  // of the block it dropped in, doesn't repeat text.
110
117
  this.blocks = [];
@@ -252,6 +259,10 @@ class Loop {
252
259
  case "turn_limit":
253
260
  this.stopReason = STOP_REASONS[event.capKind];
254
261
  return false;
262
+ case "output":
263
+ case "output_error":
264
+ this.output = event;
265
+ return false;
255
266
  case "text_start":
256
267
  case "text_end":
257
268
  this.onText(event);
@@ -366,8 +377,18 @@ function link(signal, controller) {
366
377
  signal.addEventListener("abort", onAbort, { once: true });
367
378
  return () => signal.removeEventListener("abort", onAbort);
368
379
  }
380
+ /** `finalOutput` for an agent with an `outputType`: the parsed value, or undefined when the turn produced none
381
+ * (`outputSkipped` says why). A mismatch throws `ModelBehaviorError`. */
382
+ function structuredOutput(outputType, event) {
383
+ if ((event === null || event === void 0 ? void 0 : event.kind) === "output_error")
384
+ throw new ModelBehaviorError(event.rawText, event.errors, event.note);
385
+ if ((event === null || event === void 0 ? void 0 : event.kind) === "output" && event.output !== null && event.output !== undefined) {
386
+ return parseOutput(outputType, event.output, event.note);
387
+ }
388
+ return undefined;
389
+ }
369
390
  async function execute(p, controller, emit) {
370
- var _a, _b;
391
+ var _a, _b, _c, _d, _e, _f, _g, _h;
371
392
  const signal = controller.signal;
372
393
  const unlink = link(p.opts.signal, controller);
373
394
  const stopper = new Stopper(p.transport, signal);
@@ -403,14 +424,34 @@ async function execute(p, controller, emit) {
403
424
  }
404
425
  cancelled = cancelled || signal.aborted;
405
426
  const text = loop.text;
427
+ const outputType = p.agent.outputType;
428
+ let finalOutput;
429
+ if (interruptions.length || cancelled)
430
+ finalOutput = undefined;
431
+ else if (outputType !== undefined) {
432
+ try {
433
+ finalOutput = structuredOutput(outputType, loop.output);
434
+ }
435
+ catch (err) {
436
+ if (err instanceof ModelBehaviorError)
437
+ err.conversationId = (_b = loop.conversationId) !== null && _b !== void 0 ? _b : fallbackConversation;
438
+ throw err;
439
+ }
440
+ }
441
+ else
442
+ finalOutput = text;
406
443
  return {
407
- finalOutput: interruptions.length || cancelled ? undefined : text,
444
+ finalOutput,
408
445
  outputText: text,
409
446
  newItems: loop.items,
410
447
  interruptions,
411
448
  stopReason: loop.stopReason,
412
- conversationId: (_b = loop.conversationId) !== null && _b !== void 0 ? _b : fallbackConversation,
449
+ conversationId: (_c = loop.conversationId) !== null && _c !== void 0 ? _c : fallbackConversation,
413
450
  cancelled,
451
+ outputCitations: ((_d = loop.output) === null || _d === void 0 ? void 0 : _d.kind) === "output" ? ((_e = loop.output.citations) !== null && _e !== void 0 ? _e : []).slice() : [],
452
+ outputNote: (_f = loop.output) === null || _f === void 0 ? void 0 : _f.note,
453
+ outputSkipped: ((_g = loop.output) === null || _g === void 0 ? void 0 : _g.kind) === "output" ? loop.output.skipped : undefined,
454
+ outputMode: ((_h = loop.output) === null || _h === void 0 ? void 0 : _h.kind) === "output" ? loop.output.mode : undefined,
414
455
  };
415
456
  }
416
457
  // -- streaming ---------------------------------------------------------------------------------------------------
@@ -426,6 +467,11 @@ export class StreamedRunResult {
426
467
  this.stopReason = undefined;
427
468
  this.conversationId = undefined;
428
469
  this.cancelled = false;
470
+ /** As on `RunResult`; read after `completed` settles. */
471
+ this.outputCitations = [];
472
+ this.outputNote = undefined;
473
+ this.outputSkipped = undefined;
474
+ this.outputMode = undefined;
429
475
  this.queue = [];
430
476
  this.waiters = [];
431
477
  this.done = false;
@@ -441,6 +487,10 @@ export class StreamedRunResult {
441
487
  this.stopReason = outcome.stopReason;
442
488
  this.conversationId = outcome.conversationId;
443
489
  this.cancelled = outcome.cancelled;
490
+ this.outputCitations = outcome.outputCitations;
491
+ this.outputNote = outcome.outputNote;
492
+ this.outputSkipped = outcome.outputSkipped;
493
+ this.outputMode = outcome.outputMode;
444
494
  this.end();
445
495
  }, (error) => {
446
496
  this.failure = { error };