sarvam-agents-client 0.2.3 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (178) hide show
  1. package/README.md +16 -1
  2. package/dist/apis/AgentsApi.d.ts +4 -4
  3. package/dist/apis/AgentsApi.js +4 -4
  4. package/dist/apis/AppsApi.d.ts +1 -0
  5. package/dist/apis/AppsApi.js +3 -0
  6. package/dist/apis/FunctionToolsApi.d.ts +33 -0
  7. package/dist/apis/FunctionToolsApi.js +65 -0
  8. package/dist/apis/QueueApi.d.ts +1 -0
  9. package/dist/apis/QueueApi.js +3 -0
  10. package/dist/apis/ResponsesApi.d.ts +2 -0
  11. package/dist/apis/ResponsesApi.js +6 -0
  12. package/dist/apis/index.d.ts +1 -0
  13. package/dist/apis/index.js +1 -0
  14. package/dist/compose/agent.d.ts +26 -6
  15. package/dist/compose/agent.js +84 -7
  16. package/dist/compose/deploy.d.ts +3 -2
  17. package/dist/compose/errors.d.ts +22 -1
  18. package/dist/compose/errors.js +21 -1
  19. package/dist/compose/events.d.ts +38 -0
  20. package/dist/compose/events.js +59 -2
  21. package/dist/compose/functionTool.d.ts +101 -0
  22. package/dist/compose/functionTool.js +420 -0
  23. package/dist/compose/index.d.ts +7 -3
  24. package/dist/compose/index.js +3 -1
  25. package/dist/compose/output.d.ts +40 -0
  26. package/dist/compose/output.js +476 -0
  27. package/dist/compose/run.d.ts +44 -15
  28. package/dist/compose/run.js +164 -21
  29. package/dist/compose/runState.d.ts +28 -2
  30. package/dist/compose/runState.js +30 -0
  31. package/dist/compose/settingsTransport.d.ts +23 -3
  32. package/dist/compose/settingsTransport.js +295 -3
  33. package/dist/compose/transport.d.ts +21 -3
  34. package/dist/esm/apis/AgentsApi.d.ts +4 -4
  35. package/dist/esm/apis/AgentsApi.js +4 -4
  36. package/dist/esm/apis/AppsApi.d.ts +1 -0
  37. package/dist/esm/apis/AppsApi.js +3 -0
  38. package/dist/esm/apis/FunctionToolsApi.d.ts +33 -0
  39. package/dist/esm/apis/FunctionToolsApi.js +61 -0
  40. package/dist/esm/apis/QueueApi.d.ts +1 -0
  41. package/dist/esm/apis/QueueApi.js +3 -0
  42. package/dist/esm/apis/ResponsesApi.d.ts +2 -0
  43. package/dist/esm/apis/ResponsesApi.js +6 -0
  44. package/dist/esm/apis/index.d.ts +1 -0
  45. package/dist/esm/apis/index.js +1 -0
  46. package/dist/esm/compose/agent.d.ts +26 -6
  47. package/dist/esm/compose/agent.js +84 -7
  48. package/dist/esm/compose/deploy.d.ts +3 -2
  49. package/dist/esm/compose/errors.d.ts +22 -1
  50. package/dist/esm/compose/errors.js +21 -1
  51. package/dist/esm/compose/events.d.ts +38 -0
  52. package/dist/esm/compose/events.js +58 -2
  53. package/dist/esm/compose/functionTool.d.ts +101 -0
  54. package/dist/esm/compose/functionTool.js +406 -0
  55. package/dist/esm/compose/index.d.ts +7 -3
  56. package/dist/esm/compose/index.js +1 -0
  57. package/dist/esm/compose/output.d.ts +40 -0
  58. package/dist/esm/compose/output.js +466 -0
  59. package/dist/esm/compose/run.d.ts +44 -15
  60. package/dist/esm/compose/run.js +165 -22
  61. package/dist/esm/compose/runState.d.ts +28 -2
  62. package/dist/esm/compose/runState.js +31 -1
  63. package/dist/esm/compose/settingsTransport.d.ts +23 -3
  64. package/dist/esm/compose/settingsTransport.js +298 -7
  65. package/dist/esm/compose/transport.d.ts +21 -3
  66. package/dist/esm/models/AgentConversationDetail.d.ts +7 -0
  67. package/dist/esm/models/AgentConversationDetail.js +3 -0
  68. package/dist/esm/models/AppResource.d.ts +29 -0
  69. package/dist/esm/models/AppResource.js +16 -0
  70. package/dist/esm/models/AppToolsResponse.d.ts +3 -4
  71. package/dist/esm/models/AppToolsResponse.js +3 -2
  72. package/dist/esm/models/AppView.d.ts +48 -0
  73. package/dist/esm/models/AppView.js +23 -0
  74. package/dist/esm/models/ClarifyBody.d.ts +6 -0
  75. package/dist/esm/models/ClarifyBody.js +2 -0
  76. package/dist/esm/models/ConversationDetail.d.ts +7 -0
  77. package/dist/esm/models/ConversationDetail.js +3 -0
  78. package/dist/esm/models/ErrorDetail.d.ts +1 -0
  79. package/dist/esm/models/ErrorDetail.js +2 -1
  80. package/dist/esm/models/FunctionResultBody.d.ts +44 -0
  81. package/dist/esm/models/FunctionResultBody.js +49 -0
  82. package/dist/esm/models/McpSecurityAppealView.d.ts +50 -0
  83. package/dist/esm/models/McpSecurityAppealView.js +47 -0
  84. package/dist/esm/models/McpSecurityView.d.ts +105 -0
  85. package/dist/esm/models/McpSecurityView.js +66 -0
  86. package/dist/esm/models/MessagesResponse.d.ts +6 -0
  87. package/dist/esm/models/MessagesResponse.js +2 -0
  88. package/dist/esm/models/QueueMessageInput.d.ts +23 -0
  89. package/dist/esm/models/QueueMessageInput.js +14 -0
  90. package/dist/esm/models/RequiredAction.d.ts +77 -0
  91. package/dist/esm/models/RequiredAction.js +69 -0
  92. package/dist/esm/models/ResponseDetail.d.ts +40 -0
  93. package/dist/esm/models/ResponseDetail.js +12 -0
  94. package/dist/esm/models/ResponseInput.d.ts +23 -0
  95. package/dist/esm/models/ResponseInput.js +14 -0
  96. package/dist/esm/models/ToolResults200Response.d.ts +38 -0
  97. package/dist/esm/models/ToolResults200Response.js +47 -0
  98. package/dist/esm/models/ToolResultsBody.d.ts +39 -0
  99. package/dist/esm/models/ToolResultsBody.js +48 -0
  100. package/dist/esm/models/index.d.ts +6 -0
  101. package/dist/esm/models/index.js +6 -0
  102. package/dist/esm/streaming.d.ts +14 -2
  103. package/dist/esm/streaming.js +26 -4
  104. package/dist/models/AgentConversationDetail.d.ts +7 -0
  105. package/dist/models/AgentConversationDetail.js +3 -0
  106. package/dist/models/AppResource.d.ts +29 -0
  107. package/dist/models/AppResource.js +17 -1
  108. package/dist/models/AppToolsResponse.d.ts +3 -4
  109. package/dist/models/AppToolsResponse.js +3 -2
  110. package/dist/models/AppView.d.ts +48 -0
  111. package/dist/models/AppView.js +24 -1
  112. package/dist/models/ClarifyBody.d.ts +6 -0
  113. package/dist/models/ClarifyBody.js +2 -0
  114. package/dist/models/ConversationDetail.d.ts +7 -0
  115. package/dist/models/ConversationDetail.js +3 -0
  116. package/dist/models/ErrorDetail.d.ts +1 -0
  117. package/dist/models/ErrorDetail.js +2 -1
  118. package/dist/models/FunctionResultBody.d.ts +44 -0
  119. package/dist/models/FunctionResultBody.js +56 -0
  120. package/dist/models/McpSecurityAppealView.d.ts +50 -0
  121. package/dist/models/McpSecurityAppealView.js +54 -0
  122. package/dist/models/McpSecurityView.d.ts +105 -0
  123. package/dist/models/McpSecurityView.js +73 -0
  124. package/dist/models/MessagesResponse.d.ts +6 -0
  125. package/dist/models/MessagesResponse.js +2 -0
  126. package/dist/models/QueueMessageInput.d.ts +23 -0
  127. package/dist/models/QueueMessageInput.js +15 -1
  128. package/dist/models/RequiredAction.d.ts +77 -0
  129. package/dist/models/RequiredAction.js +77 -0
  130. package/dist/models/ResponseDetail.d.ts +40 -0
  131. package/dist/models/ResponseDetail.js +12 -0
  132. package/dist/models/ResponseInput.d.ts +23 -0
  133. package/dist/models/ResponseInput.js +15 -0
  134. package/dist/models/ToolResults200Response.d.ts +38 -0
  135. package/dist/models/ToolResults200Response.js +54 -0
  136. package/dist/models/ToolResultsBody.d.ts +39 -0
  137. package/dist/models/ToolResultsBody.js +55 -0
  138. package/dist/models/index.d.ts +6 -0
  139. package/dist/models/index.js +6 -0
  140. package/dist/streaming.d.ts +14 -2
  141. package/dist/streaming.js +27 -4
  142. package/package.json +4 -3
  143. package/src/apis/AgentsApi.ts +4 -4
  144. package/src/apis/AppsApi.ts +5 -0
  145. package/src/apis/FunctionToolsApi.ts +102 -0
  146. package/src/apis/QueueApi.ts +5 -0
  147. package/src/apis/ResponsesApi.ts +10 -0
  148. package/src/apis/index.ts +1 -0
  149. package/src/compose/agent.ts +108 -15
  150. package/src/compose/deploy.ts +6 -5
  151. package/src/compose/errors.ts +35 -2
  152. package/src/compose/events.ts +79 -1
  153. package/src/compose/functionTool.ts +441 -0
  154. package/src/compose/index.ts +7 -3
  155. package/src/compose/output.ts +436 -0
  156. package/src/compose/run.ts +208 -39
  157. package/src/compose/runState.ts +46 -6
  158. package/src/compose/settingsTransport.ts +297 -10
  159. package/src/compose/transport.ts +27 -3
  160. package/src/models/AgentConversationDetail.ts +15 -0
  161. package/src/models/AppResource.ts +42 -0
  162. package/src/models/AppToolsResponse.ts +11 -4
  163. package/src/models/AppView.ts +73 -0
  164. package/src/models/ClarifyBody.ts +8 -0
  165. package/src/models/ConversationDetail.ts +15 -0
  166. package/src/models/ErrorDetail.ts +2 -1
  167. package/src/models/FunctionResultBody.ts +83 -0
  168. package/src/models/McpSecurityAppealView.ts +89 -0
  169. package/src/models/McpSecurityView.ts +169 -0
  170. package/src/models/MessagesResponse.ts +8 -0
  171. package/src/models/QueueMessageInput.ts +28 -0
  172. package/src/models/RequiredAction.ts +128 -0
  173. package/src/models/ResponseDetail.ts +48 -0
  174. package/src/models/ResponseInput.ts +30 -0
  175. package/src/models/ToolResults200Response.ts +75 -0
  176. package/src/models/ToolResultsBody.ts +83 -0
  177. package/src/models/index.ts +6 -0
  178. package/src/streaming.ts +39 -3
