@aeye/schema 0.0.0-stage → 0.9.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.
- package/LICENSE +674 -0
- package/README.md +60 -3
- package/aeye-schema.md +501 -0
- package/dist/index.d.ts +2391 -0
- package/dist/index.js +4834 -0
- package/package.json +84 -4
package/README.md
CHANGED
|
@@ -1,3 +1,60 @@
|
|
|
1
|
-
#
|
|
2
|
-
|
|
3
|
-
|
|
1
|
+
# @aeye/schema
|
|
2
|
+
|
|
3
|
+
The LLM-first schema builder for the @aeye framework: `a` is to aeye what `z` is to zod, built for
|
|
4
|
+
tool arguments and structured outputs.
|
|
5
|
+
|
|
6
|
+
## Features
|
|
7
|
+
|
|
8
|
+
- **Typed like zod**: `a.infer<typeof X>` is the exact code type, recursion included
|
|
9
|
+
- **Named, lazy and dynamic types**: `a.define(...).dynamic((ctx) => ...).result(...)`, checked at compile time in every case
|
|
10
|
+
- **Rendered per model**: records as pairs only where the dialect needs it, `null` for absent on OpenAI strict, JSON text where recursion or "any" can't be said — chosen from the model's capabilities
|
|
11
|
+
- **Request-wide budgets**: every schema of one request fitted together (Anthropic's 20 strict tools / 24 optional / 16 unions, OpenAI's size limits, 128 tools), each choice recorded
|
|
12
|
+
- **One rendering for everything**: the JSON sent, decoding, error paths, examples and `{{encode value}}` in instructions all agree
|
|
13
|
+
- **Copy-light decoding**: validated and decoded in one pass, in place; untouched subtrees are the same references
|
|
14
|
+
- **Errors for the model**: its own JSON echoed back with a marker under each mistake, "did you mean", the expected type, a hard size cap; the detail level is set per tool / prompt
|
|
15
|
+
- **Imports** JSON Schema (MCP, OpenAPI) and gin types
|
|
16
|
+
|
|
17
|
+
## Installation
|
|
18
|
+
|
|
19
|
+
Not yet published (`private`); used from the monorepo workspace.
|
|
20
|
+
|
|
21
|
+
## Quick Start
|
|
22
|
+
|
|
23
|
+
```ts
|
|
24
|
+
import { a, profileFor } from '@aeye/schema';
|
|
25
|
+
|
|
26
|
+
const SetBudget = a.object({
|
|
27
|
+
owner: a.string(),
|
|
28
|
+
limits: a.record(a.number().min(0)).describe((v) => `Limit per category, as ${v.recordWord}.`),
|
|
29
|
+
note: a.string().optional(),
|
|
30
|
+
});
|
|
31
|
+
|
|
32
|
+
const req = profileFor(model).request([{ kind: 'tool', name: 'set_budget', schema: SetBudget }]);
|
|
33
|
+
const tool = req.get('set_budget');
|
|
34
|
+
|
|
35
|
+
send({ parameters: tool.jsonSchema, strict: tool.strict });
|
|
36
|
+
const res = tool.parseText(rawArgs);
|
|
37
|
+
if (res.ok) console.log(res.value.limits.food);
|
|
38
|
+
else reprompt(res.message); // the model's JSON with "^^^ limits[0].value: Must be at least 0." under the bad value
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
In instructions:
|
|
42
|
+
|
|
43
|
+
```hbs
|
|
44
|
+
Example: {{encode example}}
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
```ts
|
|
48
|
+
instructions(vars, { helpers: tool.helpers() });
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
See [aeye-schema.md](./aeye-schema.md) for the full reference and [DESIGN.md](./DESIGN.md) for
|
|
52
|
+
the design and its history.
|
|
53
|
+
|
|
54
|
+
## Scripts
|
|
55
|
+
|
|
56
|
+
```bash
|
|
57
|
+
npm test # vitest + type tests (tsc -p tsconfig.typetest.json)
|
|
58
|
+
npm run typecheck
|
|
59
|
+
npm run build # tsup → dist
|
|
60
|
+
```
|
package/aeye-schema.md
ADDED
|
@@ -0,0 +1,501 @@
|
|
|
1
|
+
# @aeye/schema
|
|
2
|
+
|
|
3
|
+
**The LLM-first schema builder** for the `@aeye` stack. `a` is to aeye what `z` is to zod:
|
|
4
|
+
you describe a value once, in its CODE shape, and get the exact TypeScript type. Then, for
|
|
5
|
+
whichever model a request goes to, `@aeye/schema` renders the JSON Schema that model can read,
|
|
6
|
+
decodes its answer back into the code shape in one pass (copying almost nothing), reports
|
|
7
|
+
mistakes where the model made them, and shows values in instructions exactly as the model
|
|
8
|
+
writes them.
|
|
9
|
+
|
|
10
|
+
It is built for what LLM schemas need and zod doesn't have:
|
|
11
|
+
|
|
12
|
+
- **Named types, refs and dynamic parts** — a chain of `define` / `declare` / `dynamic` /
|
|
13
|
+
`result`, fully typed in every case, so tool args and structured outputs are static instances
|
|
14
|
+
whose dynamic parts (a registry, a DB catalog, a ctx) are bound per call.
|
|
15
|
+
- **Per-model rendering** — the same schema becomes records-as-pairs for OpenAI strict, open
|
|
16
|
+
objects for Gemini, JSON text where recursion isn't allowed, and so on, from the model's
|
|
17
|
+
capabilities.
|
|
18
|
+
- **Request-wide budgets** — every schema of one request is fitted together, because providers
|
|
19
|
+
limit the request (20 strict tools, 24 optional parameters…), not just each schema.
|
|
20
|
+
- **One rendering for everything** — the JSON sent, decoding, error paths, examples and values
|
|
21
|
+
in instructions all come from the same rendering, so they can't disagree.
|
|
22
|
+
|
|
23
|
+
> `private: true` for now: built and tested in the monorepo, not yet published. `@aeye/core` takes
|
|
24
|
+
> `a` schemas (step 1, done; core re-exports `a`); `@aeye/gin`, `@aeye/query` and the harness follow.
|
|
25
|
+
|
|
26
|
+
## Install / import
|
|
27
|
+
|
|
28
|
+
```ts
|
|
29
|
+
import { a, profileFor } from '@aeye/schema';
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
One entry point. No runtime dependencies.
|
|
33
|
+
|
|
34
|
+
## Quick start
|
|
35
|
+
|
|
36
|
+
```ts
|
|
37
|
+
import { a, profileFor } from '@aeye/schema';
|
|
38
|
+
|
|
39
|
+
const Budget = a.object({
|
|
40
|
+
owner: a.string().describe('Who owns the budget.'),
|
|
41
|
+
limits: a.record(a.number().min(0)).describe((v) => `Spending limit per category, as ${v.recordWord}.`),
|
|
42
|
+
note: a.string().optional(),
|
|
43
|
+
});
|
|
44
|
+
type Budget = a.infer<typeof Budget>;
|
|
45
|
+
// { owner: string; limits: Record<string, number>; note?: string }
|
|
46
|
+
|
|
47
|
+
// Per request: the model's profiles come from its capabilities (@aeye/models).
|
|
48
|
+
const req = profileFor(model).request([
|
|
49
|
+
{ kind: 'tool', name: 'set_budget', schema: Budget },
|
|
50
|
+
{ kind: 'output', schema: Report },
|
|
51
|
+
]);
|
|
52
|
+
|
|
53
|
+
const tool = req.get('set_budget');
|
|
54
|
+
tool.jsonSchema; // send as the tool's parameters (strict: tool.strict)
|
|
55
|
+
const res = tool.parseText(rawArgs); // decode the model's answer
|
|
56
|
+
if (res.ok) res.value; // Budget, in the code shape
|
|
57
|
+
else res.message; // "- at limits[0].value: Must be at least 0." → re-prompt
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
On OpenAI strict the model sees `limits` as `[{key, value}]` and `note` as `string | null`; on
|
|
61
|
+
Gemini it sees an open object and an optional field. `res.value` is a `Budget` either way.
|
|
62
|
+
|
|
63
|
+
## The builder
|
|
64
|
+
|
|
65
|
+
```ts
|
|
66
|
+
a.string() a.number() a.int() a.boolean() a.null() a.literal('x') a.enum(['a', 'b'])
|
|
67
|
+
a.unknown() // any JSON value, typed unknown
|
|
68
|
+
a.json() // any JSON value, typed JsonValue
|
|
69
|
+
a.object({ ... }) a.array(T) a.tuple([A, B]) a.record(V) a.record(a.enum([...]), V)
|
|
70
|
+
a.union([A, B]) a.discriminatedUnion('kind', [A, B]) a.optional(T) a.nullable(T)
|
|
71
|
+
a.intersection([A, B]) // allOf / gin and: objects merge
|
|
72
|
+
a.not(excluded, base?) // gin not / JSON Schema not
|
|
73
|
+
a.conditional(base, { if, then, else })
|
|
74
|
+
a.dependent(on, schemaFor, base?) // a value typed by a sibling field
|
|
75
|
+
a.ref('Name') a.codec(wire, { decode, encode })
|
|
76
|
+
a.refOf<Out>(name) // a ref whose NAME is runtime data (`Fields_${table}`), typed by you, checked at bind
|
|
77
|
+
a.never() // no value: an empty runtime list, a list that must stay empty
|
|
78
|
+
a.default(T, value) // = T.default(value): optional on the wire, required in code, filled in on decode
|
|
79
|
+
a.dispatch([{ name, schema }]) // { tool, args }: args typed by tool, picked by name (the request dispatcher)
|
|
80
|
+
a.define({...}) a.declare<{...}>() a.module() a.fromJSONSchema(json)
|
|
81
|
+
type T = a.infer<typeof X>;
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
Modifiers (every class; all immutable — build schemas once, at module scope):
|
|
85
|
+
|
|
86
|
+
| Modifier | What it does |
|
|
87
|
+
|---|---|
|
|
88
|
+
| `.describe(text \| (view) => text)` | Description. The function form sees the model-facing view (`view.recordWord`, `view.optional`), so prose matches the wire shape. |
|
|
89
|
+
| `.title(t)` | Title. |
|
|
90
|
+
| `.example(...values)` | Examples in the CODE shape, checked against the schema; each profile shows them in its own wire shape. |
|
|
91
|
+
| `.refine(fn, message?, { visible })` | A rule the types can't say. Runs on the decoded value; with a message it is shown to the model as `Rules: …`. |
|
|
92
|
+
| `.brand<'Zone'>()` | Nominal type only. |
|
|
93
|
+
| `.forPeople()` | Never shown to or accepted from a model (web forms, API callers see it). |
|
|
94
|
+
| `.forModels(narrower)` | What a model sees instead (e.g. an enum minus people-only members). |
|
|
95
|
+
| `.optional()` `.nullable()` | Optional means the key is ABSENT after decoding, never `undefined`. |
|
|
96
|
+
| `.default(value)` | zod's `.default`: the model may leave it out (or write `null` where absent is null); the code type is required and the default is written in. The description says `Default when left out: …`. |
|
|
97
|
+
|
|
98
|
+
`a.enum(list)`, `a.union(list)` and `a.discriminatedUnion(tag, list)` also take lists built at
|
|
99
|
+
runtime (typed by the element; an empty list is `never`). A union whose options all carry a
|
|
100
|
+
literal field with distinct values (a `kind`) is discriminated by it even when not declared so;
|
|
101
|
+
errors land inside the chosen option. `.refine` may return several messages (zod's `superRefine`).
|
|
102
|
+
|
|
103
|
+
Type-specific: `string().min/max/pattern(re, flags?)/format`, `number().int/min/max/gt/lt/positive/negative/nonnegative`, `array().min/max`,
|
|
104
|
+
`object().strict()` (unknown keys are errors), `.extend(shape)`, `.rest(V)` (extra keys, zod's
|
|
105
|
+
`catchall`), `.patterns({ '^x-': V })` (`patternProperties`), `.dependent(key, on, fn, base?)`.
|
|
106
|
+
|
|
107
|
+
### Values typed by a sibling
|
|
108
|
+
|
|
109
|
+
```ts
|
|
110
|
+
const CreateVar = a.object({ name: a.string(), type: TypeDef })
|
|
111
|
+
.dependent('value', 'type', (type) => schemaOfType(type)); // `type` is typed from the sibling
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
The model sees `value` as any JSON (JSON text on strict dialects) with "Its type is given by
|
|
115
|
+
"type"."; decoding checks the value against the schema built from the `type` it just wrote,
|
|
116
|
+
in the code shape. `schemaFor` may name the bind's own types (`a.ref(name)`).
|
|
117
|
+
|
|
118
|
+
## Named types and the chain
|
|
119
|
+
|
|
120
|
+
```ts
|
|
121
|
+
const Tree = a
|
|
122
|
+
.define({ Node: a.object({ value: a.number(), children: a.array(a.ref('Node')) }) })
|
|
123
|
+
.result('Node'); // a.infer<typeof Tree> is a real recursive type
|
|
124
|
+
|
|
125
|
+
const Query = a
|
|
126
|
+
.define({ Filter: a.object({ field: a.ref('Field'), equals: a.string() }) })
|
|
127
|
+
.dynamic((ctx: Ctx) => ({ Field: a.enum(ctx.fields) }), { key: (ctx) => ctx.version })
|
|
128
|
+
.result(a.object({ where: a.ref('Filter') }));
|
|
129
|
+
const bound = Query.bind(ctx); // cached by key
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
Every mistake is a compile error: an undefined ref, a dynamic step that misses a ref, a wrong
|
|
133
|
+
declared shape, redefining a name, a ctx that doesn't supply the dynamic args. `declare<{ Type:
|
|
134
|
+
TypeDef }>()` pins the code type of a ref the dynamic step will supply. A bound schema is
|
|
135
|
+
`Bound<Out>`; a ref-free schema is its own bound (`schema.bind()`, `schema.render(profile)`).
|
|
136
|
+
|
|
137
|
+
## Profiles
|
|
138
|
+
|
|
139
|
+
A **profile** is what one model reads, for one kind of schema, strict or not. Every field is
|
|
140
|
+
read by exactly one place in rendering. Pick profiles with `profileFor(model)` — never by hand at
|
|
141
|
+
a call site.
|
|
142
|
+
|
|
143
|
+
### What each provider gets
|
|
144
|
+
|
|
145
|
+
| Profile | Records | Optional | Tuples | Null | Any | Recursion | Constraints | Notes |
|
|
146
|
+
|---|---|---|---|---|---|---|---|---|
|
|
147
|
+
| `OPENAI_STRICT` | pairs | `null` | `{"0":…}` | `anyOf` | JSON text | yes | all; basic regex; 9 formats | root object; 5,000 props / 10 levels / 120k chars / 1,000 enum values per schema; 128 tools |
|
|
148
|
+
| `OPENAI_FINETUNED_STRICT` | pairs | `null` | `{"0":…}` | `anyOf` | JSON text | yes | none, no formats | fine-tunes reject every constraint keyword |
|
|
149
|
+
| `OPENAI_NON_STRICT` | open | omit | prefixItems | type array | `{}` | yes | all | best effort |
|
|
150
|
+
| `ANTHROPIC_STRICT` | pairs | omit | `items: anyOf` | type array | JSON text | **no** (JSON text) | none but `minItems` 0/1; basic regex; 10 formats | 20 strict tools, 24 optional, 16 union-typed params **per request**; output always strict |
|
|
151
|
+
| `ANTHROPIC_NON_STRICT` | open | omit | prefixItems | type array | `{}` | yes | all | tool input_schema root is an object |
|
|
152
|
+
| `GOOGLE_STRICT` | open | omit | prefixItems | type array | `{}` | guarded | range, items; no length, no pattern; date/time formats | enum cap 40 (measured) |
|
|
153
|
+
| `GOOGLE_NON_STRICT` | open | omit | prefixItems | type array | `{}` | guarded | all | enum cap 40 |
|
|
154
|
+
| `GOOGLE_OPENAPI` | pairs | omit | `items: anyOf` | `nullable: true` | JSON text | no (no `$defs`) | all; basic regex | Gemini `responseSchema`; `propertyOrdering` |
|
|
155
|
+
| `XAI_STRICT` | **open** | omit | prefixItems | type array | flat `anyOf` | no (JSON text) | all; basic regex; 8 formats | tools are always strict |
|
|
156
|
+
| `OLLAMA` | open | omit | prefixItems | type array | `{}` | yes | all | llama.cpp grammar; never sent `strict` |
|
|
157
|
+
| `LENIENT` / `PEOPLE` | open | omit | prefixItems | type array | `{}` | yes | all | the code shape; `PEOPLE` shows people-only fields |
|
|
158
|
+
| `MINIMAL` | pairs | `null` | `{"0":…}` | type array | JSON text | no | none | test dialect: no combinators (tagged unions), no `$defs`, depth 6, enum cap 8 |
|
|
159
|
+
|
|
160
|
+
"Guarded" recursion: a `$ref` may point back only through an optional or nullable value, or an
|
|
161
|
+
array/record that may be empty (Gemini rejects ref loops through required values). Any other
|
|
162
|
+
back-edge becomes JSON text.
|
|
163
|
+
|
|
164
|
+
**"Strict models see pairs" is a dialect rule, not a strictness rule.** A record is written as
|
|
165
|
+
`[{key, value}]` only where the dialect forbids a schema-valued `additionalProperties`: OpenAI
|
|
166
|
+
strict and Anthropic strict (`additionalProperties` must be `false`) and Gemini's OpenAPI subset
|
|
167
|
+
(no `additionalProperties`). xAI strict and Gemini's JSON Schema mode are strict and take open
|
|
168
|
+
records, so their models see plain objects.
|
|
169
|
+
|
|
170
|
+
Sources: each provider's docs (OpenAI Structured Outputs + function calling, Anthropic structured
|
|
171
|
+
outputs, Gemini structured output + function calling + `Schema` reference, xAI structured
|
|
172
|
+
outputs, OpenRouter structured outputs + provider routing, Ollama structured outputs), read
|
|
173
|
+
2026-11-04 and listed in `docs/plans/schema-dialects-2026.md`; plus aeye's live measurements
|
|
174
|
+
(core `dialects/*`, the 2026-11-04/05 live-schema run). Each profile's doc comment cites its facts.
|
|
175
|
+
|
|
176
|
+
### `profileFor(model)`
|
|
177
|
+
|
|
178
|
+
```ts
|
|
179
|
+
profileFor(model: ModelLike, opts?: { speaks?: ReadonlySet<string> }): ModelProfile
|
|
180
|
+
// ModelProfile { tool: Profile; output: Profile; outputDelivery: 'structured' | 'prompt'; request(items) }
|
|
181
|
+
```
|
|
182
|
+
|
|
183
|
+
`ModelLike` is `{ id, provider, strictFormat?, capabilities? }` — `@aeye/ai`'s `ModelInfo` fits
|
|
184
|
+
as it is.
|
|
185
|
+
|
|
186
|
+
- The family comes from `strictFormat` (pinned by `@aeye/models`' `strictSupport`; `'none'` opts
|
|
187
|
+
out), else the provider (`openai`, `anthropic`, `google`, `xai`, `ollama`; Bedrock Claude ids
|
|
188
|
+
→ `anthropic`), else the `vendor/` id prefix — routers like OpenRouter pass the schema through
|
|
189
|
+
to the upstream family. Open-weight models under a vendor prefix (`openai/gpt-oss-*`,
|
|
190
|
+
`google/gemma-*`) are served by other hosts and stay lenient.
|
|
191
|
+
- Tools are strict with the `'toolsStrict'` capability; xAI tools always are.
|
|
192
|
+
- Output is strict with `'structured'`. Without it, the output is delivered as prompt text when
|
|
193
|
+
the family has no non-strict structured output (Anthropic, Bedrock) or the model has no `'json'`.
|
|
194
|
+
- OpenAI fine-tunes (`ft:` ids) get `OPENAI_FINETUNED_STRICT`.
|
|
195
|
+
- `speaks`: families the provider can send; anything else is `LENIENT`.
|
|
196
|
+
|
|
197
|
+
Custom dialects: `registerProfile(profile)` (lookup by id with `getProfile`, by family with
|
|
198
|
+
`familyProfile(family, strict)`).
|
|
199
|
+
|
|
200
|
+
## Requests: fitting every schema together
|
|
201
|
+
|
|
202
|
+
```ts
|
|
203
|
+
const req = profileFor(model).request([
|
|
204
|
+
{ kind: 'tool', name: 'search', schema: Search, strict: 2, errorFormat: 'list' },
|
|
205
|
+
{ kind: 'tool', name: 'rows', schema: Rows.bind(catalog) }, // dynamic bundles are bound first
|
|
206
|
+
{ kind: 'output', schema: Report }, // name defaults to 'output'
|
|
207
|
+
]);
|
|
208
|
+
req.get('search'); // RequestEntry<a.infer<typeof Search>> — typed by name
|
|
209
|
+
req.sent; // what to send: the direct tools (and the dispatcher, if any)
|
|
210
|
+
req.decodeCall(name, args); // { ok, tool, value } — a dispatcher call comes back as the original tool
|
|
211
|
+
// { ok: false, tool, issues, message } — message speaks of the original tool
|
|
212
|
+
req.encodeCall(tool, value); // { name, args } as this model would call it
|
|
213
|
+
req.degradations; // everything that was degraded to fit, readable (informative, never thrown)
|
|
214
|
+
req.assertNoDegradation(); // opt-in: throws RequestLimitError if anything was degraded
|
|
215
|
+
profileFor(model).request(items, { failOnDegrade: true }); // the same, at planning time
|
|
216
|
+
```
|
|
217
|
+
|
|
218
|
+
**A request always comes back sendable**, whatever its tools: tools are often not known ahead of
|
|
219
|
+
time, and an error where a degradation works is worse than the degradation. Nothing is thrown by
|
|
220
|
+
default; each compromise is recorded on its entry and listed in `degradations`.
|
|
221
|
+
|
|
222
|
+
`strict` is core's tri-state: `true` is the strongest preference (not a guarantee), `false`
|
|
223
|
+
refuses, a number > 0 prefers (default `1`).
|
|
224
|
+
Items are fitted in priority order (`true` first, then higher numbers), so the most wanted
|
|
225
|
+
schemas spend the budget first. For each schema the first choice that fits its per-schema limits
|
|
226
|
+
AND what is left of the request's limits wins:
|
|
227
|
+
|
|
228
|
+
1. the model's profile for its kind, as is;
|
|
229
|
+
2. absent optionals written as `null` (Anthropic: trades optional parameters for union types);
|
|
230
|
+
3. large enums widened to a string listing the values (fewer enum values and characters; still
|
|
231
|
+
enforced on decode);
|
|
232
|
+
4. deep nesting written as JSON text (fewer levels and properties);
|
|
233
|
+
5. not strict: the family's loose profile — or, for an output whose family is always strict
|
|
234
|
+
(Claude), prompt-text delivery.
|
|
235
|
+
|
|
236
|
+
When the strict tool slots or the totals run out, the lowest-priority schemas go non-strict (the
|
|
237
|
+
model isn't constrained; the answer is still validated by the same schema), each with its reason.
|
|
238
|
+
Two items with one name: the second is renamed `name_2` (`requestedName` keeps the original).
|
|
239
|
+
More tools than the provider takes (OpenAI 128): the highest-priority ones stay tools and the rest
|
|
240
|
+
go behind ONE dispatcher tool, `run_tool({ tool, args })`, whose `tool` lists them (with their
|
|
241
|
+
`description`s) and whose `args` are their own argument schemas (one nullable field per tool on a
|
|
242
|
+
dialect without unions). `decodeCall('run_tool', args)` returns the original tool's name and
|
|
243
|
+
decoded args; each dispatched tool keeps its own entry (`delivery: 'dispatched'`, `via`).
|
|
244
|
+
Tool parameters are always an object: a non-object root is wrapped as `{ input: … }` and
|
|
245
|
+
unwrapped on decode (no copy).
|
|
246
|
+
|
|
247
|
+
### `RequestEntry`
|
|
248
|
+
|
|
249
|
+
| Member | What |
|
|
250
|
+
|---|---|
|
|
251
|
+
| `name`, `kind`, `requested` | the item |
|
|
252
|
+
| `base` | the profile the model offers for this kind |
|
|
253
|
+
| `profile` | exactly what the schema was rendered with (`base` + adjustments; a memoized variant like `anthropic-strict[optional=null]`) |
|
|
254
|
+
| `strict` | send with `strict: true` / as strict structured output |
|
|
255
|
+
| `delivery` | `'structured'`, `'prompt'` or `'dispatched'` (reached through `via`, the dispatcher) |
|
|
256
|
+
| `adjustments` | `optional-as-null`, `enums-widened {maxEnumValues}`, `depth-limited {maxDepth}`, `root-wrapped`, `not-strict {reason}`, `prompt-text {reason}`, `renamed {from}`, `dispatched {via, reason}` |
|
|
257
|
+
| `reasons` | the limits that ruled out the earlier choices |
|
|
258
|
+
| `jsonSchema` | the schema to send (`undefined` for prompt delivery) |
|
|
259
|
+
| `promptText` | the schema as TypeScript-like text plus the family's JSON instruction |
|
|
260
|
+
| `measure` | what it counts toward the limits (properties, depth, characters, enum values, optionals, unions) |
|
|
261
|
+
| `parse` / `parseText` / `parseOrThrow` | decode the answer — through the same rendering; a failure's `message` in the entry's `errorFormat` |
|
|
262
|
+
| `errorFormat`, `label` | how a bad answer is told to the model (the request's format, then the item's), and what it is called |
|
|
263
|
+
| `encode` / `encodeText` / `encoder` | code value → this model's wire shape |
|
|
264
|
+
| `helpers()` | Handlebars helpers for this schema |
|
|
265
|
+
|
|
266
|
+
`RenderedRequest` also has `entries` (in the order given), `tools`, `sent`, `output`, `dispatcher`,
|
|
267
|
+
`used` (the strict totals), `strictTools`, `limits`, `degradations`, `helpers(defaultName)`.
|
|
268
|
+
|
|
269
|
+
A bundle whose dynamic step takes other arguments than a tool's ctx is adapted:
|
|
270
|
+
`QueryModule.result(...).adapt((ctx: Ctx) => [ctx.catalog, { strict: true }])`.
|
|
271
|
+
|
|
272
|
+
## Values in instructions and prompts
|
|
273
|
+
|
|
274
|
+
A value written into a template as plain JSON is in the CODE shape; a strict model may write the
|
|
275
|
+
same record as pairs or an absent optional as `null`. `{{encode value}}` writes it in the shape
|
|
276
|
+
of the schema the model actually has, for its profile, in this request.
|
|
277
|
+
|
|
278
|
+
```hbs
|
|
279
|
+
Call it like: {{encode example}}
|
|
280
|
+
The current limits are {{encode limits path="limits"}}.
|
|
281
|
+
Return something like {{encode sample output=true pretty=true}}.
|
|
282
|
+
Search takes {{encode query tool="search"}}.
|
|
283
|
+
The shape: {{schema}}
|
|
284
|
+
```
|
|
285
|
+
|
|
286
|
+
| Option | Meaning |
|
|
287
|
+
|---|---|
|
|
288
|
+
| `path="a.b"` | the value is the part at this code path (`*` for any element/key) |
|
|
289
|
+
| `pretty=true` / `pretty=2` | indent the JSON |
|
|
290
|
+
| `tool="name"` / `output=true` | another schema of the request (request helpers only) |
|
|
291
|
+
|
|
292
|
+
Two ways to supply them (both work with core's `noEscape: true`, and without it — the JSON is
|
|
293
|
+
never HTML-escaped):
|
|
294
|
+
|
|
295
|
+
```ts
|
|
296
|
+
// per render
|
|
297
|
+
template(vars, { helpers: req.helpers('search') }); // or entry.helpers(), schemaHelpers(rendered)
|
|
298
|
+
|
|
299
|
+
// once
|
|
300
|
+
registerSchemaHelpers(Handlebars); // names: { encode?, schema? }
|
|
301
|
+
template(vars, { data: schemaData(req, 'search') });
|
|
302
|
+
```
|
|
303
|
+
|
|
304
|
+
Function-form instructions use the entry's **encoder**, which needs only the value (the profile
|
|
305
|
+
and bind come from the entry):
|
|
306
|
+
|
|
307
|
+
```ts
|
|
308
|
+
const encode = req.get('search').encoder;
|
|
309
|
+
encode({ query: 'x' }); // JSON text in the model's shape
|
|
310
|
+
encode({ kind: 'note' }, { path: 'filters' });
|
|
311
|
+
encode.wire({ query: 'x' }); // the same, as a JSON value
|
|
312
|
+
```
|
|
313
|
+
|
|
314
|
+
## Decoding
|
|
315
|
+
|
|
316
|
+
```ts
|
|
317
|
+
rendered.parse(wire, { inPlace?: true, repair?: true, errorFormat?, label? }): ParseResult<Out>
|
|
318
|
+
rendered.parseText(text) // JSON.parse, then decode in place
|
|
319
|
+
rendered.parseOrThrow(wire) // throws SchemaParseError
|
|
320
|
+
```
|
|
321
|
+
|
|
322
|
+
`ParseResult` is `{ ok: true, value, stats } | { ok: false, issues, message, stats }`. Each
|
|
323
|
+
`Issue` has `path` (where the MODEL wrote it, e.g. `['limits', 0, 'value']` or
|
|
324
|
+
`['children', 0, '(json)', 'value']`), `codePath` (where the code sees it, `['limits', 'food']`)
|
|
325
|
+
and `message`. The result's `message` is the re-prompt text, in the call's `errorFormat` (below,
|
|
326
|
+
"Errors for the model").
|
|
327
|
+
|
|
328
|
+
**Repair** (default on): a container sent as a string of JSON text (also double-encoded) is
|
|
329
|
+
parsed, and a value sent directly where JSON text was asked for is taken as is. Each repair is
|
|
330
|
+
counted in `stats.repaired`.
|
|
331
|
+
|
|
332
|
+
### Copies
|
|
333
|
+
|
|
334
|
+
| Situation | Allocation | Counter |
|
|
335
|
+
|---|---|---|
|
|
336
|
+
| A subtree whose wire shape is its code shape | none; checked and returned as the same reference | — |
|
|
337
|
+
| A whole non-strict answer with no rewrites | none; `parse(x).value === x` | — |
|
|
338
|
+
| Optional written as `null` (strict) | none; the key is deleted in place | `edits` |
|
|
339
|
+
| A child whose decoded value differs (in place) | none; written back into the parent | `edits` |
|
|
340
|
+
| A record sent as `[{key, value}]` | one new object per record; values moved by reference | `objects` |
|
|
341
|
+
| A tuple sent as `{"0":…}` | one new array per tuple; items moved | `arrays` |
|
|
342
|
+
| JSON text (escape hatch, `any` on strict) | one `JSON.parse`, then decoded in place | `parsed` |
|
|
343
|
+
| A container sent as a JSON string | one `JSON.parse` | `repaired` |
|
|
344
|
+
| `parse(x, { inPlace: false })` | the first change in a container clones that container once; siblings shared | `objects` / `arrays` |
|
|
345
|
+
| A tagged union (no combinators) | none; the wrapper is dropped | — |
|
|
346
|
+
| A `{input}`-wrapped root | none; the field is picked | — |
|
|
347
|
+
|
|
348
|
+
Encoding never mutates the code value: where the wire shape is the code shape it returns the
|
|
349
|
+
value itself; otherwise only containers on the path to a change are new (`encode(value, stats)`
|
|
350
|
+
counts them).
|
|
351
|
+
|
|
352
|
+
## Errors for the model
|
|
353
|
+
|
|
354
|
+
When an answer doesn't fit, `message` is what the model is told. It follows gin's and query's
|
|
355
|
+
diagnostics (`Code.formatProblems`, `aids.ts`): the model's own JSON echoed back, trimmed around
|
|
356
|
+
the problems, with a marker under each bad spot, the message at the marker, and "did you mean" for
|
|
357
|
+
names it misspelt. It is always in the model's shape: the paths and JSON are what it wrote (pairs,
|
|
358
|
+
`null` for absent, JSON text, a call through the dispatcher), never the code shape, and the
|
|
359
|
+
expected type is read from the JSON Schema it was given.
|
|
360
|
+
|
|
361
|
+
```
|
|
362
|
+
2 problems in the arguments of web_api_call:
|
|
363
|
+
|
|
364
|
+
{
|
|
365
|
+
"url": "https://api.example.com/v1/items",
|
|
366
|
+
"method": "PUTT",
|
|
367
|
+
^^^^^^ method: Expected one of: GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS — did you mean `PUT`?
|
|
368
|
+
"headers": [
|
|
369
|
+
{
|
|
370
|
+
^ headers[0].key: Required.
|
|
371
|
+
expected: string
|
|
372
|
+
"name": "X-Id",
|
|
373
|
+
"value": "1"
|
|
374
|
+
}
|
|
375
|
+
],
|
|
376
|
+
"body": null,
|
|
377
|
+
"requestType": null,
|
|
378
|
+
… 1 more key
|
|
379
|
+
}
|
|
380
|
+
```
|
|
381
|
+
|
|
382
|
+
### `errorFormat`
|
|
383
|
+
|
|
384
|
+
Set on a tool or prompt definition (`ToolItem.errorFormat`, `OutputItem.errorFormat`; core's
|
|
385
|
+
`Tool` / `Prompt` take the same), for a whole request (`request(items, { errorFormat })`), or for
|
|
386
|
+
one call (`parse(wire, { errorFormat })`, `decodeCall(name, args, { errorFormat })`). Later wins:
|
|
387
|
+
request < definition < call. A detail level alone is shorthand: `errorFormat: 'summary'`.
|
|
388
|
+
|
|
389
|
+
| Option | Default | What |
|
|
390
|
+
|---|---|---|
|
|
391
|
+
| `detail` | `'full'` | `'summary'`: one line, the first problem and how many more · `'list'`: one line per problem · `'markers'`: the echo with markers · `'full'`: markers plus the expected type |
|
|
392
|
+
| `maxErrors` | `5` | distinct problems shown; the same mistake repeated counts once (`(the same at rows[3].id, rows[5].id and 997 more places)`); the rest are counted |
|
|
393
|
+
| `maxChars` | `2000` | a hard cap. Detail is dropped step by step until it fits: expected types, context, levels, problems shown, then value lists become counts (`one of 12 values`, the suggestion kept), then `list`, then `summary`, and only then is the text cut |
|
|
394
|
+
| `suggestions` | `true` | "did you mean" for enum values, literal and discriminator tags, unknown keys, a missing key the model misspelt (`Required — you wrote \`titel\`…`), tool names |
|
|
395
|
+
| `expected` | on for `'full'` | a short TypeScript-like type of just that spot (`{ key: string; value: Expr }[]`), only where the message doesn't already say it |
|
|
396
|
+
| `context` | `3` | sibling keys / items shown next to a bad spot (short ones first); the rest are summarized (`{… 4 keys}`, `[… 1000 items]`, `… 3 more keys`) |
|
|
397
|
+
| `depth` | `6` | levels shown above a bad spot; a deeper one is echoed from there, under a header with its path (`at program.ifs[0]…:`), its marker naming the rest (`….body.kind`) |
|
|
398
|
+
| `header` | `true` | the first line: how many problems, in what (`the arguments of search`, `your answer`) |
|
|
399
|
+
|
|
400
|
+
`label` (a parse option) names what the model wrote; request entries set it (`the arguments of
|
|
401
|
+
search`, `the arguments of search (called through run_tool)`, `your answer`).
|
|
402
|
+
|
|
403
|
+
The ranking of "did you mean" is gin's and query's, ported algorithm-identical (`suggest.ts`;
|
|
404
|
+
tested against both): Levenshtein, case-insensitive, within `floor(len / 3)` edits (1 to 3), ties
|
|
405
|
+
by exact case then order. It fires on genuine typos only: a transposition is two edits, so `opne`
|
|
406
|
+
is too far from `open` for a four-letter word.
|
|
407
|
+
|
|
408
|
+
A misspelt key on a closed object is one mistake, told once (at the missing key). A tool name the
|
|
409
|
+
request doesn't have gets the nearest name (`No tool named "serach_docs" in this request — did you
|
|
410
|
+
mean \`search_docs\`?`), else the list; a tool behind the dispatcher called by its own name is
|
|
411
|
+
decoded, not refused.
|
|
412
|
+
|
|
413
|
+
On failure the answer is put back as the model sent it (in-place writes are logged and undone,
|
|
414
|
+
key order included), so the echo is the wire. With `'summary'` or `'list'` nothing is logged and
|
|
415
|
+
the value may be left half-decoded, as before. `parseText` re-reads its text instead.
|
|
416
|
+
|
|
417
|
+
Cost: nothing on the happy path but, for an echoing format, one log entry per in-place write.
|
|
418
|
+
On a failure, union option trials record nothing (count only), and suggestions and expected
|
|
419
|
+
types are computed only for the problems shown.
|
|
420
|
+
|
|
421
|
+
Lower level: `formatErrors(issues, wire, format, label)` formats any issues; `issueKind(issue)`
|
|
422
|
+
(`'type'`, `'required'`, `'unknown-key'`, `'enum'`, `'tag'`, `'tool'`, `'rule'`, …) and
|
|
423
|
+
`suggestionFor(issue)` read what an issue was about; `formatIssues(issues)` is the bare
|
|
424
|
+
`- at <path>: <message>` list (logs, `SchemaParseError` without a format).
|
|
425
|
+
|
|
426
|
+
## Errors
|
|
427
|
+
|
|
428
|
+
| Error | When |
|
|
429
|
+
|---|---|
|
|
430
|
+
| `SchemaParseError` | `parseOrThrow` failed; `issues` has both paths, `message` is the model's message |
|
|
431
|
+
| `SchemaDefinitionError` | the code's own mistake the types couldn't catch: a missing ref at bind time, a dynamic step redefining a name, an example that doesn't fit its schema, encoding at a path that doesn't exist |
|
|
432
|
+
| `RequestLimitError` | only on request: `assertNoDegradation()` / `{ failOnDegrade: true }`, with `problems` listing the degradations |
|
|
433
|
+
|
|
434
|
+
Model mistakes are never thrown by `parse`; they come back as issues for a re-prompt.
|
|
435
|
+
|
|
436
|
+
## Importing outside schemas
|
|
437
|
+
|
|
438
|
+
`fromJSONSchema(json, report?)` turns an MCP tool's `inputSchema`, an elicitation form or an
|
|
439
|
+
OpenAPI body into a bundle: `$defs`/`definitions` become named types and `$ref`s refs (recursion
|
|
440
|
+
stays recursion), `allOf` an intersection (objects merge), `not` and `if`/`then`/`else` rules,
|
|
441
|
+
`patternProperties` and a schema-valued `additionalProperties` next to `properties` extra keys.
|
|
442
|
+
A type-less schema whose keywords imply a type (`{ minLength: 2 }`) is read as that type.
|
|
443
|
+
`dependentSchemas`, `dependentRequired` and external `$ref`s are reported in
|
|
444
|
+
`report.unsupported` and left unchecked.
|
|
445
|
+
|
|
446
|
+
## Gin
|
|
447
|
+
|
|
448
|
+
`fromGin(typeDef)` converts a gin `TypeDef` (and `GinSchema<T>` types it): `text`, `num`, `bool`,
|
|
449
|
+
`list`, `map` (a record; pairs are the profile's job), `obj`, `optional`, `nullable`, `enum`,
|
|
450
|
+
`literal`, `or`, `tuple`, `and` (merged objects), `not`, `iface` (an open object with its props),
|
|
451
|
+
`date`/`timestamp`/`duration`/`color`, `typ` → `a.ref('TypeDef')`, `fn` → `a.ref('Expr')`, and any
|
|
452
|
+
other name → `a.ref(name)`. `ginNamedTypes(registry)` gives a registry's named types as the defs
|
|
453
|
+
of a dynamic step.
|
|
454
|
+
|
|
455
|
+
## Gotchas
|
|
456
|
+
|
|
457
|
+
- Build schemas once at module scope. Renderings are memoized per (schema instance, profile);
|
|
458
|
+
a schema rebuilt per call renders per call.
|
|
459
|
+
- A `dynamic` step without `key` runs on every `bind`. Give it a key (a registry version).
|
|
460
|
+
- Under a `null`-for-absent profile, an optional NULLABLE field keeps `null` as `null`: absent is
|
|
461
|
+
never produced for it (the two can't be told apart on the wire).
|
|
462
|
+
- Unknown keys are left in place on decode (no copy to strip them) unless the object is
|
|
463
|
+
`.strict()`; encoding keeps them too, except people-only fields, which are dropped.
|
|
464
|
+
- `schemaFor` of a sibling-typed value should return cached schemas: a new instance is compiled
|
|
465
|
+
on first use.
|
|
466
|
+
- Where a union option is written as JSON text (an escape, or `a.json()` on a strict dialect) it
|
|
467
|
+
is sent as `{ "json": "…" }`, and a record written as pairs next to a list option as
|
|
468
|
+
`{ "entries": [...] }`, so neither can pass for another option.
|
|
469
|
+
- JSON-text escapes name their type (`… JSON text of this TypeScript type: Expr …`); the
|
|
470
|
+
`type X = …` definitions are written once, in the description of the whole schema.
|
|
471
|
+
- Without `$defs` (Gemini OpenAPI, MINIMAL) a big recursive grammar is written out once per
|
|
472
|
+
recursive named type, its later uses as JSON text (rather than inlined exponentially).
|
|
473
|
+
- `render(profile)` is the raw rendering; only `request()` fits a schema to the provider's size
|
|
474
|
+
limits (a deep grammar can render past OpenAI's 10 levels on its own).
|
|
475
|
+
- A record sent as an object (or a JSON string of one) where pairs were asked for is repaired:
|
|
476
|
+
its values are read in the code shape.
|
|
477
|
+
|
|
478
|
+
## Migrating from zod
|
|
479
|
+
|
|
480
|
+
Core's `Tool` and `Prompt` take `a` schemas. Most code moves one-for-one:
|
|
481
|
+
|
|
482
|
+
| zod | `a` |
|
|
483
|
+
|---|---|
|
|
484
|
+
| `import { z } from 'zod'` | `import { a } from '@aeye/schema'` (or from `@aeye/core`) |
|
|
485
|
+
| `z.object / string / number / boolean / array / enum / literal / union / tuple / null` | the same names on `a` |
|
|
486
|
+
| `z.number().int()`, `z.int()` | `a.int()` (or `a.number().int()`) |
|
|
487
|
+
| `z.record(z.string(), V)` | `a.record(V)`; `z.record(z.enum([...]), V)` → `a.record(a.enum([...]), V)` (keys optional) |
|
|
488
|
+
| `z.any()` / `z.unknown()` | `a.unknown()` (or `a.json()` typed `JsonValue`) |
|
|
489
|
+
| `z.string().email()` / `.url()` / `z.iso.date()` | `a.string().format('email' \| 'uri' \| 'date')` |
|
|
490
|
+
| `.optional()`, `.nullable()`, `.default(v)`, `.describe()`, `.min/.max`, `.refine` | the same (`.optional().default(v)` → `.default(v)`); optional means the key is ABSENT after decoding, never `undefined` |
|
|
491
|
+
| `.transform(fn)` | `a.codec(wire, { decode, encode })` — both directions, so values can be shown to the model |
|
|
492
|
+
| `z.lazy(() => Node)` | a named type: `a.define({ Node: a.object({ kids: a.array(a.ref('Node')) }) }).result('Node')` |
|
|
493
|
+
| `z.infer<typeof X>` | `a.infer<typeof X>` |
|
|
494
|
+
| `schema: (ctx) => z...` (Tool) | a bundle: `a.declare<{ T: … }>().dynamic((ctx) => ({ T: … }), { key }).result(…)` — build it once, at module scope |
|
|
495
|
+
| `schema: (input, ctx) => z...` (Prompt) | `.dynamic((ctx, input) => …)` — note the order |
|
|
496
|
+
| `schema: () => undefined` / `() => false` | `applicable: (ctx) => false` |
|
|
497
|
+
| `schema: z.string()` on a Prompt | `a.string()`: the answer is the model's text, checked |
|
|
498
|
+
| a custom `parse` hook | `a.codec` / `.refine` on the schema (the hook still works, deprecated) |
|
|
499
|
+
| `toJSONSchema(strictify(s, d), d)` in a provider | `await prepareRequest(request, model, { speaks })`, then `sentTools` / `sentOutput` (core) |
|
|
500
|
+
|
|
501
|
+
Things that read differently on purpose: the value a tool receives is the code shape on every model (no `null` for left-out optionals, records are records); errors are the model's JSON with markers, not zod issue lists; `ToolDefinition.parameters` is a `Bound` (`schema.bind()`). Until @aeye/gin and @aeye/query produce `a` (step 2), core also accepts their zod schemas through a temporary bridge — new code shouldn't rely on it.
|