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