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