@aeye/schema 0.10.2 → 0.11.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/aeye-schema.md CHANGED
@@ -180,19 +180,67 @@ profileFor(model: ModelLike, opts?: { speaks?: ReadonlySet<string> }): ModelProf
180
180
  // ModelProfile { tool: Profile; output: Profile; outputDelivery: 'structured' | 'prompt'; request(items) }
181
181
  ```
182
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`.
183
+ `ModelLike` is `{ id, provider, schema?, strictFormat?, capabilities? }` — `@aeye/ai`'s `ModelInfo` fits
184
+ as it is. Everything comes from data on the model; nothing is matched on its id or provider name.
185
+
186
+ - The rules are `model.schema` (`ModelSchema`, `rules.ts`): a named base (`registerSchemaBase`:
187
+ `lenient`, `openai`, `openai-finetuned`, `anthropic`, `google`, `google-openapi`, `xai`,
188
+ `ollama`) overridden field by field — `tools` / `output` (`strict`, `dialect`, `loose`, `rules`,
189
+ `limits`, `constraints`, `formats`, `looseRules`), `delivery`, and request-wide `limits`
190
+ (`requestProperties`, …). `@aeye/models` fills it per model, with each model's measured limits
191
+ (`{ base: 'anthropic', limits: { requestProperties: 66 }, tools: { limits: { objectProperties: 38 } } }`).
192
+ - Every `Profile` field is data except `id`, `family` and `strict`, which come from the profile
193
+ `dialect` / `loose` names (provider wire code keys on the family). `rules` overrides the strict
194
+ dialect's shape, `looseRules` (`{ rules, limits, constraints, formats }`) the non-strict one's,
195
+ so a model with no base can say its whole dialect inline. Merging is field by field at every
196
+ level, so an override may change one rule. An unknown key or value throws when the rules are
197
+ resolved (`validateModelSchema`), and so do strict-side rules on a side whose `dialect` isn't strict.
198
+
199
+ ```ts
200
+ schema: {
201
+ base: 'openai', // optional
202
+ tools: {
203
+ strict: true, dialect: 'openai-strict', loose: 'openai',
204
+ rules: {
205
+ optional: 'null', // 'omit' | 'null'
206
+ closedObjects: true,
207
+ records: 'pairs', // 'open' | 'pairs'
208
+ tuples: 'object', // 'prefixItems' | 'object' | 'array'
209
+ unions: 'anyOf', // 'anyOf' | 'tagged'
210
+ nulls: 'anyOf', // 'type-array' | 'anyOf' | 'nullable'
211
+ allOf: false, conditionals: false, patternProperties: false, defs: true, refSiblings: false,
212
+ recursion: true, // true | 'guarded' | false
213
+ any: 'json-text', // 'empty' | 'flat' | 'json-text'
214
+ examples: 'description', // 'keyword' | 'description' | 'none'
215
+ propertyOrdering: false, rootObject: true, alwaysStrictOutput: false,
216
+ jsonInstruction: 'Return only JSON.', audience: 'model', // 'model' | 'people'
217
+ },
218
+ limits: {
219
+ properties: 5000, objectProperties: 100, objectOptionals: 50, optionals: 100, unions: 50,
220
+ depth: 10, enumSize: 40, enumValues: 1000, stringChars: 120000, largeEnumValues: 250, largeEnumChars: 15000,
221
+ },
222
+ constraints: { length: true, range: true, items: 'all', pattern: 'basic' }, // items: 'all' | 'min-0-1' | 'none'; pattern: 'full' | 'basic' | 'none'
223
+ formats: ['date', 'date-time', 'uuid'], // or 'all'
224
+ looseRules: { rules: { rootObject: true }, limits: { enumSize: 90 }, constraints: { pattern: 'none' }, formats: 'all' },
225
+ },
226
+ output: { /* the same */ },
227
+ delivery: 'structured', // 'structured' | 'prompt'
228
+ limits: {
229
+ tools: 128, strictTools: 20, requestProperties: 66, requestOptionals: 24, requestUnions: 16,
230
+ requestDepth: 10, requestStringChars: 120000, requestEnumValues: 1000, requestLargeEnumValues: 250,
231
+ requestLargeEnumChars: 15000, requestObjectProperties: 38, requestObjectOptionals: 13,
232
+ },
233
+ }
234
+ ```
235
+ - No `schema`: `strictFormat` (a base name; `'none'` is `lenient`), else `opts.defaults` (the
236
+ provider's declared default), else `lenient`.
237
+ - Tools are strict when `tools.strict` says so, else with the `'toolsStrict'` capability (the
238
+ `xai` base sets `strict: true`).
239
+ - Output is strict when `output.strict`, else with `'structured'`. Otherwise it's delivered as
240
+ `delivery` says, else as prompt text when the strict output is always compiled (Anthropic), the
241
+ provider has no non-strict output (`opts.nonStrictOutput: false`, Bedrock) or the model has no `'json'`.
242
+ - `speaks`: families the provider can send; anything else is `lenient`.
243
+ - `applySchemaRules(profile, dialect, requestLimits, loose?)` gives the derived profile (memoized by what was applied, in a fixed key order; a rule equal to the profile's own value is no change).
196
244
 
197
245
  Custom dialects: `registerProfile(profile)` (lookup by id with `getProfile`, by family with
198
246
  `familyProfile(family, strict)`).
package/dist/index.d.ts CHANGED
@@ -85,9 +85,10 @@ type SchemaError<Message extends string, Detail> = {
85
85
  * short keys, e.g. [OAI-SO], are the URLs in `docs/plans/schema-dialects-2026.md`,
86
86
  * read 2026-11-04) and from what aeye's providers measured live
87
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.
88
+ * live-schema run 2026-11-04/05). The numbers here are each dialect's
89
+ * conservative defaults; a model's own measured limits are data on the
90
+ * model (`ModelInfo.schema`, see `rules.ts`), applied over these by
91
+ * `profileFor(model)`. Never hard-code a profile at a call site.
91
92
  *
92
93
  * "Strict models see pairs" is NOT a rule of strictness. A record is written
93
94
  * as `[{key, value}]` only where the dialect forbids a schema-valued
@@ -136,6 +137,10 @@ interface SchemaLimits {
136
137
  readonly maxOptional?: number;
137
138
  /** Schema nodes with a union type (`anyOf`, or a `type` array), summed. */
138
139
  readonly maxUnions?: number;
140
+ /** Properties of any one object (Anthropic strict tools: "Schema is too complex" past it). */
141
+ readonly maxObjectProperties?: number;
142
+ /** Optional properties of any one object (Anthropic structured output: "Schema is too complex" past it). */
143
+ readonly maxObjectOptional?: number;
139
144
  }
140
145
  /** Limits a provider applies to a whole request, across every schema in it. */
141
146
  interface RequestLimits {
@@ -238,6 +243,12 @@ interface Profile {
238
243
  readonly loose?: Profile;
239
244
  /** Structured output is always compiled (no non-strict output to fall back to): an unfitting output goes as prompt text. */
240
245
  readonly alwaysStrictOutput?: boolean;
246
+ /**
247
+ * The profile strict structured output is rendered with, when the family's
248
+ * output grammar has other limits than its tools' (Anthropic). `profileFor`
249
+ * picks it for a model's output. Unset: the same profile as tools.
250
+ */
251
+ readonly output?: Profile;
241
252
  /** Appended after a schema delivered as prompt text. */
242
253
  readonly jsonInstruction?: string;
243
254
  /**
@@ -278,20 +289,14 @@ declare const OPENAI_FINETUNED_STRICT: Profile;
278
289
  /** Anthropic non-strict tools: any JSON Schema, not grammar-enforced [ANT-SO]. Tool `input_schema` must be an object. */
279
290
  declare const ANTHROPIC_NON_STRICT: Profile;
280
291
  /**
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.
292
+ * Anthropic strict structured output (`output_config.format`): the strict
293
+ * tool dialect with the output grammar's measured limits (2026-11-29):
294
+ * "Schema is too complex" past 13 optional properties in one object (a tool
295
+ * takes 24), so 12 are kept; one object may have more properties than a
296
+ * tool's (72 required strings pass alone, past the request total of 54 the
297
+ * tools share with it).
294
298
  */
299
+ declare const ANTHROPIC_STRICT_OUTPUT: Profile;
295
300
  declare const ANTHROPIC_STRICT: Profile;
296
301
  /**
297
302
  * Gemini, no `VALIDATED` mode (`responseJsonSchema` / `parametersJsonSchema`):
@@ -420,6 +425,10 @@ interface SchemaMeasure {
420
425
  readonly optional: number;
421
426
  /** Nodes with a union type: `anyOf`/`oneOf` with 2+ options, or a `type` array with 2+ types. */
422
427
  readonly unions: number;
428
+ /** The most properties one object has. */
429
+ readonly objectProperties: number;
430
+ /** The most optional properties one object has. */
431
+ readonly objectOptional: number;
423
432
  }
424
433
  declare const ZERO_MEASURE: SchemaMeasure;
425
434
  declare function measureJson(schema: J$1): SchemaMeasure;
@@ -1713,6 +1722,255 @@ declare namespace a {
1713
1722
  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
1723
  }
1715
1724
 
1725
+ /**
1726
+ * Schema rules: what a model's schemas are written in, as plain data on the
1727
+ * model (`ModelInfo.schema` in `@aeye/ai`, filled by `@aeye/models`).
1728
+ *
1729
+ * A model's `schema` may name a base rule set (`'anthropic'`, `'openai'`, …,
1730
+ * see {@link registerSchemaBase}) and overrides it field by field, or say
1731
+ * everything itself with no base. For tool arguments and for structured
1732
+ * output separately it gives:
1733
+ *
1734
+ * - `strict`: whether that kind is sent strict (grammar-enforced);
1735
+ * - `dialect` / `loose`: the registered profile (`getProfile` id) its strict
1736
+ * and its non-strict schemas extend. The profile's `family` (which the
1737
+ * provider's wire code keys on), `id` and `strict` come from it and are
1738
+ * never data;
1739
+ * - `rules` / `limits` / `constraints` / `formats`: every other field of the
1740
+ * strict profile, overridden one by one;
1741
+ * - `looseRules`: the same four groups for the non-strict profile.
1742
+ *
1743
+ * Plus `delivery` of non-strict output and request-wide `limits`. Every
1744
+ * option, with what each value means:
1745
+ *
1746
+ * ```ts
1747
+ * schema: {
1748
+ * base: 'openai', // optional: a registered base to override
1749
+ * tools: {
1750
+ * strict: true, // unset: the 'toolsStrict' capability ('structured' for output)
1751
+ * dialect: 'openai-strict', // the strict profile this extends (family, id, strict come from it)
1752
+ * loose: 'openai', // the non-strict profile this extends
1753
+ * rules: { // shape of a strict schema (unset fields: the dialect's)
1754
+ * optional: 'null', // 'omit' (left out) | 'null' (required, written null)
1755
+ * closedObjects: true, // additionalProperties: false on every object
1756
+ * records: 'pairs', // 'open' (additionalProperties: V) | 'pairs' ([{key, value}])
1757
+ * tuples: 'object', // 'prefixItems' | 'object' ({"0": A}) | 'array' (items: anyOf)
1758
+ * unions: 'anyOf', // 'anyOf' | 'tagged' (one nullable field per option)
1759
+ * nulls: 'anyOf', // 'type-array' | 'anyOf' | 'nullable' (OpenAPI)
1760
+ * allOf: false, // allOf accepted (else intersections are merged)
1761
+ * conditionals: false, // not / if-then-else accepted (else said in words)
1762
+ * patternProperties: false, // patternProperties accepted
1763
+ * defs: true, // $defs/$ref (else named types are inlined)
1764
+ * refSiblings: false, // keywords beside a $ref (else it is wrapped in anyOf)
1765
+ * recursion: true, // true | 'guarded' (only through optional/empty) | false
1766
+ * any: 'json-text', // 'empty' ({}) | 'flat' (anyOf of JSON types) | 'json-text'
1767
+ * examples: 'description', // 'keyword' | 'description' | 'none'
1768
+ * propertyOrdering: false, // emit propertyOrdering (Gemini responseSchema)
1769
+ * rootObject: true, // a non-object root is wrapped as { input }
1770
+ * alwaysStrictOutput: false, // output is always compiled: an unfitting one goes as prompt text
1771
+ * jsonInstruction: 'Return JSON.', // appended after a schema sent as prompt text
1772
+ * audience: 'model', // 'model' | 'people' (forPeople() fields kept)
1773
+ * },
1774
+ * limits: { // of ONE schema; numbers
1775
+ * properties: 5000, objectProperties: 100, objectOptionals: 50, optionals: 100, unions: 50,
1776
+ * depth: 10, // deeper nesting is written as JSON text
1777
+ * enumSize: 40, // a larger enum is widened to a string that lists its values
1778
+ * enumValues: 1000, stringChars: 120000, largeEnumValues: 250, largeEnumChars: 15000,
1779
+ * },
1780
+ * constraints: { length: true, range: true, items: 'all', pattern: 'basic' }, // items: 'all' | 'min-0-1' | 'none'; pattern: 'full' | 'basic' | 'none'
1781
+ * formats: ['date', 'date-time', 'uuid'], // or 'all'
1782
+ * looseRules: { rules: { rootObject: true }, limits: { enumSize: 90 }, constraints: { pattern: 'none' }, formats: 'all' },
1783
+ * },
1784
+ * output: { … the same … },
1785
+ * delivery: 'structured', // non-strict output: 'structured' (schema without strict) | 'prompt'
1786
+ * limits: { // across the whole request (every STRICT schema summed)
1787
+ * tools: 128, strictTools: 20,
1788
+ * requestProperties: 66, requestOptionals: 24, requestUnions: 16, requestDepth: 10,
1789
+ * requestStringChars: 120000, requestEnumValues: 1000, requestLargeEnumValues: 250, requestLargeEnumChars: 15000,
1790
+ * requestObjectProperties: 38, requestObjectOptionals: 13,
1791
+ * },
1792
+ * }
1793
+ * ```
1794
+ *
1795
+ * e.g. Claude Opus 4.8, the anthropic dialect with its own measured grammar
1796
+ * limits: `{ base: 'anthropic', limits: { requestProperties: 66 }, tools: { limits: { objectProperties: 38 } } }`.
1797
+ *
1798
+ * `profileFor(model)` builds the `Profile`s from this data alone; nothing is
1799
+ * chosen by matching the model's id. Everything here is JSON: it is
1800
+ * generated into `@aeye/models`, merged with measured overrides, and may be
1801
+ * overridden again by an app, one field at a time. An unknown key or value
1802
+ * is an error when the rules are resolved: a model's rules must say exactly
1803
+ * what it reads.
1804
+ */
1805
+
1806
+ /** The `Profile` fields a model's rules may set in `rules` (every JSON-expressible shape field). */
1807
+ type ModelSchemaRuleKey = 'optional' | 'closedObjects' | 'records' | 'tuples' | 'unions' | 'nulls' | 'allOf' | 'conditionals' | 'patternProperties' | 'defs' | 'refSiblings' | 'recursion' | 'any' | 'examples' | 'propertyOrdering' | 'rootObject' | 'alwaysStrictOutput' | 'jsonInstruction' | 'audience';
1808
+ /**
1809
+ * The shape of one dialect, field by field: each is the `Profile` field of
1810
+ * the same name (see `profile.ts` for what each value renders). Unset: the
1811
+ * extended profile's.
1812
+ */
1813
+ type ModelSchemaRules = {
1814
+ readonly [K in ModelSchemaRuleKey]?: Profile[K];
1815
+ };
1816
+ /** Limits of ONE schema (a tool's arguments, or the output), mapped onto `Profile`. */
1817
+ interface ModelSchemaLimits {
1818
+ /** Object properties summed over every level (`limits.maxProperties`). */
1819
+ readonly properties?: number;
1820
+ /** Properties of any one object (`limits.maxObjectProperties`; Anthropic "Schema is too complex"). */
1821
+ readonly objectProperties?: number;
1822
+ /** Optional properties of any one object (`limits.maxObjectOptional`). */
1823
+ readonly objectOptionals?: number;
1824
+ /** Optional properties summed (`limits.maxOptional`). */
1825
+ readonly optionals?: number;
1826
+ /** Properties with a union type, summed (`limits.maxUnions`). */
1827
+ readonly unions?: number;
1828
+ /** Levels of nesting; deeper is written as JSON text (`maxDepth` and `limits.maxDepth`). */
1829
+ readonly depth?: number;
1830
+ /** Values of one enum; a larger enum is widened to a string that lists them (`maxEnumValues`). */
1831
+ readonly enumSize?: number;
1832
+ /** Enum values summed over every enum (`limits.maxEnumValues`). */
1833
+ readonly enumValues?: number;
1834
+ /** Characters of names, enum and const values (`limits.maxStringChars`). */
1835
+ readonly stringChars?: number;
1836
+ /** An enum over this many values is a large enum... (`limits.largeEnumValues`) */
1837
+ readonly largeEnumValues?: number;
1838
+ /** ...whose values may total this many characters (`limits.maxLargeEnumChars`). */
1839
+ readonly largeEnumChars?: number;
1840
+ }
1841
+ /** Limits across a whole request: every tool and the output together (`Profile.request`). */
1842
+ interface ModelRequestLimits {
1843
+ /** Tools in one request (`request.maxTools`). */
1844
+ readonly tools?: number;
1845
+ /** Tools sent strict (`request.maxStrictTools`). */
1846
+ readonly strictTools?: number;
1847
+ /** Properties over every strict schema (`request.totals.maxProperties`; Anthropic "The compiled grammar is too large"). */
1848
+ readonly requestProperties?: number;
1849
+ /** Optional properties over every strict schema (`request.totals.maxOptional`). */
1850
+ readonly requestOptionals?: number;
1851
+ /** Union-typed properties over every strict schema (`request.totals.maxUnions`). */
1852
+ readonly requestUnions?: number;
1853
+ /** Deepest nesting of any strict schema (`request.totals.maxDepth`). */
1854
+ readonly requestDepth?: number;
1855
+ /** Characters of names, enum and const values over every strict schema (`request.totals.maxStringChars`). */
1856
+ readonly requestStringChars?: number;
1857
+ /** Enum values over every strict schema (`request.totals.maxEnumValues`). */
1858
+ readonly requestEnumValues?: number;
1859
+ /** An enum over this many values is a large enum... (`request.totals.largeEnumValues`) */
1860
+ readonly requestLargeEnumValues?: number;
1861
+ /** ...whose values may total this many characters, in any strict schema (`request.totals.maxLargeEnumChars`). */
1862
+ readonly requestLargeEnumChars?: number;
1863
+ /** Properties of any one object of any strict schema (`request.totals.maxObjectProperties`). */
1864
+ readonly requestObjectProperties?: number;
1865
+ /** Optional properties of any one object of any strict schema (`request.totals.maxObjectOptional`). */
1866
+ readonly requestObjectOptionals?: number;
1867
+ }
1868
+ /** What one dialect (the strict or the loose one of a side) is overridden with. */
1869
+ interface ModelSchemaDialect {
1870
+ /** Shape fields of the profile. */
1871
+ readonly rules?: ModelSchemaRules;
1872
+ /** Limits of one schema. */
1873
+ readonly limits?: ModelSchemaLimits;
1874
+ /** Constraint keywords the model enforces (the rest are said in words, and always validated). */
1875
+ readonly constraints?: Partial<ConstraintSupport>;
1876
+ /** String formats the model accepts, or `'all'`. */
1877
+ readonly formats?: readonly string[] | 'all';
1878
+ }
1879
+ /** The rules of one kind of schema: tool arguments, or structured output. Its own fields are the strict dialect's. */
1880
+ interface ModelSchemaSide extends ModelSchemaDialect {
1881
+ /**
1882
+ * Whether this kind is sent strict (grammar-enforced). Unset: tools are
1883
+ * strict when the model has the `'toolsStrict'` capability, output when it
1884
+ * has `'structured'`.
1885
+ */
1886
+ readonly strict?: boolean;
1887
+ /**
1888
+ * The profile (`getProfile` id) a strict schema extends, e.g.
1889
+ * `'anthropic-strict'`. A profile that isn't strict means this kind is
1890
+ * never strict (then `rules`, `limits`, `constraints` and `formats` must
1891
+ * be unset: say them in `looseRules`).
1892
+ */
1893
+ readonly dialect?: string;
1894
+ /** The profile a non-strict schema extends, e.g. `'anthropic'`. */
1895
+ readonly loose?: string;
1896
+ /** The non-strict dialect's overrides. */
1897
+ readonly looseRules?: ModelSchemaDialect;
1898
+ }
1899
+ /** Everything about the schemas a model reads: plain, serializable data. */
1900
+ interface ModelSchema {
1901
+ /** A base rule set by name ({@link registerSchemaBase}); this object overrides it field by field. */
1902
+ readonly base?: string;
1903
+ /** Tool arguments. */
1904
+ readonly tools?: ModelSchemaSide;
1905
+ /** Structured output. */
1906
+ readonly output?: ModelSchemaSide;
1907
+ /**
1908
+ * How output that isn't strict is delivered: `'structured'` (the API takes
1909
+ * a schema without strict) or `'prompt'` (the schema goes as prompt text).
1910
+ * Unset: `'prompt'` when the strict output dialect is always compiled, or
1911
+ * the model has no `'json'` capability; else `'structured'`.
1912
+ */
1913
+ readonly delivery?: 'structured' | 'prompt';
1914
+ /** Limits across the whole request. */
1915
+ readonly limits?: ModelRequestLimits;
1916
+ }
1917
+ /** A schema with its base chain merged in: every field the model reads. */
1918
+ interface ResolvedModelSchema {
1919
+ /** The base chain, outermost first. */
1920
+ readonly bases: readonly string[];
1921
+ readonly tools: ModelSchemaSide & {
1922
+ readonly dialect: string;
1923
+ readonly loose: string;
1924
+ };
1925
+ readonly output: ModelSchemaSide & {
1926
+ readonly dialect: string;
1927
+ readonly loose: string;
1928
+ };
1929
+ readonly delivery?: 'structured' | 'prompt';
1930
+ readonly limits?: ModelRequestLimits;
1931
+ }
1932
+ /**
1933
+ * Throws when a `ModelSchema` has a key or value the rules don't read
1934
+ * (an unknown key, a misspelt enum value, a wrong type), naming the path.
1935
+ * `where` says whose rules they are in the message.
1936
+ */
1937
+ declare function validateModelSchema(schema: ModelSchema, where?: string): void;
1938
+ /**
1939
+ * Register a named base rule set, which a model's `schema.base` may name.
1940
+ * A base may itself have a `base`. Re-registering a name replaces it.
1941
+ * Its rules are checked as {@link validateModelSchema} does.
1942
+ */
1943
+ declare function registerSchemaBase(name: string, schema: ModelSchema): void;
1944
+ /** A registered base by name. */
1945
+ declare function getSchemaBase(name: string): ModelSchema | undefined;
1946
+ /** The names of every registered base. */
1947
+ declare function schemaBases(): string[];
1948
+ /**
1949
+ * Two schemas as one: `over` wins field by field (sides, their `rules`,
1950
+ * `limits`, `constraints` and `looseRules`, and the request limits merge;
1951
+ * `formats` and the rest replace). `over.base`, when set, replaces `base`.
1952
+ */
1953
+ declare function mergeModelSchema(base: ModelSchema | undefined, over: ModelSchema | undefined): ModelSchema | undefined;
1954
+ /**
1955
+ * A schema with its base chain merged in. An unknown base name, key or
1956
+ * value throws: a model's rules must say exactly what it reads.
1957
+ */
1958
+ declare function resolveModelSchema(schema: ModelSchema | undefined): ResolvedModelSchema;
1959
+ /**
1960
+ * A profile with a dialect's overrides and the request limits applied,
1961
+ * memoized by what was applied so the same rules give the same instance
1962
+ * (and id), which keeps rendering memos stable. A rule equal to the
1963
+ * profile's own value is no change. No changes: the profile itself.
1964
+ */
1965
+ declare function applySchemaRules(profile: Profile, side: ModelSchemaDialect | undefined, request: ModelRequestLimits | undefined, loose?: Profile): Profile;
1966
+ /** The strict and loose profiles of one side of resolved rules. */
1967
+ declare function sideProfiles(rules: ResolvedModelSchema, kind: 'tools' | 'output'): {
1968
+ strict: Profile;
1969
+ loose: Profile;
1970
+ };
1971
+ /** The family a resolved rule set's tools are written for (`'lenient'` when none). */
1972
+ declare function rulesFamily(rules: ResolvedModelSchema): string;
1973
+
1716
1974
  /**
1717
1975
  * Showing values in instructions and prompts exactly as the model reads and
1718
1976
  * writes them.
@@ -2079,26 +2337,46 @@ declare class RenderedRequest<I extends readonly RequestItem[] = readonly Reques
2079
2337
  declare function planRequest<const I extends readonly RequestItem[]>(target: ModelProfile, items: I, opts?: RequestOptions): RenderedRequest<I>;
2080
2338
 
2081
2339
  /**
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.
2340
+ * From a model to its profiles. Everything comes from data on the model:
2341
+ * its `schema` rules (`@aeye/ai` `ModelInfo.schema`, generated into
2342
+ * `@aeye/models`) and its capabilities (`'toolsStrict'`, `'structured'`,
2343
+ * `'json'`). Nothing is chosen by matching the model's id or provider name,
2344
+ * so a call site never picks a profile by hand and a model's own measured
2345
+ * limits reach the planner.
2086
2346
  */
2087
2347
 
2088
2348
  /**
2089
2349
  * A model, structurally — `@aeye/ai`'s `ModelInfo` (and `@aeye/models`'
2090
- * entries with `strictSupport` applied) fit as they are.
2350
+ * entries) fit as they are.
2091
2351
  */
2092
2352
  interface ModelLike {
2093
2353
  readonly id: string;
2094
2354
  readonly provider: string;
2095
- /** `@aeye/models` `strictSupport` pins this; `'none'` opts out. */
2355
+ /** The model's schema rules (see `rules.ts`). Unset: `strictFormat`, else the provider's defaults, else `lenient`. */
2356
+ readonly schema?: ModelSchema;
2357
+ /**
2358
+ * Shorthand for `schema: { base: strictFormat }` (a base name), read only
2359
+ * when `schema` is unset; `'none'` is `lenient`.
2360
+ */
2096
2361
  readonly strictFormat?: string;
2097
- /** `'toolsStrict'` → strict tools; `'structured'` → structured output (strict where the family has it). */
2362
+ /** `'toolsStrict'` → strict tools; `'structured'` → strict structured output; `'json'` → non-strict structured output. */
2098
2363
  readonly capabilities?: ReadonlySet<string> | readonly string[];
2099
2364
  }
2100
- /** The family a model's schemas are written for (see `@aeye/ai` `resolveStrictFormat`). */
2101
- declare function familyOf(model: ModelLike): ProfileFamily;
2365
+ /** How `profileFor` reads a model. */
2366
+ interface ProfileForOptions {
2367
+ /** The families a provider can send; a model of another family gets `lenient` rules. */
2368
+ readonly speaks?: ReadonlySet<string>;
2369
+ /** The rules of a model that has none (`schema` and `strictFormat` unset): the provider's declared default. */
2370
+ readonly defaults?: ModelSchema;
2371
+ /** `false` when the provider's API has no structured output without strict (Bedrock Converse): non-strict output goes as prompt text. */
2372
+ readonly nonStrictOutput?: boolean;
2373
+ }
2374
+ /** The rules a model's schemas follow: its own, else its `strictFormat`, else the defaults, else `lenient`. */
2375
+ declare function modelSchemaOf(model: ModelLike, defaults?: ModelSchema): ModelSchema;
2376
+ /** A model's rules with their base chain merged in; `lenient` when the provider doesn't speak their family. */
2377
+ declare function rulesFor(model: ModelLike, opts?: ProfileForOptions): ResolvedModelSchema;
2378
+ /** The family a model's schemas are written for, from its rules. */
2379
+ declare function familyOf(model: ModelLike, opts?: ProfileForOptions): ProfileFamily;
2102
2380
  /**
2103
2381
  * What one model reads: the profile for its tool arguments, the profile for
2104
2382
  * its structured output, and how output is delivered. Start a request with
@@ -2122,21 +2400,20 @@ declare class ModelProfile {
2122
2400
  static of(profile: Profile): ModelProfile;
2123
2401
  }
2124
2402
  /**
2125
- * The profiles for a model, from its capabilities (`@aeye/models`):
2403
+ * The profiles for a model, from its data alone:
2126
2404
  *
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;
2405
+ * - the rules are `model.schema` (a named base overridden field by field),
2406
+ * else `strictFormat`, else `opts.defaults` (the provider's), else `lenient`;
2407
+ * - tools are strict when the rules say so (`tools.strict`), else when the
2408
+ * model has `'toolsStrict'`; output when `output.strict`, else `'structured'`;
2409
+ * - each side is written with its rules' strict or loose dialect, with the
2410
+ * model's own limits (per schema and per request) applied;
2411
+ * - output that isn't strict is delivered as the rules say (`delivery`),
2412
+ * else as prompt text when the strict output is always compiled, the
2413
+ * provider has no non-strict output, or the model has no `'json'`;
2414
+ * - `speaks` limits the families a provider can send (others are `lenient`).
2415
+ */
2416
+ declare function profileFor(model: ModelLike, opts?: ProfileForOptions): ModelProfile;
2140
2417
 
2141
2418
  /** What a deferred value is written with, once the request is planned. */
2142
2419
  interface DeferredSpec {
@@ -2455,4 +2732,4 @@ declare function ginNamedTypes<T extends Record<string, unknown> = {}>(registry:
2455
2732
  readonly [K in keyof T]: SchemaOf<T[K]>;
2456
2733
  } & Record<string, AnySchema>;
2457
2734
 
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 };
2735
+ export { ANTHROPIC_NON_STRICT, ANTHROPIC_STRICT, ANTHROPIC_STRICT_OUTPUT, 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, type ModelRequestLimits, type ModelSchema, type ModelSchemaDialect, type ModelSchemaLimits, type ModelSchemaRuleKey, type ModelSchemaRules, type ModelSchemaSide, 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, type ProfileForOptions, 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 ResolvedModelSchema, 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, applySchemaRules, brokenLimits, deferEncode, deferSchema, deferredRequest, didYouMean, editDistance, errorFormat, familyOf, familyProfile, fillDeferred, formatErrors, formatIssues, formatPath, fromGin, fromJSONSchema, getProfile, getSchemaBase, ginNamedTypes, hasDeferred, isBasicPattern, isNever, issueKind, measureJson, mergeErrorFormats, mergeModelSchema, modelPath, modelSchemaOf, nearest, newStats, overLimits, plainDeferred, planRequest, profileFor, rankNear, readJsonText, registerProfile, registerSchemaBase, registerSchemaHelpers, resolveModelSchema, rulesFamily, rulesFor, schemaBases, schemaData, schemaHelpers, shortType, sideProfiles, staticBundle, strictPriority, suggestionBudget, suggestionFor, validateModelSchema, variant, viewOf };
package/dist/index.js CHANGED
@@ -124,7 +124,7 @@ var ANTHROPIC_NON_STRICT = Object.freeze({
124
124
  family: "anthropic",
125
125
  rootObject: true
126
126
  });
127
- var ANTHROPIC_STRICT = Object.freeze({
127
+ var ANTHROPIC_STRICT_TOOLS = {
128
128
  id: "anthropic-strict",
129
129
  family: "anthropic",
130
130
  strict: true,
@@ -145,10 +145,17 @@ var ANTHROPIC_STRICT = Object.freeze({
145
145
  examples: "description",
146
146
  propertyOrdering: false,
147
147
  rootObject: true,
148
- request: Object.freeze({ maxStrictTools: 20, totals: Object.freeze({ maxOptional: 24, maxUnions: 16 }) }),
148
+ limits: Object.freeze({ maxObjectProperties: 34 }),
149
+ request: Object.freeze({ maxStrictTools: 20, totals: Object.freeze({ maxOptional: 24, maxUnions: 16, maxProperties: 54 }) }),
149
150
  loose: ANTHROPIC_NON_STRICT,
150
151
  alwaysStrictOutput: true
152
+ };
153
+ var ANTHROPIC_STRICT_OUTPUT = Object.freeze({
154
+ ...ANTHROPIC_STRICT_TOOLS,
155
+ id: "anthropic-strict-output",
156
+ limits: Object.freeze({ maxObjectOptional: 12 })
151
157
  });
158
+ var ANTHROPIC_STRICT = Object.freeze({ ...ANTHROPIC_STRICT_TOOLS, output: ANTHROPIC_STRICT_OUTPUT });
152
159
  var GEMINI_JSON_INSTRUCTION = "Return ONLY a single raw JSON object that conforms to the schema above. Do NOT wrap it in markdown code fences, do NOT add any prose before or after it, and do NOT echo the schema itself: emit only the JSON instance.";
153
160
  var GOOGLE_NON_STRICT = Object.freeze({
154
161
  ...LENIENT,
@@ -276,6 +283,7 @@ for (const p of [
276
283
  OPENAI_FINETUNED_STRICT,
277
284
  ANTHROPIC_NON_STRICT,
278
285
  ANTHROPIC_STRICT,
286
+ ANTHROPIC_STRICT_OUTPUT,
279
287
  GOOGLE_NON_STRICT,
280
288
  GOOGLE_STRICT,
281
289
  GOOGLE_OPENAPI,
@@ -342,7 +350,9 @@ var ZERO_MEASURE = Object.freeze({
342
350
  enumValues: 0,
343
351
  enums: Object.freeze([]),
344
352
  optional: 0,
345
- unions: 0
353
+ unions: 0,
354
+ objectProperties: 0,
355
+ objectOptional: 0
346
356
  });
347
357
  function measureJson(schema) {
348
358
  let properties = 0;
@@ -350,6 +360,8 @@ function measureJson(schema) {
350
360
  let enumValues = 0;
351
361
  let optional2 = 0;
352
362
  let unions = 0;
363
+ let objectProperties = 0;
364
+ let objectOptional = 0;
353
365
  const enums = [];
354
366
  const defs = schema.$defs ?? {};
355
367
  for (const name of Object.keys(defs)) stringChars += name.length;
@@ -363,6 +375,9 @@ function measureJson(schema) {
363
375
  if (o.properties && typeof o.properties === "object") {
364
376
  const props = o.properties;
365
377
  const required = new Set(Array.isArray(o.required) ? o.required : []);
378
+ const keys = Object.keys(props);
379
+ objectProperties = Math.max(objectProperties, keys.length);
380
+ objectOptional = Math.max(objectOptional, keys.filter((k) => !required.has(k)).length);
366
381
  for (const [k, p] of Object.entries(props)) {
367
382
  properties++;
368
383
  stringChars += k.length;
@@ -427,7 +442,7 @@ function measureJson(schema) {
427
442
  return (container ? 1 : 0) + inner;
428
443
  };
429
444
  const depth = depthOf(body);
430
- return { properties, depth, stringChars, enumValues, enums, optional: optional2, unions };
445
+ return { properties, depth, stringChars, enumValues, enums, optional: optional2, unions, objectProperties, objectOptional };
431
446
  }
432
447
  function components(defs, refName2) {
433
448
  const edges = /* @__PURE__ */ new Map();
@@ -498,7 +513,9 @@ function addMeasures(a, b) {
498
513
  enumValues: a.enumValues + b.enumValues,
499
514
  enums: [...a.enums, ...b.enums],
500
515
  optional: a.optional + b.optional,
501
- unions: a.unions + b.unions
516
+ unions: a.unions + b.unions,
517
+ objectProperties: Math.max(a.objectProperties, b.objectProperties),
518
+ objectOptional: Math.max(a.objectOptional, b.objectOptional)
502
519
  };
503
520
  }
504
521
  function overLimits(m, limits, scope) {
@@ -513,6 +530,8 @@ function overLimits(m, limits, scope) {
513
530
  over("enum values", m.enumValues, limits.maxEnumValues);
514
531
  over("optional properties", m.optional, limits.maxOptional);
515
532
  over("union-typed properties", m.unions, limits.maxUnions);
533
+ over("properties in one object", m.objectProperties, limits.maxObjectProperties);
534
+ over("optional properties in one object", m.objectOptional, limits.maxObjectOptional);
516
535
  if (limits.largeEnumValues !== void 0 && limits.maxLargeEnumChars !== void 0) {
517
536
  for (const e of m.enums) {
518
537
  if (e.values > limits.largeEnumValues && e.chars > limits.maxLargeEnumChars) {
@@ -533,6 +552,8 @@ function brokenLimits(m, limits, out = /* @__PURE__ */ new Set()) {
533
552
  over("maxEnumValues", m.enumValues, limits.maxEnumValues);
534
553
  over("maxOptional", m.optional, limits.maxOptional);
535
554
  over("maxUnions", m.unions, limits.maxUnions);
555
+ over("maxObjectProperties", m.objectProperties, limits.maxObjectProperties);
556
+ over("maxObjectOptional", m.objectOptional, limits.maxObjectOptional);
536
557
  if (limits.largeEnumValues !== void 0 && limits.maxLargeEnumChars !== void 0) {
537
558
  for (const e of m.enums) if (e.values > limits.largeEnumValues && e.chars > limits.maxLargeEnumChars) out.add("largeEnum");
538
559
  }
@@ -1067,10 +1088,10 @@ var Echo = class {
1067
1088
  const others = keys.filter((key) => !on.includes(key));
1068
1089
  const short = new Set(others.filter((key) => inline(obj[key], 40).length <= 40 && !isContainer(obj[key])).slice(0, this.f.context));
1069
1090
  for (const key of others) if (short.size < this.f.context && !short.has(key)) short.add(key);
1070
- const show = keys.filter((key) => on.includes(key) || short.has(key));
1071
- const elided = keys.length - show.length;
1072
- show.forEach((key, i) => {
1073
- const last = i === show.length - 1 && !elided;
1091
+ const show2 = keys.filter((key) => on.includes(key) || short.has(key));
1092
+ const elided = keys.length - show2.length;
1093
+ show2.forEach((key, i) => {
1094
+ const last = i === show2.length - 1 && !elided;
1074
1095
  this.node(obj[key], [...path, key], indent, `${JSON.stringify(key)}: `, last ? "" : ",");
1075
1096
  });
1076
1097
  if (elided) this.out.push(`${indent}\u2026 ${elided} more key${elided === 1 ? "" : "s"}`);
@@ -2875,7 +2896,7 @@ var RecordType = class extends Schema {
2875
2896
  hint: (view) => this.hintOf(pairs ? [`A map written as ${view.recordWord}; each key at most once.`] : []),
2876
2897
  emit: () => {
2877
2898
  if (pairs) {
2878
- return { type: "array", items: c.object({ key: key.json(), value: val.json() }, ["key", "value"], true) };
2899
+ return { type: "array", items: c.object({ key: key.json(), value: val.json() }, ["key", "value"], c.profile.closedObjects) };
2879
2900
  }
2880
2901
  const j = { type: "object", additionalProperties: val.json() };
2881
2902
  if (this.key && !c.profile.closedObjects && !(this.key instanceof StringType && !Object.keys(this.key.options).length)) j.propertyNames = key.json();
@@ -3993,6 +4014,288 @@ var define = (defs) => new Module(defs);
3993
4014
  var declare = () => new Module();
3994
4015
  var module_ = () => new Module();
3995
4016
 
4017
+ // src/rules.ts
4018
+ var RULE_CHECKS = {
4019
+ optional: ["omit", "null"],
4020
+ closedObjects: "boolean",
4021
+ records: ["open", "pairs"],
4022
+ tuples: ["prefixItems", "object", "array"],
4023
+ unions: ["anyOf", "tagged"],
4024
+ nulls: ["type-array", "anyOf", "nullable"],
4025
+ allOf: "boolean",
4026
+ conditionals: "boolean",
4027
+ patternProperties: "boolean",
4028
+ defs: "boolean",
4029
+ refSiblings: "boolean",
4030
+ recursion: [true, false, "guarded"],
4031
+ any: ["empty", "flat", "json-text"],
4032
+ examples: ["keyword", "description", "none"],
4033
+ propertyOrdering: "boolean",
4034
+ rootObject: "boolean",
4035
+ alwaysStrictOutput: "boolean",
4036
+ jsonInstruction: "string",
4037
+ audience: ["model", "people"]
4038
+ };
4039
+ var LIMIT_FIELDS = {
4040
+ properties: "maxProperties",
4041
+ objectProperties: "maxObjectProperties",
4042
+ objectOptionals: "maxObjectOptional",
4043
+ optionals: "maxOptional",
4044
+ unions: "maxUnions",
4045
+ depth: "maxDepth",
4046
+ enumSize: null,
4047
+ // `Profile.maxEnumValues`
4048
+ enumValues: "maxEnumValues",
4049
+ stringChars: "maxStringChars",
4050
+ largeEnumValues: "largeEnumValues",
4051
+ largeEnumChars: "maxLargeEnumChars"
4052
+ };
4053
+ var REQUEST_FIELDS = {
4054
+ tools: ["request", "maxTools"],
4055
+ strictTools: ["request", "maxStrictTools"],
4056
+ requestProperties: ["totals", "maxProperties"],
4057
+ requestOptionals: ["totals", "maxOptional"],
4058
+ requestUnions: ["totals", "maxUnions"],
4059
+ requestDepth: ["totals", "maxDepth"],
4060
+ requestStringChars: ["totals", "maxStringChars"],
4061
+ requestEnumValues: ["totals", "maxEnumValues"],
4062
+ requestLargeEnumValues: ["totals", "largeEnumValues"],
4063
+ requestLargeEnumChars: ["totals", "maxLargeEnumChars"],
4064
+ requestObjectProperties: ["totals", "maxObjectProperties"],
4065
+ requestObjectOptionals: ["totals", "maxObjectOptional"]
4066
+ };
4067
+ var CONSTRAINT_CHECKS = {
4068
+ length: "boolean",
4069
+ range: "boolean",
4070
+ items: ["all", "min-0-1", "none"],
4071
+ pattern: ["full", "basic", "none"]
4072
+ };
4073
+ var numbers = (o) => Object.fromEntries(Object.keys(o).map((k) => [k, "number"]));
4074
+ var DIALECT_SPEC = {
4075
+ rules: RULE_CHECKS,
4076
+ limits: numbers(LIMIT_FIELDS),
4077
+ constraints: CONSTRAINT_CHECKS,
4078
+ formats: "formats"
4079
+ };
4080
+ var SIDE_SPEC = { strict: "boolean", dialect: "string", loose: "string", ...DIALECT_SPEC, looseRules: DIALECT_SPEC };
4081
+ var SCHEMA_SPEC = {
4082
+ base: "string",
4083
+ tools: SIDE_SPEC,
4084
+ output: SIDE_SPEC,
4085
+ delivery: ["structured", "prompt"],
4086
+ limits: numbers(REQUEST_FIELDS)
4087
+ };
4088
+ var isObject2 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
4089
+ var show = (v) => JSON.stringify(v) ?? String(v);
4090
+ function checkValue(v, check, path, where) {
4091
+ const fail2 = (want) => {
4092
+ throw new Error(`Schema rules${where}: ${path} is ${show(v)}, expected ${want}`);
4093
+ };
4094
+ if (Array.isArray(check)) {
4095
+ if (!check.includes(v)) fail2(check.map(show).join(" | "));
4096
+ } else if (check === "boolean" || check === "string") {
4097
+ if (typeof v !== check) fail2(`a ${check}`);
4098
+ } else if (check === "number") {
4099
+ if (typeof v !== "number" || !(v >= 0)) fail2("a number of 0 or more");
4100
+ } else if (check === "formats") {
4101
+ if (v !== "all" && !(Array.isArray(v) && v.every((f) => typeof f === "string"))) fail2(`"all" or a list of format names`);
4102
+ } else {
4103
+ checkObject(v, check, path, where);
4104
+ }
4105
+ }
4106
+ function checkObject(o, spec, path, where) {
4107
+ if (!isObject2(o)) throw new Error(`Schema rules${where}: ${path || "the rules"} is ${show(o)}, expected an object`);
4108
+ for (const [key, value] of Object.entries(o)) {
4109
+ const at = path ? `${path}.${key}` : key;
4110
+ const check = spec[key];
4111
+ if (!check) throw new Error(`Schema rules${where}: unknown key "${at}" (known: ${Object.keys(spec).join(", ")})`);
4112
+ if (value !== void 0) checkValue(value, check, at, where);
4113
+ }
4114
+ }
4115
+ var VALID = /* @__PURE__ */ new WeakSet();
4116
+ function validateModelSchema(schema, where) {
4117
+ if (isObject2(schema) && VALID.has(schema)) return;
4118
+ checkObject(schema, SCHEMA_SPEC, "", where ? ` of ${where}` : "");
4119
+ VALID.add(schema);
4120
+ }
4121
+ var BASES = /* @__PURE__ */ new Map();
4122
+ function registerSchemaBase(name, schema) {
4123
+ validateModelSchema(schema, `base "${name}"`);
4124
+ const frozen = Object.freeze({ ...schema });
4125
+ VALID.add(frozen);
4126
+ BASES.set(name, frozen);
4127
+ }
4128
+ function getSchemaBase(name) {
4129
+ return BASES.get(name);
4130
+ }
4131
+ function schemaBases() {
4132
+ return [...BASES.keys()];
4133
+ }
4134
+ var both = (dialect, loose) => ({ tools: { dialect, loose }, output: { dialect, loose } });
4135
+ registerSchemaBase("lenient", both("lenient", "lenient"));
4136
+ registerSchemaBase("openai", both("openai-strict", "openai"));
4137
+ registerSchemaBase("openai-finetuned", { base: "openai", ...both("openai-finetuned-strict", "openai") });
4138
+ registerSchemaBase("anthropic", { tools: { dialect: "anthropic-strict", loose: "anthropic" }, output: { dialect: "anthropic-strict-output", loose: "anthropic" } });
4139
+ registerSchemaBase("google", both("google-strict", "google"));
4140
+ registerSchemaBase("google-openapi", both("google-openapi", "google"));
4141
+ registerSchemaBase("xai", { tools: { strict: true, dialect: "xai-strict", loose: "xai" }, output: { dialect: "xai-strict", loose: "xai" } });
4142
+ registerSchemaBase("ollama", both("ollama", "ollama"));
4143
+ function shallow(a, b) {
4144
+ return a || b ? { ...a, ...b } : void 0;
4145
+ }
4146
+ function mergeDialect(a, b) {
4147
+ if (!a) return b;
4148
+ if (!b) return a;
4149
+ const rules = shallow(a.rules, b.rules);
4150
+ const limits = shallow(a.limits, b.limits);
4151
+ const constraints = shallow(a.constraints, b.constraints);
4152
+ return {
4153
+ ...a,
4154
+ ...b,
4155
+ ...rules ? { rules } : {},
4156
+ ...limits ? { limits } : {},
4157
+ ...constraints ? { constraints } : {}
4158
+ };
4159
+ }
4160
+ function mergeSide(a, b) {
4161
+ const side = mergeDialect(a, b);
4162
+ if (!a || !b) return side;
4163
+ const looseRules = mergeDialect(a.looseRules, b.looseRules);
4164
+ return { ...side, ...looseRules ? { looseRules } : {} };
4165
+ }
4166
+ function mergeModelSchema(base, over) {
4167
+ if (!base) return over;
4168
+ if (!over) return base;
4169
+ const tools = mergeSide(base.tools, over.tools);
4170
+ const output = mergeSide(base.output, over.output);
4171
+ const limits = shallow(base.limits, over.limits);
4172
+ return {
4173
+ ...base,
4174
+ ...over,
4175
+ ...tools ? { tools } : {},
4176
+ ...output ? { output } : {},
4177
+ ...limits ? { limits } : {}
4178
+ };
4179
+ }
4180
+ function resolveModelSchema(schema) {
4181
+ const bases = [];
4182
+ let merged = {};
4183
+ let current = schema ?? { base: "lenient" };
4184
+ validateModelSchema(current);
4185
+ const layers = [];
4186
+ while (current) {
4187
+ layers.unshift(current);
4188
+ const name = current.base;
4189
+ if (!name) break;
4190
+ if (bases.includes(name)) throw new Error(`Schema base "${name}" includes itself`);
4191
+ bases.push(name);
4192
+ const next = BASES.get(name);
4193
+ if (!next) throw new Error(`Unknown schema base "${name}" (registered: ${[...BASES.keys()].join(", ")})`);
4194
+ current = next;
4195
+ }
4196
+ for (const layer of layers) merged = mergeModelSchema(merged, layer);
4197
+ const side = (s) => {
4198
+ const dialect = s?.dialect ?? s?.loose ?? "lenient";
4199
+ return { ...s, dialect, loose: s?.loose ?? dialect };
4200
+ };
4201
+ return {
4202
+ bases,
4203
+ tools: side(merged.tools),
4204
+ output: side(merged.output),
4205
+ ...merged.delivery ? { delivery: merged.delivery } : {},
4206
+ ...merged.limits ? { limits: merged.limits } : {}
4207
+ };
4208
+ }
4209
+ function profileById(id) {
4210
+ const p = getProfile(id);
4211
+ if (!p) throw new Error(`Unknown schema profile "${id}"`);
4212
+ return p;
4213
+ }
4214
+ var DERIVED = /* @__PURE__ */ new Map();
4215
+ function definedEntries(o) {
4216
+ const out = {};
4217
+ for (const [k, v] of Object.entries(o)) if (v !== void 0) out[k] = v;
4218
+ return Object.keys(out).length ? out : void 0;
4219
+ }
4220
+ function applySchemaRules(profile, side, request, loose) {
4221
+ const rules = {};
4222
+ for (const key2 of Object.keys(RULE_CHECKS)) {
4223
+ const v = side?.rules?.[key2];
4224
+ if (v !== void 0 && v !== profile[key2]) rules[key2] = v;
4225
+ }
4226
+ const l = side?.limits ?? {};
4227
+ const limits = {};
4228
+ for (const [key2, field] of Object.entries(LIMIT_FIELDS)) {
4229
+ const v = l[key2];
4230
+ if (field && v !== void 0) limits[field] = v;
4231
+ }
4232
+ const totals = {};
4233
+ const req = {};
4234
+ for (const [key2, [where, field]] of Object.entries(REQUEST_FIELDS)) {
4235
+ const v = request?.[key2];
4236
+ if (v !== void 0) (where === "totals" ? totals : req)[field] = v;
4237
+ }
4238
+ const constraints = side?.constraints ? definedEntries({ length: side.constraints.length, range: side.constraints.range, items: side.constraints.items, pattern: side.constraints.pattern }) : void 0;
4239
+ const has2 = (o) => Object.keys(o).length > 0;
4240
+ const patch = {
4241
+ ...has2(rules) ? { rules } : {},
4242
+ ...has2(limits) ? { limits } : {},
4243
+ ...has2(totals) || has2(req) ? { request: { ...req, ...has2(totals) ? { totals } : {} } } : {},
4244
+ ...l.enumSize !== void 0 ? { maxEnumValues: l.enumSize } : {},
4245
+ ...l.depth !== void 0 ? { maxDepth: l.depth } : {},
4246
+ ...constraints ? { constraints } : {},
4247
+ ...side?.formats ? { formats: side.formats === "all" ? "all" : [...side.formats].sort() } : {}
4248
+ };
4249
+ const sameLoose = !loose || loose === profile.loose;
4250
+ if (!has2(patch) && sameLoose) return profile;
4251
+ const key = `${profile.id}${has2(patch) ? JSON.stringify(patch) : ""}${sameLoose ? "" : `~${loose.id}`}`;
4252
+ let p = DERIVED.get(key);
4253
+ if (!p) {
4254
+ const r = patch.request;
4255
+ p = Object.freeze({
4256
+ ...profile,
4257
+ ...patch.rules,
4258
+ id: key,
4259
+ ...patch.limits ? { limits: Object.freeze({ ...profile.limits, ...patch.limits }) } : {},
4260
+ ...r ? {
4261
+ request: Object.freeze({
4262
+ ...profile.request,
4263
+ ...r,
4264
+ ...r.totals ? { totals: Object.freeze({ ...profile.request?.totals, ...r.totals }) } : {}
4265
+ })
4266
+ } : {},
4267
+ ...patch.maxEnumValues !== void 0 ? { maxEnumValues: patch.maxEnumValues } : {},
4268
+ ...patch.maxDepth !== void 0 ? { maxDepth: patch.maxDepth } : {},
4269
+ ...patch.constraints ? { constraints: Object.freeze({ ...profile.constraints, ...patch.constraints }) } : {},
4270
+ ...patch.formats ? { formats: patch.formats === "all" ? "all" : new Set(patch.formats) } : {},
4271
+ ...sameLoose ? {} : { loose }
4272
+ });
4273
+ DERIVED.set(key, p);
4274
+ }
4275
+ return p;
4276
+ }
4277
+ var dialectSet = (d) => ["rules", "limits", "constraints", "formats"].filter((k) => d[k] !== void 0);
4278
+ function sideProfiles(rules, kind2) {
4279
+ const side = rules[kind2];
4280
+ const tools = rules.limits?.tools;
4281
+ const looseBase = profileById(side.loose);
4282
+ const loose = applySchemaRules(looseBase, side.looseRules, tools !== void 0 ? { tools } : void 0);
4283
+ const strictBase = profileById(side.dialect);
4284
+ const customised = !!side.looseRules && applySchemaRules(looseBase, side.looseRules, void 0) !== looseBase;
4285
+ const fallback = strictBase.loose || customised ? loose : void 0;
4286
+ if (!strictBase.strict) {
4287
+ const set = dialectSet(side);
4288
+ if (set.length) {
4289
+ throw new Error(`Schema rules: ${kind2}.${set.join(`, ${kind2}.`)} set, but its dialect "${side.dialect}" is not strict, so ${kind2} are never strict; say them in ${kind2}.looseRules`);
4290
+ }
4291
+ return { strict: loose, loose };
4292
+ }
4293
+ return { strict: applySchemaRules(strictBase, side, rules.limits, fallback), loose };
4294
+ }
4295
+ function rulesFamily(rules) {
4296
+ return getProfile(rules.tools.dialect)?.family ?? LENIENT.family;
4297
+ }
4298
+
3996
4299
  // src/template.ts
3997
4300
  var SCHEMA_DATA_KEY = "aeyeSchema";
3998
4301
  var Safe = class {
@@ -4313,9 +4616,9 @@ function climb(base, first, broken, wantNull, attempt) {
4313
4616
  const top = Math.min(m.depth - 1, (base.maxDepth ?? Infinity) - 1);
4314
4617
  if (top < 1) return void 0;
4315
4618
  const lastCap = caps.length ? caps[caps.length - 1] : void 0;
4316
- const shallow = withCap(lastCap, 1);
4317
- if (shallow.problems.length) return void 0;
4318
- let lo = 1, hi = top, best = shallow;
4619
+ const shallow2 = withCap(lastCap, 1);
4620
+ if (shallow2.problems.length) return void 0;
4621
+ let lo = 1, hi = top, best = shallow2;
4319
4622
  while (lo < hi) {
4320
4623
  const mid = lo + hi + 1 >> 1;
4321
4624
  const t = withCap(lastCap, mid);
@@ -4453,7 +4756,7 @@ function planRequest(target, items, opts = {}) {
4453
4756
  const broken = brokenLimits(m, base.limits);
4454
4757
  brokenLimits(m, totals, broken);
4455
4758
  brokenLimits(addMeasures(used, m), totals, broken);
4456
- const wantNull = !!totals?.maxOptional && used.optional + m.optional > totals.maxOptional;
4759
+ const wantNull = !!totals?.maxOptional && used.optional + m.optional > totals.maxOptional || broken.has("maxObjectOptional");
4457
4760
  chosen = climb(base, first, broken, wantNull, attempt);
4458
4761
  } else reasons.push(...firstProblems);
4459
4762
  if (chosen) {
@@ -4505,27 +4808,25 @@ function planRequest(target, items, opts = {}) {
4505
4808
  }
4506
4809
 
4507
4810
  // src/model.ts
4508
- var PROVIDER_FAMILY = {
4509
- openai: "openai",
4510
- anthropic: "anthropic",
4511
- google: "google",
4512
- gemini: "google",
4513
- xai: "xai",
4514
- "x-ai": "xai",
4515
- ollama: "ollama"
4516
- };
4517
- function familyOf(model) {
4518
- if (model.strictFormat === "none") return model.provider === "ollama" ? "ollama" : "lenient";
4519
- if (model.strictFormat) return PROVIDER_FAMILY[model.strictFormat] ?? model.strictFormat;
4520
- const id = model.id.replace(/^~/, "");
4521
- if (model.provider === "aws") {
4522
- return /(^|\.)anthropic\.claude/.test(id) ? "anthropic" : "lenient";
4523
- }
4524
- const direct = PROVIDER_FAMILY[model.provider];
4525
- if (direct) return direct;
4526
- if (/^(openai\/gpt-oss|google\/gemma)/.test(id)) return "lenient";
4527
- const slash = id.indexOf("/");
4528
- return slash > 0 ? PROVIDER_FAMILY[id.slice(0, slash)] ?? "lenient" : "lenient";
4811
+ function modelSchemaOf(model, defaults) {
4812
+ if (model.schema) return model.schema;
4813
+ const format = model.strictFormat;
4814
+ if (format === "none") return { base: "lenient" };
4815
+ if (format) {
4816
+ if (getSchemaBase(format)) return { base: format };
4817
+ const strictProfile = familyProfile(format, true);
4818
+ const strict = strictProfile.id;
4819
+ const loose = strictProfile.loose?.id ?? familyProfile(format, false).id;
4820
+ return { tools: { dialect: strict, loose }, output: { dialect: strict, loose } };
4821
+ }
4822
+ return defaults ?? { base: "lenient" };
4823
+ }
4824
+ function rulesFor(model, opts = {}) {
4825
+ const rules = resolveModelSchema(modelSchemaOf(model, opts.defaults));
4826
+ return opts.speaks && !opts.speaks.has(rulesFamily(rules)) ? resolveModelSchema({ base: "lenient" }) : rules;
4827
+ }
4828
+ function familyOf(model, opts = {}) {
4829
+ return rulesFamily(rulesFor(model, opts));
4529
4830
  }
4530
4831
  function has(caps, cap) {
4531
4832
  if (!caps) return false;
@@ -4554,16 +4855,13 @@ var ModelProfile = class _ModelProfile {
4554
4855
  }
4555
4856
  };
4556
4857
  function profileFor(model, opts = {}) {
4557
- let family = familyOf(model);
4558
- if (opts.speaks && !opts.speaks.has(family)) family = "lenient";
4559
- const toolsStrict = family === "xai" || has(model.capabilities, "toolsStrict");
4560
- const structured = has(model.capabilities, "structured");
4561
- const finetuned = family === "openai" && /(^|\/)ft:/.test(model.id);
4562
- const pick = (strict) => finetuned && strict ? OPENAI_FINETUNED_STRICT : familyProfile(family, strict);
4563
- const tool = pick(toolsStrict);
4564
- const output = pick(structured);
4565
- const delivery = !structured && (model.provider === "aws" || output.alwaysStrictOutput || familyProfile(family, true).alwaysStrictOutput || !has(model.capabilities, "json")) ? "prompt" : "structured";
4566
- return new ModelProfile(tool, output, delivery);
4858
+ const rules = rulesFor(model, opts);
4859
+ const tools = sideProfiles(rules, "tools");
4860
+ const output = sideProfiles(rules, "output");
4861
+ const toolsStrict = rules.tools.strict ?? has(model.capabilities, "toolsStrict");
4862
+ const outputStrict = rules.output.strict ?? has(model.capabilities, "structured");
4863
+ const delivery = outputStrict ? "structured" : rules.delivery ?? (opts.nonStrictOutput === false || output.strict.alwaysStrictOutput || !has(model.capabilities, "json") ? "prompt" : "structured");
4864
+ return new ModelProfile(toolsStrict ? tools.strict : tools.loose, outputStrict ? output.strict : output.loose, delivery);
4567
4865
  }
4568
4866
 
4569
4867
  // src/deferred.ts
@@ -4886,6 +5184,7 @@ function ginNamedTypes(registry) {
4886
5184
  export {
4887
5185
  ANTHROPIC_NON_STRICT,
4888
5186
  ANTHROPIC_STRICT,
5187
+ ANTHROPIC_STRICT_OUTPUT,
4889
5188
  AnyType,
4890
5189
  ArrayType,
4891
5190
  BooleanType,
@@ -4950,6 +5249,7 @@ export {
4950
5249
  ZERO_MEASURE,
4951
5250
  a_exports as a,
4952
5251
  addMeasures,
5252
+ applySchemaRules,
4953
5253
  brokenLimits,
4954
5254
  deferEncode,
4955
5255
  deferSchema,
@@ -4966,6 +5266,7 @@ export {
4966
5266
  fromGin,
4967
5267
  fromJSONSchema,
4968
5268
  getProfile,
5269
+ getSchemaBase,
4969
5270
  ginNamedTypes,
4970
5271
  hasDeferred,
4971
5272
  isBasicPattern,
@@ -4973,7 +5274,9 @@ export {
4973
5274
  issueKind,
4974
5275
  measureJson,
4975
5276
  mergeErrorFormats,
5277
+ mergeModelSchema,
4976
5278
  modelPath,
5279
+ modelSchemaOf,
4977
5280
  nearest,
4978
5281
  newStats,
4979
5282
  overLimits,
@@ -4983,14 +5286,21 @@ export {
4983
5286
  rankNear,
4984
5287
  readJsonText,
4985
5288
  registerProfile,
5289
+ registerSchemaBase,
4986
5290
  registerSchemaHelpers,
5291
+ resolveModelSchema,
5292
+ rulesFamily,
5293
+ rulesFor,
5294
+ schemaBases,
4987
5295
  schemaData,
4988
5296
  schemaHelpers,
4989
5297
  shortType,
5298
+ sideProfiles,
4990
5299
  staticBundle,
4991
5300
  strictPriority,
4992
5301
  suggestionBudget,
4993
5302
  suggestionFor,
5303
+ validateModelSchema,
4994
5304
  variant,
4995
5305
  viewOf
4996
5306
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aeye/schema",
3
- "version": "0.10.2",
3
+ "version": "0.11.1",
4
4
  "description": "@aeye/schema - LLM-first schema builder: named and dynamic types, per-model rendering, request-wide budgets, copy-light decoding",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -57,8 +57,8 @@
57
57
  "author": "ClickerMonkey",
58
58
  "dependencies": {},
59
59
  "devDependencies": {
60
- "@aeye/gin": "0.10.2",
61
- "@aeye/query": "0.10.2",
60
+ "@aeye/gin": "0.11.1",
61
+ "@aeye/query": "0.11.1",
62
62
  "expect-type": "^1.3.0",
63
63
  "handlebars": "^4.7.0",
64
64
  "tinybench": "^2.9.0",