@aeye/schema 0.0.0-stage → 0.10.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.
@@ -0,0 +1,2458 @@
1
+ /**
2
+ * Type-level machinery for `@aeye/schema`.
3
+ *
4
+ * Every schema class carries two phantom types:
5
+ *
6
+ * - `_out` — the CODE shape the caller gets after decoding. A reference to a
7
+ * named type that is not known yet (`a.ref('Node')`) appears in `_out` as a
8
+ * `RefMarker<'Node'>` placeholder.
9
+ * - `_refs` — the union of ref names used anywhere below the schema. The chain
10
+ * (`define → dynamic → result`) uses it to prove at compile time that every
11
+ * ref is defined, statically or by the dynamic step.
12
+ *
13
+ * When the chain ends, `Resolve<Out, Env>` swaps every placeholder for the
14
+ * named type's own (resolved) output. Mapped types are evaluated lazily per
15
+ * property, so recursive named types (Node → Node[]) resolve to a finite,
16
+ * cyclic TypeScript type instead of an infinite expansion.
17
+ */
18
+ declare const REF: unique symbol;
19
+ declare const BRAND: unique symbol;
20
+ /** Placeholder for "the output of named type `N`", swapped out by `Resolve`. */
21
+ interface RefMarker<N extends string> {
22
+ readonly [REF]: N;
23
+ }
24
+ /** Nominal tag added by `.brand<B>()`. */
25
+ interface Brand<B extends string> {
26
+ readonly [BRAND]: {
27
+ readonly [K in B]: true;
28
+ };
29
+ }
30
+ type Primitive = string | number | boolean | bigint | symbol | null | undefined;
31
+ /**
32
+ * Replace every `RefMarker<N>` in `T` with the resolved output of `Env[N]`.
33
+ * Distributes over unions; leaves primitives (and branded primitives) alone.
34
+ * A marker whose name is not in `Env` resolves to `never` — the chain's
35
+ * checks make that unreachable for anything it returns.
36
+ */
37
+ type Resolve<T, Env> = unknown extends T ? T : T extends RefMarker<infer N> ? (N extends keyof Env ? Resolve<Env[N], Env> : never) : T extends Primitive ? T : T extends readonly unknown[] ? ResolveArray<T, Env> : {
38
+ [K in keyof T]: Resolve<T[K], Env>;
39
+ };
40
+ type ResolveArray<T extends readonly unknown[], Env> = number extends T['length'] ? (T extends unknown[] ? Resolve<T[number], Env>[] : readonly Resolve<T[number], Env>[]) : {
41
+ [K in keyof T]: Resolve<T[K], Env>;
42
+ };
43
+ /**
44
+ * `T` where any position may instead be a not-yet-resolved ref. A dynamic
45
+ * step's schema for a declared ref is checked against this (it may use refs,
46
+ * itself included); the exact check after resolution happens at `result`.
47
+ */
48
+ type AllowRefs<T> = RefMarker<string> | (unknown extends T ? T : T extends Primitive ? T : T extends readonly (infer E)[] ? AllowRefs<E>[] : {
49
+ [K in keyof T]: AllowRefs<T[K]>;
50
+ });
51
+ /** Same as `Resolve`, but an unknown name becomes `unknown` (used for examples/refinements typed before the chain closes). */
52
+ type Loose<T> = unknown extends T ? T : T extends RefMarker<string> ? unknown : T extends Primitive ? T : T extends readonly unknown[] ? Loose<T[number]>[] : {
53
+ [K in keyof T]: Loose<T[K]>;
54
+ };
55
+ /** Flatten intersections for readable hovers. */
56
+ type Simplify<T> = {
57
+ [K in keyof T]: T[K];
58
+ } & {};
59
+ /** Merge two records, right wins (used by `define` chains). */
60
+ type Merge<A, B> = Simplify<Omit<A, keyof B> & B>;
61
+ /** A JSON value. */
62
+ type JsonValue = string | number | boolean | null | JsonValue[] | {
63
+ [key: string]: JsonValue;
64
+ };
65
+ /**
66
+ * A compile-time error carried in a parameter type. The property name is the
67
+ * message and its value names the offending refs, so the TypeScript error
68
+ * reads e.g. `Property '"unresolved ref"' is missing ... { "unresolved ref": "Ghost" }`.
69
+ */
70
+ type SchemaError<Message extends string, Detail> = {
71
+ readonly [K in Message]: Detail;
72
+ };
73
+
74
+ /**
75
+ * Profiles: what one model can read, for one kind of schema (tool arguments
76
+ * or structured output), strict or not.
77
+ *
78
+ * A profile is the successor of core's `FormatDescriptor`: the same facts,
79
+ * fewer knobs, and every field is read by exactly one place in rendering.
80
+ * Rendering, decoding, validation, error paths, examples, descriptions and
81
+ * the request budget ALL read the same profile, so they can never disagree
82
+ * about the shape the model sees.
83
+ *
84
+ * The built-in table below is sourced from each provider's own docs (the
85
+ * short keys, e.g. [OAI-SO], are the URLs in `docs/plans/schema-dialects-2026.md`,
86
+ * read 2026-11-04) and from what aeye's providers measured live
87
+ * (`packages/core/src/schema/dialects/*`, `packages/test-integration`
88
+ * live-schema run 2026-11-04/05). Pick one with `profileFor(model)`, which
89
+ * reads the model's `@aeye/models` capabilities; never hard-code a profile
90
+ * at a call site.
91
+ *
92
+ * "Strict models see pairs" is NOT a rule of strictness. A record is written
93
+ * as `[{key, value}]` only where the dialect forbids a schema-valued
94
+ * `additionalProperties`: OpenAI strict and Anthropic strict (both require
95
+ * `additionalProperties: false` [OAI-SO, ANT-SO]) and Gemini's OpenAPI
96
+ * subset (no `additionalProperties` at all [GEM-REF]). xAI strict and
97
+ * Gemini's JSON Schema mode are strict and still take open records
98
+ * [XAI-SO, GEM-SO], so their models see plain objects.
99
+ */
100
+ /** Provider family of a profile. Any string is allowed for custom profiles. */
101
+ type ProfileFamily = 'lenient' | 'people' | 'openai' | 'anthropic' | 'google' | 'xai' | 'ollama' | (string & {});
102
+ /** Which constraint keywords the dialect accepts. Anything it lacks is said in words and still validated. */
103
+ interface ConstraintSupport {
104
+ /** `minLength` / `maxLength`. */
105
+ readonly length: boolean;
106
+ /** `minimum` / `maximum`. */
107
+ readonly range: boolean;
108
+ /** `minItems` / `maxItems`: all, only `minItems` of 0 or 1 (Anthropic), or none. */
109
+ readonly items: 'all' | 'min-0-1' | 'none';
110
+ /**
111
+ * `pattern`: any regex (`full`), the common subset only (`basic`: no
112
+ * lookaround, backreferences, `\b`, `\p{…}` or large `{n,m}`), or none.
113
+ * A pattern outside the subset is said in words.
114
+ */
115
+ readonly pattern: 'full' | 'basic' | 'none';
116
+ }
117
+ /**
118
+ * Documented ceilings on the SIZE of one schema. Used per schema
119
+ * (`Profile.limits`) and, where a provider sums them over the whole request,
120
+ * as request totals (`RequestLimits.totals`).
121
+ */
122
+ interface SchemaLimits {
123
+ /** Object properties, summed over every level (a pairs record counts its `key` and `value`). */
124
+ readonly maxProperties?: number;
125
+ /** Levels of nested objects/arrays below the root. */
126
+ readonly maxDepth?: number;
127
+ /** Characters over property names, `$defs` names, enum values and const values. */
128
+ readonly maxStringChars?: number;
129
+ /** Enum values summed over every enum. */
130
+ readonly maxEnumValues?: number;
131
+ /** An enum with more values than this is a "large enum"... */
132
+ readonly largeEnumValues?: number;
133
+ /** ...whose string values may total at most this many characters. */
134
+ readonly maxLargeEnumChars?: number;
135
+ /** Optional properties (not in `required`), summed. */
136
+ readonly maxOptional?: number;
137
+ /** Schema nodes with a union type (`anyOf`, or a `type` array), summed. */
138
+ readonly maxUnions?: number;
139
+ }
140
+ /** Limits a provider applies to a whole request, across every schema in it. */
141
+ interface RequestLimits {
142
+ /** Tools in one request, strict or not. */
143
+ readonly maxTools?: number;
144
+ /** Tools sent with `strict: true`. */
145
+ readonly maxStrictTools?: number;
146
+ /** Totals over every STRICT schema in the request (tools and the output). */
147
+ readonly totals?: SchemaLimits;
148
+ }
149
+ interface Profile {
150
+ /** Stable id; the memo key for rendered schemas. */
151
+ readonly id: string;
152
+ readonly family: ProfileFamily;
153
+ /** The schema is compiled into a grammar (sent with `strict: true` / as strict structured output). */
154
+ readonly strict: boolean;
155
+ /**
156
+ * How an optional object field is written.
157
+ * - `omit`: it may be left out (`required` lists the required ones).
158
+ * - `null`: every field is required and an absent value is written `null`
159
+ * (OpenAI strict: "every property must be listed" [OAI-SO]). Decoding
160
+ * turns that `null` back into an ABSENT key.
161
+ */
162
+ readonly optional: 'omit' | 'null';
163
+ /** Emit `additionalProperties: false` on every object. */
164
+ readonly closedObjects: boolean;
165
+ /**
166
+ * How `a.record(V)` is written: an open object
167
+ * (`additionalProperties: V`) or `[{key, value}]` pairs, for dialects that
168
+ * forbid a schema-valued `additionalProperties`.
169
+ */
170
+ readonly records: 'open' | 'pairs';
171
+ /**
172
+ * How `a.tuple([...])` is written: `prefixItems`; `object` (`{"0": A, "1": B}`,
173
+ * OpenAI strict has no `prefixItems`); or `array` (`items: anyOf`, positions
174
+ * checked on decode).
175
+ */
176
+ readonly tuples: 'prefixItems' | 'object' | 'array';
177
+ /** `anyOf`, or `tagged` (one nullable field per option) for dialects with no combinators. */
178
+ readonly unions: 'anyOf' | 'tagged';
179
+ /**
180
+ * How `T | null` is spelled: a `type` array (`["string","null"]`), `anyOf`
181
+ * with `{type:"null"}` (o3 rejects type arrays in strict tools, measured
182
+ * 2026-11-04), or OpenAPI's `nullable: true` (Gemini `responseSchema`).
183
+ */
184
+ readonly nulls: 'type-array' | 'anyOf' | 'nullable';
185
+ /** `allOf` is accepted. Without it an intersection of objects is merged; anything else is said in words. */
186
+ readonly allOf: boolean;
187
+ /** `not` and `if`/`then`/`else` are accepted. Without them they are said in words (and always validated). */
188
+ readonly conditionals: boolean;
189
+ /** `patternProperties` is accepted. */
190
+ readonly patternProperties: boolean;
191
+ /** Named types may go to `$defs` and be used by `$ref`. Off → inlined. */
192
+ readonly defs: boolean;
193
+ /**
194
+ * Whether a `$ref` may carry a description, title or examples beside it. `false` (OpenAI strict: "$ref cannot have
195
+ * keywords {'description'}", which fails the whole request) → the ref is wrapped, `{ anyOf: [{ $ref }], description }`,
196
+ * so the field keeps its words. Unset means allowed.
197
+ */
198
+ readonly refSiblings?: boolean;
199
+ /**
200
+ * Whether a `$ref` may point back into itself:
201
+ * - `true`: anywhere;
202
+ * - `'guarded'`: only through an optional or nullable field, or an array
203
+ * or record that may be empty (Gemini: "avoid recursing through required
204
+ * properties or arrays with minItems greater than zero" [GEM-SO, GEM-FC]);
205
+ * - `false`: never.
206
+ * A back-edge the dialect can't take becomes JSON text (the escape hatch).
207
+ */
208
+ readonly recursion: boolean | 'guarded';
209
+ /**
210
+ * How "any JSON value" (`a.unknown()` / `a.json()`) is written: the empty
211
+ * schema `{}`; a flat `anyOf` of the JSON types (xAI, which rejects
212
+ * recursive `$defs`); or a string of JSON text, parsed on decode.
213
+ */
214
+ readonly any: 'empty' | 'flat' | 'json-text';
215
+ /** Constraint keywords the dialect accepts. */
216
+ readonly constraints: ConstraintSupport;
217
+ /** String `format` values the dialect accepts, or `'all'`. Others are said in words. */
218
+ readonly formats: 'all' | ReadonlySet<string>;
219
+ /** Where examples go: the `examples` keyword, the description text, or nowhere. */
220
+ readonly examples: 'keyword' | 'description' | 'none';
221
+ /** Emit `propertyOrdering` on objects (Gemini `responseSchema` orders keys alphabetically without it [VTX]). */
222
+ readonly propertyOrdering: boolean;
223
+ /** An enum with more values than this is widened to a string listing them (still validated). */
224
+ readonly maxEnumValues?: number;
225
+ /** Nesting deeper than this is written as JSON text (the escape hatch). */
226
+ readonly maxDepth?: number;
227
+ /**
228
+ * The root must be a plain object (tool parameters everywhere; OpenAI
229
+ * structured output: "root must be `type: object`, not `anyOf`" [OAI-SO]).
230
+ * Any other root is wrapped as `{ input: … }` and unwrapped on decode.
231
+ */
232
+ readonly rootObject: boolean;
233
+ /** Size limits of ONE schema under this profile. */
234
+ readonly limits?: SchemaLimits;
235
+ /** Limits across the whole request (see `ModelProfile.request`). */
236
+ readonly request?: RequestLimits;
237
+ /** The same family, not strict: what an item that can't be strict is rendered with. */
238
+ readonly loose?: Profile;
239
+ /** Structured output is always compiled (no non-strict output to fall back to): an unfitting output goes as prompt text. */
240
+ readonly alwaysStrictOutput?: boolean;
241
+ /** Appended after a schema delivered as prompt text. */
242
+ readonly jsonInstruction?: string;
243
+ /**
244
+ * Who reads the schema. `'model'` (default): `forPeople()` fields are left
245
+ * out and `forModels(...)` variants are used. `'people'` renders the full
246
+ * code shape (web forms, API docs, validating a person's input).
247
+ */
248
+ readonly audience?: 'model' | 'people';
249
+ }
250
+ declare const DEFAULT_JSON_INSTRUCTION = "Return ONLY a single raw JSON object conforming to the schema above: no markdown code fences, no prose, and do NOT echo the schema itself.";
251
+ /** No rewrites: the code shape as it is. Also the shape of JSON text inside an escape hatch. */
252
+ declare const LENIENT: Profile;
253
+ /** The full code shape, for people: every field, no rewrites. */
254
+ declare const PEOPLE: Profile;
255
+ /** OpenAI non-strict tools / `json_schema` with `strict: false`: any JSON Schema, best effort [OAI-FC]. */
256
+ declare const OPENAI_NON_STRICT: Profile;
257
+ /**
258
+ * OpenAI Structured Outputs (strict tools and strict `json_schema`) [OAI-SO, OAI-FC]:
259
+ * every property required (optional → null), `additionalProperties: false`
260
+ * everywhere (so records are pairs), no `prefixItems` (tuples are numeric-key
261
+ * objects), `anyOf` but no `allOf`/`oneOf`/`not`/`if`, `$defs` and recursion,
262
+ * formats below, `pattern`, numeric and array bounds. `minLength`/`maxLength`
263
+ * are listed as unsupported only for fine-tuned models and were honoured by
264
+ * gpt-5.4-mini (2026-10-30). Nullable is spelled `anyOf` (o3 rejects type
265
+ * arrays, 2026-11-04). The size limits are PER SCHEMA ("A schema may have up
266
+ * to 5000 object properties total, with up to 10 levels of nesting", 120,000
267
+ * characters, 1,000 enum values, 15,000 characters for a >250-value enum;
268
+ * raised July 2025 — the older 100/15,000/500/7,500 figures are stale). No
269
+ * per-request strict budget is documented.
270
+ */
271
+ declare const OPENAI_STRICT: Profile;
272
+ /**
273
+ * OpenAI fine-tuned models, strict: as `OPENAI_STRICT`, minus every keyword
274
+ * fine-tuned models reject ("minLength, maxLength, pattern, format, minimum,
275
+ * maximum, multipleOf, patternProperties, minItems, maxItems" [OAI-SO]).
276
+ */
277
+ declare const OPENAI_FINETUNED_STRICT: Profile;
278
+ /** Anthropic non-strict tools: any JSON Schema, not grammar-enforced [ANT-SO]. Tool `input_schema` must be an object. */
279
+ declare const ANTHROPIC_NON_STRICT: Profile;
280
+ /**
281
+ * Anthropic strict tools and `output_config.format` (Claude 4.5 and later)
282
+ * [ANT-SO]: `additionalProperties` may only be `false` (so records are
283
+ * pairs, although optional fields may be omitted), `anyOf`, `allOf` (not with
284
+ * `$ref`, so intersections are merged), non-circular `$defs` only (back-edges
285
+ * become JSON text), no `prefixItems` (tuples are `items: anyOf`), no
286
+ * length/range bounds, `minItems` only 0 or 1, the closed format list below,
287
+ * the basic regex subset, and no spelling for "any" (`{}`, a typeless schema
288
+ * and `additionalProperties: true` are all rejected, measured 2026-11-04) —
289
+ * JSON text instead. Limits across EVERY strict schema in the request: 20
290
+ * strict tools, 24 optional parameters, 16 parameters with union types
291
+ * (`anyOf` or type arrays). Structured output is always compiled (OpenRouter
292
+ * adds the beta header for every `json_schema` bound for Claude), so an
293
+ * output that doesn't fit goes as prompt text.
294
+ */
295
+ declare const ANTHROPIC_STRICT: Profile;
296
+ /**
297
+ * Gemini, no `VALIDATED` mode (`responseJsonSchema` / `parametersJsonSchema`):
298
+ * permissive, but Gemini compiles a grammar whenever a call is forced, so the
299
+ * dialect's own rules stay: the empty schema for "any" (a recursive
300
+ * `$defs/Any` is rejected), guarded recursion, and the measured 40-value enum
301
+ * cap (a real 98-name enum 400'd; 90 passed, 93 failed, 2026-08-23).
302
+ */
303
+ declare const GOOGLE_NON_STRICT: Profile;
304
+ /**
305
+ * Gemini structured output / `VALIDATED` function calling with the JSON
306
+ * Schema fields [GEM-SO, GEM-FC, GEM-BLOG]: types incl. type arrays,
307
+ * `properties`/`required`/`additionalProperties` (open records are fine),
308
+ * `enum`, formats date-time/date/time, `minimum`/`maximum`, `items`,
309
+ * `prefixItems`, `minItems`/`maxItems`, `anyOf`, `$defs`/`$ref`, recursion
310
+ * only through optional/nullable values. `minLength`/`maxLength` are silently
311
+ * stripped and `pattern` is undocumented (a pattern tool timed out live), so
312
+ * both are said in words. No published size numbers; the 40-value enum cap
313
+ * is measured (see `GOOGLE_NON_STRICT`). No per-tool `strict` flag: strictness
314
+ * is the request's `function_calling_config.mode: VALIDATED`.
315
+ */
316
+ declare const GOOGLE_STRICT: Profile;
317
+ /**
318
+ * Gemini's OpenAPI-subset `Schema` (`responseSchema` / `parameters`, also
319
+ * Vertex) [GEM-REF, VTX]: `type` + `nullable: true`, `properties`,
320
+ * `required`, `enum` (strings), `format`, `minimum`/`maximum`,
321
+ * `minLength`/`maxLength`, `pattern`, `items`, `minItems`/`maxItems`,
322
+ * `anyOf`, `propertyOrdering`. No `additionalProperties` (records are pairs),
323
+ * no `$defs`/`$ref` (named types are inlined, recursion is JSON text), no
324
+ * `prefixItems`, and no empty schema (any is JSON text).
325
+ */
326
+ declare const GOOGLE_OPENAPI: Profile;
327
+ /**
328
+ * xAI Grok 4 [XAI-SO]: tool calls are ALWAYS strict ("the strict flag is
329
+ * implicitly always true"). `anyOf` and `oneOf`, single-subschema `allOf`
330
+ * only (so intersections are merged), non-circular `$defs` (back-edges are
331
+ * JSON text), `prefixItems` (array-form `items` is a 400), formats below, the
332
+ * basic regex subset, length/item/numeric bounds, and `additionalProperties`
333
+ * defaulting to `false` — open records must say so and are accepted, so
334
+ * records stay open objects. "Any" is the flat `anyOf` (recursive `$defs`
335
+ * are rejected); empty `enum`/`anyOf` are 400s and never emitted.
336
+ */
337
+ declare const XAI_STRICT: Profile;
338
+ /** xAI structured output without `strict` (best effort): xAI's rules, not grammar-compiled. */
339
+ declare const XAI_NON_STRICT: Profile;
340
+ /**
341
+ * Ollama: `format` takes a JSON Schema that llama.cpp compiles to a grammar
342
+ * (ollama.com/blog/structured-outputs; github.com/ollama/ollama docs/api.md
343
+ * "format"), and tools are best effort. aeye's Ollama provider extends the
344
+ * OpenAI one and resolves no strict family, so it is never sent `strict`
345
+ * (packages/ollama). Local `$ref`s, recursion and the usual keywords are
346
+ * understood, so it renders the code shape.
347
+ */
348
+ declare const OLLAMA: Profile;
349
+ /**
350
+ * A deliberately poor dialect: no combinators, no `$defs`, no recursion,
351
+ * closed objects, shallow. Used by tests to prove that ANY schema still has a
352
+ * faithful rendering when almost nothing is supported.
353
+ */
354
+ declare const MINIMAL: Profile;
355
+ /**
356
+ * Make a profile addressable by id and by `(family, strict)`. The built-ins
357
+ * are registered at load; register your own for a new dialect.
358
+ */
359
+ declare function registerProfile(profile: Profile): void;
360
+ /** A profile by id (`undefined` when unknown). Variants made by `variant` resolve too. */
361
+ declare function getProfile(id: string): Profile | undefined;
362
+ /** The family's strict profile (its loose one when it has none) or its loose one; `LENIENT` for an unknown family. */
363
+ declare function familyProfile(family: ProfileFamily, strict: boolean): Profile;
364
+ /** The changes the request budget may make to a profile for one schema. */
365
+ interface ProfileAdjustment {
366
+ /** Widen enums with more values than this (fewer enum values and characters on the wire). */
367
+ readonly maxEnumValues?: number;
368
+ /** Write nesting below this depth as JSON text (fewer levels and properties). */
369
+ readonly maxDepth?: number;
370
+ /** Write absent optionals as `null` (moves optional parameters into union types). */
371
+ readonly optionalAsNull?: boolean;
372
+ /** Wrap a non-object root as `{ input }`. */
373
+ readonly rootObject?: boolean;
374
+ }
375
+ /**
376
+ * A profile with adjustments applied, memoized so the same adjustments give
377
+ * the same instance (and id), which keeps every rendering memo stable.
378
+ */
379
+ declare function variant(base: Profile, adj: ProfileAdjustment): Profile;
380
+ /** What a description callback sees, so prose can match the model-facing shape. */
381
+ interface View {
382
+ readonly profile: Profile;
383
+ /** `'pairs'` when records are written as `[{key, value}]`. */
384
+ readonly records: Profile['records'];
385
+ /** `'null'` when an absent optional is written as `null`. */
386
+ readonly optional: Profile['optional'];
387
+ /** How to say "a record" in prose: `"a list of {key, value} entries"` or `"an object"`. */
388
+ readonly recordWord: string;
389
+ }
390
+ declare function viewOf(profile: Profile): View;
391
+
392
+ /**
393
+ * Measuring an emitted schema against a provider's size limits.
394
+ *
395
+ * The count is taken from the JSON Schema that is actually sent (never from
396
+ * the code-shape schema), so it is exact for the profile it was rendered
397
+ * with: a record sent as pairs counts its `key`/`value` properties, a widened
398
+ * enum counts nothing, an escaped subtree counts as one string.
399
+ */
400
+
401
+ type J$1 = {
402
+ [key: string]: unknown;
403
+ };
404
+ /** What a provider's limits count, for one emitted schema. */
405
+ interface SchemaMeasure {
406
+ /** Object properties, summed over every level and every `$defs` entry. */
407
+ readonly properties: number;
408
+ /** Deepest nesting of objects/arrays below the root, following `$ref`s (cycles stop). */
409
+ readonly depth: number;
410
+ /** Characters over property names, `$defs` names, enum and const string values. */
411
+ readonly stringChars: number;
412
+ /** Enum values summed over every enum. */
413
+ readonly enumValues: number;
414
+ /** Each enum: how many values, and the characters of its string values. */
415
+ readonly enums: readonly {
416
+ readonly values: number;
417
+ readonly chars: number;
418
+ }[];
419
+ /** Properties not listed in their object's `required`. */
420
+ readonly optional: number;
421
+ /** Nodes with a union type: `anyOf`/`oneOf` with 2+ options, or a `type` array with 2+ types. */
422
+ readonly unions: number;
423
+ }
424
+ declare const ZERO_MEASURE: SchemaMeasure;
425
+ declare function measureJson(schema: J$1): SchemaMeasure;
426
+ /** Add measures (request totals). */
427
+ declare function addMeasures(a: SchemaMeasure, b: SchemaMeasure): SchemaMeasure;
428
+ /** Which limits a measure breaks, as readable reasons (empty when it fits). */
429
+ declare function overLimits(m: SchemaMeasure, limits: SchemaLimits | undefined, scope: string): string[];
430
+ /** The limit a measure breaks, by name (`largeEnum` for the large-enum characters rule). */
431
+ type LimitName = Exclude<keyof SchemaLimits, 'largeEnumValues' | 'maxLargeEnumChars'> | 'largeEnum';
432
+ /** Which limits a measure breaks, by name (what `overLimits` explains). */
433
+ declare function brokenLimits(m: SchemaMeasure, limits: SchemaLimits | undefined, out?: Set<LimitName>): Set<LimitName>;
434
+
435
+ /**
436
+ * Errors for the model: what a model is told when its answer doesn't fit.
437
+ *
438
+ * The approach is gin's and query's (`Code.formatProblems`, `aids.ts`): the
439
+ * model's own JSON echoed back with a marker under each bad spot, the message
440
+ * at the marker, and "did you mean" for names it misspelt. Here it is the
441
+ * native output of every decode, with a size budget, so a huge schema (the
442
+ * whole gin grammar, query's `typed` functions) still gets a short message.
443
+ *
444
+ * Everything is in the MODEL's shape: the paths and the JSON are what it
445
+ * wrote (pairs, `null` for absent, JSON text, a tool called through the
446
+ * dispatcher), never the code shape. The expected type at a bad spot is read
447
+ * from the JSON Schema the model was given, so it is the wire type too.
448
+ *
449
+ * Cost: nothing is computed on the happy path. On a failure, only the
450
+ * problems that are shown get suggestions and expected types, and the echo
451
+ * walks only the paths to them (siblings are summarized, never serialized
452
+ * whole).
453
+ */
454
+
455
+ /**
456
+ * How much the model is told:
457
+ *
458
+ * - `'summary'` — one line: the first problem and how many more.
459
+ * - `'list'` — one line per problem: where and what (and "did you mean").
460
+ * - `'markers'` — the model's JSON echoed back, trimmed around the problems,
461
+ * with a marker (`^^^`) and the message under each bad spot.
462
+ * - `'full'` — markers, plus the expected type at each spot.
463
+ */
464
+ type ErrorDetail = 'summary' | 'list' | 'markers' | 'full';
465
+ /** Options for the error feedback a model gets. Set on a tool / prompt, overridable per call. */
466
+ interface ErrorFormat {
467
+ /** Default `'full'`. */
468
+ readonly detail?: ErrorDetail;
469
+ /** Distinct problems shown (repeats of one mistake count once); the rest are counted. Default 5. */
470
+ readonly maxErrors?: number;
471
+ /** Hard cap on the message, in characters. Detail is dropped step by step to fit. Default 2000. */
472
+ readonly maxChars?: number;
473
+ /** "Did you mean" for unknown keys, enum values, tags and tool names. Default true. */
474
+ readonly suggestions?: boolean;
475
+ /** The expected type (a short TypeScript-like type of just that spot). Default: on for `'full'`. */
476
+ readonly expected?: boolean;
477
+ /** Sibling keys / items shown next to a bad spot in the echo. Default 3. */
478
+ readonly context?: number;
479
+ /** Levels of the answer shown above a bad spot; a deeper spot is echoed from there down. Default 6. */
480
+ readonly depth?: number;
481
+ /** The first line saying how many problems there are and in what. Default true. */
482
+ readonly header?: boolean;
483
+ }
484
+ /** An `ErrorFormat`, or just its detail level. */
485
+ type ErrorFormatInput = ErrorDetail | ErrorFormat;
486
+ /** The defaults (`expected` follows the detail level unless set). */
487
+ declare const DEFAULT_ERROR_FORMAT: Readonly<Required<Omit<ErrorFormat, 'expected'>>>;
488
+ type ResolvedErrorFormat = Required<ErrorFormat>;
489
+ /** Merge formats left to right (later wins: request, then definition, then call), without filling defaults. */
490
+ declare function mergeErrorFormats(...inputs: readonly (ErrorFormatInput | undefined)[]): ErrorFormat | undefined;
491
+ /** Merge formats left to right (later wins) and fill the defaults. */
492
+ declare function errorFormat(...inputs: readonly (ErrorFormatInput | undefined)[]): ResolvedErrorFormat;
493
+ /**
494
+ * The kind of a problem. It decides what "did you mean" compares, and
495
+ * whether the expected type adds anything to the message.
496
+ */
497
+ type IssueKind = 'type' | 'required' | 'unknown-key' | 'not-allowed' | 'enum' | 'literal' | 'tag' | 'tool' | 'union' | 'rule' | 'json' | 'other';
498
+ /** What an issue was about (`'other'` for issues not made by a decode). */
499
+ declare function issueKind(issue: Issue): IssueKind;
500
+ /**
501
+ * The nearest valid name to what the model wrote at an issue (an unknown key,
502
+ * enum value, tag or tool), if it is a genuine typo. For a missing key, the
503
+ * key the model wrote instead of it (`pth` for a missing `path`).
504
+ */
505
+ declare function suggestionFor(issue: Issue): string | undefined;
506
+ /** `rows[2].tags`, with a JSON-text step written `→ JSON text →`. */
507
+ declare function modelPath(path: readonly PathSeg[]): string;
508
+ /** A short TypeScript-like type of a JSON Schema (what the model was given at one spot), at most `max` characters. */
509
+ declare function shortType(json: JsonSchema, max?: number): string;
510
+ /**
511
+ * The message for a failed decode: `issues` (from `parse`) over `wire`, the
512
+ * value the model sent (untouched: `parse` keeps it when it echoes). `label`
513
+ * names what the model wrote: `'your answer'`, `'the arguments of search'`.
514
+ */
515
+ declare function formatErrors(issues: readonly Issue[], wire: unknown, format?: ErrorFormatInput | ResolvedErrorFormat, label?: string): string;
516
+
517
+ /**
518
+ * Rendering: one compiled `Node` per (schema, profile). A node knows how to
519
+ *
520
+ * - `json()` — emit the JSON Schema the model is given (memoized),
521
+ * - `run()` — validate the model's answer AND decode it into the code
522
+ * shape in one walk, reporting errors at the path the model
523
+ * wrote (wire path) and the path the code sees (code path),
524
+ * - `encode()` — turn a code-shape value into the wire shape (examples,
525
+ * few-shot messages, values shown in instructions, echoing
526
+ * prior arguments back).
527
+ *
528
+ * The schema classes in `schema.ts` own their logic (`compile`); this file
529
+ * holds the shared machinery: the compiler (refs, `$defs`, cycles, depth, the
530
+ * JSON-text escape hatch), the walk context with copy accounting, and the
531
+ * `Rendered` result callers hold.
532
+ *
533
+ * COPY RULES (asserted in tests, tabled in aeye-schema.md):
534
+ * - Decoding a subtree whose wire shape is its code shape allocates nothing:
535
+ * it is validated and returned as the SAME reference.
536
+ * - Default `inPlace: true` (the caller owns the `JSON.parse` result): a
537
+ * changed child is written back into its parent (`edits`), `null`-for-absent
538
+ * keys are deleted (`edits`). Parents are never copied.
539
+ * - `inPlace: false` (copy-on-write): the first change inside an object/array
540
+ * clones THAT container once (`objects`/`arrays`); untouched siblings and
541
+ * subtrees are shared, never cloned.
542
+ * - The only unavoidable allocations are shape changes: a record sent as
543
+ * `[{key, value}]` becomes one new object (values moved, not copied); a
544
+ * tuple sent as `{"0":…}` becomes one new array; JSON text is parsed once
545
+ * (`parsed`); a container sent as a JSON string is parsed once (`repaired`).
546
+ * - Encoding never mutates the code value. A node whose wire shape is its
547
+ * code shape (`needs === false`) returns the value itself; otherwise only
548
+ * the containers on the path to a change are new.
549
+ */
550
+
551
+ type JsonSchema = {
552
+ [key: string]: unknown;
553
+ };
554
+ type PathSeg = string | number;
555
+ /** One problem with the model's answer. */
556
+ interface Issue {
557
+ /** Where it is in what the MODEL wrote (e.g. `['tags', 2, 'value']` for a pairs record). */
558
+ readonly path: readonly PathSeg[];
559
+ /** Where it is in the CODE shape (e.g. `['tags', 'urgent']`). */
560
+ readonly codePath: readonly PathSeg[];
561
+ readonly message: string;
562
+ }
563
+ /**
564
+ * A problem a refinement or a codec reports BELOW the value it checks, at a
565
+ * path relative to it in the code shape (`['fields', 2, 'name']`). The model
566
+ * is told it at that path; where the wire shape differs below the value (a
567
+ * pairs record, a tuple sent as an object) the echo falls back to a plain line.
568
+ */
569
+ interface RuleIssue {
570
+ readonly path: readonly PathSeg[];
571
+ readonly message: string;
572
+ }
573
+ /**
574
+ * What a codec's `decode` returns to reject a value with problems at paths
575
+ * below it (one `Error` is one problem at the value itself).
576
+ */
577
+ declare class Rejection {
578
+ readonly issues: readonly RuleIssue[];
579
+ constructor(issues: readonly RuleIssue[]);
580
+ }
581
+ /** Allocation counters for one `parse` or `encode`. */
582
+ interface CopyStats {
583
+ /** Objects allocated (records from pairs, copy-on-write clones, encoded objects). */
584
+ objects: number;
585
+ /** Arrays allocated (tuples from numeric-key objects, copy-on-write clones, encoded arrays). */
586
+ arrays: number;
587
+ /** In-place writes/deletes into the caller's value. */
588
+ edits: number;
589
+ /** JSON texts parsed (escape hatches, `json-text` any). */
590
+ parsed: number;
591
+ /** Values repaired: a container sent as a JSON string, or a value sent where JSON text was asked for. */
592
+ repaired: number;
593
+ }
594
+ declare function newStats(): CopyStats;
595
+ declare function formatPath(path: readonly PathSeg[]): string;
596
+ /**
597
+ * The walk context. Paths are stacks with explicit depths, so the happy path
598
+ * allocates nothing: `push`/`pop` on a plain array let V8 shrink and regrow
599
+ * its storage at every level, an allocation per value decoded; these only grow.
600
+ */
601
+ declare class Cx {
602
+ /** Mutate the caller's value (default) or copy-on-write. */
603
+ readonly inPlace: boolean;
604
+ /** Dry run: validate only, never write (used to pick a union option). */
605
+ readonly dry: boolean;
606
+ readonly stats: CopyStats;
607
+ /** Accept a container sent as JSON text, and a value sent where JSON text was asked for. */
608
+ readonly repair: boolean;
609
+ /** Only whether it fails matters (union option trials): no issue objects, no paths. */
610
+ readonly countOnly: boolean;
611
+ readonly errors: Issue[];
612
+ /**
613
+ * In-place writes, as (container, key, old value) triples, so a failed
614
+ * decode can put the model's answer back as it was sent (the echo shows
615
+ * the wire, not a half-decoded mix). Only kept when the message echoes.
616
+ */
617
+ undo: unknown[] | undefined;
618
+ private undoN;
619
+ private readonly wire;
620
+ private readonly code;
621
+ private wd;
622
+ private cd;
623
+ constructor(
624
+ /** Mutate the caller's value (default) or copy-on-write. */
625
+ inPlace: boolean,
626
+ /** Dry run: validate only, never write (used to pick a union option). */
627
+ dry: boolean, stats: CopyStats,
628
+ /** Accept a container sent as JSON text, and a value sent where JSON text was asked for. */
629
+ repair?: boolean,
630
+ /** Only whether it fails matters (union option trials): no issue objects, no paths. */
631
+ countOnly?: boolean);
632
+ /**
633
+ * Record a problem at the current path. `kind` and `candidates` drive the
634
+ * model's message ("did you mean"); `received` is what the model wrote
635
+ * there; `node` is the expected type when it isn't the failing node (which
636
+ * claims its issues as the run unwinds: nothing is tracked while it passes).
637
+ */
638
+ fail(message: string, kind?: IssueKind, received?: unknown, candidates?: () => readonly string[], node?: Node): void;
639
+ /** Record a problem at `rel` below the current path (code-shape segments, used for both paths). */
640
+ failAt(rel: readonly PathSeg[], message: string, kind?: IssueKind): void;
641
+ enter(wire: PathSeg, code?: PathSeg | null): void;
642
+ leave(code?: boolean): void;
643
+ /**
644
+ * A dry sibling (for union option tests). Count-only by default: only
645
+ * whether it fails is read. With `issues`, its failures are real issues
646
+ * at the current paths (they are copied into this context).
647
+ */
648
+ dryRun(issues?: boolean): Cx;
649
+ /**
650
+ * Before an in-place write of `key`: remember its old value (when keeping
651
+ * the undo log). Before the first delete from an object, its key order too:
652
+ * a key put back after a delete would otherwise come last.
653
+ */
654
+ saving(container: object, key: PathSeg, deleting?: boolean): void;
655
+ private ordered;
656
+ /** Put every in-place write back, newest first: the caller's value is as the model sent it. */
657
+ restore(): void;
658
+ /** Start keeping the undo log (a reused buffer). */
659
+ keepUndo(): void;
660
+ /** Drop the undo log's references and hand the buffer back. */
661
+ releaseUndo(): void;
662
+ }
663
+ /** What a schema class supplies to build its node. */
664
+ interface NodeImpl {
665
+ /** This node itself changes the value's shape (pairs→record, null→absent, JSON text…). */
666
+ readonly own?: boolean;
667
+ /** Child nodes (for the `needs` fixpoint). */
668
+ readonly deps?: readonly Node[];
669
+ /** Automatic description text this node adds for the model, e.g. how pairs work. */
670
+ readonly hint?: (view: View) => string | undefined;
671
+ emit(): JsonSchema;
672
+ run(value: unknown, cx: Cx): unknown;
673
+ /** Code shape → wire shape. Only called when `needs` is true; must not mutate `value`. */
674
+ encode(value: unknown, stats: CopyStats): unknown;
675
+ /** The node of a child at a code-path segment (`'*'` for "any element"), for encoding a part. */
676
+ child?(seg: PathSeg): Node | undefined;
677
+ }
678
+ /** A compiled (schema, profile) node. */
679
+ declare class Node {
680
+ impl: NodeImpl | undefined;
681
+ readonly compiler: Compiler;
682
+ /** True when decoding or encoding may change this subtree (its own change or any dependency's). */
683
+ needs: boolean;
684
+ schema: AnySchema | undefined;
685
+ /** An outer wrapper (e.g. `.optional()` around a field) whose metadata also applies. */
686
+ outer: AnySchema | undefined;
687
+ /** The model writes this value as a string of JSON text (an escape, or "any" on a dialect without it). */
688
+ jsonText: boolean;
689
+ private _json;
690
+ constructor(impl: NodeImpl | undefined, compiler: Compiler);
691
+ get own(): boolean;
692
+ get deps(): readonly Node[];
693
+ json(): JsonSchema;
694
+ run(value: unknown, cx: Cx): unknown;
695
+ private check;
696
+ /** This node's schema as TypeScript-like text (the code shape; for spots written as JSON text). */
697
+ typeText(): string;
698
+ encode(value: unknown, stats?: CopyStats): unknown;
699
+ child(seg: PathSeg): Node | undefined;
700
+ }
701
+ /** Builds and prints a TypeScript-like shape (escape-hatch descriptions, prompt-text delivery). */
702
+ declare class Printer {
703
+ readonly env: ReadonlyMap<string, AnySchema>;
704
+ private readonly names;
705
+ constructor(env: ReadonlyMap<string, AnySchema>);
706
+ print(s: AnySchema): string;
707
+ ref(name: string): string;
708
+ /** The named types printed so far. */
709
+ used(): string[];
710
+ /** `type X = …` for these named types and every named type they reach. */
711
+ definitions(names: Iterable<string>): string;
712
+ /** The shape plus a `type X = …` line for every named type it reaches. */
713
+ full(s: AnySchema): string;
714
+ }
715
+ /** Nodes an inlining (no `$defs`) compile may make before it restarts as `inlineOnce`. */
716
+ declare const INLINE_BUDGET = 4000;
717
+ /** Thrown inside a compile that inlined past `INLINE_BUDGET`; `Bound.render` restarts it. */
718
+ declare class InlineBudgetExceeded extends Error {
719
+ }
720
+ /** Compiles schemas for one (bound env, profile). */
721
+ declare class Compiler {
722
+ readonly profile: Profile;
723
+ readonly env: ReadonlyMap<string, AnySchema>;
724
+ /** The LENIENT rendering of the same bound env (escape hatches validate against it). */
725
+ readonly lenient: () => Rendered<unknown>;
726
+ /**
727
+ * Without `$defs` every use of a named type is inlined, which for a big
728
+ * recursive grammar (query's Expr ⇄ Query) grows exponentially. Past
729
+ * `INLINE_BUDGET` nodes the compile restarts in this mode: each recursive
730
+ * named type is written out once, its later uses are JSON text of it.
731
+ */
732
+ readonly inlineOnce: boolean;
733
+ /** The per-profile compiler of ref-free nodes (`sharedCompiler`): it forgets its nodes after `finish`. */
734
+ readonly shared: boolean;
735
+ readonly nodes: Node[];
736
+ /** Named types emitted into `$defs` (defs mode). */
737
+ readonly defs: Map<string, DefTarget>;
738
+ /** Named types the JSON-text escapes mention: defined once, in the root description. */
739
+ readonly glossary: Set<string>;
740
+ /** Without `$defs`: recursive named types inlined so far (`inlineOnce` mode). */
741
+ private readonly inlined;
742
+ private readonly recursive;
743
+ readonly view: View;
744
+ /** Named types being compiled, with the guard level at their start. */
745
+ private readonly stack;
746
+ private depth;
747
+ /** How many optional / nullable / may-be-empty containers enclose the current position. */
748
+ private guard;
749
+ constructor(profile: Profile, env: ReadonlyMap<string, AnySchema>,
750
+ /** The LENIENT rendering of the same bound env (escape hatches validate against it). */
751
+ lenient: () => Rendered<unknown>,
752
+ /**
753
+ * Without `$defs` every use of a named type is inlined, which for a big
754
+ * recursive grammar (query's Expr ⇄ Query) grows exponentially. Past
755
+ * `INLINE_BUDGET` nodes the compile restarts in this mode: each recursive
756
+ * named type is written out once, its later uses are JSON text of it.
757
+ */
758
+ inlineOnce?: boolean,
759
+ /** The per-profile compiler of ref-free nodes (`sharedCompiler`): it forgets its nodes after `finish`. */
760
+ shared?: boolean);
761
+ /** Does a named type reach itself? */
762
+ private isRecursive;
763
+ node(impl: NodeImpl): Node;
764
+ /** Compile a schema; `outer` is a wrapper whose metadata/checks also apply (an optional field). */
765
+ compile(s: AnySchema, outer?: AnySchema): Node;
766
+ /** Compile below a position the value may skip (optional, nullable, an array that may be empty). */
767
+ guarded(s: AnySchema, outer?: AnySchema): Node;
768
+ /** A use of a named type. */
769
+ ref(name: string): Node;
770
+ private defRef;
771
+ /**
772
+ * The escape hatch: a string holding JSON text in the CODE shape, used for
773
+ * whatever the profile cannot express (recursion, depth, "any"). The JSON
774
+ * text is parsed once and validated by the LENIENT rendering of the same
775
+ * schema, so nothing is lost — only moved into a string.
776
+ */
777
+ escape(s: AnySchema, why: string, name?: string): Node;
778
+ /** A node for a subschema in this compiler, compiled on demand (after `finish`). */
779
+ late(s: AnySchema): Node;
780
+ /** Least fixpoint of `needs = own || any(dep.needs)` (handles cycles). */
781
+ finish(): void;
782
+ /** Text of a `Text` for this profile. */
783
+ text(t: Text | undefined): string | undefined;
784
+ /** `T | null` in this profile's spelling. */
785
+ nullable(j: JsonSchema): JsonSchema;
786
+ /** An object schema, closed when the profile closes objects. */
787
+ object(properties: Record<string, JsonSchema>, required: readonly string[], closed?: boolean): JsonSchema;
788
+ /** Add description, examples and title to an emitted schema. */
789
+ decorate(node: Node, json: JsonSchema): JsonSchema;
790
+ /** An example is typed in the code shape; one that doesn't fit is a definition mistake, reported once. */
791
+ private checkExample;
792
+ }
793
+ /** The `$defs` entry of a named type; filled in after its body compiles (cycles point at it first). */
794
+ declare class DefTarget extends Node {
795
+ target: Node;
796
+ constructor(compiler: Compiler);
797
+ get own(): boolean;
798
+ get deps(): readonly Node[];
799
+ json(): JsonSchema;
800
+ run(v: unknown, cx: Cx): unknown;
801
+ encode(v: unknown, stats?: CopyStats): unknown;
802
+ child(seg: PathSeg): Node | undefined;
803
+ }
804
+ /** Returned by `readJsonText` when the value was not usable. */
805
+ declare const FAILED: unique symbol;
806
+ /**
807
+ * Read a value the model was asked to write as JSON text. With repair on, a
808
+ * value written directly (an object where a string of JSON was asked for) is
809
+ * taken as it is — models do this often, and it is unambiguous.
810
+ */
811
+ declare function readJsonText(v: unknown, cx: Cx): unknown;
812
+ /** Options for `Rendered.parse`. */
813
+ interface ParseOptions {
814
+ /** Decode into the caller's value (default `true`), or copy-on-write. */
815
+ readonly inPlace?: boolean;
816
+ /**
817
+ * Accept common slips (default `true`): an object/array/record sent as a
818
+ * string of JSON text (also double-encoded), and a value sent directly
819
+ * where JSON text was asked for. Each is counted in `stats.repaired`.
820
+ */
821
+ readonly repair?: boolean;
822
+ /**
823
+ * How the failure `message` is written for the model: detail level, size
824
+ * cap, suggestions, expected types (feedback.ts). Default `'full'` within
825
+ * 2000 characters; a request entry passes its tool's / prompt's format.
826
+ */
827
+ readonly errorFormat?: ErrorFormatInput | undefined;
828
+ /** What the model wrote, for the message's first line (default `'your answer'`). */
829
+ readonly label?: string | undefined;
830
+ }
831
+ /** Successful or failed parse. */
832
+ type ParseResult<Out> = {
833
+ readonly ok: true;
834
+ readonly value: Out;
835
+ readonly stats: CopyStats;
836
+ } | {
837
+ readonly ok: false;
838
+ readonly issues: readonly Issue[];
839
+ readonly message: string;
840
+ readonly stats: CopyStats;
841
+ };
842
+ /** Options for `Rendered.encodeText` and the template helpers. */
843
+ interface EncodeTextOptions {
844
+ /** Indent the JSON (`true` = 2 spaces). */
845
+ readonly pretty?: boolean | number;
846
+ /**
847
+ * Encode a PART: the value given is what sits at this code path of the
848
+ * schema (`limits`, `rows.*.tags`; `*` is any element or key).
849
+ */
850
+ readonly path?: string | readonly PathSeg[];
851
+ }
852
+ /** Encode values in a rendering's wire shape, needing only the value. */
853
+ interface Encoder<Out> {
854
+ /** The value as the model would write it, as JSON text. */
855
+ (value: Out, opts?: EncodeTextOptions): string;
856
+ /** The value as the model would write it, as a JSON value. */
857
+ readonly wire: (value: Out, path?: EncodeTextOptions['path']) => unknown;
858
+ }
859
+ /** A schema rendered for one profile: JSON schema + codec + validation, memoized. */
860
+ declare class Rendered<Out> {
861
+ readonly compiler: Compiler;
862
+ readonly root: Node;
863
+ readonly _out: Out;
864
+ private _json;
865
+ private _body;
866
+ private _wrapped;
867
+ private _measure;
868
+ private _encoder;
869
+ constructor(compiler: Compiler, root: Node);
870
+ get profile(): Profile;
871
+ /** The root schema without `$defs` (a root ref is inlined). */
872
+ private body;
873
+ /**
874
+ * True when the profile needs an object root and this schema's root isn't
875
+ * one: the model then writes `{ "input": … }`, unwrapped on decode.
876
+ */
877
+ get wrapped(): boolean;
878
+ /** The JSON Schema the model is given. */
879
+ get jsonSchema(): JsonSchema;
880
+ /** Size of the emitted schema: properties, depth, enum values, optionals, unions (memoized). */
881
+ get measure(): SchemaMeasure;
882
+ /**
883
+ * Validate + decode the model's answer (already `JSON.parse`d). With
884
+ * `inPlace` (default) the value is decoded in place and returned; see the
885
+ * copy rules at the top of this file. On failure `message` is the feedback
886
+ * for the model (`opts.errorFormat`, see feedback.ts); with an echoing
887
+ * format (the default) the value is first put back as the model sent it.
888
+ */
889
+ parse(wire: unknown, opts?: ParseOptions): ParseResult<Out>;
890
+ private decode;
891
+ /** `JSON.parse` then decode in place (we own the parsed value; a failure's echo re-reads the text). */
892
+ parseText(text: string, opts?: Omit<ParseOptions, 'inPlace'>): ParseResult<Out>;
893
+ /** `parse`, throwing a `SchemaParseError` (with the issues and the model's message) on failure. */
894
+ parseOrThrow(wire: unknown, opts?: ParseOptions): Out;
895
+ /**
896
+ * Code shape → the shape this model writes (few-shot examples, values in
897
+ * instructions, echoing prior args). Never mutates `value`; untouched
898
+ * subtrees are shared. Pass `stats` to count what was allocated.
899
+ */
900
+ encode(value: Out, stats?: CopyStats): unknown;
901
+ /** `encode` of a part: `value` is the value at code path `path` (`'limits'`, `['rows', '*', 'tags']`). */
902
+ encodeAt(value: unknown, path: EncodeTextOptions['path'], stats?: CopyStats): unknown;
903
+ /** `encode` as JSON text (of a part, with `opts.path`). */
904
+ encodeText(value: Out, opts?: EncodeTextOptions): string;
905
+ /** An encoder bound to this rendering: hand it to code that has only the value. */
906
+ get encoder(): Encoder<Out>;
907
+ /**
908
+ * Node for a subschema in this rendering (escape hatches use the LENIENT one),
909
+ * compiled once per subschema instance: union encoding and checks ask for the
910
+ * same option nodes on every value, and a fresh compile each time grew the
911
+ * compiler (and its `needs` fixpoint) by the subschema's size per call.
912
+ */
913
+ nodeFor(s: AnySchema): Node;
914
+ private readonly lateNodes;
915
+ /** The whole shape as TypeScript-like text (prompt-text delivery). */
916
+ typescript(): string;
917
+ }
918
+ /**
919
+ * Issues as bare lines, `- at <path>: <message>` (paths where the model wrote
920
+ * them). The model's message is `formatErrors` (feedback.ts), with markers,
921
+ * suggestions and a size cap.
922
+ */
923
+ declare function formatIssues(issues: readonly Issue[]): string;
924
+
925
+ /**
926
+ * Named types and the chain:
927
+ *
928
+ * a.define({ ...named types, may use a.ref() to names defined later... })
929
+ * .define({ ...more... }) // any number of steps
930
+ * .declare<{ Name: CodeType }>() // optional: pin the type of a ref the dynamic step will supply
931
+ * .dynamic((...args) => ({ ...the refs not defined yet... }), { key }) // optional
932
+ * .result('Name' | a.object({...})) // a ref to a named type, or an inline schema
933
+ *
934
+ * Every step is checked at compile time:
935
+ * - `define` may not redefine a name;
936
+ * - `dynamic` must return EVERY ref still missing (used but undefined, or
937
+ * declared), each typed as declared; it may add new names; it may not
938
+ * redefine a static one;
939
+ * - `result` fails if any ref (in the defs or the root) is still undefined.
940
+ *
941
+ * The result is a `Bundle<Out, Args>`: a static instance built once at
942
+ * module scope. `Out` is fully resolved (refs swapped for their types,
943
+ * recursion included); `Args` is what the dynamic step needs (`[]` when
944
+ * there is none). `bundle.bind(...args)` supplies the dynamic part at call
945
+ * time and returns a `Bound<Out>`; `bound.render(profile)` gives the model's
946
+ * JSON schema and the codec.
947
+ */
948
+
949
+ type Defs = {
950
+ readonly [name: string]: AnySchema;
951
+ };
952
+ /** Name → unresolved output of each named type. */
953
+ type EnvOf<D extends Defs> = {
954
+ [K in keyof D]: D[K]['_out'];
955
+ };
956
+ /**
957
+ * A schema typed loosely as `AnySchema` (refs `any`, e.g. built from runtime
958
+ * data) contributes no static refs; `Bound` still checks them at bind time.
959
+ */
960
+ type KnownRefs<R> = 0 extends 1 & R ? never : R;
961
+ type DefRefs<D extends Defs> = {
962
+ [K in keyof D]: KnownRefs<D[K]['_refs']>;
963
+ }[keyof D];
964
+ /** Refs used by the defs (or declared) but not defined yet. */
965
+ type Missing<D extends Defs, Decl> = Exclude<DefRefs<D> | (keyof Decl & string), keyof D> & string;
966
+ /** What the dynamic step must return: every missing ref (typed as declared), no redefinitions, and any new names. */
967
+ type DynamicDefs<D extends Defs, Decl> = {
968
+ readonly [K in Missing<D, Decl>]: K extends keyof Decl ? SchemaOf<AllowRefs<Decl[K]>> : AnySchema;
969
+ } & {
970
+ readonly [K in keyof D]?: never;
971
+ };
972
+ type Root<D extends Defs> = AnySchema | (keyof D & string);
973
+ type RootOut<R> = R extends string ? RefMarker<R> : R extends AnySchema ? R['_out'] : never;
974
+ type RootRefs<R> = R extends string ? R : R extends AnySchema ? KnownRefs<R['_refs']> : never;
975
+ type Unresolved<D extends Defs, Decl, R> = Exclude<RootRefs<R>, keyof D> | Missing<D, Decl>;
976
+ /** Declared refs whose RESOLVED type does not match the declaration. */
977
+ type Mismatched<D extends Defs, Decl> = {
978
+ [K in keyof Decl & keyof D]: Resolve<D[K]['_out'], EnvOf<D>> extends Decl[K] ? never : K;
979
+ }[keyof Decl & keyof D];
980
+ type CheckRoot<D extends Defs, Decl, R> = [
981
+ Unresolved<D, Decl, R>
982
+ ] extends [never] ? [Mismatched<D, Decl>] extends [never] ? unknown : SchemaError<'declared type does not match', Mismatched<D, Decl>> : SchemaError<'unresolved ref', Unresolved<D, Decl, R>>;
983
+ type NoRedefine<D extends Defs, D2> = {
984
+ [K in keyof D & keyof D2]: SchemaError<'already defined', K>;
985
+ };
986
+ /** The resolved output of a chain ending at `R`. */
987
+ type ResultOut<D extends Defs, R> = Resolve<RootOut<R>, EnvOf<D>>;
988
+ interface DynamicOptions<A extends unknown[]> {
989
+ /**
990
+ * Cache key for the dynamic part (e.g. a registry's version). Binds with an
991
+ * equal key reuse the same `Bound` — so neither the dynamic function nor
992
+ * the rendering runs again. Without a key every `bind` calls the function
993
+ * (ref-free subtrees still render once per profile, see `render.ts`).
994
+ */
995
+ readonly key?: (...args: A) => unknown;
996
+ /** How many keyed binds to keep (default 4). */
997
+ readonly cacheSize?: number;
998
+ }
999
+ /** Chain step: named types, possibly with refs still undefined. */
1000
+ declare class Module<D extends Defs = {}, Decl = {}> {
1001
+ readonly defs: Readonly<Record<string, AnySchema>>;
1002
+ constructor(defs?: Readonly<Record<string, AnySchema>>);
1003
+ define<const D2 extends Defs>(defs: D2 & NoRedefine<D, D2>): Module<Merge<D, D2>, Decl>;
1004
+ /** Pin the code type of refs the dynamic step will supply. */
1005
+ declare<T extends Record<string, unknown>>(): Module<D, Merge<Decl, T>>;
1006
+ /** Supply the remaining refs from runtime args (a ctx, a registry, a DB engine...). */
1007
+ dynamic<A extends unknown[], R extends Defs & DynamicDefs<D, Decl>>(fn: (...args: A) => R, opts?: DynamicOptions<A>): DynamicModule<Merge<D, R>, Decl, A>;
1008
+ /** End the chain: a named type, or an inline schema (which may use refs). */
1009
+ result<const R extends Root<D>>(root: R & CheckRoot<D, Decl, R>): Bundle<ResultOut<D, R>, []>;
1010
+ }
1011
+ /** Chain step after `dynamic`: only `result` is left. */
1012
+ declare class DynamicModule<D extends Defs, Decl, A extends unknown[]> {
1013
+ readonly defs: Readonly<Record<string, AnySchema>>;
1014
+ readonly fn: (...args: A) => Defs;
1015
+ readonly opts: DynamicOptions<A>;
1016
+ constructor(defs: Readonly<Record<string, AnySchema>>, fn: (...args: A) => Defs, opts: DynamicOptions<A>);
1017
+ result<const R extends Root<D>>(root: R & CheckRoot<D, Decl, R>): Bundle<ResultOut<D, R>, A>;
1018
+ }
1019
+ /**
1020
+ * Anything Tool/Prompt accept: a ref-free schema or a bundle, whose dynamic
1021
+ * part (if any) is supplied by `A` at call time. `bind` is a property (not a
1022
+ * method) so `A` is checked contravariantly: a bundle that needs
1023
+ * `{ registry }` cannot be given to a tool whose ctx lacks one.
1024
+ */
1025
+ interface Bindable<Out, A extends unknown[] = []> {
1026
+ readonly _out: Out;
1027
+ readonly _refs: never;
1028
+ readonly bind: (...args: A) => Bound<Out>;
1029
+ }
1030
+ /** A finished chain. Build once (module scope); bind per call. */
1031
+ declare class Bundle<Out, A extends unknown[] = []> {
1032
+ readonly defs: Readonly<Record<string, AnySchema>>;
1033
+ readonly root: AnySchema;
1034
+ readonly dyn?: {
1035
+ readonly fn: (...args: A) => Defs;
1036
+ readonly opts: DynamicOptions<A>;
1037
+ } | undefined;
1038
+ readonly _out: Out;
1039
+ readonly _refs: never;
1040
+ private readonly cache;
1041
+ private staticBound;
1042
+ constructor(defs: Readonly<Record<string, AnySchema>>, root: AnySchema, dyn?: {
1043
+ readonly fn: (...args: A) => Defs;
1044
+ readonly opts: DynamicOptions<A>;
1045
+ } | undefined);
1046
+ readonly bind: (...args: A) => Bound<Out>;
1047
+ /**
1048
+ * The same bundle, bound from other arguments: `QueryModule.result(...)`
1049
+ * takes `(catalog, options)`, a tool's schema takes `(ctx)` —
1050
+ * `bundle.adapt((ctx: Ctx) => [ctx.catalog, { strict: true }])`. The bind
1051
+ * cache keys on the mapped arguments.
1052
+ */
1053
+ adapt<B extends unknown[]>(map: (...args: B) => A): Bundle<Out, B>;
1054
+ /** Shorthand for `bind(...args).render(profile)`. */
1055
+ render(profile: Profile, ...args: A): Rendered<Out>;
1056
+ }
1057
+ /** A bundle with its dynamic part supplied: every ref resolved. */
1058
+ declare class Bound<Out> {
1059
+ readonly env: ReadonlyMap<string, AnySchema>;
1060
+ readonly root: AnySchema;
1061
+ readonly _out: Out;
1062
+ private readonly rendered;
1063
+ constructor(env: ReadonlyMap<string, AnySchema>, root: AnySchema);
1064
+ /** The model-facing rendering for a profile, memoized on this bound instance. */
1065
+ render(profile: Profile): Rendered<Out>;
1066
+ }
1067
+ /** The static bundle of a ref-free schema (one per schema instance). */
1068
+ declare function staticBundle<Out>(s: Schema<Out, never>): Bundle<Out, []>;
1069
+
1070
+ /**
1071
+ * The schema classes. Each class:
1072
+ *
1073
+ * - carries its static types (`_out`, `_refs`, see `types.ts`),
1074
+ * - is immutable — `.describe()`, `.optional()` etc. return new instances,
1075
+ * built once at module scope, never per call,
1076
+ * - owns its model-facing logic in `compile(c)`: what JSON it emits for a
1077
+ * profile, how it validates + decodes the model's answer, how it encodes a
1078
+ * code value into the model's shape, and what prose hint it adds.
1079
+ */
1080
+
1081
+ /** Description text: plain, or computed from the model-facing view so prose matches the wire shape. */
1082
+ type Text = string | ((view: View) => string);
1083
+ /** Who a field is for. `people` fields are never shown to (or accepted from) a model. */
1084
+ type Audience = 'all' | 'people';
1085
+ interface Meta {
1086
+ readonly description?: Text;
1087
+ readonly title?: string;
1088
+ readonly examples?: readonly unknown[];
1089
+ readonly audience?: Audience;
1090
+ /** A narrower schema the MODEL sees in place of this one (e.g. an enum minus people-only members). */
1091
+ readonly forModels?: AnySchema;
1092
+ }
1093
+ interface Check {
1094
+ /**
1095
+ * `true` passes; `false`, a message, or several (zod's `superRefine`)
1096
+ * fail. A `{ path, message }` entry is a problem below the value.
1097
+ */
1098
+ readonly fn: (value: any) => boolean | string | readonly (string | RuleIssue)[];
1099
+ readonly message?: string;
1100
+ /** Show the rule to the model in the description (default true when a message is given). */
1101
+ readonly visible?: boolean;
1102
+ }
1103
+ type SchemaKind = 'string' | 'number' | 'boolean' | 'null' | 'literal' | 'enum' | 'array' | 'tuple' | 'object' | 'record' | 'union' | 'optional' | 'nullable' | 'ref' | 'any' | 'codec' | 'intersection' | 'not' | 'conditional' | 'dependent' | 'never' | 'default' | 'dispatch';
1104
+ /**
1105
+ * Any schema, structurally. An interface (not `Schema<any, any>`) so class
1106
+ * methods returning `this` never make one schema class "incompatible" with
1107
+ * the base during deep structural comparison.
1108
+ */
1109
+ interface AnySchema {
1110
+ readonly _out: unknown;
1111
+ readonly _refs: any;
1112
+ readonly kind: SchemaKind;
1113
+ readonly meta: Meta;
1114
+ readonly checks: readonly Check[];
1115
+ refNames(): ReadonlySet<string>;
1116
+ children(): readonly AnySchema[];
1117
+ compile(c: Compiler): Node;
1118
+ print(p: Printer): string;
1119
+ describe(text: Text): this;
1120
+ title(title: string): this;
1121
+ example(...values: any[]): this;
1122
+ refine(fn: (value: any) => boolean | string | readonly (string | RuleIssue)[], message?: string, opts?: {
1123
+ visible?: boolean;
1124
+ }): this;
1125
+ }
1126
+ /** `this` of a schema that uses no refs (so it can be bound without a chain). */
1127
+ interface RefFree {
1128
+ readonly _refs: never;
1129
+ }
1130
+ /** A schema whose code output is `Out`. */
1131
+ type SchemaOf<Out> = AnySchema & {
1132
+ readonly _out: Out;
1133
+ };
1134
+ type OutOf<S extends AnySchema> = S['_out'];
1135
+ type RefsOf<S extends AnySchema> = S['_refs'];
1136
+ declare abstract class Schema<Out = unknown, Refs extends string = never> {
1137
+ /** Code-shape output (phantom). */
1138
+ readonly _out: Out;
1139
+ /** Names of refs used below (phantom). */
1140
+ readonly _refs: Refs;
1141
+ abstract readonly kind: SchemaKind;
1142
+ readonly meta: Meta;
1143
+ readonly checks: readonly Check[];
1144
+ private _refNames;
1145
+ /** Direct children (for traversal / ref collection). */
1146
+ abstract children(): readonly AnySchema[];
1147
+ /** Build this schema's node for a profile. */
1148
+ abstract compile(c: Compiler): Node;
1149
+ /** TypeScript-like text of this schema. */
1150
+ abstract print(p: Printer): string;
1151
+ /** Runtime twin of `_refs`. */
1152
+ refNames(): ReadonlySet<string>;
1153
+ /** @internal A copy with metadata/checks/fields replaced (schemas are immutable). */
1154
+ with(patch: {
1155
+ meta?: Meta;
1156
+ checks?: readonly Check[];
1157
+ [field: string]: unknown;
1158
+ }): this;
1159
+ /** Description for the model (a string, or a function of the model-facing view). */
1160
+ describe(text: Text): this;
1161
+ title(title: string): this;
1162
+ /** Examples in the CODE shape; each profile renders them in its own wire shape. */
1163
+ example(...values: Loose<Out>[]): this;
1164
+ /**
1165
+ * A rule the type system can't say. Runs after decoding on the code value;
1166
+ * the error path is where the model wrote it (a `{ path, message }`
1167
+ * entry is a problem at that path below it). With a message the rule is
1168
+ * also shown to the model (pass `{ visible: false }` to keep it quiet).
1169
+ */
1170
+ refine(fn: (value: Loose<Out>) => boolean | string | readonly (string | RuleIssue)[], message?: string, opts?: {
1171
+ visible?: boolean;
1172
+ }): this;
1173
+ /** Nominal brand (type only). */
1174
+ brand<B extends string>(): this & {
1175
+ readonly _out: Out & Brand<B>;
1176
+ };
1177
+ /** Only for people (web forms, API callers); a model never sees or sends it. */
1178
+ forPeople(): this;
1179
+ /** What the model sees instead of this schema; its output must fit this one's. */
1180
+ forModels<M extends SchemaOf<Out>>(model: M): this;
1181
+ optional(): OptionalType<this>;
1182
+ nullable(): NullableType<this>;
1183
+ /** May be left out; then decodes as `value` (zod's `.default`). Required in the code shape. */
1184
+ default(value: Exclude<Loose<Out>, undefined>): DefaultType<this>;
1185
+ /** A ref-free schema is its own static bundle. */
1186
+ bind(this: RefFree): Bound<Out>;
1187
+ /** Shorthand for `bind().render(profile)` (ref-free schemas only). */
1188
+ render(this: RefFree, profile: Profile): Rendered<Out>;
1189
+ /** Rules with messages, as model-facing text. */
1190
+ protected ruleHint(): string | undefined;
1191
+ /** Constraint words (what the dialect couldn't say as keywords) and the rules, as one hint. */
1192
+ protected hintOf(words: readonly string[]): string | undefined;
1193
+ }
1194
+ interface StringOptions {
1195
+ readonly minLength?: number;
1196
+ readonly maxLength?: number;
1197
+ readonly pattern?: string;
1198
+ readonly format?: string;
1199
+ /** Regex flags (gin's `flags`, e.g. `'i'`). JSON Schema has none: a flagged pattern is said in words, and checked. */
1200
+ readonly flags?: string;
1201
+ }
1202
+ /** A regex in the subset strict providers compile: no lookaround, backreferences, `\b`, `\p{…}` or large `{n,m}`. */
1203
+ declare function isBasicPattern(p: string): boolean;
1204
+ declare class StringType extends Schema<string> {
1205
+ readonly options: StringOptions;
1206
+ readonly kind: "string";
1207
+ constructor(options?: StringOptions);
1208
+ children(): never[];
1209
+ min(n: number): this;
1210
+ max(n: number): this;
1211
+ pattern(re: RegExp | string, flags?: string): this;
1212
+ format(f: string): this;
1213
+ private opts;
1214
+ print(): string;
1215
+ compile(c: Compiler): Node;
1216
+ }
1217
+ interface NumberOptions {
1218
+ readonly int?: boolean;
1219
+ readonly minimum?: number;
1220
+ readonly maximum?: number;
1221
+ /** Strictly greater than (zod `.gt` / `.positive()`). */
1222
+ readonly exclusiveMinimum?: number;
1223
+ /** Strictly less than (zod `.lt` / `.negative()`). */
1224
+ readonly exclusiveMaximum?: number;
1225
+ }
1226
+ declare class NumberType extends Schema<number> {
1227
+ readonly options: NumberOptions;
1228
+ readonly kind: "number";
1229
+ constructor(options?: NumberOptions);
1230
+ children(): never[];
1231
+ min(n: number): this;
1232
+ max(n: number): this;
1233
+ /** Strictly greater than `n` (`exclusiveMinimum`). */
1234
+ gt(n: number): this;
1235
+ /** Strictly less than `n` (`exclusiveMaximum`). */
1236
+ lt(n: number): this;
1237
+ positive(): this;
1238
+ negative(): this;
1239
+ nonnegative(): this;
1240
+ int(): this;
1241
+ private opts;
1242
+ print(): string;
1243
+ compile(c: Compiler): Node;
1244
+ }
1245
+ declare class BooleanType extends Schema<boolean> {
1246
+ readonly kind: "boolean";
1247
+ children(): never[];
1248
+ print(): string;
1249
+ compile(c: Compiler): Node;
1250
+ }
1251
+ declare class NullType extends Schema<null> {
1252
+ readonly kind: "null";
1253
+ children(): never[];
1254
+ print(): string;
1255
+ compile(c: Compiler): Node;
1256
+ }
1257
+ type LiteralValue = string | number | boolean | null;
1258
+ declare class LiteralType<V extends LiteralValue> extends Schema<V> {
1259
+ readonly value: V;
1260
+ readonly kind: "literal";
1261
+ constructor(value: V);
1262
+ children(): never[];
1263
+ print(): string;
1264
+ compile(c: Compiler): Node;
1265
+ }
1266
+ declare class EnumType<V extends readonly [string, ...string[]]> extends Schema<V[number]> {
1267
+ readonly values: V;
1268
+ readonly kind: "enum";
1269
+ constructor(values: V);
1270
+ children(): never[];
1271
+ print(): string;
1272
+ compile(c: Compiler): Node;
1273
+ }
1274
+ /** Any JSON value (`a.unknown()` types it `unknown`, `a.json()` types it `JsonValue`). */
1275
+ declare class AnyType<Out = unknown> extends Schema<Out> {
1276
+ readonly kind: "any";
1277
+ children(): never[];
1278
+ print(): string;
1279
+ compile(c: Compiler): Node;
1280
+ }
1281
+ declare class ArrayType<E extends AnySchema> extends Schema<OutOf<E>[], RefsOf<E>> {
1282
+ readonly element: E;
1283
+ readonly options: {
1284
+ readonly minItems?: number;
1285
+ readonly maxItems?: number;
1286
+ };
1287
+ readonly kind: "array";
1288
+ constructor(element: E, options?: {
1289
+ readonly minItems?: number;
1290
+ readonly maxItems?: number;
1291
+ });
1292
+ children(): E[];
1293
+ min(n: number): this;
1294
+ max(n: number): this;
1295
+ print(p: Printer): string;
1296
+ compile(c: Compiler): Node;
1297
+ }
1298
+ type TupleOut<T extends readonly AnySchema[]> = {
1299
+ -readonly [K in keyof T]: T[K] extends AnySchema ? OutOf<T[K]> : never;
1300
+ };
1301
+ declare class TupleType<T extends readonly [AnySchema, ...AnySchema[]]> extends Schema<TupleOut<T>, RefsOf<T[number]>> {
1302
+ readonly items: T;
1303
+ readonly kind: "tuple";
1304
+ constructor(items: T);
1305
+ children(): T;
1306
+ print(p: Printer): string;
1307
+ compile(c: Compiler): Node;
1308
+ }
1309
+ type Shape = {
1310
+ readonly [key: string]: AnySchema;
1311
+ };
1312
+ type IsOptional<S> = S extends OptionalType<any> ? true : false;
1313
+ type OptionalKeys<S extends Shape> = {
1314
+ [K in keyof S]: IsOptional<S[K]> extends true ? K : never;
1315
+ }[keyof S];
1316
+ type RequiredKeys<S extends Shape> = Exclude<keyof S, OptionalKeys<S>>;
1317
+ /** Object output: required keys, then `?:` keys (absent — never `undefined` — after decoding). */
1318
+ type ObjectOut<S extends Shape> = Simplify<{
1319
+ -readonly [K in RequiredKeys<S>]: OutOf<S[K]>;
1320
+ } & {
1321
+ -readonly [K in OptionalKeys<S>]?: Exclude<OutOf<S[K]>, undefined>;
1322
+ }>;
1323
+ type ShapeRefs<S extends Shape> = {
1324
+ [K in keyof S]: RefsOf<S[K]>;
1325
+ }[keyof S] & string;
1326
+ /** An object with extra keys (`rest`) adds an index signature. */
1327
+ type ObjectRestOut<S extends Shape, R> = [R] extends [AnySchema] ? ObjectOut<S> & {
1328
+ [key: string]: OutOf<R>;
1329
+ } : ObjectOut<S>;
1330
+ type RestRefs<R> = R extends AnySchema ? RefsOf<R> & string : never;
1331
+ /** Extra keys of an object beyond its shape: by key pattern, then any other key. */
1332
+ interface ObjectExtras {
1333
+ /** The schema of any other key (`additionalProperties: schema`). */
1334
+ readonly rest?: AnySchema;
1335
+ /** Schemas of keys matching a pattern (`patternProperties`), tried before `rest`. */
1336
+ readonly patterns?: readonly {
1337
+ readonly pattern: string;
1338
+ readonly schema: AnySchema;
1339
+ }[];
1340
+ }
1341
+ declare class ObjectType<S extends Shape, R extends AnySchema | undefined = undefined> extends Schema<ObjectRestOut<S, R>, ShapeRefs<S> | RestRefs<R>> {
1342
+ readonly shape: S;
1343
+ readonly closed: boolean;
1344
+ readonly extras: ObjectExtras;
1345
+ readonly kind: "object";
1346
+ constructor(shape: S, closed?: boolean, extras?: ObjectExtras);
1347
+ children(): AnySchema[];
1348
+ /** Unknown keys are an error (default: left in place untouched — no copy to strip them). */
1349
+ strict(): this;
1350
+ extend<S2 extends Shape>(more: S2): ObjectType<Simplify<Omit<S, keyof S2> & S2>, R>;
1351
+ /** Keys beyond the shape, each a `V` (zod's `catchall`). */
1352
+ rest<V extends AnySchema>(value: V): ObjectType<S, V>;
1353
+ /** Keys matching a pattern (`patternProperties`); their values are typed `unknown` in the code shape. */
1354
+ patterns(patterns: {
1355
+ readonly [pattern: string]: AnySchema;
1356
+ }): ObjectType<S, AnyType<unknown>>;
1357
+ /**
1358
+ * A field whose schema depends on a sibling's DECODED value — e.g. a value
1359
+ * typed by the `type` the model wrote next to it. The model sees `base`
1360
+ * (default any JSON); decoding checks the value against `schemaFor(sibling)`.
1361
+ */
1362
+ dependent<K extends string, On extends keyof S & string, B extends AnySchema = AnyType<unknown>>(key: K, on: On, schemaFor: (sibling: Loose<OutOf<S[On]>>) => AnySchema | undefined, base?: B): ObjectType<Simplify<Omit<S, K> & {
1363
+ [P in K]: DependentType<OutOf<B>>;
1364
+ }>, R>;
1365
+ print(p: Printer): string;
1366
+ private _extraValue;
1367
+ /** The schema of an extra key's value as the model sees it (rest and patterns together). */
1368
+ private extraValue;
1369
+ compile(c: Compiler): Node;
1370
+ }
1371
+ declare class RecordType<V extends AnySchema, K extends string = string> extends Schema<string extends K ? Record<string, OutOf<V>> : Partial<Record<K, OutOf<V>>>, RefsOf<V>> {
1372
+ readonly value: V;
1373
+ readonly key?: (StringType | EnumType<any>) | undefined;
1374
+ readonly kind: "record";
1375
+ constructor(value: V, key?: (StringType | EnumType<any>) | undefined);
1376
+ children(): (StringType | V | EnumType<any>)[];
1377
+ print(p: Printer): string;
1378
+ compile(c: Compiler): Node;
1379
+ }
1380
+ declare class UnionType<O extends readonly [AnySchema, ...AnySchema[]]> extends Schema<OutOf<O[number]>, RefsOf<O[number]>> {
1381
+ readonly options: O;
1382
+ readonly tag?: string | undefined;
1383
+ readonly kind: "union";
1384
+ constructor(options: O, tag?: string | undefined);
1385
+ children(): O;
1386
+ print(p: Printer): string;
1387
+ /**
1388
+ * For a discriminated union: option index by tag value. A tag that is a
1389
+ * ref (e.g. a dynamic enum of registered names) is resolved through the
1390
+ * bound env. Options whose tag can't be indexed (a plain string) are the
1391
+ * fallback, tried in order.
1392
+ */
1393
+ private tagIndex;
1394
+ private label;
1395
+ compile(c: Compiler): Node;
1396
+ /** Which option a CODE value belongs to (by tag, else the first whose code shape accepts it). */
1397
+ private optionOf;
1398
+ }
1399
+ /**
1400
+ * Every member at once (`allOf`; gin's `and`). Objects are MERGED into one
1401
+ * object, which every dialect can say. Otherwise the first member is the
1402
+ * wire shape; the rest are `allOf` where the dialect has it (and no member
1403
+ * changes shape) or words, and always validated on the decoded value.
1404
+ */
1405
+ declare class IntersectionType<T extends readonly [AnySchema, ...AnySchema[]]> extends Schema<IntersectOut<T>, RefsOf<T[number]>> {
1406
+ readonly members: T;
1407
+ readonly kind: "intersection";
1408
+ constructor(members: T);
1409
+ children(): T;
1410
+ print(p: Printer): string;
1411
+ private readonly mergedByEnv;
1412
+ /** The members as one object, when every member is (or refers to) an object. */
1413
+ merged(env: ReadonlyMap<string, AnySchema>): AnySchema | undefined;
1414
+ compile(c: Compiler): Node;
1415
+ }
1416
+ type IntersectOut<T extends readonly AnySchema[]> = T extends readonly [infer H extends AnySchema, ...infer Rest extends readonly AnySchema[]] ? Rest extends readonly [] ? OutOf<H> : OutOf<H> & IntersectOut<Rest> : unknown;
1417
+ /** A value of `base` that must NOT match `excluded` (gin's `not<T>`; JSON Schema `not`). */
1418
+ declare class NotType<B extends AnySchema> extends Schema<OutOf<B>, RefsOf<B>> {
1419
+ readonly excluded: AnySchema;
1420
+ readonly base: B;
1421
+ readonly kind: "not";
1422
+ constructor(excluded: AnySchema, base: B);
1423
+ children(): AnySchema[];
1424
+ print(p: Printer): string;
1425
+ compile(c: Compiler): Node;
1426
+ }
1427
+ /** `if`/`then`/`else`: a value of `base`; when it matches `if` it must match `then`, otherwise `else`. */
1428
+ declare class ConditionalType<B extends AnySchema> extends Schema<OutOf<B>, RefsOf<B>> {
1429
+ readonly base: B;
1430
+ readonly when: AnySchema;
1431
+ readonly then?: AnySchema | undefined;
1432
+ readonly otherwise?: AnySchema | undefined;
1433
+ readonly kind: "conditional";
1434
+ constructor(base: B, when: AnySchema, then?: AnySchema | undefined, otherwise?: AnySchema | undefined);
1435
+ children(): AnySchema[];
1436
+ print(p: Printer): string;
1437
+ compile(c: Compiler): Node;
1438
+ }
1439
+ /**
1440
+ * A field typed by a sibling's value (see `ObjectType.dependent`). On its
1441
+ * own it is just `base`; inside an object the object decodes it last and
1442
+ * checks it against `schemaFor(sibling)`, rendered in the code shape (as
1443
+ * JSON text inside an escape hatch is). `schemaFor` should return cached
1444
+ * schemas: each new instance is compiled on first use.
1445
+ */
1446
+ declare class DependentType<Out = unknown> extends Schema<Out> {
1447
+ readonly on: string;
1448
+ readonly schemaFor: (sibling: unknown) => AnySchema | undefined;
1449
+ readonly base: AnySchema;
1450
+ readonly kind: "dependent";
1451
+ constructor(on: string, schemaFor: (sibling: unknown) => AnySchema | undefined, base?: AnySchema);
1452
+ children(): AnySchema[];
1453
+ print(p: Printer): string;
1454
+ compile(c: Compiler): Node;
1455
+ }
1456
+ /** One tool reachable through a dispatcher. */
1457
+ interface DispatchCase {
1458
+ readonly name: string;
1459
+ readonly description?: string;
1460
+ readonly schema: AnySchema;
1461
+ }
1462
+ /**
1463
+ * `{ tool, args }` where `args` is typed by `tool`: the arguments of one of
1464
+ * several tools, sent through ONE tool. A request with more tools than the
1465
+ * provider allows sends the overflow this way (`planRequest`). The model
1466
+ * sees the tool names as an enum and the arguments as the union of the
1467
+ * tools' argument schemas (one nullable field per tool where the dialect has
1468
+ * no unions); decoding picks the tool by name, never by trying shapes, and
1469
+ * decodes `args` with that tool's own node.
1470
+ */
1471
+ declare class DispatchType extends Schema<{
1472
+ tool: string;
1473
+ args: unknown;
1474
+ }> {
1475
+ readonly cases: readonly DispatchCase[];
1476
+ readonly tagKey: string;
1477
+ readonly argsKey: string;
1478
+ readonly kind: "dispatch";
1479
+ constructor(cases: readonly DispatchCase[], tagKey?: string, argsKey?: string);
1480
+ children(): AnySchema[];
1481
+ print(p: Printer): string;
1482
+ compile(c: Compiler): Node;
1483
+ }
1484
+ /**
1485
+ * No value at all (zod's `never`). Used where a runtime list comes out empty:
1486
+ * query's `joins` when no type has a relation, a function name when no
1487
+ * function is selected. A union leaves never options out; a list of never
1488
+ * must be empty; an optional object field of never is not shown to the
1489
+ * model (and refused if sent).
1490
+ */
1491
+ declare class NeverType extends Schema<never> {
1492
+ readonly kind: "never";
1493
+ children(): never[];
1494
+ print(): string;
1495
+ compile(c: Compiler): Node;
1496
+ }
1497
+ /** Does this schema (through refs) admit no value at all? */
1498
+ declare function isNever(s: AnySchema | undefined, env: ReadonlyMap<string, AnySchema>): boolean;
1499
+ /**
1500
+ * A value that may be left out and then reads as `value` (zod's `.default`).
1501
+ * In an object the key is optional for the model (or `null` where absent is
1502
+ * written null) and REQUIRED in the code shape: decoding writes the default
1503
+ * in. Outside an object `undefined` decodes to the default.
1504
+ */
1505
+ declare class DefaultType<T extends AnySchema> extends Schema<Exclude<OutOf<T>, undefined>, RefsOf<T>> {
1506
+ readonly inner: T;
1507
+ readonly value: Exclude<OutOf<T>, undefined>;
1508
+ readonly kind: "default";
1509
+ constructor(inner: T, value: Exclude<OutOf<T>, undefined>);
1510
+ children(): T[];
1511
+ print(p: Printer): string;
1512
+ /** A fresh copy of the default (containers are never shared between decoded values). */
1513
+ fresh(stats?: CopyStats): unknown;
1514
+ compile(c: Compiler): Node;
1515
+ }
1516
+ declare class OptionalType<T extends AnySchema> extends Schema<OutOf<T> | undefined, RefsOf<T>> {
1517
+ readonly inner: T;
1518
+ readonly kind: "optional";
1519
+ constructor(inner: T);
1520
+ children(): T[];
1521
+ print(p: Printer): string;
1522
+ /** Outside an object (array element, root): null-for-absent becomes `undefined`. */
1523
+ compile(c: Compiler): Node;
1524
+ }
1525
+ declare class NullableType<T extends AnySchema> extends Schema<OutOf<T> | null, RefsOf<T>> {
1526
+ readonly inner: T;
1527
+ readonly kind: "nullable";
1528
+ constructor(inner: T);
1529
+ children(): T[];
1530
+ print(p: Printer): string;
1531
+ compile(c: Compiler): Node;
1532
+ }
1533
+ /** A use of a named type, defined in the chain (statically or by the dynamic step). */
1534
+ declare class RefType<N extends string, Out = RefMarker<N>, R extends string = N> extends Schema<Out, R> {
1535
+ readonly name: N;
1536
+ readonly kind: "ref";
1537
+ constructor(name: N);
1538
+ children(): never[];
1539
+ print(p: Printer): string;
1540
+ compile(c: Compiler): Node;
1541
+ }
1542
+ /**
1543
+ * A value whose CODE form differs from what the model writes — e.g. a fn
1544
+ * name the model spells `sys__a__b` and the code calls `sys/a.b`. The model
1545
+ * sees `wire`; decoding maps through `decode`, examples through `encode`.
1546
+ */
1547
+ declare class CodecType<W extends AnySchema, Out> extends Schema<Out, RefsOf<W>> {
1548
+ readonly wire: W;
1549
+ /** `decode` may reject: an `Error` (one problem here) or a `Rejection` (problems at paths below). */
1550
+ readonly codec: {
1551
+ readonly decode: (wire: OutOf<W>) => Out | Error | Rejection;
1552
+ readonly encode: (value: Out) => OutOf<W>;
1553
+ };
1554
+ readonly kind: "codec";
1555
+ constructor(wire: W,
1556
+ /** `decode` may reject: an `Error` (one problem here) or a `Rejection` (problems at paths below). */
1557
+ codec: {
1558
+ readonly decode: (wire: OutOf<W>) => Out | Error | Rejection;
1559
+ readonly encode: (value: Out) => OutOf<W>;
1560
+ });
1561
+ children(): W[];
1562
+ print(p: Printer): string;
1563
+ compile(c: Compiler): Node;
1564
+ }
1565
+
1566
+ type J = {
1567
+ [key: string]: any;
1568
+ } | boolean;
1569
+ interface ImportReport {
1570
+ /** Keywords that could not be represented exactly. */
1571
+ readonly unsupported: string[];
1572
+ }
1573
+ declare function fromJSONSchema<T = unknown>(schema: J, report?: ImportReport): Bundle<T, []>;
1574
+
1575
+ /**
1576
+ * `a` — the builder, like zod's `z`.
1577
+ *
1578
+ * import { a } from '@aeye/schema';
1579
+ * const Task = a.object({ title: a.string(), tags: a.record(a.number()) });
1580
+ * type Task = a.infer<typeof Task>;
1581
+ */
1582
+
1583
+ declare const string: () => StringType;
1584
+ declare const number: () => NumberType;
1585
+ declare const int: () => NumberType;
1586
+ declare const boolean: () => BooleanType;
1587
+ declare const null_: () => NullType;
1588
+ declare const literal: <const V extends LiteralValue>(value: V) => LiteralType<V>;
1589
+ /**
1590
+ * `a.enum(['a', 'b'])` — typed by its values. A list known only at runtime
1591
+ * (`a.enum(names)`, a `string[]`) is typed `string`; an empty one admits
1592
+ * nothing (`never`).
1593
+ */
1594
+ declare function enum_<const V extends readonly [string, ...string[]]>(values: V): EnumType<V>;
1595
+ declare function enum_(values: readonly string[]): EnumType<[string, ...string[]]>;
1596
+ /** No value at all (zod's `never`): an empty runtime list, a list that must stay empty. */
1597
+ declare const never_: () => NeverType;
1598
+
1599
+ /** Any JSON value, typed `unknown`. */
1600
+ declare const unknown: () => AnyType<unknown>;
1601
+ /** Any JSON value, typed `JsonValue`. */
1602
+ declare const json: () => AnyType<JsonValue>;
1603
+ declare const object: <const S extends Shape>(shape: S) => ObjectType<S>;
1604
+ declare const array: <E extends AnySchema>(element: E) => ArrayType<E>;
1605
+ declare const tuple: <const T extends readonly [AnySchema, ...AnySchema[]]>(items: T) => TupleType<T>;
1606
+ /** `a.record(V)` — string keys; `a.record(a.enum([...]), V)` — known keys (all optional). */
1607
+ declare function record<V extends AnySchema>(value: V): RecordType<V>;
1608
+ declare function record<K extends StringType | EnumType<any>, V extends AnySchema>(key: K, value: V): RecordType<V, K extends EnumType<infer E> ? E[number] : string>;
1609
+ /**
1610
+ * `a.union([A, B])` — typed per option. Options built at runtime
1611
+ * (`a.union(list)`, an `S[]`) are typed by the element type; an empty list
1612
+ * admits nothing (`never`).
1613
+ */
1614
+ declare function union<const O extends readonly [AnySchema, ...AnySchema[]]>(options: O): UnionType<O>;
1615
+ declare function union<S extends AnySchema>(options: readonly S[]): UnionType<[S, ...S[]]>;
1616
+ type TagCheck<Tag extends string, O extends readonly unknown[]> = {
1617
+ readonly [I in keyof O]: O[I] extends ObjectType<infer S> ? (Tag extends keyof S ? unknown : {
1618
+ readonly 'missing tag field': Tag;
1619
+ }) : unknown;
1620
+ };
1621
+ /** A union picked by a literal field (`tag`) on each object option; options may be a runtime list. */
1622
+ declare function discriminatedUnion<const Tag extends string, const O extends readonly [ObjectType<any>, ...ObjectType<any>[]]>(tag: Tag, options: O & TagCheck<Tag, O>): UnionType<O>;
1623
+ /** Options that are named types (refs): each keeps its own `$defs` entry; checked when bound. */
1624
+ declare function discriminatedUnion<const Tag extends string, const O extends readonly [AnySchema & {
1625
+ readonly kind: 'ref';
1626
+ }, ...(AnySchema & {
1627
+ readonly kind: 'ref';
1628
+ })[]]>(tag: Tag, options: O): UnionType<O>;
1629
+ declare function discriminatedUnion<const Tag extends string, S extends ObjectType<{
1630
+ readonly [K in Tag]: AnySchema;
1631
+ }, any>>(tag: Tag, options: readonly S[]): UnionType<[S, ...S[]]>;
1632
+ /** Every member at once (`allOf`, gin's `and`): objects are merged, anything else is validated after the first. */
1633
+ declare const intersection: <const T extends readonly [AnySchema, ...AnySchema[]]>(members: T) => IntersectionType<T>;
1634
+ /** A value of `base` (default any JSON) that must NOT match `excluded` (gin's `not`, JSON Schema `not`). */
1635
+ declare function not<B extends AnySchema = AnyType<unknown>>(excluded: AnySchema, base?: B): NotType<B>;
1636
+ /** JSON Schema `if`/`then`/`else` over a value of `base`: said in words where unsupported, always validated. */
1637
+ declare function conditional<B extends AnySchema>(base: B, rule: {
1638
+ if: AnySchema;
1639
+ then?: AnySchema;
1640
+ else?: AnySchema;
1641
+ }): ConditionalType<B>;
1642
+ /**
1643
+ * A field typed by a sibling field's decoded value; use inside `a.object`.
1644
+ * `a.object({...}).dependent(key, on, fn)` types `fn`'s argument from the sibling.
1645
+ */
1646
+ declare function dependent<Out = unknown>(on: string, schemaFor: (sibling: unknown) => AnySchema | undefined, base?: AnySchema): DependentType<Out>;
1647
+ declare const optional: <T extends AnySchema>(inner: T) => OptionalType<T>;
1648
+ /** `inner`, which may be left out and then reads as `value` (zod's `.default`); same as `inner.default(value)`. */
1649
+ declare const default_: <T extends AnySchema>(inner: T, value: Exclude<OutOf<T>, undefined>) => DefaultType<T>;
1650
+
1651
+ declare const nullable: <T extends AnySchema>(inner: T) => NullableType<T>;
1652
+ /** A use of a named type; defined later in the chain (statically or by the dynamic step). */
1653
+ declare const ref: <const N extends string>(name: N) => RefType<N>;
1654
+ /**
1655
+ * A use of a named type whose NAME is only known at runtime (a dynamic step
1656
+ * that names types after runtime data: `Fields_${table}`, a registry's
1657
+ * types). The code type is stated (`a.refOf<string>(name)`); the name can't
1658
+ * be checked at compile time, so it is checked when the bundle is bound.
1659
+ */
1660
+ declare const refOf: <Out>(name: string) => RefType<string, Out, never>;
1661
+ /** A value the model writes as `wire` and the code holds as `Out`. */
1662
+ declare const codec: <W extends AnySchema, Out>(wire: W, codec: {
1663
+ decode: (wire: OutOf<W>) => Out | Error | Rejection;
1664
+ encode: (value: Out) => OutOf<W>;
1665
+ }) => CodecType<W, Out>;
1666
+ /** `{ tool, args }`: the arguments of one of several tools, picked by name (see `DispatchType`). */
1667
+ declare const dispatch: (cases: readonly DispatchCase[], keys?: {
1668
+ tag?: string;
1669
+ args?: string;
1670
+ }) => DispatchType;
1671
+ /** Start a chain with named types. */
1672
+ declare const define: <const D extends Defs>(defs: D) => Module<D, {}>;
1673
+ /** Start a chain by pinning the types of refs a dynamic step will supply. */
1674
+ declare const declare: <T extends Record<string, unknown>>() => Module<{}, T>;
1675
+ /** Start an empty chain. */
1676
+ declare const module_: () => Module<{}, {}>;
1677
+
1678
+ /** The code-shape type of a schema or bundle. */
1679
+ type Infer<S extends {
1680
+ readonly _out: unknown;
1681
+ }> = S['_out'];
1682
+
1683
+ type a_Infer<S extends {
1684
+ readonly _out: unknown;
1685
+ }> = Infer<S>;
1686
+ declare const a_array: typeof array;
1687
+ declare const a_boolean: typeof boolean;
1688
+ declare const a_codec: typeof codec;
1689
+ declare const a_conditional: typeof conditional;
1690
+ declare const a_declare: typeof declare;
1691
+ declare const a_define: typeof define;
1692
+ declare const a_dependent: typeof dependent;
1693
+ declare const a_discriminatedUnion: typeof discriminatedUnion;
1694
+ declare const a_dispatch: typeof dispatch;
1695
+ declare const a_fromJSONSchema: typeof fromJSONSchema;
1696
+ declare const a_int: typeof int;
1697
+ declare const a_intersection: typeof intersection;
1698
+ declare const a_json: typeof json;
1699
+ declare const a_literal: typeof literal;
1700
+ declare const a_not: typeof not;
1701
+ declare const a_nullable: typeof nullable;
1702
+ declare const a_number: typeof number;
1703
+ declare const a_object: typeof object;
1704
+ declare const a_optional: typeof optional;
1705
+ declare const a_record: typeof record;
1706
+ declare const a_ref: typeof ref;
1707
+ declare const a_refOf: typeof refOf;
1708
+ declare const a_string: typeof string;
1709
+ declare const a_tuple: typeof tuple;
1710
+ declare const a_union: typeof union;
1711
+ declare const a_unknown: typeof unknown;
1712
+ declare namespace a {
1713
+ export { type a_Infer as Infer, a_array as array, a_boolean as boolean, a_codec as codec, a_conditional as conditional, a_declare as declare, default_ as default, a_define as define, a_dependent as dependent, a_discriminatedUnion as discriminatedUnion, a_dispatch as dispatch, enum_ as enum, a_fromJSONSchema as fromJSONSchema, type Infer as infer, a_int as int, a_intersection as intersection, a_json as json, a_literal as literal, module_ as module, never_ as never, a_not as not, null_ as null, a_nullable as nullable, a_number as number, a_object as object, a_optional as optional, a_record as record, a_ref as ref, a_refOf as refOf, a_string as string, a_tuple as tuple, a_union as union, a_unknown as unknown };
1714
+ }
1715
+
1716
+ /**
1717
+ * Showing values in instructions and prompts exactly as the model reads and
1718
+ * writes them.
1719
+ *
1720
+ * aeye's tools and prompts render their instructions/content with Handlebars
1721
+ * (`Handlebars.compile(template, { noEscape: true })` in `@aeye/core`'s
1722
+ * `Tool.compileInstructions` / `Prompt.compileContent`). A value written into
1723
+ * those templates as plain JSON is in the CODE shape — but a strict model
1724
+ * might write the same record as `[{key, value}]` pairs, an absent optional
1725
+ * as `null`, or a recursive part as JSON text. `{{encode value}}` writes it in
1726
+ * the shape of the schema the model actually has, for its profile, in this
1727
+ * request:
1728
+ *
1729
+ * ```hbs
1730
+ * Call it like this: {{encode example}}
1731
+ * The current limits are {{encode limits path="limits"}}.
1732
+ * The report you return looks like {{encode sample output=true pretty=true}}.
1733
+ * Search takes {{encode query tool="search"}}.
1734
+ * ```
1735
+ *
1736
+ * Two ways to supply the helpers, both work with `noEscape` on or off:
1737
+ *
1738
+ * - per render: `template(vars, { helpers: entry.helpers() })` (or
1739
+ * `request.helpers('toolName')`);
1740
+ * - once: `registerSchemaHelpers(Handlebars)`, then per render
1741
+ * `template(vars, { data: schemaData(entry) })`.
1742
+ *
1743
+ * Function-form instructions (core's `instructionsFn`) use the entry's
1744
+ * `encoder` instead: it needs only the value.
1745
+ */
1746
+
1747
+ /** What a template helper can encode through. */
1748
+ type SchemaTarget = Rendered<any> | RequestEntry<any> | RenderedRequest<any>;
1749
+ /** The Handlebars helper options this module reads (structural; no Handlebars import). */
1750
+ interface HelperOptions {
1751
+ readonly hash?: {
1752
+ readonly [key: string]: unknown;
1753
+ };
1754
+ readonly data?: {
1755
+ readonly [key: string]: unknown;
1756
+ };
1757
+ }
1758
+ type Helper = (...args: any[]) => unknown;
1759
+ /** `encode` and `schema` helpers (a Handlebars `helpers` object). */
1760
+ interface HelperSet {
1761
+ readonly [name: string]: Helper;
1762
+ /** `{{encode value [pretty=true|2] [path="a.b"] [tool="name"] [output=true]}}` → JSON text in the model's shape. */
1763
+ readonly encode: Helper;
1764
+ /** `{{schema [tool="name"] [output=true]}}` → the schema as TypeScript-like text. */
1765
+ readonly schema: Helper;
1766
+ }
1767
+ /** The `data` key `registerSchemaHelpers` reads its target from. */
1768
+ declare const SCHEMA_DATA_KEY = "aeyeSchema";
1769
+ /**
1770
+ * Helpers bound to one target: a rendering, a request entry, or a whole
1771
+ * request (then `defaultName` is the schema `{{encode value}}` means).
1772
+ * Pass as `template(vars, { helpers: schemaHelpers(entry) })`.
1773
+ */
1774
+ declare function schemaHelpers(target: SchemaTarget, defaultName?: string): HelperSet;
1775
+ /** The `data` for a render when the helpers are registered globally. */
1776
+ declare function schemaData(target: SchemaTarget, defaultName?: string): {
1777
+ readonly [SCHEMA_DATA_KEY]: {
1778
+ target: SchemaTarget;
1779
+ defaultName: string | undefined;
1780
+ };
1781
+ };
1782
+ /**
1783
+ * Register `encode` and `schema` on a Handlebars instance; each render then
1784
+ * names its target with `{ data: schemaData(entry) }`.
1785
+ */
1786
+ declare function registerSchemaHelpers(handlebars: {
1787
+ registerHelper(name: string, fn: Helper): void;
1788
+ }, names?: {
1789
+ encode?: string;
1790
+ schema?: string;
1791
+ }): void;
1792
+
1793
+ /**
1794
+ * One request, rendered as a whole.
1795
+ *
1796
+ * Providers limit the REQUEST, not only each schema: Anthropic allows 20
1797
+ * strict tools, 24 optional parameters and 16 union-typed parameters across
1798
+ * every strict schema in one request [ANT-SO]; OpenAI caps a request at 128
1799
+ * tools and each strict schema at 5,000 properties / 10 levels / 120,000
1800
+ * characters / 1,000 enum values [OAI-SO]. So the rendering of one schema
1801
+ * depends on the others: `planRequest` decides, for every tool's arguments
1802
+ * and the structured output together, what each schema is rendered with,
1803
+ * and records it on the schema's `RequestEntry`.
1804
+ *
1805
+ * A request ALWAYS comes back sendable, whatever it holds — tools are often
1806
+ * not known ahead of time, and an error where degrading works is worse than
1807
+ * the degradation (Phil, DESIGN.md). Nothing is thrown; every compromise is
1808
+ * recorded on its entry (`adjustments`, `reasons`) and summarized in
1809
+ * `degradations`. A caller that wants an error opts in
1810
+ * (`assertNoDegradation()`, or `{ failOnDegrade: true }`).
1811
+ *
1812
+ * Every later use of a schema — the JSON sent, decoding the answer, error
1813
+ * paths, values encoded into instructions and examples — goes through the
1814
+ * entry's ONE `Rendered`, so nothing can drift from what the model was shown.
1815
+ *
1816
+ * How a schema is fitted, in order (the first that fits wins):
1817
+ *
1818
+ * 1. the model's profile for its kind, as is;
1819
+ * 2. the same profile with absent optionals written as `null` (Anthropic:
1820
+ * trades optional parameters for union types);
1821
+ * 3. with large enums widened to strings that list their values (fewer enum
1822
+ * values and characters; still enforced on decode);
1823
+ * 4. with deep nesting written as JSON text (fewer levels and properties);
1824
+ * 5. not strict: the family's loose profile — the model isn't constrained,
1825
+ * the answer is still validated by the same schema (a strict structured
1826
+ * output on a family whose output is always strict goes as prompt text).
1827
+ *
1828
+ * Items are fitted in priority order (`strict: true` first, then higher
1829
+ * numbers; core's convention), so the most wanted schemas spend the budget
1830
+ * first. `strict: true` is the strongest preference, not a guarantee: when the
1831
+ * strict slots or totals run out, it is sent non-strict and says why.
1832
+ *
1833
+ * More tools than the provider takes: the highest-priority ones stay tools;
1834
+ * the rest go behind ONE dispatcher tool (`run_tool({ tool, args })`, a
1835
+ * `DispatchType`) whose args are the overflow tools' own schemas.
1836
+ * `decodeCall` turns a dispatcher call back into the original tool's name and
1837
+ * decoded args, so callers never see the dispatcher.
1838
+ */
1839
+
1840
+ /** A schema in a request: a bound bundle, or a ref-free schema / static bundle. */
1841
+ type RequestSchema<Out> = Bound<Out> | Bindable<Out, []>;
1842
+ /** Strict request, as core spells it: `true` most wanted, `false` refuses, a number > 0 prefers (higher first). */
1843
+ type Strictness = boolean | number;
1844
+ interface ToolItem<N extends string = string, Out = unknown> {
1845
+ readonly kind: 'tool';
1846
+ readonly name: N;
1847
+ readonly schema: RequestSchema<Out>;
1848
+ /** Default `1` (prefer strict). */
1849
+ readonly strict?: Strictness;
1850
+ /** Shown in the dispatcher's tool list if this tool ends up behind it. */
1851
+ readonly description?: string;
1852
+ /** How a bad call is told to the model (the tool definition's choice; a call can override). */
1853
+ readonly errorFormat?: ErrorFormatInput;
1854
+ }
1855
+ interface OutputItem<N extends string = 'output', Out = unknown> {
1856
+ readonly kind: 'output';
1857
+ /** Default `'output'`. */
1858
+ readonly name?: N;
1859
+ readonly schema: RequestSchema<Out>;
1860
+ /** Default `1` (prefer strict). */
1861
+ readonly strict?: Strictness;
1862
+ /** `'prompt'` always sends the schema as prompt text; `'auto'` (default) only when it can't be structured. */
1863
+ readonly delivery?: 'auto' | 'structured' | 'prompt';
1864
+ /** How a bad answer is told to the model (the prompt definition's choice; a call can override). */
1865
+ readonly errorFormat?: ErrorFormatInput;
1866
+ }
1867
+ type RequestItem = ToolItem<string, any> | OutputItem<string, any>;
1868
+ interface RequestOptions {
1869
+ /** Throw a `RequestLimitError` when anything had to be degraded (default false: never throw). */
1870
+ readonly failOnDegrade?: boolean;
1871
+ /** The dispatcher tool's name (default `run_tool`, made unique among the tools). */
1872
+ readonly dispatcherName?: string;
1873
+ /** The error format of every schema in the request; an item's own `errorFormat` wins over it. */
1874
+ readonly errorFormat?: ErrorFormatInput;
1875
+ }
1876
+ /** The name an item is looked up by. */
1877
+ type ItemName<I> = I extends {
1878
+ readonly kind: 'output';
1879
+ } ? (I extends {
1880
+ readonly name: infer N extends string;
1881
+ } ? N : 'output') : I extends {
1882
+ readonly name: infer N extends string;
1883
+ } ? N : never;
1884
+ /** The code-shape output of an item's schema (`unknown` when the item list is computed). */
1885
+ type ItemOut<I> = I extends {
1886
+ readonly schema: {
1887
+ readonly _out: infer O;
1888
+ };
1889
+ } ? (0 extends 1 & O ? unknown : O) : unknown;
1890
+ /** The item named `N` (an item whose name is only known as `string` may be any of them). */
1891
+ type ByName<I, N> = I extends unknown ? (N extends ItemName<I> ? I : string extends ItemName<I> ? I : never) : never;
1892
+ /** One change made to the model's profile (or the item) for this schema. */
1893
+ type Adjustment = {
1894
+ readonly kind: 'optional-as-null';
1895
+ } | {
1896
+ readonly kind: 'enums-widened';
1897
+ readonly maxEnumValues: number;
1898
+ } | {
1899
+ readonly kind: 'depth-limited';
1900
+ readonly maxDepth: number;
1901
+ } | {
1902
+ readonly kind: 'root-wrapped';
1903
+ } | {
1904
+ readonly kind: 'not-strict';
1905
+ readonly reason: string;
1906
+ } | {
1907
+ readonly kind: 'prompt-text';
1908
+ readonly reason: string;
1909
+ } | {
1910
+ readonly kind: 'renamed';
1911
+ readonly from: string;
1912
+ } | {
1913
+ readonly kind: 'dispatched';
1914
+ readonly via: string;
1915
+ readonly reason: string;
1916
+ };
1917
+ /** Core's priority order: `true` first, `false` last, numbers by size, unset/0 → 0. */
1918
+ declare function strictPriority(requested: Strictness | undefined): number;
1919
+ /** One schema of a rendered request: what it is rendered with, why, and its codec. */
1920
+ declare class RequestEntry<Out = unknown> {
1921
+ readonly name: string;
1922
+ readonly kind: 'tool' | 'output';
1923
+ readonly requested: Strictness;
1924
+ /** What the model offers for this kind of schema. */
1925
+ readonly base: Profile;
1926
+ /** Exactly what this schema is rendered with (the base plus `adjustments`). */
1927
+ readonly profile: Profile;
1928
+ /** Send with `strict: true` (or as strict structured output). */
1929
+ readonly strict: boolean;
1930
+ /**
1931
+ * `structured`: sent as its own tool / response format. `prompt`: the
1932
+ * schema goes as prompt text. `dispatched`: a tool reached through the
1933
+ * dispatcher (`via`); not sent on its own.
1934
+ */
1935
+ readonly delivery: 'structured' | 'prompt' | 'dispatched';
1936
+ readonly adjustments: readonly Adjustment[];
1937
+ /** The limits that ruled out the earlier choices (empty when the base fit). */
1938
+ readonly reasons: readonly string[];
1939
+ readonly rendered: Rendered<Out>;
1940
+ /** The name the caller gave (differs from `name` only when two items shared one). */
1941
+ readonly requestedName: string;
1942
+ /** The dispatcher tool this tool is reached through. */
1943
+ readonly via?: string | undefined;
1944
+ /** The bound schema itself (for renderings other than `rendered`). */
1945
+ readonly boundSchema: Bound<Out>;
1946
+ readonly _out: Out;
1947
+ constructor(name: string, kind: 'tool' | 'output', requested: Strictness,
1948
+ /** What the model offers for this kind of schema. */
1949
+ base: Profile,
1950
+ /** Exactly what this schema is rendered with (the base plus `adjustments`). */
1951
+ profile: Profile,
1952
+ /** Send with `strict: true` (or as strict structured output). */
1953
+ strict: boolean,
1954
+ /**
1955
+ * `structured`: sent as its own tool / response format. `prompt`: the
1956
+ * schema goes as prompt text. `dispatched`: a tool reached through the
1957
+ * dispatcher (`via`); not sent on its own.
1958
+ */
1959
+ delivery: 'structured' | 'prompt' | 'dispatched', adjustments: readonly Adjustment[],
1960
+ /** The limits that ruled out the earlier choices (empty when the base fit). */
1961
+ reasons: readonly string[], rendered: Rendered<Out>,
1962
+ /** The name the caller gave (differs from `name` only when two items shared one). */
1963
+ requestedName?: string,
1964
+ /** The dispatcher tool this tool is reached through. */
1965
+ via?: string | undefined,
1966
+ /** The bound schema itself (for renderings other than `rendered`). */
1967
+ boundSchema?: Bound<Out>);
1968
+ /** How a bad answer is told to the model: the request's format, then the item's (`ToolItem.errorFormat`). */
1969
+ errorFormat: ErrorFormat | undefined;
1970
+ /** What the model wrote, as the error message names it: `the arguments of search`, `your answer`. */
1971
+ get label(): string;
1972
+ /** Parse options with this entry's error format and label (a call's own options win). */
1973
+ private opts;
1974
+ /** The JSON Schema to send; `undefined` when the schema goes as prompt text or through the dispatcher. */
1975
+ get jsonSchema(): JsonSchema | undefined;
1976
+ /** The schema as prompt text (prompt-text delivery), with the family's JSON instruction. */
1977
+ get promptText(): string;
1978
+ /** What this schema counts toward the provider's limits. */
1979
+ get measure(): SchemaMeasure;
1980
+ /** Decode the model's answer; a failure's `message` is in this entry's error format. */
1981
+ parse(wire: unknown, opts?: ParseOptions): ParseResult<Out>;
1982
+ parseText(text: string, opts?: Omit<ParseOptions, 'inPlace'>): ParseResult<Out>;
1983
+ parseOrThrow(wire: unknown, opts?: ParseOptions): Out;
1984
+ /** A value as this model writes it for this schema. */
1985
+ encode(value: Out, stats?: CopyStats): unknown;
1986
+ encodeText(value: Out, opts?: EncodeTextOptions): string;
1987
+ /** `encode` needing only the value: for instruction functions, examples and injected values. */
1988
+ get encoder(): Encoder<Out>;
1989
+ /** Handlebars helpers bound to this schema (`{{encode value}}`, `{{schema}}`). */
1990
+ helpers(): HelperSet;
1991
+ }
1992
+ /** A tool call decoded back to the tool the caller registered (through the dispatcher or not). */
1993
+ type DecodedCall = {
1994
+ readonly ok: true;
1995
+ readonly tool: string;
1996
+ readonly value: unknown;
1997
+ readonly via?: string;
1998
+ } | {
1999
+ readonly ok: false;
2000
+ readonly tool: string | undefined;
2001
+ readonly issues: readonly Issue[];
2002
+ readonly message: string;
2003
+ };
2004
+ /** Every schema of one request, fitted together. Always sendable. */
2005
+ declare class RenderedRequest<I extends readonly RequestItem[] = readonly RequestItem[]> {
2006
+ readonly target: ModelProfile;
2007
+ /** In the order the items were given (then the dispatcher, if one was needed). */
2008
+ readonly entries: readonly RequestEntry<any>[];
2009
+ /** What the strict schemas add up to (the request totals). */
2010
+ readonly used: SchemaMeasure;
2011
+ /** How many tools went strict. */
2012
+ readonly strictTools: number;
2013
+ /** The request limits that applied. */
2014
+ readonly limits: RequestLimits;
2015
+ /** Everything that was degraded to make the request fit, readable. Empty when nothing was. */
2016
+ readonly degradations: readonly string[];
2017
+ /** The dispatcher tool, when there were more tools than the provider takes. */
2018
+ readonly dispatcher?: RequestEntry<{
2019
+ tool: string;
2020
+ args: unknown;
2021
+ }> | undefined;
2022
+ /** Dispatched tools whose args the dispatcher took as plain JSON (named-type clash): checked on decode. */
2023
+ private readonly checkLater;
2024
+ private readonly byName;
2025
+ constructor(target: ModelProfile,
2026
+ /** In the order the items were given (then the dispatcher, if one was needed). */
2027
+ entries: readonly RequestEntry<any>[],
2028
+ /** What the strict schemas add up to (the request totals). */
2029
+ used: SchemaMeasure,
2030
+ /** How many tools went strict. */
2031
+ strictTools: number,
2032
+ /** The request limits that applied. */
2033
+ limits: RequestLimits,
2034
+ /** Everything that was degraded to make the request fit, readable. Empty when nothing was. */
2035
+ degradations: readonly string[],
2036
+ /** The dispatcher tool, when there were more tools than the provider takes. */
2037
+ dispatcher?: RequestEntry<{
2038
+ tool: string;
2039
+ args: unknown;
2040
+ }> | undefined,
2041
+ /** Dispatched tools whose args the dispatcher took as plain JSON (named-type clash): checked on decode. */
2042
+ checkLater?: ReadonlySet<string>);
2043
+ /** The entry of a tool by name, or of the output (`'output'` unless named). */
2044
+ get<N extends ItemName<I[number]>>(name: N): RequestEntry<ItemOut<ByName<I[number], N>>>;
2045
+ has(name: string): boolean;
2046
+ /** Every tool entry (dispatched ones included). */
2047
+ get tools(): readonly RequestEntry<unknown>[];
2048
+ /** The tools to SEND: each direct tool, and the dispatcher. */
2049
+ get sent(): readonly RequestEntry<unknown>[];
2050
+ get output(): RequestEntry<unknown> | undefined;
2051
+ /**
2052
+ * Decode a tool call the model made: by the name it called and its raw
2053
+ * args (parsed JSON). A dispatcher call comes back as the ORIGINAL tool's
2054
+ * name and decoded args, with `via` naming the dispatcher.
2055
+ */
2056
+ decodeCall(name: string, args: unknown, opts?: ParseOptions): DecodedCall;
2057
+ /** A call to a tool the request doesn't have: the nearest name, or the list. */
2058
+ private unknownTool;
2059
+ /** A call to a tool as this model would make it: `{ name, args }` (through the dispatcher when the tool is behind it). */
2060
+ encodeCall(tool: string, value: unknown): {
2061
+ name: string;
2062
+ args: unknown;
2063
+ };
2064
+ /** Throw a `RequestLimitError` when anything was degraded (opt-in; requests never throw by themselves). */
2065
+ assertNoDegradation(): this;
2066
+ /**
2067
+ * Handlebars helpers over the whole request: `{{encode value}}` uses
2068
+ * `defaultName` (a tool's own schema in its instructions, the output in a
2069
+ * prompt), `{{encode value tool="search"}}` / `{{encode value output=true}}`
2070
+ * pick another schema of the request.
2071
+ */
2072
+ helpers(defaultName?: ItemName<I[number]>): HelperSet;
2073
+ }
2074
+ /**
2075
+ * Fit every schema of one request to a model (see the top of this file).
2076
+ * Usually reached as `profileFor(model).request(items)`. Never throws unless
2077
+ * `failOnDegrade` is set.
2078
+ */
2079
+ declare function planRequest<const I extends readonly RequestItem[]>(target: ModelProfile, items: I, opts?: RequestOptions): RenderedRequest<I>;
2080
+
2081
+ /**
2082
+ * From a model to its profiles. The family and strictness come from the
2083
+ * model's own capabilities (`@aeye/models`: `strictFormat`, `'toolsStrict'`,
2084
+ * `'structured'`, `'json'`), mirroring `@aeye/ai`'s `resolveStrictFormat` and
2085
+ * `buildSchemaBudget`, so a call site never picks a profile by hand.
2086
+ */
2087
+
2088
+ /**
2089
+ * A model, structurally — `@aeye/ai`'s `ModelInfo` (and `@aeye/models`'
2090
+ * entries with `strictSupport` applied) fit as they are.
2091
+ */
2092
+ interface ModelLike {
2093
+ readonly id: string;
2094
+ readonly provider: string;
2095
+ /** `@aeye/models` `strictSupport` pins this; `'none'` opts out. */
2096
+ readonly strictFormat?: string;
2097
+ /** `'toolsStrict'` → strict tools; `'structured'` → structured output (strict where the family has it). */
2098
+ readonly capabilities?: ReadonlySet<string> | readonly string[];
2099
+ }
2100
+ /** The family a model's schemas are written for (see `@aeye/ai` `resolveStrictFormat`). */
2101
+ declare function familyOf(model: ModelLike): ProfileFamily;
2102
+ /**
2103
+ * What one model reads: the profile for its tool arguments, the profile for
2104
+ * its structured output, and how output is delivered. Start a request with
2105
+ * `request(items)`.
2106
+ */
2107
+ declare class ModelProfile {
2108
+ readonly tool: Profile;
2109
+ readonly output: Profile;
2110
+ /** `'prompt'` when the model has no structured output: the schema goes as prompt text. */
2111
+ readonly outputDelivery: 'structured' | 'prompt';
2112
+ constructor(tool: Profile, output?: Profile,
2113
+ /** `'prompt'` when the model has no structured output: the schema goes as prompt text. */
2114
+ outputDelivery?: 'structured' | 'prompt');
2115
+ /**
2116
+ * Render every schema of one request together, so the request as a whole
2117
+ * fits this model's limits (see `planRequest`). Each entry records what
2118
+ * its schema was rendered with; parse and encode through the entry.
2119
+ */
2120
+ request<const I extends readonly RequestItem[]>(items: I, opts?: RequestOptions): RenderedRequest<I>;
2121
+ /** Both kinds through one profile. */
2122
+ static of(profile: Profile): ModelProfile;
2123
+ }
2124
+ /**
2125
+ * The profiles for a model, from its capabilities (`@aeye/models`):
2126
+ *
2127
+ * - the family comes from `strictFormat`, else the provider, else the
2128
+ * `vendor/` id prefix (OpenRouter passes schemas through to the upstream);
2129
+ * - tools are strict when the model has `'toolsStrict'`, except xAI, whose
2130
+ * tools are always strict;
2131
+ * - output is strict structured output when the model has `'structured'`;
2132
+ * with neither `'structured'` nor a family that offers non-strict output,
2133
+ * the schema is delivered as prompt text;
2134
+ * - OpenAI fine-tunes (`ft:` ids) get the stripped fine-tune dialect;
2135
+ * - `speaks` limits the families a provider can send (others are LENIENT).
2136
+ */
2137
+ declare function profileFor(model: ModelLike, opts?: {
2138
+ speaks?: ReadonlySet<string>;
2139
+ }): ModelProfile;
2140
+
2141
+ /** What a deferred value is written with, once the request is planned. */
2142
+ interface DeferredSpec {
2143
+ /** The tool of the request whose arguments it is (or a part of, with `path`). */
2144
+ readonly tool?: string;
2145
+ /** The request's structured output instead of a tool. */
2146
+ readonly output?: boolean;
2147
+ /** The value, in the code shape (ignored for `type`). */
2148
+ readonly value?: unknown;
2149
+ /** A part: the value sits at this code path of the schema (`limits`, `rows.*.tags`). */
2150
+ readonly path?: string | readonly PathSeg[];
2151
+ /** Indent the JSON (`true` = 2 spaces). */
2152
+ readonly pretty?: boolean | number;
2153
+ /** Write the schema itself as TypeScript-like text (`{{schema}}`) instead of a value. */
2154
+ readonly type?: boolean;
2155
+ /**
2156
+ * For a tool the request may not have (one offered in a later step): its schema as lenient JSON Schema. When the
2157
+ * request has no tool of that name, the value is written as that schema would be, planned alone for the request's
2158
+ * model (with `strict`); without it the value is written in the code shape.
2159
+ */
2160
+ readonly schema?: JsonSchema;
2161
+ /** The strictness the tool would be asked with (`schema` only). Default `1`. */
2162
+ readonly strict?: Strictness;
2163
+ /**
2164
+ * Show only this part of what was written (a dotted path in the WIRE value): the whole value is written, then the
2165
+ * part picked, e.g. a dispatcher-like tool's `args` as it writes them for the one it names (`{ fn, args }`, pick
2166
+ * `args`). Unlike `path`, the part is written as the whole value has it.
2167
+ */
2168
+ readonly pick?: string;
2169
+ /** What to show when the plan can't write it (no such tool, no plan, a value that doesn't fit): else the code shape. */
2170
+ readonly fallback?: string;
2171
+ }
2172
+ /** One deferred value, captured whole: `text.split(DEFERRED_SPAN)` gives the text around them at even indexes and the values at odd ones. */
2173
+ declare const DEFERRED_SPAN: RegExp;
2174
+ /** The text of a deferred value: the spec, to be written through the request's plan. */
2175
+ declare function deferEncode(spec: DeferredSpec): string;
2176
+ /** The text of a deferred `{{schema}}`: the schema of a tool (or the output) as TypeScript-like text. */
2177
+ declare function deferSchema(spec: Pick<DeferredSpec, 'tool' | 'output' | 'schema' | 'strict'>): string;
2178
+ /** Whether a text holds any deferred value. */
2179
+ declare function hasDeferred(text: string): boolean;
2180
+ /** How `fillDeferred` treats what isn't in the plan. */
2181
+ interface FillOptions {
2182
+ /** A bound schema for a lenient JSON Schema a deferred value carries (default: `a.fromJSONSchema`, kept by JSON). */
2183
+ readonly schemaOf?: (schema: JsonSchema) => Bound<unknown>;
2184
+ }
2185
+ /**
2186
+ * Write every deferred value of a text through a request's plan: as the model writes that tool's arguments (or the
2187
+ * output), a part of them with `path`; a tool the plan doesn't have through the schema the value carries, planned
2188
+ * alone for the plan's model, else in the code shape. Without a plan, the code shape (`plainDeferred`). Text with no
2189
+ * deferred value comes back as it is.
2190
+ */
2191
+ declare function fillDeferred(text: string, plan: RenderedRequest<any> | undefined, opts?: FillOptions): string;
2192
+ /** A text with each deferred value in the code shape: for estimates, logs and people, before a plan exists. */
2193
+ declare function plainDeferred(text: string): string;
2194
+ /**
2195
+ * A stand-in for a request's plan whose encoders write deferred values: render a request's templates for it (core's
2196
+ * `deferRequest`) and the text carries each value to be written once the request is planned where it is sent. `known`
2197
+ * supplies schemas a template may name that the request doesn't have (a tool offered in a later step): their deferred
2198
+ * values carry the schema. `wire` (a JSON value, not text) can't be deferred: it gives the code shape.
2199
+ */
2200
+ declare function deferredRequest(plan: RenderedRequest<any>, known?: (name: string) => Bound<any> | undefined): RenderedRequest;
2201
+
2202
+ /**
2203
+ * Runtime errors of `@aeye/schema`. Model mistakes are never thrown: `parse`
2204
+ * returns them as `Issue`s for a re-prompt. These are for the code's own
2205
+ * mistakes, and for callers that prefer throwing.
2206
+ */
2207
+
2208
+ /**
2209
+ * A schema or chain is defined wrongly in a way the types could not catch:
2210
+ * a ref missing at bind time, a dynamic step redefining a name, an example
2211
+ * that doesn't fit its own schema, encoding at a path that doesn't exist.
2212
+ */
2213
+ declare class SchemaDefinitionError extends Error {
2214
+ constructor(message: string);
2215
+ }
2216
+ /** A value did not match its schema (`parseOrThrow`). `issues` has both paths; the message is the model's feedback. */
2217
+ declare class SchemaParseError extends Error {
2218
+ readonly issues: readonly Issue[];
2219
+ constructor(issues: readonly Issue[], message?: string);
2220
+ }
2221
+ /**
2222
+ * A request cannot fit its provider's limits whatever is degraded (too many
2223
+ * tools, or more hard-`strict: true` schemas than the budget allows).
2224
+ * Thrown only on request (`RenderedRequest.assertNoDegradation()` or `{ failOnDegrade: true }`); `problems` lists each degradation.
2225
+ */
2226
+ declare class RequestLimitError extends Error {
2227
+ readonly problems: readonly string[];
2228
+ constructor(problems: readonly string[]);
2229
+ }
2230
+
2231
+ /**
2232
+ * "Did you mean?" for the model's mistakes: an unknown key, an enum value, a
2233
+ * literal or discriminator tag, a tool name.
2234
+ *
2235
+ * Ported algorithm-identical from `@aeye/query`'s `aids.ts` (gin's `aids.ts`
2236
+ * is the same port), so a suggestion here is exactly the one gin and query
2237
+ * make for the same input:
2238
+ *
2239
+ * - Levenshtein distance, compared case-insensitively;
2240
+ * - a length-scaled budget (`floor(len / 3)`, at least 1, at most 3), so it
2241
+ * fires on a genuine typo and never on an unrelated word;
2242
+ * - ties broken by the case-sensitive distance, then the candidates' order.
2243
+ *
2244
+ * One addition that cannot change a result: candidates whose length differs
2245
+ * from the input's by more than the budget are skipped before the distance
2246
+ * is computed (their distance is at least that difference). A widened enum of
2247
+ * thousands of values then costs a length check per value.
2248
+ */
2249
+ /** Levenshtein edit distance (one rolling row). */
2250
+ declare function editDistance(a: string, b: string): number;
2251
+ /** The edit budget tolerated for an input of `len` characters: `floor(len / 3)`, at least 1, at most 3. */
2252
+ declare function suggestionBudget(len: number): number;
2253
+ /** Candidates within `budget` edits of `input`, nearest first (case-insensitive; ties: exact case, then order). */
2254
+ declare function rankNear(input: string, candidates: readonly string[], budget?: number): string[];
2255
+ /** The nearest candidate within the budget, or `undefined` when nothing is a genuine typo of one. */
2256
+ declare function nearest(input: string, candidates: readonly string[], budget?: number): string | undefined;
2257
+ /** `" — did you mean `X`?"` (up to `max` matches, default 1), or `''`. The same wording as gin and query. */
2258
+ declare function didYouMean(input: string, candidates: readonly string[], opts?: {
2259
+ readonly max?: number;
2260
+ }): string;
2261
+
2262
+ /**
2263
+ * Gin → `a`. Gin types generate `a` schemas instead of zod.
2264
+ *
2265
+ * In the real migration this lives in @aeye/gin as `Type.toA()` next to
2266
+ * (then replacing) `Type.toValueSchema()`; here it works on the TypeDef JSON
2267
+ * (structurally the same `TypeDef` gin serializes) so this package needs no gin
2268
+ * build. Two halves:
2269
+ *
2270
+ * - TYPE level: `GinSchema<T>` maps a `const` TypeDef literal to the exact
2271
+ * `a` class, so `a.infer` of a converted gin type is the gin type's code
2272
+ * shape (`fromGin({name:'list', generic:{V:{name:'num'}}})` → `ArrayType<NumberType>`).
2273
+ * - RUNTIME: `fromGin(def)` builds it; a named (registered) gin type becomes
2274
+ * `a.ref(name)`; `ginNamedTypes(registry)` turns a registry's named types
2275
+ * into the defs a chain's dynamic step returns.
2276
+ *
2277
+ * Every kind accepts exactly what gin's `toValueSchema` accepts (checked
2278
+ * value-for-value against @aeye/gin in corpus/gin-values.test.ts), with two
2279
+ * deliberate differences:
2280
+ * - `map<text, V>` is a RECORD in the code shape. The pairs encoding is the
2281
+ * profile's job (`[{key, value}]` only where the dialect forbids an open
2282
+ * `additionalProperties`); gin's runtime reads a record. `map<K, V>` with a
2283
+ * non-text key stays pairs in the code shape too (JSON has no non-string keys).
2284
+ * - Named types are refs into `$defs`, not `z.lazy` + `aid` meta.
2285
+ */
2286
+
2287
+ /** Structurally gin's `TypeDef` (packages/gin/src/schema.ts). */
2288
+ interface GinTypeDef {
2289
+ readonly name: string;
2290
+ readonly docs?: string;
2291
+ /** A registered type's definition: the type it extends (`{name: 'Task', extends: 'obj', props}`). */
2292
+ readonly extends?: string;
2293
+ readonly generic?: {
2294
+ readonly [key: string]: GinTypeDef;
2295
+ };
2296
+ readonly options?: {
2297
+ readonly [key: string]: unknown;
2298
+ };
2299
+ readonly props?: {
2300
+ readonly [key: string]: {
2301
+ readonly type: GinTypeDef;
2302
+ readonly docs?: string;
2303
+ readonly get?: unknown;
2304
+ };
2305
+ };
2306
+ /** A runtime predicate every value must satisfy (a gin ExprDef). */
2307
+ readonly constraint?: unknown;
2308
+ }
2309
+ type Props<P> = {
2310
+ [K in keyof P]: P[K] extends {
2311
+ readonly type: infer T;
2312
+ } ? GinSchema<T> : never;
2313
+ };
2314
+ /** The `a` classes of a tuple of gin TypeDefs. */
2315
+ type GinParts<O extends readonly unknown[]> = O extends readonly [infer H, ...infer R] ? [GinSchema<H>, ...GinParts<R>] : [];
2316
+ type EnumOf<U> = [U] extends [string] ? EnumType<[U, ...U[]]> : SchemaOf<U>;
2317
+ /** The `a` class for a gin TypeDef literal. Unknown names are named types → refs; a non-literal def is any schema. */
2318
+ type GinSchema<T> = T extends {
2319
+ readonly name: infer N;
2320
+ } ? (string extends N ? AnySchema : GinKnown<T>) : AnySchema;
2321
+ type GinKnown<T> = T extends {
2322
+ readonly name: 'text';
2323
+ } ? StringType : T extends {
2324
+ readonly name: 'num';
2325
+ } ? NumberType : T extends {
2326
+ readonly name: 'bool';
2327
+ } ? BooleanType : T extends {
2328
+ readonly name: 'null' | 'void';
2329
+ } ? NullType : T extends {
2330
+ readonly name: 'any';
2331
+ } ? AnyType<unknown> : T extends {
2332
+ readonly name: 'date' | 'timestamp';
2333
+ } ? StringType : T extends {
2334
+ readonly name: 'duration' | 'color';
2335
+ } ? NumberType : T extends {
2336
+ readonly name: 'list';
2337
+ readonly generic: {
2338
+ readonly V: infer V;
2339
+ };
2340
+ } ? ArrayType<GinSchema<V>> : T extends {
2341
+ readonly name: 'map';
2342
+ readonly generic: {
2343
+ readonly V: infer V;
2344
+ readonly K: {
2345
+ readonly name: 'text';
2346
+ };
2347
+ };
2348
+ } ? RecordType<GinSchema<V>> : T extends {
2349
+ readonly name: 'map';
2350
+ readonly generic: {
2351
+ readonly V: infer V;
2352
+ readonly K: infer K;
2353
+ };
2354
+ } ? ArrayType<ObjectType<{
2355
+ key: GinSchema<K>;
2356
+ value: GinSchema<V>;
2357
+ }>> : T extends {
2358
+ readonly name: 'map';
2359
+ readonly generic: {
2360
+ readonly V: infer V;
2361
+ };
2362
+ } ? RecordType<GinSchema<V>> : T extends {
2363
+ readonly name: 'record';
2364
+ readonly generic: {
2365
+ readonly V: infer V;
2366
+ };
2367
+ } ? RecordType<GinSchema<V>> : T extends {
2368
+ readonly name: 'optional';
2369
+ readonly generic: {
2370
+ readonly T: infer I;
2371
+ };
2372
+ } ? OptionalType<GinSchema<I>> : T extends {
2373
+ readonly name: 'nullable';
2374
+ readonly generic: {
2375
+ readonly T: infer I;
2376
+ };
2377
+ } ? NullableType<GinSchema<I>> : T extends {
2378
+ readonly name: 'obj';
2379
+ readonly props: infer P;
2380
+ } ? ObjectType<Props<P>> : T extends {
2381
+ readonly name: 'enum';
2382
+ readonly options: {
2383
+ readonly values: infer V;
2384
+ };
2385
+ } ? EnumOf<V[keyof V]> : T extends {
2386
+ readonly name: 'literal';
2387
+ readonly options: {
2388
+ readonly value: infer V extends LiteralValue;
2389
+ };
2390
+ } ? LiteralType<V> : T extends {
2391
+ readonly name: 'or';
2392
+ readonly options: {
2393
+ readonly types: infer O extends readonly unknown[];
2394
+ };
2395
+ } ? UnionType<{
2396
+ [I in keyof O]: GinSchema<O[I]>;
2397
+ } & [AnySchema, ...AnySchema[]]> : T extends {
2398
+ readonly name: 'tuple';
2399
+ readonly options: {
2400
+ readonly elements: infer O extends readonly unknown[];
2401
+ };
2402
+ } ? (GinParts<O> extends infer P extends readonly [AnySchema, ...AnySchema[]] ? TupleType<P> : AnySchema) : T extends {
2403
+ readonly name: 'and';
2404
+ readonly options: {
2405
+ readonly types: infer O extends readonly unknown[];
2406
+ };
2407
+ } ? (GinParts<O> extends infer P extends readonly [AnySchema, ...AnySchema[]] ? IntersectionType<P> : AnyType<unknown>) : T extends {
2408
+ readonly name: 'not';
2409
+ readonly options: {
2410
+ readonly excluded: unknown;
2411
+ };
2412
+ } ? NotType<AnyType<unknown>> : T extends {
2413
+ readonly name: 'interface' | 'iface';
2414
+ readonly props: infer P;
2415
+ } ? ObjectType<Props<P>> : T extends {
2416
+ readonly name: 'interface' | 'iface';
2417
+ } ? ObjectType<{}> : T extends {
2418
+ readonly name: 'typ';
2419
+ } ? RefType<'TypeDef'> : T extends {
2420
+ readonly name: 'fn';
2421
+ } ? RefType<'Expr'> : T extends {
2422
+ readonly name: infer N extends string;
2423
+ } ? RefType<N> : AnySchema;
2424
+ /** Gin type names with their own `a` mapping; anything else is a named (registered) type. */
2425
+ declare const GIN_BUILTINS: Set<string>;
2426
+ interface FromGinOptions {
2427
+ /**
2428
+ * The registry's named types. With it, a GENERIC named type used with
2429
+ * arguments (`{name: 'Box', generic: {T: num}}`) is instantiated in place
2430
+ * (its generic parameters replaced by the arguments). Without it, a named
2431
+ * type is always a ref.
2432
+ */
2433
+ readonly named?: ReadonlyMap<string, GinTypeDef>;
2434
+ }
2435
+ /** Convert one gin TypeDef. */
2436
+ declare function fromGin<const T extends GinTypeDef>(def: T, opts?: FromGinOptions): GinSchema<T>;
2437
+ /** A gin registry, structurally: its named types as TypeDefs. */
2438
+ interface GinRegistryLike {
2439
+ readonly version: number;
2440
+ named(): ReadonlyMap<string, GinTypeDef>;
2441
+ }
2442
+ /**
2443
+ * The registry's named types as `a` defs — what a chain's dynamic step
2444
+ * returns. A registry's names are runtime data, so the caller states the
2445
+ * ones its code relies on and their TS types (`T`); `Bound` checks at bind
2446
+ * time that they exist. Every other registered name comes along untyped.
2447
+ *
2448
+ * Both serializations work: a structural def under its name
2449
+ * (`Task → {name: 'obj', props}`) and gin's own extension form
2450
+ * (`{name: 'Task', extends: 'obj', props}`, `Type.toJSON()`). A generic
2451
+ * named type's parameters stand for their declared bounds in its own
2452
+ * definition; uses with arguments are instantiated.
2453
+ */
2454
+ declare function ginNamedTypes<T extends Record<string, unknown> = {}>(registry: GinRegistryLike): {
2455
+ readonly [K in keyof T]: SchemaOf<T[K]>;
2456
+ } & Record<string, AnySchema>;
2457
+
2458
+ export { ANTHROPIC_NON_STRICT, ANTHROPIC_STRICT, type Adjustment, type AllowRefs, type AnySchema, AnyType, ArrayType, type Audience, type Bindable, BooleanType, Bound, type Brand, Bundle, type Check, CodecType, Compiler, ConditionalType, type ConstraintSupport, type CopyStats, Cx, DEFAULT_ERROR_FORMAT, DEFAULT_JSON_INSTRUCTION, DEFERRED_SPAN, type DecodedCall, DefTarget, DefaultType, type DeferredSpec, type Defs, DependentType, type DispatchCase, DispatchType, type DynamicDefs, DynamicModule, type DynamicOptions, type EncodeTextOptions, type Encoder, EnumType, type EnvOf, type ErrorDetail, type ErrorFormat, type ErrorFormatInput, FAILED, type FillOptions, GIN_BUILTINS, GOOGLE_NON_STRICT, GOOGLE_OPENAPI, GOOGLE_STRICT, type GinRegistryLike, type GinSchema, type GinTypeDef, type Helper, type HelperOptions, type HelperSet, INLINE_BUDGET, type ImportReport, InlineBudgetExceeded, IntersectionType, type Issue, type IssueKind, type ItemName, type ItemOut, type JsonSchema, type JsonValue, LENIENT, type LimitName, LiteralType, type LiteralValue, type Loose, MINIMAL, type Merge, type Meta, type Missing, type ModelLike, ModelProfile, Module, NeverType, Node, type NodeImpl, NotType, NullType, NullableType, type NumberOptions, NumberType, OLLAMA, OPENAI_FINETUNED_STRICT, OPENAI_NON_STRICT, OPENAI_STRICT, type ObjectExtras, type ObjectOut, type ObjectRestOut, ObjectType, OptionalType, type OutOf, type OutputItem, PEOPLE, type ParseOptions, type ParseResult, type PathSeg, Printer, type Profile, type ProfileAdjustment, type ProfileFamily, RecordType, type RefFree, type RefMarker, RefType, type RefsOf, Rejection, Rendered, RenderedRequest, RequestEntry, type RequestItem, RequestLimitError, type RequestLimits, type RequestOptions, type RequestSchema, type Resolve, type ResolvedErrorFormat, type ResultOut, type RuleIssue, SCHEMA_DATA_KEY, Schema, SchemaDefinitionError, type SchemaError, type SchemaKind, type SchemaLimits, type SchemaMeasure, type SchemaOf, SchemaParseError, type SchemaTarget, type Shape, type ShapeRefs, type Simplify, type Strictness, type StringOptions, StringType, type Text, type ToolItem, TupleType, UnionType, type View, XAI_NON_STRICT, XAI_STRICT, ZERO_MEASURE, a, addMeasures, brokenLimits, deferEncode, deferSchema, deferredRequest, didYouMean, editDistance, errorFormat, familyOf, familyProfile, fillDeferred, formatErrors, formatIssues, formatPath, fromGin, fromJSONSchema, getProfile, ginNamedTypes, hasDeferred, isBasicPattern, isNever, issueKind, measureJson, mergeErrorFormats, modelPath, nearest, newStats, overLimits, plainDeferred, planRequest, profileFor, rankNear, readJsonText, registerProfile, registerSchemaHelpers, schemaData, schemaHelpers, shortType, staticBundle, strictPriority, suggestionBudget, suggestionFor, variant, viewOf };