@@ -0,0 +1,436 @@
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
+ export 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>, label = "outputType"): unknown {
90
+ if (Array.isArray(node)) return node.map((v) => inline(v, defs, seen, label));
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(`${label}: ${name} is recursive; the server accepts no references`);
97
+ if (!(name in defs)) throw new UserError(`${label}: ${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]), label);
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, label);
114
+ out[key] = map;
115
+ } else out[key] = inline(value, defs, seen, label);
116
+ }
117
+ return out;
118
+ }
119
+
120
+ /** A JSON Schema (a copy) with every `$defs`/`definitions` entry inlined and `$schema` dropped (function tools'
121
+ * `parameters`). `label` names the field in the UserError a recursive or dangling reference raises. */
122
+ export function inlineSchema(schema: Record<string, unknown>, label: string): Record<string, unknown> {
123
+ const raw = JSON.parse(JSON.stringify(schema)) as Record<string, unknown>;
124
+ const defs = { ...(isObject(raw["$defs"]) ? raw["$defs"] : {}), ...(isObject(raw["definitions"]) ? raw["definitions"] : {}) };
125
+ delete raw["$defs"];
126
+ delete raw["definitions"];
127
+ delete raw["$schema"];
128
+ return inline(raw, defs, new Set(), label) as Record<string, unknown>;
129
+ }
130
+
131
+ /** Nesting depth of a JSON value, counted like the server: the root is 1. */
132
+ export function schemaDepth(node: unknown): number {
133
+ let deepest = 0;
134
+ const stack: [unknown, number][] = [[node, 1]];
135
+ while (stack.length) {
136
+ const [value, depth] = stack.pop() as [unknown, number];
137
+ deepest = Math.max(deepest, depth);
138
+ if (depth > MAX_DEPTH) break;
139
+ if (Array.isArray(value)) for (const v of value) stack.push([v, depth + 1]);
140
+ else if (isObject(value)) for (const v of Object.values(value)) stack.push([v, depth + 1]);
141
+ }
142
+ return deepest;
143
+ }
144
+
145
+ /** Subschemas of `node` that apply to the members of its value (each member gets at most one of them). */
146
+ function children(node: Record<string, unknown>): unknown[] {
147
+ const out: unknown[] = [];
148
+ if (isObject(node["properties"])) out.push(...Object.values(node["properties"]));
149
+ if (isObject(node["items"])) out.push(node["items"]);
150
+ else if (Array.isArray(node["items"])) out.push(...node["items"]); // the tuple form of drafts before 2020-12
151
+ if (isObject(node["additionalProperties"])) out.push(node["additionalProperties"]);
152
+ if (Array.isArray(node["prefixItems"])) out.push(...node["prefixItems"]);
153
+ return out;
154
+ }
155
+
156
+ /** Every schema position under `node`; property names and enum/const/default/examples values are data. */
157
+ function subschemas(node: Record<string, unknown>): unknown[] {
158
+ const out = children(node);
159
+ for (const key of BRANCH_LISTS) if (Array.isArray(node[key])) out.push(...(node[key] as unknown[]));
160
+ return out;
161
+ }
162
+
163
+ /** Most subschemas of `node` (itself included) that apply to one value, computed as the server does. */
164
+ function valueLoad(node: unknown): number {
165
+ const sameValue: unknown[] = [];
166
+ const stack: unknown[] = [node];
167
+ while (stack.length) {
168
+ const each = stack.pop();
169
+ sameValue.push(each);
170
+ if (isObject(each)) for (const key of BRANCH_LISTS) if (Array.isArray(each[key])) stack.push(...(each[key] as unknown[]));
171
+ }
172
+ let below = 0;
173
+ for (const each of sameValue) {
174
+ if (isObject(each)) below += Math.max(0, ...children(each).map(valueLoad));
175
+ }
176
+ return Math.max(sameValue.length, below);
177
+ }
178
+
179
+ function shown(keyword: string): string {
180
+ return JSON.stringify(keyword.length > KEYWORD_SHOWN_MAX ? keyword.slice(0, KEYWORD_SHOWN_MAX) + "..." : keyword);
181
+ }
182
+
183
+ function isEnumScalar(v: unknown): boolean {
184
+ return v === null || ["string", "number", "boolean"].includes(typeof v);
185
+ }
186
+
187
+ /** [why a keyword is refused or undefined, enum entries], walked as the server walks. */
188
+ function screen(schema: Record<string, unknown>): [string | undefined, number] {
189
+ let enumEntries = 0;
190
+ const stack: [unknown, boolean][] = [[schema, true]];
191
+ while (stack.length) {
192
+ const [node, isRoot] = stack.pop() as [unknown, boolean];
193
+ if (!isObject(node)) continue;
194
+ for (const key of Object.keys(node)) {
195
+ if (ROOT_ONLY.has(key) && !isRoot) return [`uses ${shown(key)} below the root, which the server doesn't support`, 0];
196
+ if (!ALLOWED.has(key) && !ROOT_ONLY.has(key)) {
197
+ return [`uses ${shown(key)}, which the server doesn't support in output_schema (allowed: type, properties, ` +
198
+ "required, additionalProperties, items, prefixItems, anyOf, oneOf, allOf, enum, const, numeric/length/count " +
199
+ "limits, format and annotations)", 0];
200
+ }
201
+ }
202
+ const en = node["enum"];
203
+ if (Array.isArray(en)) {
204
+ if (!en.every(isEnumScalar)) {
205
+ return ["lists an object or array in enum, which the server doesn't support; enum may list only strings, " +
206
+ "numbers, booleans and null", 0];
207
+ }
208
+ enumEntries += en.length;
209
+ }
210
+ for (const child of subschemas(node)) stack.push([child, false]);
211
+ }
212
+ return [undefined, enumEntries];
213
+ }
214
+
215
+ /** `uri` normalized as the server's JSON Schema library looks dialects up (Python's `urlsplit(uri).geturl()`): the
216
+ * scheme lowercased and an empty query or fragment dropped. */
217
+ function dialectKey(uri: string): string {
218
+ let out = uri.replace(/[\t\r\n]/g, "").replace(/^[\x00-\x20]+/, "");
219
+ const scheme = /^([A-Za-z][A-Za-z0-9+.-]*):/.exec(out);
220
+ if (scheme) out = scheme[1].toLowerCase() + out.slice(scheme[1].length);
221
+ if (out.endsWith("#")) out = out.slice(0, -1);
222
+ if (out.endsWith("?")) out = out.slice(0, -1);
223
+ return out;
224
+ }
225
+
226
+ // -- the meta-schema check ---------------------------------------------------------------------------------------
227
+ // After the allowlist the server runs `validator_for(schema).check_schema(schema)`: the schema must be valid under its
228
+ // dialect's meta-schema. This checks the same rules for the allowlisted keywords (the only ones the screen lets
229
+ // through), per dialect, with the server's messages (which show values as Python writes them). Keywords a dialect does
230
+ // not define (`prefixItems` before 2020-12, `const` in draft-04...) are not checked, as the server does not check them.
231
+
232
+ /** `value` as the server's messages show it: Python's repr of the JSON value. */
233
+ function pyRepr(value: unknown): string {
234
+ if (value === null) return "None";
235
+ if (value === true) return "True";
236
+ if (value === false) return "False";
237
+ if (typeof value === "number") return String(value);
238
+ if (typeof value === "string") {
239
+ const quote = value.includes("'") && !value.includes('"') ? '"' : "'";
240
+ const body = value.replace(/\\/g, "\\\\").replace(/\n/g, "\\n").replace(/\r/g, "\\r").replace(/\t/g, "\\t");
241
+ return quote + (quote === "'" ? body.replace(/'/g, "\\'") : body) + quote;
242
+ }
243
+ if (Array.isArray(value)) return "[" + value.map(pyRepr).join(", ") + "]";
244
+ if (isObject(value)) return "{" + Object.entries(value).map(([k, v]) => `${pyRepr(k)}: ${pyRepr(v)}`).join(", ") + "}";
245
+ return String(value);
246
+ }
247
+
248
+ function isNumber(v: unknown): v is number {
249
+ return typeof v === "number";
250
+ }
251
+
252
+ /** A value's identity for uniqueness, as the server compares: `1` equals `1.0`, `true` is not `1`. */
253
+ /** A canonical key for a JSON value: equal keys for equal values, key order ignored. */
254
+ export function sameKey(v: unknown): string {
255
+ if (Array.isArray(v)) return "[" + v.map(sameKey).join(",") + "]";
256
+ if (isObject(v)) return "{" + Object.keys(v).sort().map((k) => JSON.stringify(k) + ":" + sameKey(v[k])).join(",") + "}";
257
+ return JSON.stringify(v);
258
+ }
259
+
260
+ function unique(values: unknown[]): boolean {
261
+ return new Set(values.map(sameKey)).size === values.length;
262
+ }
263
+
264
+ /** Why `schema` fails its dialect's meta-schema (allowlisted keywords only), or undefined. */
265
+ /** Why `schema` is not a valid JSON Schema for its `$schema` dialect (2020-12 when absent or unknown, as the server's
266
+ * `validator_for` picks), or undefined. Checks the keywords the output-schema allowlist knows; others pass. */
267
+ export function schemaProblem(schema: Record<string, unknown>): string | undefined {
268
+ const uri = schema["$schema"];
269
+ if (uri !== undefined && typeof uri !== "string") return "$schema must be a dialect URI string";
270
+ const draft = typeof uri === "string" ? DIALECTS[dialectKey(uri)] ?? 2020 : 2020;
271
+ return metaProblem(schema, draft);
272
+ }
273
+
274
+ function metaProblem(schema: unknown, draft: number): string | undefined {
275
+ const stack: [unknown, string][] = [[schema, ""]];
276
+ while (stack.length) {
277
+ const [node, path] = stack.pop() as [unknown, string];
278
+ const found = nodeProblem(node, draft, stack, path);
279
+ if (found) return found[0] + (found[1] ? ` (at ${found[1]})` : "");
280
+ }
281
+ return undefined;
282
+ }
283
+
284
+ /** [why, where] when one schema position is invalid; pushes its subschemas on `stack`. */
285
+ function nodeProblem(node: unknown, draft: number, stack: [unknown, string][], path: string): [string, string] | undefined {
286
+ if (typeof node === "boolean" && draft > 4) return undefined;
287
+ if (!isObject(node)) return [`${pyRepr(node)} is not of type ${draft === 4 ? "'object'" : "'object', 'boolean'"}`, path];
288
+ const at = (...parts: (string | number)[]) => [...(path ? [path] : []), ...parts.map(String)].join("/");
289
+ const notOfType = (v: unknown, t: string) => `${pyRepr(v)} is not of type '${t}'`;
290
+ const notUnderAny = (v: unknown) => `${pyRepr(v)} is not valid under any of the given schemas`;
291
+ const schemas = (key: string, value: unknown): string | undefined => {
292
+ if (!Array.isArray(value)) return notOfType(value, "array");
293
+ if (!value.length) return "[] should be non-empty";
294
+ value.forEach((child, n) => stack.push([child, at(key, n)]));
295
+ return undefined;
296
+ };
297
+ const strings = new Set(["format", "title", "description", "$schema"]);
298
+ if (draft > 4) strings.add("$id");
299
+ if (draft > 6) strings.add("$comment");
300
+ const flags = new Set<string>();
301
+ if (draft > 6) flags.add("readOnly");
302
+ if (draft > 7) { flags.add("deprecated"); flags.add("writeOnly"); }
303
+
304
+ const problem = (key: string, value: unknown): string | undefined => {
305
+ switch (key) {
306
+ case "type": {
307
+ const ok = typeof value === "string" ? SIMPLE_TYPES.has(value)
308
+ : Array.isArray(value) && value.length > 0 && value.every((t) => typeof t === "string" && SIMPLE_TYPES.has(t)) && unique(value);
309
+ return ok ? undefined : notUnderAny(value);
310
+ }
311
+ case "properties":
312
+ if (!isObject(value)) return notOfType(value, "object");
313
+ for (const [name, child] of Object.entries(value)) stack.push([child, at(key, name)]);
314
+ return undefined;
315
+ case "required":
316
+ if (!Array.isArray(value)) return notOfType(value, "array");
317
+ for (const each of value) if (typeof each !== "string") return notOfType(each, "string");
318
+ if (draft === 4 && !value.length) return "[] should be non-empty";
319
+ return unique(value) ? undefined : `${pyRepr(value)} has non-unique elements`;
320
+ case "additionalProperties":
321
+ if (draft === 4 && typeof value !== "boolean" && !isObject(value)) return notUnderAny(value); // a flag or a schema
322
+ if (!(draft === 4 && typeof value === "boolean")) 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")) return notUnderAny(value);
329
+ stack.push([value, at(key)]);
330
+ return undefined;
331
+ case "prefixItems":
332
+ return draft === 2020 ? schemas(key, value) : undefined;
333
+ case "anyOf":
334
+ case "oneOf":
335
+ case "allOf":
336
+ return schemas(key, value);
337
+ case "enum":
338
+ if (!Array.isArray(value)) return notOfType(value, "array");
339
+ if (draft === 4 && !value.length) return "[] should be non-empty";
340
+ if (draft === 4 && !unique(value)) return `${pyRepr(value)} has non-unique elements`;
341
+ return undefined;
342
+ case "minimum":
343
+ case "maximum":
344
+ return isNumber(value) ? undefined : notOfType(value, "number");
345
+ case "exclusiveMinimum":
346
+ case "exclusiveMaximum": {
347
+ if (draft > 4) return isNumber(value) ? undefined : notOfType(value, "number");
348
+ // draft-04: a flag on minimum / maximum
349
+ if (typeof value !== "boolean") 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)) return notOfType(value, "number");
355
+ return value > 0 ? undefined : `${pyRepr(value)} is less than or equal to the minimum of 0`;
356
+ case "examples":
357
+ return draft === 4 || Array.isArray(value) ? undefined : notOfType(value, "array");
358
+ default:
359
+ break;
360
+ }
361
+ if (COUNTS.has(key)) {
362
+ if (!isNumber(value) || !Number.isInteger(value)) return notOfType(value, "integer");
363
+ return value >= 0 ? undefined : `${pyRepr(value)} is less than the minimum of 0`;
364
+ }
365
+ if (strings.has(key)) {
366
+ if (typeof value !== "string") return notOfType(value, "string");
367
+ if (key === "$id" && draft >= 2019 && value.slice(0, -1).includes("#")) { // at most an empty fragment
368
+ return `${pyRepr(value)} does not match '^[^#]*#?$'`;
369
+ }
370
+ return undefined;
371
+ }
372
+ if (flags.has(key)) return typeof value === "boolean" ? undefined : notOfType(value, "boolean");
373
+ return undefined; // default, const: any value; a keyword this dialect does not define: not checked
374
+ };
375
+
376
+ // Checked in sorted order so the reported problem does not depend on key order (as in Python).
377
+ for (const key of Object.keys(node).sort()) {
378
+ const found = problem(key, node[key]);
379
+ if (found !== undefined) return [found, at(key)];
380
+ }
381
+ return undefined;
382
+ }
383
+
384
+ /** The output type's JSON Schema with definitions inlined, an OpenAPI `discriminator` and a no-op
385
+ * `propertyNames: {type: "string"}` dropped, and a root `$schema` naming 2020-12 (what zod writes, and the server's
386
+ * default) dropped; throws UserError on what the server refuses. Another `$schema` is kept, so the server reads the
387
+ * schema in the dialect it names, and must be draft-04 to 2020-12. A zod `.regex()`, `z.email()`, `z.uuid()`,
388
+ * `z.url()` or `z.iso.datetime()` becomes a `pattern`, which it refuses. */
389
+ export function outputSchema(outputType: OutputType): Record<string, unknown> {
390
+ const raw = JSON.parse(JSON.stringify(
391
+ isSchemaLike(outputType) ? outputType.toJSONSchema() : (outputType as JsonSchemaOutputType).schema)) as Record<string, unknown>;
392
+ const defs = { ...(isObject(raw["$defs"]) ? raw["$defs"] : {}), ...(isObject(raw["definitions"]) ? raw["definitions"] : {}) };
393
+ delete raw["$defs"];
394
+ delete raw["definitions"];
395
+ if (typeof raw["$schema"] === "string" && dialectKey(raw["$schema"]) === LATEST_DIALECT) delete raw["$schema"];
396
+ const schema = inline(raw, defs, new Set()) as Record<string, unknown>;
397
+ if (schema["type"] !== "object") throw new UserError("outputType: the schema's root must be an object");
398
+ const size = new TextEncoder().encode(JSON.stringify(schema)).length;
399
+ if (size > MAX_BYTES) throw new UserError(`outputType: the schema is ${size} bytes; the server allows at most ${MAX_BYTES}`);
400
+ if (schemaDepth(schema) > MAX_DEPTH) {
401
+ throw new UserError(`outputType: the schema is nested too deeply (more than ${MAX_DEPTH} levels)`);
402
+ }
403
+ const named = schema["$schema"];
404
+ const draft = named === undefined ? 2020 : typeof named === "string" ? DIALECTS[dialectKey(named)] : undefined;
405
+ if (draft === undefined) {
406
+ throw new UserError("outputType: the schema names a $schema other than JSON Schema draft-04 to 2020-12");
407
+ }
408
+ const [refusal, enumEntries] = screen(schema);
409
+ if (refusal !== undefined) throw new UserError(`outputType: the schema ${refusal}`);
410
+ const invalid = metaProblem(schema, draft);
411
+ if (invalid !== undefined) throw new UserError(`outputType: the schema is not a valid JSON Schema: ${invalid}`);
412
+ if (valueLoad(schema) - 1 > MAX_BRANCHES) {
413
+ throw new UserError(`outputType: the schema applies more than ${MAX_BRANCHES} anyOf/oneOf/allOf entries to the same ` +
414
+ "value (nested ones and those of enclosing objects add up); merge alternatives");
415
+ }
416
+ if (enumEntries > MAX_ENUM_ENTRIES) {
417
+ throw new UserError(`outputType: the schema has more than ${MAX_ENUM_ENTRIES} enum entries in total; use a plain ` +
418
+ "type and list the values in the instructions instead");
419
+ }
420
+ return schema;
421
+ }
422
+
423
+ /** `data-output`'s JSON as the output type's value; a schema-like type's `parse` must accept it, or this throws
424
+ * `ModelBehaviorError` with `source: "local_parse"` and the server's `note`. */
425
+ export function parseOutput(outputType: OutputType, output: unknown, note?: string): unknown {
426
+ if (!isSchemaLike(outputType)) return output;
427
+ try {
428
+ return outputType.parse(output);
429
+ } catch (err) {
430
+ const issues = (err as { issues?: { path?: unknown[]; message?: string }[] }).issues;
431
+ const errors = Array.isArray(issues) && issues.length
432
+ ? issues.slice(0, 3).map((i) => `${(i.path ?? []).join(".") || "$"}: ${i.message ?? "invalid"}`)
433
+ : [String((err as Error).message ?? err)];
434
+ throw new ModelBehaviorError(JSON.stringify(output), errors, note, "local_parse");
435
+ }
436
+ }