gemi 0.225.0 → 0.225.2
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/dist/ai/Agent.d.ts +2 -0
- package/dist/ai/Agent.d.ts.map +1 -1
- package/dist/ai/index.js +2 -2
- package/dist/ai/index.js.map +1 -1
- package/dist/ai/providers/anthropicStream.d.ts +6 -0
- package/dist/ai/providers/anthropicStream.d.ts.map +1 -1
- package/dist/ai/providers/call.d.ts +15 -0
- package/dist/ai/providers/call.d.ts.map +1 -1
- package/dist/ai/providers/endpoints.d.ts +25 -0
- package/dist/ai/providers/endpoints.d.ts.map +1 -1
- package/dist/ai/providers/errors.d.ts +12 -0
- package/dist/ai/providers/errors.d.ts.map +1 -1
- package/dist/ai/providers/stream.d.ts +3 -0
- package/dist/ai/providers/stream.d.ts.map +1 -1
- package/dist/ai/testing/index.js +2 -2
- package/dist/ai/testing/index.js.map +2 -2
- package/dist/ai/types.d.ts +6 -0
- package/dist/ai/types.d.ts.map +1 -1
- package/dist/app/index.js +1 -1
- package/dist/bun/plugin.js +1 -1
- package/dist/bun/preload.js +1 -1
- package/dist/{chunk-p1ern8r4.js → chunk-1jyzg1ex.js} +3 -3
- package/dist/{chunk-p1ern8r4.js.map → chunk-1jyzg1ex.js.map} +1 -1
- package/dist/{chunk-97tj0d7v.js → chunk-21hhvphe.js} +2 -2
- package/dist/{chunk-97tj0d7v.js.map → chunk-21hhvphe.js.map} +1 -1
- package/dist/{chunk-zmt5kdpb.js → chunk-2450kxym.js} +2 -2
- package/dist/{chunk-zmt5kdpb.js.map → chunk-2450kxym.js.map} +1 -1
- package/dist/{chunk-vmmjq9fn.js → chunk-3dkaz47e.js} +2 -2
- package/dist/{chunk-vmmjq9fn.js.map → chunk-3dkaz47e.js.map} +1 -1
- package/dist/{chunk-bqm79ar0.js → chunk-3e55yw7v.js} +3 -3
- package/dist/{chunk-bqm79ar0.js.map → chunk-3e55yw7v.js.map} +1 -1
- package/dist/chunk-3vgjrn2r.js +12 -0
- package/dist/{chunk-dpmvvwts.js.map → chunk-3vgjrn2r.js.map} +6 -6
- package/dist/{chunk-snmyjq03.js → chunk-40yd1n60.js} +2 -2
- package/dist/{chunk-snmyjq03.js.map → chunk-40yd1n60.js.map} +1 -1
- package/dist/{chunk-6ttbhhnn.js → chunk-421hq1rw.js} +1 -1
- package/dist/{chunk-k16phdjv.js → chunk-4qyp7w89.js} +1 -1
- package/dist/{chunk-j9abwrkv.js → chunk-5kgqfczk.js} +3 -3
- package/dist/{chunk-j9abwrkv.js.map → chunk-5kgqfczk.js.map} +1 -1
- package/dist/{chunk-wy82t7mz.js → chunk-64yf0shq.js} +2 -2
- package/dist/{chunk-wy82t7mz.js.map → chunk-64yf0shq.js.map} +1 -1
- package/dist/{chunk-8a3fqcf0.js → chunk-6et7jwp8.js} +2 -2
- package/dist/{chunk-8a3fqcf0.js.map → chunk-6et7jwp8.js.map} +1 -1
- package/dist/{chunk-0k2r6bep.js → chunk-6h1hjzj7.js} +2 -2
- package/dist/{chunk-0k2r6bep.js.map → chunk-6h1hjzj7.js.map} +1 -1
- package/dist/{chunk-nzd7z4s6.js → chunk-70jhw0ft.js} +1 -1
- package/dist/{chunk-b87wvmsz.js → chunk-7901z26g.js} +2 -2
- package/dist/{chunk-b87wvmsz.js.map → chunk-7901z26g.js.map} +1 -1
- package/dist/{chunk-sfrjkysf.js → chunk-7d1f5gyv.js} +2 -2
- package/dist/{chunk-sfrjkysf.js.map → chunk-7d1f5gyv.js.map} +1 -1
- package/dist/{chunk-50791bmz.js → chunk-7mvfk0q9.js} +2 -2
- package/dist/{chunk-50791bmz.js.map → chunk-7mvfk0q9.js.map} +1 -1
- package/dist/{chunk-4wh4dfgf.js → chunk-81y96dax.js} +1 -1
- package/dist/{chunk-2vv04thj.js → chunk-8pdke84p.js} +2 -2
- package/dist/{chunk-2vv04thj.js.map → chunk-8pdke84p.js.map} +1 -1
- package/dist/{chunk-h9nt7hm6.js → chunk-8szsd6vy.js} +2 -2
- package/dist/{chunk-h9nt7hm6.js.map → chunk-8szsd6vy.js.map} +1 -1
- package/dist/{chunk-t8ygf6zj.js → chunk-9xxgj5zk.js} +3 -3
- package/dist/{chunk-t8ygf6zj.js.map → chunk-9xxgj5zk.js.map} +1 -1
- package/dist/{chunk-8pz8yzax.js → chunk-9znec0we.js} +4 -4
- package/dist/{chunk-8pz8yzax.js.map → chunk-9znec0we.js.map} +3 -3
- package/dist/{chunk-3dkv4989.js → chunk-ads3c8m0.js} +2 -2
- package/dist/{chunk-3dkv4989.js.map → chunk-ads3c8m0.js.map} +1 -1
- package/dist/{chunk-fqhkkpq3.js → chunk-awryyak8.js} +2 -2
- package/dist/{chunk-fqhkkpq3.js.map → chunk-awryyak8.js.map} +1 -1
- package/dist/{chunk-5jvbr0e5.js → chunk-bch7xbsr.js} +2 -2
- package/dist/{chunk-5jvbr0e5.js.map → chunk-bch7xbsr.js.map} +1 -1
- package/dist/{chunk-3y91vexx.js → chunk-bwjaq694.js} +3 -3
- package/dist/{chunk-3y91vexx.js.map → chunk-bwjaq694.js.map} +1 -1
- package/dist/chunk-bzrta2sw.js +10 -0
- package/dist/{chunk-qs2xvc8g.js.map → chunk-bzrta2sw.js.map} +9 -4
- package/dist/{chunk-4v5nwqw6.js → chunk-crk4ddqa.js} +3 -3
- package/dist/{chunk-4v5nwqw6.js.map → chunk-crk4ddqa.js.map} +1 -1
- package/dist/{chunk-37209psn.js → chunk-d3a29hyg.js} +3 -3
- package/dist/{chunk-37209psn.js.map → chunk-d3a29hyg.js.map} +1 -1
- package/dist/{chunk-knfvx96p.js → chunk-ehr5pnm8.js} +2 -2
- package/dist/{chunk-knfvx96p.js.map → chunk-ehr5pnm8.js.map} +1 -1
- package/dist/{chunk-yj7pbbnm.js → chunk-enqrjcdk.js} +2 -2
- package/dist/{chunk-yj7pbbnm.js.map → chunk-enqrjcdk.js.map} +1 -1
- package/dist/{chunk-adw279ge.js → chunk-eydww2nn.js} +2 -2
- package/dist/{chunk-adw279ge.js.map → chunk-eydww2nn.js.map} +1 -1
- package/dist/{chunk-fxa72ppw.js → chunk-fjnhqbtx.js} +1 -1
- package/dist/{chunk-726gd69z.js → chunk-ftc9292d.js} +2 -2
- package/dist/{chunk-726gd69z.js.map → chunk-ftc9292d.js.map} +1 -1
- package/dist/{chunk-pxjptskr.js → chunk-gj0bwm41.js} +2 -2
- package/dist/{chunk-pxjptskr.js.map → chunk-gj0bwm41.js.map} +1 -1
- package/dist/{chunk-5mrtgr7q.js → chunk-hvyzp9p6.js} +2 -2
- package/dist/{chunk-5mrtgr7q.js.map → chunk-hvyzp9p6.js.map} +1 -1
- package/dist/{chunk-8vpe54ek.js → chunk-j0rhz378.js} +2 -2
- package/dist/{chunk-8vpe54ek.js.map → chunk-j0rhz378.js.map} +1 -1
- package/dist/{chunk-swmf6w3z.js → chunk-j13jmjkr.js} +2 -2
- package/dist/{chunk-swmf6w3z.js.map → chunk-j13jmjkr.js.map} +1 -1
- package/dist/{chunk-anc5v266.js → chunk-j7pzdvxr.js} +2 -2
- package/dist/{chunk-anc5v266.js.map → chunk-j7pzdvxr.js.map} +1 -1
- package/dist/{chunk-h1wmpa03.js → chunk-ja3n968b.js} +2 -2
- package/dist/{chunk-h1wmpa03.js.map → chunk-ja3n968b.js.map} +1 -1
- package/dist/{chunk-vcw98sp6.js → chunk-k657v3ed.js} +3 -3
- package/dist/{chunk-vcw98sp6.js.map → chunk-k657v3ed.js.map} +1 -1
- package/dist/{chunk-t586p2g2.js → chunk-kxc2mzzr.js} +2 -2
- package/dist/{chunk-t586p2g2.js.map → chunk-kxc2mzzr.js.map} +1 -1
- package/dist/{chunk-nqqyn3cx.js → chunk-kzz2nfzf.js} +2 -2
- package/dist/{chunk-nqqyn3cx.js.map → chunk-kzz2nfzf.js.map} +1 -1
- package/dist/{chunk-k6af7qek.js → chunk-m7v4erdg.js} +2 -2
- package/dist/{chunk-k6af7qek.js.map → chunk-m7v4erdg.js.map} +1 -1
- package/dist/{chunk-p4v71qfx.js → chunk-mca5s0bf.js} +3 -3
- package/dist/{chunk-p4v71qfx.js.map → chunk-mca5s0bf.js.map} +1 -1
- package/dist/{chunk-79wjkaa4.js → chunk-me70vszk.js} +2 -2
- package/dist/{chunk-79wjkaa4.js.map → chunk-me70vszk.js.map} +1 -1
- package/dist/{chunk-qy0k2s5f.js → chunk-mvb8m247.js} +2 -2
- package/dist/{chunk-qy0k2s5f.js.map → chunk-mvb8m247.js.map} +1 -1
- package/dist/{chunk-0av1gyns.js → chunk-mvp6fkg2.js} +3 -3
- package/dist/{chunk-0av1gyns.js.map → chunk-mvp6fkg2.js.map} +1 -1
- package/dist/{chunk-e4zxacxd.js → chunk-n2c748aw.js} +2 -2
- package/dist/{chunk-e4zxacxd.js.map → chunk-n2c748aw.js.map} +1 -1
- package/dist/{chunk-nqgeny8m.js → chunk-ng6pbd7f.js} +4 -4
- package/dist/{chunk-nqgeny8m.js.map → chunk-ng6pbd7f.js.map} +1 -1
- package/dist/{chunk-7xe5vd4w.js → chunk-pdymdjpq.js} +2 -2
- package/dist/{chunk-7xe5vd4w.js.map → chunk-pdymdjpq.js.map} +1 -1
- package/dist/{chunk-dj0nvj66.js → chunk-pn3egz75.js} +1 -1
- package/dist/chunk-qjn6a2ed.js +5 -0
- package/dist/{chunk-89egc0h3.js.map → chunk-qjn6a2ed.js.map} +1 -1
- package/dist/chunk-qrc2r0ce.js +5 -0
- package/dist/{chunk-kp7wcpx7.js.map → chunk-qrc2r0ce.js.map} +3 -3
- package/dist/{chunk-gyszenps.js → chunk-qtz4g4kv.js} +3 -3
- package/dist/{chunk-gyszenps.js.map → chunk-qtz4g4kv.js.map} +1 -1
- package/dist/{chunk-55btq9c7.js → chunk-qx9p15em.js} +2 -2
- package/dist/{chunk-55btq9c7.js.map → chunk-qx9p15em.js.map} +1 -1
- package/dist/{chunk-fp9yn4k8.js → chunk-rq0dpv7r.js} +2 -2
- package/dist/{chunk-fp9yn4k8.js.map → chunk-rq0dpv7r.js.map} +1 -1
- package/dist/{chunk-ps5rpy9n.js → chunk-ryh6rfts.js} +2 -2
- package/dist/{chunk-ps5rpy9n.js.map → chunk-ryh6rfts.js.map} +1 -1
- package/dist/{chunk-7etvj6w2.js → chunk-svrvb47q.js} +2 -2
- package/dist/{chunk-7etvj6w2.js.map → chunk-svrvb47q.js.map} +1 -1
- package/dist/{chunk-mdg8g8h2.js → chunk-t5aft2ra.js} +4 -4
- package/dist/{chunk-mdg8g8h2.js.map → chunk-t5aft2ra.js.map} +2 -2
- package/dist/{chunk-ncnygh0s.js → chunk-t9fh0ptd.js} +2 -2
- package/dist/{chunk-ncnygh0s.js.map → chunk-t9fh0ptd.js.map} +1 -1
- package/dist/{chunk-jf2dr481.js → chunk-tbvrv4h2.js} +2 -2
- package/dist/{chunk-jf2dr481.js.map → chunk-tbvrv4h2.js.map} +1 -1
- package/dist/{chunk-6r7956dh.js → chunk-tgy75n24.js} +2 -2
- package/dist/{chunk-6r7956dh.js.map → chunk-tgy75n24.js.map} +1 -1
- package/dist/{chunk-pxjkxhf9.js → chunk-tp1gxcke.js} +3 -3
- package/dist/{chunk-pxjkxhf9.js.map → chunk-tp1gxcke.js.map} +1 -1
- package/dist/{chunk-dgy6pf2h.js → chunk-v0fqq5z7.js} +2 -2
- package/dist/{chunk-dgy6pf2h.js.map → chunk-v0fqq5z7.js.map} +1 -1
- package/dist/{chunk-cf8bztwq.js → chunk-v4ecxbgd.js} +2 -2
- package/dist/{chunk-cf8bztwq.js.map → chunk-v4ecxbgd.js.map} +1 -1
- package/dist/{chunk-rat2827k.js → chunk-v5sg62xm.js} +2 -2
- package/dist/{chunk-rat2827k.js.map → chunk-v5sg62xm.js.map} +1 -1
- package/dist/chunk-v979k0be.js +5 -0
- package/dist/{chunk-zcmz311y.js.map → chunk-v979k0be.js.map} +3 -8
- package/dist/{chunk-rdfatx17.js → chunk-w2yd62vs.js} +2 -2
- package/dist/{chunk-rdfatx17.js.map → chunk-w2yd62vs.js.map} +1 -1
- package/dist/{chunk-rw45xz3f.js → chunk-we65r9fh.js} +3 -3
- package/dist/{chunk-rw45xz3f.js.map → chunk-we65r9fh.js.map} +1 -1
- package/dist/{chunk-2y0nr525.js → chunk-wnmpwb4s.js} +3 -3
- package/dist/{chunk-2y0nr525.js.map → chunk-wnmpwb4s.js.map} +1 -1
- package/dist/{chunk-s3gn68dy.js → chunk-wzr8tzv0.js} +2 -2
- package/dist/{chunk-s3gn68dy.js.map → chunk-wzr8tzv0.js.map} +1 -1
- package/dist/{chunk-wt4ekzp9.js → chunk-x47kwv2x.js} +2 -2
- package/dist/{chunk-wt4ekzp9.js.map → chunk-x47kwv2x.js.map} +1 -1
- package/dist/{chunk-8ddt5fa2.js → chunk-x93dpv6e.js} +2 -2
- package/dist/{chunk-8ddt5fa2.js.map → chunk-x93dpv6e.js.map} +1 -1
- package/dist/{chunk-tac25cnj.js → chunk-xpzdwhjg.js} +3 -3
- package/dist/{chunk-tac25cnj.js.map → chunk-xpzdwhjg.js.map} +1 -1
- package/dist/{chunk-ax042w6k.js → chunk-z4fhhtjh.js} +2 -2
- package/dist/{chunk-ax042w6k.js.map → chunk-z4fhhtjh.js.map} +1 -1
- package/dist/{chunk-jychsmhf.js → chunk-z5am43fj.js} +2 -2
- package/dist/{chunk-jychsmhf.js.map → chunk-z5am43fj.js.map} +1 -1
- package/dist/{chunk-5h2xj3cx.js → chunk-z6x78wb3.js} +2 -2
- package/dist/{chunk-5h2xj3cx.js.map → chunk-z6x78wb3.js.map} +1 -1
- package/dist/{chunk-q5xcjm5z.js → chunk-zvg2qsa5.js} +2 -2
- package/dist/{chunk-q5xcjm5z.js.map → chunk-zvg2qsa5.js.map} +1 -1
- package/dist/{chunk-mt82209n.js → chunk-zy56kaws.js} +2 -2
- package/dist/{chunk-mt82209n.js.map → chunk-zy56kaws.js.map} +1 -1
- package/dist/config/index.js +1 -1
- package/dist/console/run.js +2 -2
- package/dist/console/run.js.map +1 -1
- package/dist/container/index.js +2 -2
- package/dist/container/index.js.map +1 -1
- package/dist/database/index.js +2 -2
- package/dist/database/index.js.map +1 -1
- package/dist/email/Email.d.ts.map +1 -1
- package/dist/email/index.js +3 -4
- package/dist/email/index.js.map +4 -15
- package/dist/facades/index.js +2 -2
- package/dist/facades/index.js.map +1 -1
- package/dist/foundation/index.js +2 -2
- package/dist/foundation/index.js.map +1 -1
- package/dist/http/index.js +2 -2
- package/dist/http/index.js.map +1 -1
- package/dist/i18n/dictionaryRuntime.js +2 -2
- package/dist/i18n/dictionaryRuntime.js.map +1 -1
- package/dist/i18n/index.js +2 -2
- package/dist/i18n/index.js.map +1 -1
- package/dist/kernel/index.js +2 -2
- package/dist/kernel/index.js.map +1 -1
- package/dist/orm/index.js +2 -2
- package/dist/orm/index.js.map +1 -1
- package/dist/probe/index.js +2 -2
- package/dist/probe/index.js.map +1 -1
- package/dist/server/index.js +2 -2
- package/dist/server/index.js.map +1 -1
- package/dist/services/index.js +2 -2
- package/dist/services/index.js.map +2 -2
- package/dist/services/queue/work.js +2 -2
- package/dist/services/queue/work.js.map +1 -1
- package/dist/stats/route-table.js +1 -1
- package/dist/support/index.js +2 -2
- package/dist/support/index.js.map +1 -1
- package/dist/vitest/index.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-89egc0h3.js +0 -5
- package/dist/chunk-dpmvvwts.js +0 -11
- package/dist/chunk-kp7wcpx7.js +0 -5
- package/dist/chunk-qs2xvc8g.js +0 -7
- package/dist/chunk-zcmz311y.js +0 -8
- /package/dist/{chunk-6ttbhhnn.js.map → chunk-421hq1rw.js.map} +0 -0
- /package/dist/{chunk-k16phdjv.js.map → chunk-4qyp7w89.js.map} +0 -0
- /package/dist/{chunk-nzd7z4s6.js.map → chunk-70jhw0ft.js.map} +0 -0
- /package/dist/{chunk-4wh4dfgf.js.map → chunk-81y96dax.js.map} +0 -0
- /package/dist/{chunk-fxa72ppw.js.map → chunk-fjnhqbtx.js.map} +0 -0
- /package/dist/{chunk-dj0nvj66.js.map → chunk-pn3egz75.js.map} +0 -0
|
@@ -1,10 +1,15 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
|
-
"sources": ["../ai/Schema.ts"],
|
|
3
|
+
"sources": ["../ai/Schema.ts", "../facades/Facade.ts", "../services/logging/config.ts", "../services/logging/LogManager.ts", "../services/logging/consoleSink.ts", "../facades/Log.ts"],
|
|
4
4
|
"sourcesContent": [
|
|
5
|
-
"/**\n * The schema layer for tool inputs, tool outputs and structured final answers.\n *\n * Two things have to come out of one declaration: a TypeScript type, so\n * `execute(input)` is typed at the call site and the result is typed in the\n * browser, and a JSON Schema, because that is what the model is actually shown.\n * A phantom `Schema<T>` gives the first and nothing of the second, and a\n * hand-written JSON Schema next to a hand-written type gives both and lets them\n * drift. So the builder below is the single source, and `Infer` reads the type\n * back off it.\n *\n * Everything here is deliberately narrower than JSON Schema. OpenAI's strict\n * structured output only accepts a subset — every property listed in\n * `required`, `additionalProperties: false` on every object, no patterns, no\n * `oneOf` at the root — and a builder that cannot express the rejected parts is\n * better than one that lets you write a schema the API refuses at runtime.\n *\n * `json()` is the one deliberate hole in that, for the formats strict mode\n * cannot describe at all: a record with arbitrary keys, a mixed-type tuple. It\n * does not widen the subset — it turns strict mode off for the schema containing\n * it, which `supportsStrict` reads back off the tree so that no caller has to\n * remember to.\n *\n * A document that nests into itself is NOT one of those: strict mode accepts\n * `$defs` + `$ref`, and `recursive()` emits exactly that (#745).\n */\n\nexport type JSONSchema = {\n type?: string | string[];\n description?: string;\n enum?: readonly (string | number)[];\n const?: string | number | boolean;\n properties?: Record<string, JSONSchema>;\n required?: readonly string[];\n additionalProperties?: false;\n items?: JSONSchema;\n anyOf?: readonly JSONSchema[];\n /**\n * `#/$defs/<name>`, pointing at an entry of the root's `$defs`. Emitted by\n * `s.recursive` and never with a sibling keyword: OpenAI's strict mode\n * refuses `{ $ref, description }`, so a described or nullable reference is\n * wrapped in an `anyOf` instead.\n */\n $ref?: string;\n /** Only ever on the root: every `s.recursive` the schema reaches, by name. */\n $defs?: Record<string, JSONSchema>;\n};\n\n/**\n * Any value JSON can carry. The default output type of `json()`, and the\n * annotation an app reaches for when it hands one of those values on.\n */\nexport type JsonValue =\n | string\n | number\n | boolean\n | null\n | JsonValue[]\n | { [key: string]: JsonValue };\n\ndeclare const OUTPUT: unique symbol;\ndeclare const OPTIONAL: unique symbol;\n\n/**\n * `T` is carried in a phantom property rather than a real one: it exists only\n * for inference, and a real field would show up on the object the app writes.\n */\nexport interface Schema<T> {\n readonly [OUTPUT]: T;\n /** The JSON Schema handed to the provider. */\n toJSONSchema(): JSONSchema;\n /**\n * Parses a value coming back from the model. Tool arguments arrive as a JSON\n * string the model generated, so they are untrusted in exactly the way a\n * request body is: shape-checked before `execute` ever sees them.\n */\n parse(value: unknown): T;\n safeParse(value: unknown): { ok: true; value: T } | { ok: false; errors: string[] };\n}\n\n/**\n * A schema whose key may be left out of the object containing it.\n *\n * Marked with a property rather than detected from the output type, because\n * `undefined extends T` — the obvious test — is true of *everything* when\n * `strictNullChecks` is off, which is how this package and plenty of apps\n * compile. That version made every field of every tool optional, and did it\n * quietly: the JSON Schema was still right, so only the TypeScript types lied.\n */\nexport interface OptionalSchema<T> extends Schema<T | undefined> {\n readonly [OPTIONAL]: true;\n}\n\nexport type AnySchema = Schema<any>;\n\nexport type Infer<S> = S extends Schema<infer T> ? T : never;\n\n/**\n * Collapses a type into one flat object.\n *\n * `ShapeOutput` builds its result as an intersection of two mapped types, one\n * required and one optional, and that intersection is what every hover, every\n * error message and every type assertion would otherwise show. The difference\n * is between an app reading `{ command: string; cwd?: string }` and reading two\n * mapped types joined by an ampersand.\n *\n * It also drops `readonly`, which the mapped types copy from the shape literal\n * — `s.object({ ... })` infers that literal as `const` to keep the keys, and a\n * tool has no reason to receive an immutable input because of how its schema\n * was written down.\n */\ntype Flatten<T> = { -readonly [K in keyof T]: T[K] };\n\ntype ShapeOutput<S extends Record<string, AnySchema>> = Flatten<\n {\n [K in keyof S as S[K] extends OptionalSchema<any> ? never : K]: Infer<S[K]>;\n } & {\n [K in keyof S as S[K] extends OptionalSchema<any> ? K : never]?: Infer<S[K]>;\n }\n>;\n\ninterface SchemaBuilder<T> extends Schema<T> {\n /**\n * The description is not documentation — it is the only prose the model gets\n * about a field, and it is the difference between a tool that is called\n * correctly and one that is not.\n */\n describe(description: string): this;\n /**\n * Strict mode has no notion of an omitted key: every property must appear in\n * `required`. So `optional()` emits a nullable union and the model is told to\n * send `null`, while the TypeScript type says `| undefined` and the parsed\n * value drops the key. The asymmetry is the point — it is what lets an app\n * write ordinary optional fields against an API that forbids them.\n */\n optional(): OptionalSchemaBuilder<T>;\n nullable(): SchemaBuilder<T | null>;\n /**\n * `safeParse` with the failures as structured issues rather than sentences:\n * each one names the path it is about, a JSON Schema keyword as its `code`\n * and the keyword's argument in `params`. For an app that validates a value\n * against a schema itself — a form, a stored record — and wants to word or\n * group the problems per field. All failures are reported, not the first.\n */\n validate(value: unknown): { ok: true; value: T } | { ok: false; issues: SchemaIssue[] };\n}\n\n/**\n * One reason a value failed `validate`.\n *\n * `code` is the JSON Schema keyword the value broke — the same names Ajv puts\n * on its `keyword` — so a mapping written against one reads the other:\n *\n * - `required`: the key is missing (`path` ends in it).\n * - `type`: the wrong kind of value, an integer that isn't whole, or a value\n * that isn't JSON at all.\n * - `const`, `enum`: a literal or a choice that didn't match (`params.allowedValues`).\n * - `minLength`, `maxLength`, `minimum`, `maximum`, `exclusiveMinimum`,\n * `exclusiveMaximum`, `minItems`, `maxItems`: `params.limit` is the bound.\n * - `format`: `params.format` names the format the string failed.\n * - `anyOf`: no union member matched; `message` names the closest one's problems.\n * - `additionalProperties`: a key the object doesn't declare, reported only by\n * a schema built with `s.fromJSONSchema(schema, { unknownKeys: \"error\" })`.\n * `path` ends in the key (Ajv's `instancePath` stops at the object), and\n * `params.additionalProperty` is the key, as in Ajv.\n *\n * `message` is the sentence `safeParse` reports for it, without the path.\n */\nexport type SchemaIssueCode =\n | \"required\"\n | \"type\"\n | \"const\"\n | \"enum\"\n | \"anyOf\"\n | \"minLength\"\n | \"maxLength\"\n | \"minimum\"\n | \"maximum\"\n | \"exclusiveMinimum\"\n | \"exclusiveMaximum\"\n | \"minItems\"\n | \"maxItems\"\n | \"format\"\n | \"additionalProperties\";\n\nexport type SchemaIssue = {\n /** Keys and array indices from the root, `[]` for the root itself. */\n path: (string | number)[];\n code: SchemaIssueCode;\n message: string;\n params: Record<string, unknown>;\n};\n\ninterface OptionalSchemaBuilder<T> extends SchemaBuilder<T | undefined>, OptionalSchema<T> {}\n\n// --- the runtime ---------------------------------------------------------\n\n/**\n * What a builder actually is. `optional` and `nullable` are flags rather than\n * wrapper nodes so that `.nullable().optional()` cannot nest into something\n * whose emitted shape depends on which order they were called in.\n */\ntype Definition = {\n node: SchemaNode;\n description?: string;\n optional: boolean;\n nullable: boolean;\n};\n\n/**\n * The constraints `s.fromJSONSchema` can carry over from a JSON Schema. None of\n * the builders set them; they exist so that a schema read from data validates\n * what it says it does.\n *\n * They are CHECKED, NOT EMITTED as keywords. Strict structured output refuses\n * most of them (`minLength`, `maxLength`, `minimum` on Anthropic; any `format`\n * outside a short list on both), so the model is told them in the field's\n * description instead, and `parse` enforces them — a model that ignores the\n * prose gets an `invalid_tool_input` it can correct, the same as a wrong type.\n */\ntype StringChecks = {\n minLength?: number;\n maxLength?: number;\n format?: { name: string; test: (value: string) => boolean };\n};\n\ntype NumberChecks = {\n integer?: boolean;\n minimum?: number;\n maximum?: number;\n exclusiveMinimum?: number;\n exclusiveMaximum?: number;\n};\n\ntype ArrayChecks = { minItems?: number; maxItems?: number };\n\ntype SchemaNode =\n | { kind: \"string\"; checks?: StringChecks }\n | { kind: \"number\"; checks?: NumberChecks }\n | { kind: \"boolean\" }\n | { kind: \"literal\"; value: string | number | boolean }\n | { kind: \"enum\"; values: readonly string[]; checks?: StringChecks }\n /**\n * `unknownKeys` is what parsing does with a key `shape` doesn't declare:\n * absent is \"strip\", the default and the only thing the builders make. Only\n * `s.fromJSONSchema` sets the others. Emission ignores it: every object is\n * sent with `additionalProperties: false` either way.\n */\n | { kind: \"object\"; shape: Record<string, Definition>; unknownKeys?: \"error\" | \"passthrough\" }\n | { kind: \"array\"; item: Definition; checks?: ArrayChecks }\n | { kind: \"union\"; members: readonly Definition[] }\n /** Constrains nothing. The node strict mode has no spelling for. */\n | { kind: \"json\" }\n /**\n * A use of an `s.recursive` schema — its `self`, or the builder it returned.\n * Emitted as a `$ref` into the root's `$defs`, read by following the cell.\n */\n | { kind: \"ref\"; cell: RecursiveCell };\n\n/**\n * One `s.recursive` declaration. `definition` is filled in once the callback\n * returns; until then `self` is a reference to something that does not exist\n * yet, which is the whole trick.\n *\n * `active` is the set of values being read through this cell right now, the\n * cycle guard for a JavaScript value that contains itself (a tool output an app\n * built). Per cell rather than global, so that one value read through two\n * different recursive schemas in a row is not mistaken for a cycle.\n */\ntype RecursiveCell = {\n name: string;\n definition?: Definition;\n active: Set<object>;\n};\n\nfunction bodyOf(cell: RecursiveCell): Definition {\n if (!cell.definition) {\n throw new Error(\n `gemi/ai: the recursive schema \"${cell.name}\" was used before its definition returned; \\`self\\` can be nested into the schema, but not parsed or emitted inside the callback`,\n );\n }\n return cell.definition;\n}\n\ntype ParseResult = { ok: true; value: unknown } | { ok: false; errors: string[] };\n\ntype Path = (string | number)[];\n\n/** The public interface with the phantoms and the generic taken off. */\ninterface RuntimeSchema {\n toJSONSchema(): JSONSchema;\n parse(value: unknown): unknown;\n safeParse(value: unknown): ParseResult;\n validate(value: unknown): { ok: true; value: unknown } | { ok: false; issues: SchemaIssue[] };\n describe(description: string): RuntimeSchema;\n optional(): RuntimeSchema;\n nullable(): RuntimeSchema;\n}\n\n/**\n * Definitions hang off the builders here rather than on the builders\n * themselves: a property, however obscurely named, is a property an app can\n * see, serialise or accidentally depend on, and `Schema<T>` promises exactly\n * three methods.\n */\nconst definitions = new WeakMap<object, Definition>();\n\n/**\n * Whether `value` is a schema built with `s`. How `HttpRequest` tells an `s`\n * body schema from a map of rules (#711), without a property on the builder.\n */\nexport function isSchema(value: unknown): value is SchemaBuilder<unknown> {\n return typeof value === \"object\" && value !== null && definitions.has(value);\n}\n\nfunction definitionOf(schema: AnySchema): Definition {\n const definition = definitions.get(schema);\n if (!definition) {\n throw new Error(\"gemi/ai: expected a schema built with `s`, got a foreign object\");\n }\n return definition;\n}\n\n// --- emitting ------------------------------------------------------------\n\n/**\n * What one `toJSONSchema()` call collects on its way down: the `$defs` the\n * root will carry, and which cell owns each name in them.\n */\ntype EmitContext = {\n defs: Record<string, JSONSchema>;\n cells: Map<string, RecursiveCell>;\n};\n\n/**\n * The schema as the provider sees it: the tree, plus `$defs` at the root when\n * an `s.recursive` is anywhere in it.\n *\n * A recursive schema used AS the root is inlined there, and its `$defs` entry\n * is a second copy of the same body. Pointing the root at itself with\n * `\"$ref\": \"#\"` would be shorter, and OpenAI accepts it, but `#` means \"the\n * whole document\" — and a document that gets merged into (MCP's\n * `combineSchemas` adds properties to an input's root) would then demand the\n * merged-in fields at every level of the tree.\n */\nfunction emitRoot(definition: Definition): JSONSchema {\n const context: EmitContext = { defs: {}, cells: new Map() };\n let root = definition;\n if (definition.node.kind === \"ref\") {\n const body = bodyOf(definition.node.cell);\n root = {\n ...body,\n ...(definition.description ? { description: definition.description } : {}),\n optional: definition.optional,\n nullable: definition.nullable || body.nullable,\n };\n }\n const schema = emit(root, context);\n return Object.keys(context.defs).length > 0 ? { ...schema, $defs: context.defs } : schema;\n}\n\nfunction emit(definition: Definition, context: EmitContext): JSONSchema {\n // A `json` node already admits every value there is, null included, so\n // widening it would only add an `anyOf` for the model to read past — and one\n // whose second branch is a strictly narrower repeat of its first.\n const widen = (definition.optional || definition.nullable) && definition.node.kind !== \"json\";\n let body = allowNull(emitNode(definition.node, context), widen);\n const description = [definition.description, hint(definition.node)].filter(Boolean).join(\" \");\n // `$ref` takes no siblings under strict mode, so a described reference\n // becomes a one-member `anyOf` that can carry the description beside it.\n if (description && body.$ref !== undefined) body = { anyOf: [body] };\n return description ? { description, ...body } : body;\n}\n\n/**\n * The checks a node carries, in words, for the description — the one place a\n * strict-mode provider lets them through. See `StringChecks`.\n */\nfunction hint(node: SchemaNode): string {\n const said: string[] = [];\n if (node.kind === \"string\" || node.kind === \"enum\") {\n const checks = node.checks;\n if (checks?.format) said.push(`Format: ${checks.format.name}.`);\n if (checks?.minLength !== undefined) said.push(`At least ${checks.minLength} characters.`);\n if (checks?.maxLength !== undefined) said.push(`At most ${checks.maxLength} characters.`);\n } else if (node.kind === \"number\") {\n const checks = node.checks;\n if (checks?.minimum !== undefined) said.push(`Minimum ${checks.minimum}.`);\n if (checks?.exclusiveMinimum !== undefined) {\n said.push(`Greater than ${checks.exclusiveMinimum}.`);\n }\n if (checks?.maximum !== undefined) said.push(`Maximum ${checks.maximum}.`);\n if (checks?.exclusiveMaximum !== undefined) said.push(`Less than ${checks.exclusiveMaximum}.`);\n } else if (node.kind === \"array\") {\n const checks = node.checks;\n if (checks?.minItems !== undefined) said.push(`At least ${checks.minItems} items.`);\n if (checks?.maxItems !== undefined) said.push(`At most ${checks.maxItems} items.`);\n }\n // A `ref` says nothing of its own: its body's hints are in its `$defs` entry.\n return said.join(\" \");\n}\n\nfunction emitNode(node: SchemaNode, context: EmitContext): JSONSchema {\n switch (node.kind) {\n case \"string\":\n return { type: \"string\" };\n case \"number\":\n // `integer` is in the strict subset of every provider gemi speaks to.\n return { type: node.checks?.integer ? \"integer\" : \"number\" };\n case \"boolean\":\n return { type: \"boolean\" };\n // `const` rather than a one-member `enum`, because a boolean literal has no\n // `enum` form and one branch that works for all three beats two that\n // disagree about what a literal is.\n case \"literal\":\n return { type: typeof node.value, const: node.value };\n case \"enum\":\n return { type: \"string\", enum: node.values };\n case \"array\":\n return { type: \"array\", items: emit(node.item, context) };\n case \"object\":\n return {\n type: \"object\",\n properties: Object.fromEntries(\n Object.entries(node.shape).map(([key, child]) => [key, emit(child, context)]),\n ),\n // Every declared property, optional ones included. This is the whole of\n // strict mode's bargain: the model is never allowed to omit a key, so\n // \"may be absent\" has to be spelled as \"may be null\" instead.\n required: Object.keys(node.shape),\n additionalProperties: false,\n };\n case \"union\":\n return { anyOf: node.members.map((member) => emit(member, context)) };\n // The empty schema, which is JSON Schema's own way of saying \"any value\" —\n // no `type` listing all seven, which reads as a constraint the model then\n // has to check itself. What the field actually is gets said in\n // `description`, the one channel a model reads either way.\n case \"json\":\n return {};\n case \"ref\": {\n const { cell } = node;\n const owner = context.cells.get(cell.name);\n if (owner && owner !== cell) {\n throw new Error(\n `gemi/ai: two different recursive schemas are named \"${cell.name}\" in one schema; give each s.recursive(...) its own name`,\n );\n }\n if (!owner) {\n // Claimed BEFORE the body is emitted: the body refers to itself, and\n // that inner reference has to find the name taken and stop here.\n context.cells.set(cell.name, cell);\n context.defs[cell.name] = {};\n context.defs[cell.name] = emit(bodyOf(cell), context);\n }\n return { $ref: `#/$defs/${cell.name}` };\n }\n }\n}\n\n/**\n * Widens a schema to admit `null` — for a `nullable()` field, and for the null\n * an `optional()` field tells the model to send in place of omitting the key.\n */\nfunction allowNull(base: JSONSchema, on: boolean): JSONSchema {\n if (!on) return base;\n // A union is already a list of alternatives; appending to it is flatter than\n // nesting an `anyOf` inside an `anyOf`, and reads the same to the model.\n if (base.anyOf) return { ...base, anyOf: [...base.anyOf, { type: \"null\" }] };\n // `enum` and `const` cannot carry the null themselves — `enum` here is\n // strings and numbers by declaration — so those get wrapped rather than\n // widened.\n if (base.enum || base.const !== undefined) return { anyOf: [base, { type: \"null\" }] };\n if (typeof base.type === \"string\") return { ...base, type: [base.type, \"null\"] };\n return { anyOf: [base, { type: \"null\" }] };\n}\n\n// --- parsing -------------------------------------------------------------\n\nfunction typeName(value: unknown): string {\n if (value === null) return \"null\";\n if (Array.isArray(value)) return \"array\";\n return typeof value;\n}\n\n/**\n * What the value looked like. For a literal or an enum the *type* is usually\n * right and the value is wrong, and \"expected \\\"refund\\\", got string\" tells\n * whoever is reading the failed tool call nothing they did not know.\n */\nfunction saw(node: SchemaNode, value: unknown): string {\n if (typeof value === \"number\" && !Number.isFinite(value)) return String(value);\n if (node.kind === \"literal\" || node.kind === \"enum\") {\n const primitive =\n typeof value === \"string\" || typeof value === \"number\" || typeof value === \"boolean\";\n if (primitive) return JSON.stringify(value);\n }\n return typeName(value);\n}\n\nfunction wanted(definition: Definition): string {\n const node = definition.node;\n const base = (() => {\n switch (node.kind) {\n case \"number\":\n return node.checks?.integer ? \"integer\" : \"number\";\n case \"string\":\n case \"boolean\":\n return node.kind;\n case \"literal\":\n return JSON.stringify(node.value);\n case \"enum\":\n return `one of ${node.values.map((v) => JSON.stringify(v)).join(\" | \")}`;\n case \"array\":\n return \"array\";\n case \"object\":\n return \"object\";\n case \"union\":\n return \"one of the variants\";\n case \"json\":\n return \"a JSON value\";\n case \"ref\":\n return wanted({ ...bodyOf(node.cell), optional: false, nullable: false });\n }\n })();\n return definition.optional || definition.nullable ? `${base} or null` : base;\n}\n\n/** `orders[2].total` — keys joined with dots, indices in brackets. */\nfunction formatPath(path: Path): string {\n let out = \"\";\n for (const segment of path) {\n out += typeof segment === \"number\" ? `[${segment}]` : out ? `.${segment}` : segment;\n }\n return out;\n}\n\n/** `orders[2].total: ` — empty at the root, where a prefix would be noise. */\nfunction at(path: Path): string {\n const text = formatPath(path);\n return text ? `${text}: ` : \"\";\n}\n\n/** The sentence `safeParse` reports for an issue. */\nfunction render(issue: SchemaIssue): string {\n return `${at(issue.path)}${issue.message}`;\n}\n\n/**\n * How well a value matches, used only to pick which union variant to blame.\n * A literal or an enum hit counts for far more than an ordinary field, because\n * that is what a discriminated union turns on: the variant whose `kind` matched\n * is the one the model meant, whatever else it got wrong.\n */\nfunction score(definition: Definition, value: unknown): number {\n if (value === null || value === undefined) {\n return definition.optional || definition.nullable ? 1 : 0;\n }\n const node = definition.node;\n switch (node.kind) {\n case \"string\":\n return typeof value === \"string\" ? 1 : 0;\n case \"number\":\n return typeof value === \"number\" ? 1 : 0;\n case \"boolean\":\n return typeof value === \"boolean\" ? 1 : 0;\n case \"literal\":\n return value === node.value ? 10 : 0;\n case \"enum\":\n return typeof value === \"string\" && node.values.includes(value) ? 10 : 0;\n case \"array\":\n return Array.isArray(value) ? 1 : 0;\n case \"object\": {\n if (typeof value !== \"object\" || Array.isArray(value)) return 0;\n const source = value as Record<string, unknown>;\n let total = 1;\n for (const [key, child] of Object.entries(node.shape)) {\n total += score(child, source[key]);\n }\n return total;\n }\n case \"union\":\n return node.members.reduce((best, member) => Math.max(best, score(member, value)), 0);\n // Matches, because it matches everything — but at the score of a plain\n // scalar, so a sibling variant that pinned its discriminant still wins the\n // blame.\n //\n // Reached only when no member parsed, which for a `json` member means the\n // value is not JSON at all: a function, a bigint, a cycle. Then this is\n // what makes the report name the reason the value was refused rather than\n // the discriminant of a variant the model was never aiming at.\n case \"json\":\n return 1;\n case \"ref\":\n return through(\n node.cell,\n value,\n () => 1,\n () => score(bodyOf(node.cell), value),\n );\n }\n}\n\n/**\n * Runs `walk` with `value` marked as being read through `cell`, or `cycle` when\n * it already is. A value can only meet the same cell again further down by\n * containing itself — `s.recursive` refuses a body that reaches `self` without\n * an object or array in between — so this is exactly the cycle guard, and a\n * value that merely appears twice side by side is read twice.\n */\nfunction through<R>(cell: RecursiveCell, value: unknown, cycle: () => R, walk: () => R): R {\n if (typeof value !== \"object\" || value === null) return walk();\n if (cell.active.has(value)) return cycle();\n cell.active.add(value);\n try {\n return walk();\n } finally {\n cell.active.delete(value);\n }\n}\n\n/** `drop` is a key that should not appear in the parsed object at all. */\ntype Reading = { drop: boolean; value: unknown };\n\nfunction read(definition: Definition, value: unknown, path: Path, issues: SchemaIssue[]): Reading {\n // `optional` is checked before `nullable`, so a schema that is both treats\n // null as \"absent\". They are not distinguishable on the wire: strict mode\n // gives the model one spelling for \"nothing\", and pretending otherwise would\n // mean `.nullable().optional()` silently kept a key the type says is\n // optional. What that trades away is the ability to say \"present and null\" on\n // a field that may also be absent — a distinction no model can express here.\n if (definition.optional && (value === null || value === undefined)) {\n return { drop: true, value: undefined };\n }\n if (definition.nullable && value === null) return { drop: false, value: null };\n return { drop: false, value: readNode(definition, value, path, issues) };\n}\n\nfunction readNode(\n definition: Definition,\n value: unknown,\n path: Path,\n issues: SchemaIssue[],\n): unknown {\n const node = definition.node;\n const fail = () => {\n const code: SchemaIssueCode =\n value === undefined\n ? \"required\"\n : node.kind === \"literal\"\n ? \"const\"\n : node.kind === \"enum\" && typeof value === \"string\"\n ? \"enum\"\n : \"type\";\n const params =\n code === \"const\"\n ? { allowedValue: (node as { value: unknown }).value }\n : code === \"enum\"\n ? { allowedValues: (node as { values: readonly string[] }).values }\n : {};\n issues.push({\n path,\n code,\n message: `expected ${wanted(definition)}, got ${saw(node, value)}`,\n params,\n });\n return undefined;\n };\n\n switch (node.kind) {\n case \"string\":\n if (typeof value !== \"string\") return fail();\n checkString(node.checks, value, path, issues);\n return value;\n case \"number\":\n // NaN and Infinity do not survive `JSON.stringify`, so a tool that\n // returns one produces a body the provider cannot be sent.\n if (typeof value !== \"number\" || !Number.isFinite(value)) return fail();\n if (node.checks?.integer && !Number.isInteger(value)) return fail();\n checkNumber(node.checks, value, path, issues);\n return value;\n case \"boolean\":\n return typeof value === \"boolean\" ? value : fail();\n case \"literal\":\n return value === node.value ? value : fail();\n case \"enum\":\n if (typeof value !== \"string\" || !node.values.includes(value)) return fail();\n checkString(node.checks, value, path, issues);\n return value;\n case \"array\": {\n if (!Array.isArray(value)) return fail();\n const items = value.map((item, index) => {\n const element = read(node.item, item, [...path, index], issues);\n return element.drop ? undefined : element.value;\n });\n const { minItems, maxItems } = node.checks ?? {};\n if (minItems !== undefined && value.length < minItems) {\n issues.push({\n path,\n code: \"minItems\",\n message: `expected at least ${minItems} items, got ${value.length}`,\n params: { limit: minItems },\n });\n }\n if (maxItems !== undefined && value.length > maxItems) {\n issues.push({\n path,\n code: \"maxItems\",\n message: `expected at most ${maxItems} items, got ${value.length}`,\n params: { limit: maxItems },\n });\n }\n return items;\n }\n case \"object\": {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) return fail();\n const source = value as Record<string, unknown>;\n const output: Record<string, unknown> = {};\n for (const [key, child] of Object.entries(node.shape)) {\n const element = read(child, source[key], [...path, key], issues);\n if (!element.drop) output[key] = element.value;\n }\n // By default unknown keys are DROPPED, not rejected. `additionalProperties:\n // false` has already told the model not to send them, so one arriving\n // anyway is a slip rather than an attack, and failing a whole tool call\n // over a stray field costs a turn to fix nothing. Dropping is also what\n // keeps `execute` from ever seeing a field its input type says cannot be\n // there.\n //\n // A schema read from data can ask otherwise (#753): a form submission\n // with a field the form doesn't have is a bot or a stale page, and\n // dropping it loses what the visitor typed without telling them.\n if (node.unknownKeys) {\n for (const key of Object.keys(source)) {\n // `undefined` is absent, the same as for `required`: JSON cannot\n // carry it, and `JSON.stringify` leaves the key out.\n if (Object.hasOwn(node.shape, key) || source[key] === undefined) continue;\n if (node.unknownKeys === \"error\") {\n issues.push({\n path: [...path, key],\n code: \"additionalProperties\",\n message: \"unknown key\",\n params: { additionalProperty: key },\n });\n continue;\n }\n // Kept as it came, checked only for being JSON — there is no schema\n // to read it with. Defined rather than assigned, so that a\n // `__proto__` key from `JSON.parse` stays a key instead of setting\n // the output's prototype.\n checkJson(source[key], [...path, key], issues, new Set());\n Object.defineProperty(output, key, {\n value: source[key],\n enumerable: true,\n writable: true,\n configurable: true,\n });\n }\n }\n return output;\n }\n case \"union\": {\n let best: { issues: SchemaIssue[]; score: number } | undefined;\n for (const member of node.members) {\n const attempt: SchemaIssue[] = [];\n const element = read(member, value, path, attempt);\n if (attempt.length === 0) return element.drop ? undefined : element.value;\n const points = score(member, value);\n if (!best || points > best.score) best = { issues: attempt, score: points };\n }\n // \"no match\" is useless when one field of a five-field variant was wrong.\n // Naming the closest variant and why it stopped is the difference between\n // a debuggable bad tool call and a shrug.\n issues.push({\n path,\n code: \"anyOf\",\n message: `no matching variant; closest: ${best!.issues.map(render).join(\"; \")}`,\n params: { closest: best!.issues },\n });\n return undefined;\n }\n // Passed through by reference, not rebuilt. Two reasons beyond the obvious\n // one: a rebuild would turn a `Date` into `{}` by copying own properties\n // that a `toJSON` was going to replace anyway, and the agent loop signs the\n // *parsed* input and later verifies the signature against it — a parse that\n // is exactly the identity cannot disagree with itself.\n case \"json\":\n if (value === undefined) return fail();\n checkJson(value, path, issues, new Set());\n return value;\n // The reference's own `optional`/`nullable` were settled by `read` above;\n // the body's are its own business, settled by the `read` below.\n case \"ref\":\n return through(\n node.cell,\n value,\n () => {\n issues.push({\n path,\n code: \"type\",\n message: \"expected a finite tree, got a circular reference\",\n params: {},\n });\n return undefined;\n },\n () => read(bodyOf(node.cell), value, path, issues).value,\n );\n }\n}\n\n/**\n * Length in code points, not UTF-16 units — what JSON Schema (and Ajv) count,\n * so an emoji is one character against a `maxLength` either way.\n */\nfunction length(value: string): number {\n let count = 0;\n for (const _ of value) count++;\n return count;\n}\n\nfunction checkString(\n checks: StringChecks | undefined,\n value: string,\n path: Path,\n issues: SchemaIssue[],\n): void {\n if (!checks) return;\n const { minLength, maxLength, format } = checks;\n if (minLength !== undefined || maxLength !== undefined) {\n const size = length(value);\n if (minLength !== undefined && size < minLength) {\n issues.push({\n path,\n code: \"minLength\",\n message: `expected at least ${minLength} characters, got ${size}`,\n params: { limit: minLength },\n });\n }\n if (maxLength !== undefined && size > maxLength) {\n issues.push({\n path,\n code: \"maxLength\",\n message: `expected at most ${maxLength} characters, got ${size}`,\n params: { limit: maxLength },\n });\n }\n }\n if (format) {\n let ok = false;\n try {\n ok = format.test(value) === true;\n } catch {\n // A check that throws has not said yes.\n }\n if (!ok) {\n issues.push({\n path,\n code: \"format\",\n message: `expected a string in format \"${format.name}\"`,\n params: { format: format.name },\n });\n }\n }\n}\n\nfunction checkNumber(\n checks: NumberChecks | undefined,\n value: number,\n path: Path,\n issues: SchemaIssue[],\n): void {\n if (!checks) return;\n const bound = (\n code: SchemaIssueCode,\n limit: number | undefined,\n passes: (limit: number) => boolean,\n words: string,\n ) => {\n if (limit === undefined || passes(limit)) return;\n issues.push({\n path,\n code,\n message: `expected ${words} ${limit}, got ${value}`,\n params: { limit },\n });\n };\n bound(\"minimum\", checks.minimum, (limit) => value >= limit, \"at least\");\n bound(\"exclusiveMinimum\", checks.exclusiveMinimum, (limit) => value > limit, \"more than\");\n bound(\"maximum\", checks.maximum, (limit) => value <= limit, \"at most\");\n bound(\"exclusiveMaximum\", checks.exclusiveMaximum, (limit) => value < limit, \"less than\");\n}\n\n/**\n * Checks that a value is JSON, which is the only check a `json()` node makes.\n *\n * Tool arguments arrive through `JSON.parse`, so this never fires on model\n * input. It fires on a tool *output* or a structured answer an app built, where\n * a `bigint` or a cycle throws inside `JSON.stringify` and a function or a\n * `symbol` is dropped without a word — one turn later, with the provider's\n * request body to debug instead of the value.\n *\n * `undefined` and non-plain objects are deliberately allowed below the root:\n * `JSON.stringify` drops an `undefined` property, writes `null` for an\n * `undefined` element, and calls `toJSON` where there is one. Those are JSON's\n * own answers, and rejecting a `Date` to catch a `Map` is a bad trade.\n *\n * `toJSON` is honoured rather than assumed harmless: the walk checks what it\n * returns and never the object behind it, because that is all `JSON.stringify`\n * will look at.\n */\nfunction checkJson(\n value: unknown,\n path: Path,\n issues: SchemaIssue[],\n seen: Set<object>,\n // False for the value a `toJSON` just returned: `JSON.stringify` applies\n // `toJSON` once per position, and re-applying it is how a pair of them\n // returning each other became an infinite loop.\n applyToJSON = true,\n): void {\n const reject = (what: string) => {\n issues.push({ path, code: \"type\", message: `expected a JSON value, got ${what}`, params: {} });\n };\n\n switch (typeof value) {\n case \"undefined\":\n case \"string\":\n case \"boolean\":\n return;\n case \"number\":\n if (!Number.isFinite(value)) reject(String(value));\n return;\n case \"bigint\":\n return reject(\"a bigint\");\n case \"function\":\n return reject(\"a function\");\n case \"symbol\":\n return reject(\"a symbol\");\n }\n\n if (value === null) return;\n const object = value as object;\n\n // The cycle guard comes FIRST, above `toJSON`, and that ordering is the whole\n // of it: a `toJSON` is arbitrary code that can hand back another object with a\n // `toJSON` of its own, so two of them returning each other is a cycle that\n // `seen` catches and an identity test cannot. Below the guard, that pair hung\n // `safeParse` forever — and a `toJSON` returning a fresh object each time threw\n // `RangeError` out of a function documented to return `{ ok: false, errors }`.\n if (seen.has(object)) return reject(\"a circular reference\");\n seen.add(object);\n try {\n // `JSON.stringify` asks `toJSON` what to write and never looks at the object\n // itself, so that answer is what has to be checked. Without this the walk\n // descended into the wrapper's own fields and refused values `stringify`\n // serializes without complaint — a `toJSON` returning a string off a `bigint`\n // field being the archetype, since writing a `toJSON` is exactly what one\n // does about a field JSON cannot carry. `Date` passed only by having no own\n // enumerable properties to trip over.\n const toJSON = applyToJSON ? (object as { toJSON?: unknown }).toJSON : undefined;\n if (typeof toJSON === \"function\") {\n let replaced: unknown;\n try {\n replaced = (toJSON as (key?: string) => unknown).call(object);\n } catch {\n return reject(\"a toJSON that threw\");\n }\n // `JSON.stringify` applies `toJSON` once per value position, not until it\n // stops changing, so the replacement is checked with it switched off here\n // — its nested values get their own.\n if (replaced === undefined) return reject(\"a toJSON that returns undefined\");\n return checkJson(replaced, path, issues, seen, false);\n }\n if (Array.isArray(value)) {\n value.forEach((item, index) => checkJson(item, [...path, index], issues, seen));\n } else {\n for (const [key, child] of Object.entries(object)) {\n checkJson(child, [...path, key], issues, seen);\n }\n }\n } finally {\n // Removed rather than left in: `seen` is the path currently being walked, and\n // keeping it would call the same object appearing twice side by side — which\n // `JSON.stringify` writes out twice quite happily — a cycle. In a `finally`\n // so the `toJSON` returns above cannot leave it marked.\n seen.delete(object);\n }\n}\n\n/**\n * The one cast in this file, and the reason it has to exist: `OUTPUT` and\n * `OPTIONAL` are `declare const` unique symbols. They have no runtime\n * counterpart — they are inference channels — so no object that can actually be\n * constructed satisfies `Schema<T>` structurally. Funnelling every builder\n * through here means the lie is told once, in one place, and everything else in\n * the module is checked against the real declarations.\n */\nfunction make<T>(definition: Definition): SchemaBuilder<T> {\n return build(definition) as unknown as SchemaBuilder<T>;\n}\n\n/**\n * Builders are immutable: `describe`, `optional` and `nullable` each build a\n * fresh one from a copied definition. Mutating in place is the obvious\n * implementation and it is wrong — `const id = s.string()` reused in two\n * objects, described in one of them, would carry that description into the\n * other, and the only symptom is a model being told the wrong thing about a\n * field somewhere else.\n */\nfunction build(definition: Definition): RuntimeSchema {\n const runtime: RuntimeSchema = {\n toJSONSchema: () => emitRoot(definition),\n parse(value) {\n const issues: SchemaIssue[] = [];\n const result = read(definition, value, [], issues);\n if (issues.length > 0) throw new Error(issues.map(render).join(\"; \"));\n return result.drop ? undefined : result.value;\n },\n safeParse(value) {\n const issues: SchemaIssue[] = [];\n const result = read(definition, value, [], issues);\n if (issues.length > 0) return { ok: false, errors: issues.map(render) };\n return { ok: true, value: result.drop ? undefined : result.value };\n },\n validate(value) {\n const issues: SchemaIssue[] = [];\n const result = read(definition, value, [], issues);\n if (issues.length > 0) return { ok: false, issues };\n return { ok: true, value: result.drop ? undefined : result.value };\n },\n describe: (description) => build({ ...definition, description }),\n optional: () => build({ ...definition, optional: true }),\n // Clearing `optional` is not tidiness. `nullable()` returns a\n // `SchemaBuilder`, not an `OptionalSchemaBuilder`, so the key it describes\n // is required again in `ShapeOutput` — and a parse that still dropped it\n // would hand back an object missing a key its own type declares.\n nullable: () => build({ ...definition, nullable: true, optional: false }),\n };\n definitions.set(runtime, definition);\n return runtime;\n}\n\nfunction leaf(node: SchemaNode): Definition {\n return { node, optional: false, nullable: false };\n}\n\n// --- reading a JSON Schema ---------------------------------------------------\n\n/**\n * How `s.fromJSONSchema` checks a `format`. `true` accepts any string (a format\n * that is only a hint, like `markdown`); a `RegExp` or a function decides.\n */\nexport type JSONSchemaFormat = true | RegExp | ((value: string) => boolean);\n\nexport type FromJSONSchemaOptions = {\n /**\n * The formats the schema may name. A `format` not listed here is refused, not\n * ignored: gemi ships no format checks of its own, and a format that quietly\n * checked nothing would be a constraint that only looks enforced.\n */\n formats?: Record<string, JSONSchemaFormat>;\n /**\n * Keywords to skip as annotations, on top of the ones always skipped:\n * `title`, `$schema`, `$id`, `$comment`, `examples`, `default`,\n * `deprecated`, `readOnly`, `writeOnly`, and every `x-` keyword.\n */\n ignoreKeywords?: readonly string[];\n /**\n * What `parse`, `safeParse` and `validate` do with a key an object of the\n * schema doesn't declare, at every depth:\n *\n * - `\"strip\"` (the default): drop it from the parsed value, silently.\n * - `\"error\"`: fail with an `additionalProperties` issue whose `path` ends in\n * the key and whose `params.additionalProperty` is the key.\n * - `\"passthrough\"`: keep it in the parsed value as it came (it is only\n * checked for being JSON).\n *\n * Every object is closed in `s`, so this applies whether or not the object\n * says `additionalProperties: false`, and the emitted schema still says\n * `additionalProperties: false` (strict mode requires it). It applies to\n * this schema's objects only: an `s.object` it is nested into keeps\n * stripping.\n */\n unknownKeys?: \"strip\" | \"error\" | \"passthrough\";\n};\n\nconst UNKNOWN_KEYS = [\"strip\", \"error\", \"passthrough\"] as const;\n\n/**\n * Thrown by `s.fromJSONSchema` for a schema outside the subset `s` models.\n * `problems` lists every one found, each starting with the path into the\n * schema (`properties.price.type: ...`), so a schema written by a user or a\n * model can be sent back with all of them at once.\n */\nexport class JSONSchemaError extends Error {\n readonly problems: string[];\n constructor(problems: string[]) {\n super(\n `gemi/ai: s.fromJSONSchema cannot model this schema:\\n${problems.map((p) => `- ${p}`).join(\"\\n\")}`,\n );\n this.name = \"JSONSchemaError\";\n this.problems = problems;\n }\n}\n\nconst ANNOTATIONS = new Set([\n \"title\",\n \"$schema\",\n \"$id\",\n \"$comment\",\n \"examples\",\n \"default\",\n \"deprecated\",\n \"readOnly\",\n \"writeOnly\",\n]);\n\n/** The keywords each type may carry, beyond `type`, `description`, `enum` and `const`. */\nconst KEYWORDS: Record<string, readonly string[]> = {\n string: [\"minLength\", \"maxLength\", \"format\"],\n number: [\"minimum\", \"maximum\", \"exclusiveMinimum\", \"exclusiveMaximum\"],\n integer: [\"minimum\", \"maximum\", \"exclusiveMinimum\", \"exclusiveMaximum\"],\n boolean: [],\n object: [\"properties\", \"required\", \"additionalProperties\"],\n array: [\"items\", \"minItems\", \"maxItems\"],\n};\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/**\n * Reads a JSON Schema into a definition, collecting every problem rather than\n * stopping at the first. Returns `undefined` where a node could not be read;\n * the caller throws once the walk is done.\n */\nfunction fromJSON(\n schema: unknown,\n options: FromJSONSchemaOptions,\n where: string,\n problems: string[],\n): Definition | undefined {\n const problem = (message: string, at = where) => {\n problems.push(at ? `${at}: ${message}` : message);\n return undefined;\n };\n const child = (key: string) => (where ? `${where}.${key}` : key);\n if (!isPlainObject(schema)) return problem(\"expected a schema object\");\n\n const ignored = new Set(options.ignoreKeywords ?? []);\n const skip = (key: string) => ANNOTATIONS.has(key) || key.startsWith(\"x-\") || ignored.has(key);\n\n // `type: [T, \"null\"]`, `enum` with a null in it and an `anyOf` with a\n // `{ type: \"null\" }` member all mean the same: T, nullable.\n let nullable = false;\n let type = schema.type;\n if (Array.isArray(type)) {\n const rest = type.filter((t) => t !== \"null\");\n if (rest.length !== 1) {\n return problem(\n `type ${JSON.stringify(type)} is not supported; only one type, optionally with \"null\". Use anyOf for alternatives`,\n child(\"type\"),\n );\n }\n nullable = rest.length < type.length;\n type = rest[0];\n }\n if (type !== undefined && (typeof type !== \"string\" || !(type in KEYWORDS))) {\n return problem(\n `type ${JSON.stringify(type)} is not supported; expected one of ${Object.keys(KEYWORDS).join(\", \")}`,\n child(\"type\"),\n );\n }\n\n const allowed = new Set([\n \"type\",\n \"description\",\n \"enum\",\n \"const\",\n \"anyOf\",\n ...(type ? KEYWORDS[type as string] : []),\n ]);\n let unknown = false;\n for (const key of Object.keys(schema)) {\n if (allowed.has(key) || skip(key)) continue;\n unknown = true;\n const owner = Object.entries(KEYWORDS).find(([, keys]) => keys.includes(key));\n problem(\n owner && owner[0] !== type\n ? `\"${key}\" applies to type ${owner[0]}, and this schema is ${type ? `type ${type}` : \"untyped\"}`\n : `\"${key}\" is not supported by s.fromJSONSchema`,\n child(key),\n );\n }\n if (unknown) return undefined;\n\n if (schema.description !== undefined && typeof schema.description !== \"string\") {\n return problem(\"expected a string\", child(\"description\"));\n }\n const description = schema.description as string | undefined;\n const finish = (node: SchemaNode): Definition => ({\n node,\n optional: false,\n nullable,\n ...(description ? { description } : {}),\n });\n\n if (schema.anyOf !== undefined) {\n if (type !== undefined || schema.enum !== undefined || schema.const !== undefined) {\n return problem(\"anyOf cannot be combined with type, enum or const here\", child(\"anyOf\"));\n }\n if (!Array.isArray(schema.anyOf) || schema.anyOf.length === 0) {\n return problem(\"expected a non-empty array\", child(\"anyOf\"));\n }\n const members: Definition[] = [];\n let failed = false;\n schema.anyOf.forEach((member, index) => {\n if (isPlainObject(member) && member.type === \"null\" && Object.keys(member).length === 1) {\n nullable = true;\n return;\n }\n const read = fromJSON(member, options, child(`anyOf[${index}]`), problems);\n if (read) members.push(read);\n else failed = true;\n });\n if (failed) return undefined;\n if (members.length === 0) return problem(\"anyOf has only null in it\", child(\"anyOf\"));\n if (members.length === 1) {\n const only = members[0]!;\n return {\n ...only,\n nullable: only.nullable || nullable,\n ...(description ? { description } : {}),\n };\n }\n return finish({ kind: \"union\", members });\n }\n\n if (schema.const !== undefined) {\n const value = schema.const;\n if (typeof value !== \"string\" && typeof value !== \"number\" && typeof value !== \"boolean\") {\n return problem(\"only a string, number or boolean const is supported\", child(\"const\"));\n }\n if (type !== undefined && typeof value !== (type === \"integer\" ? \"number\" : type)) {\n return problem(`const ${JSON.stringify(value)} is not of type ${type}`, child(\"const\"));\n }\n return finish({ kind: \"literal\", value });\n }\n\n let stringChecks: StringChecks | undefined;\n if (type === \"string\") {\n stringChecks = readStringChecks(schema, options, child, problems);\n if (stringChecks === null) return undefined;\n }\n\n if (schema.enum !== undefined) {\n if (!Array.isArray(schema.enum) || schema.enum.length === 0) {\n return problem(\"expected a non-empty array\", child(\"enum\"));\n }\n const values = schema.enum.filter((value) => value !== null);\n if (values.length < schema.enum.length) nullable = true;\n const bad = values.find(\n (value) =>\n !(typeof value === \"string\" || typeof value === \"number\" || typeof value === \"boolean\") ||\n (type !== undefined && typeof value !== (type === \"integer\" ? \"number\" : type)),\n );\n if (bad !== undefined || values.length === 0) {\n return problem(\n type\n ? `every value must be of type ${type}${values.length === 0 ? \", and there must be one\" : `; ${JSON.stringify(bad)} is not`}`\n : \"only strings, numbers and booleans are supported\",\n child(\"enum\"),\n );\n }\n if (values.every((value) => typeof value === \"string\")) {\n return finish({\n kind: \"enum\",\n values: [...new Set(values as string[])],\n ...(stringChecks ? { checks: stringChecks } : {}),\n });\n }\n const literals = [...new Set(values as (string | number | boolean)[])];\n if (literals.length === 1) return finish({ kind: \"literal\", value: literals[0]! });\n return finish({\n kind: \"union\",\n members: literals.map((value) => leaf({ kind: \"literal\", value })),\n });\n }\n\n switch (type) {\n case undefined:\n return problem(\"a schema needs a type, an enum, a const or an anyOf\");\n case \"string\":\n return finish({ kind: \"string\", ...(stringChecks ? { checks: stringChecks } : {}) });\n case \"number\":\n case \"integer\": {\n const checks: NumberChecks = type === \"integer\" ? { integer: true } : {};\n let failed = false;\n for (const key of KEYWORDS.number!) {\n const value = schema[key];\n if (value === undefined) continue;\n if (typeof value !== \"number\" || !Number.isFinite(value)) {\n problem(\"expected a number\", child(key));\n failed = true;\n continue;\n }\n checks[key as \"minimum\"] = value;\n }\n if (failed) return undefined;\n return finish({ kind: \"number\", ...(Object.keys(checks).length > 0 ? { checks } : {}) });\n }\n case \"boolean\":\n return finish({ kind: \"boolean\" });\n case \"array\": {\n if (!isPlainObject(schema.items)) {\n return problem(\n 'an array needs \"items\" to be one schema (tuples are not supported)',\n child(\"items\"),\n );\n }\n const checks: ArrayChecks = {};\n let failed = false;\n for (const key of [\"minItems\", \"maxItems\"] as const) {\n const value = schema[key];\n if (value === undefined) continue;\n if (typeof value !== \"number\" || !Number.isInteger(value) || value < 0) {\n problem(\"expected a non-negative integer\", child(key));\n failed = true;\n continue;\n }\n checks[key] = value;\n }\n const item = fromJSON(schema.items, options, child(\"items\"), problems);\n if (!item || failed) return undefined;\n return finish({ kind: \"array\", item, ...(Object.keys(checks).length > 0 ? { checks } : {}) });\n }\n case \"object\": {\n const properties = schema.properties ?? {};\n if (!isPlainObject(properties)) return problem(\"expected an object\", child(\"properties\"));\n if (schema.additionalProperties !== undefined && schema.additionalProperties !== false) {\n return problem(\n \"only false is supported; a record with arbitrary keys has no strict-mode form (use s.json())\",\n child(\"additionalProperties\"),\n );\n }\n const required = schema.required ?? [];\n if (!Array.isArray(required) || !required.every((key) => typeof key === \"string\")) {\n return problem(\"expected an array of property names\", child(\"required\"));\n }\n const missing = required.filter((key) => !Object.hasOwn(properties, key));\n if (missing.length > 0) {\n return problem(\n `lists properties the schema doesn't have: ${missing.join(\", \")}`,\n child(\"required\"),\n );\n }\n const shape: Record<string, Definition> = {};\n let failed = false;\n for (const [key, value] of Object.entries(properties)) {\n const read = fromJSON(value, options, child(`properties.${key}`), problems);\n if (!read) {\n failed = true;\n continue;\n }\n // Not in `required` is \"may be left out\", which is `optional()`: the\n // model is told to send null, and a parse drops the key.\n shape[key] = required.includes(key) ? read : { ...read, optional: true };\n }\n if (failed) return undefined;\n const unknownKeys = options.unknownKeys;\n return finish({\n kind: \"object\",\n shape,\n ...(unknownKeys === \"error\" || unknownKeys === \"passthrough\" ? { unknownKeys } : {}),\n });\n }\n }\n return undefined;\n}\n\n/** `null` when a problem was reported. */\nfunction readStringChecks(\n schema: Record<string, unknown>,\n options: FromJSONSchemaOptions,\n child: (key: string) => string,\n problems: string[],\n): StringChecks | undefined | null {\n const checks: StringChecks = {};\n let failed = false;\n for (const key of [\"minLength\", \"maxLength\"] as const) {\n const value = schema[key];\n if (value === undefined) continue;\n if (typeof value !== \"number\" || !Number.isInteger(value) || value < 0) {\n problems.push(`${child(key)}: expected a non-negative integer`);\n failed = true;\n continue;\n }\n checks[key] = value;\n }\n if (schema.format !== undefined) {\n const name = schema.format;\n const format = typeof name === \"string\" ? options.formats?.[name] : undefined;\n if (typeof name !== \"string\") {\n problems.push(`${child(\"format\")}: expected a string`);\n failed = true;\n } else if (!format || !Object.hasOwn(options.formats!, name)) {\n problems.push(\n `${child(\"format\")}: unknown format ${JSON.stringify(name)}; pass a check for it in the formats option`,\n );\n failed = true;\n } else {\n checks.format = { name, test: formatTest(format) };\n }\n }\n if (failed) return null;\n return Object.keys(checks).length > 0 ? checks : undefined;\n}\n\nfunction formatTest(format: JSONSchemaFormat): (value: string) => boolean {\n if (format === true) return () => true;\n if (format instanceof RegExp) {\n // A `g` or `y` regex keeps `lastIndex` between calls, so the second value\n // tested would start halfway in. Reset it every time.\n return (value) => {\n format.lastIndex = 0;\n return format.test(value);\n };\n }\n return format;\n}\n\nexport const s: {\n string(): SchemaBuilder<string>;\n number(): SchemaBuilder<number>;\n boolean(): SchemaBuilder<boolean>;\n literal<const L extends string | number | boolean>(value: L): SchemaBuilder<L>;\n /** Modelled as a JSON Schema `enum`, which strict mode does support. */\n enum<const L extends readonly [string, ...string[]]>(values: L): SchemaBuilder<L[number]>;\n object<const S extends Record<string, AnySchema>>(shape: S): SchemaBuilder<ShapeOutput<S>>;\n array<const S extends AnySchema>(item: S): SchemaBuilder<Infer<S>[]>;\n /**\n * `anyOf` of object schemas, discriminated by a literal member. Left in\n * because tool outputs are frequently a success/failure pair, and modelling\n * that as one object with everything optional is worse for the model.\n */\n union<const S extends readonly [AnySchema, AnySchema, ...AnySchema[]]>(\n members: S,\n ): SchemaBuilder<Infer<S[number]>>;\n /**\n * Any JSON value, constrained by nothing — for a format the rest of this\n * builder cannot describe: a record with arbitrary keys, a mixed-type tuple,\n * a document whose shape is not known in advance. (A document that nests\n * into itself has a strict spelling: `s.recursive`.)\n *\n * A schema containing one cannot be sent under strict mode, so a tool whose\n * input uses it is sent with `strict: false` automatically. That is not an\n * option to pass anywhere; it is read back off the schema by\n * `supportsStrict`. The rest of the tool is unaffected, and so is streaming:\n * partial arguments are parsed from the raw text, never through a schema.\n *\n * `T` is an assertion, not a guarantee. The emitted schema constrains\n * nothing, so nothing checks the model's output against `T` — only that it is\n * JSON. Validate it in `execute` and hand the model back an error it can fix,\n * the way it would any other bad argument. `describe()` is where you tell it\n * the format; with no constraints to read, that prose is all it gets.\n *\n * TWO CALL SIGNATURES, NOT A DEFAULT TYPE PARAMETER, and that is load-bearing.\n * Written `json<T = JsonValue>()`, the default lost to the surrounding\n * contextual type in the position this is actually used: `s.object`'s shape is\n * constrained to `Record<string, AnySchema>` — `Schema<any>` — which supplies\n * `any` as an inference candidate, and a candidate beats a default. So\n * `s.object({ definition: s.json() })` inferred `{ definition: any }`, which is\n * type checking switched off around exactly the field this exists for, and the\n * opposite of what the default was written to prevent. An overload with no type\n * parameter has nothing to infer, so `s.json()` is `JsonValue` wherever it is\n * written.\n *\n * `ai:generate-client` maps it to the native `JSONValue` and says nothing about\n * it. `JsonValue` is a union of every JSON shape, so it used to reach the\n * generator's \"a union that is not told apart by one string member\" warning —\n * true, and a misdescription of a field that is free-form on purpose. The\n * extractor recognises it now.\n */\n json(): SchemaBuilder<JsonValue>;\n json<T>(): SchemaBuilder<T>;\n /**\n * A schema that contains itself — a tree of UI nodes, a comment thread, a\n * folder listing — and stays strict-mode safe, unlike `s.json()`.\n *\n * ```ts\n * type Node = { tag: string; text?: string; children: Node[] };\n *\n * const node = s.recursive<Node>(\"Node\", (self) =>\n * s.object({\n * tag: s.enum([\"section\", \"heading\", \"text\"]),\n * text: s.string().optional(),\n * children: s.array(self),\n * }),\n * );\n * const output = s.object({ title: s.string(), root: node });\n * ```\n *\n * Emitted the way OpenAI's strict structured output spells recursion: the\n * body once under the root's `$defs[name]`, and `{ \"$ref\": \"#/$defs/<name>\" }`\n * wherever it is used. Used as the root itself, the body is also inlined at\n * the root, since a tool's parameters and an agent's output must be an\n * object there. `parse`, `safeParse` and `validate` follow the reference to\n * any depth.\n *\n * `T` has to be written out: TypeScript cannot infer a type from a value\n * that mentions itself. The callback's schema is checked against it, so a\n * field the type has and the schema lacks (or the reverse) is a type error.\n *\n * Rules, each an error when the schema is built:\n *\n * - `name` is the `$defs` key: letters, digits, `_` and `-`. Two different\n * recursive schemas in one tool or output need different names.\n * - `self` must be nested inside an `s.object` field or an `s.array` — a\n * body that is `self` again through a union describes no finite value.\n * - The body cannot be `optional()`; make the uses optional instead\n * (`children: s.array(self).optional()`, `next: self.optional()`).\n *\n * Strict mode limits the rest as usual: every node of the body is in the\n * strict subset or the whole schema is sent non-strict (`supportsStrict`).\n */\n recursive<T>(name: string, define: (self: SchemaBuilder<T>) => Schema<T>): SchemaBuilder<T>;\n /**\n * A schema read from a JSON Schema at runtime — for a shape that comes from\n * data rather than code, like a collection whose items a user defined.\n *\n * Only the subset `s` itself models is accepted, so the result stays\n * strict-mode safe and can be a tool's `inputSchema` like any other:\n *\n * - `type`: `string`, `number`, `integer`, `boolean`, `object`, `array`,\n * or one of them with `\"null\"` (`[\"string\", \"null\"]`).\n * - `enum` (strings become `s.enum`, numbers and booleans a union of\n * literals; a `null` in it makes the field nullable), `const`, `anyOf`.\n * - strings: `minLength`, `maxLength`, `format` (checked with\n * `options.formats`). Numbers: `minimum`, `maximum`, `exclusiveMinimum`,\n * `exclusiveMaximum`. Arrays: `items` (one schema), `minItems`, `maxItems`.\n * - objects: `properties`, `required`, `additionalProperties: false`. A\n * property not in `required` is `optional()`.\n * - `description`; annotations (`title`, `default`, `examples`, `$schema`,\n * `x-*`, … and `options.ignoreKeywords`) are skipped.\n *\n * Anything else — `pattern`, `oneOf`, `allOf`, `$ref`, a tuple, an open\n * `additionalProperties`, an unknown `format` — throws a `JSONSchemaError`\n * listing every problem with its path.\n *\n * The length, range, item-count and format constraints are enforced by\n * `parse`/`safeParse`/`validate` and told to the model in the field's\n * description, because strict structured output does not accept them as\n * keywords. By default an unknown key in an object is dropped from the\n * parsed value rather than reported; pass `unknownKeys: \"error\"` to report\n * it as an `additionalProperties` issue (as Ajv does), or `\"passthrough\"`\n * to keep it.\n *\n * The output type is `JsonValue` (or the `T` you assert). Validate a value\n * with `.validate(value)` for per-path issues, or `.safeParse(value)`.\n */\n fromJSONSchema(schema: unknown, options?: FromJSONSchemaOptions): SchemaBuilder<JsonValue>;\n fromJSONSchema<T>(schema: unknown, options?: FromJSONSchemaOptions): SchemaBuilder<T>;\n} = {\n string: () => make<string>(leaf({ kind: \"string\" })),\n number: () => make<number>(leaf({ kind: \"number\" })),\n boolean: () => make<boolean>(leaf({ kind: \"boolean\" })),\n literal: (value) => make<typeof value>(leaf({ kind: \"literal\", value })),\n enum: (values) => make<(typeof values)[number]>(leaf({ kind: \"enum\", values })),\n object: (shape) =>\n make<ShapeOutput<typeof shape>>(\n leaf({\n kind: \"object\",\n shape: Object.fromEntries(\n Object.entries(shape).map(([key, child]) => [key, definitionOf(child)]),\n ),\n }),\n ),\n array: (item) => make<Infer<typeof item>[]>(leaf({ kind: \"array\", item: definitionOf(item) })),\n // A union is legal wherever a property is, but not as the root of a tool's\n // input or an agent's structured output: the provider wants an object there.\n // `s` cannot know where a schema will be used, so `AgentTool.create` and\n // `Agent.create` are what reject it at the root.\n union: (members) =>\n make<Infer<(typeof members)[number]>>(\n leaf({ kind: \"union\", members: members.map(definitionOf) }),\n ),\n json: <T>() => make<T>(leaf({ kind: \"json\" })),\n recursive,\n fromJSONSchema: <T>(schema: unknown, options: FromJSONSchemaOptions = {}) => {\n const problems: string[] = [];\n if (\n options.unknownKeys !== undefined &&\n !(UNKNOWN_KEYS as readonly unknown[]).includes(options.unknownKeys)\n ) {\n throw new Error(\n `gemi/ai: s.fromJSONSchema's unknownKeys option must be one of ${UNKNOWN_KEYS.map((v) => JSON.stringify(v)).join(\", \")}, got ${JSON.stringify(options.unknownKeys)}`,\n );\n }\n const definition = fromJSON(schema, options, \"\", problems);\n if (!definition || problems.length > 0) {\n throw new JSONSchemaError(problems.length > 0 ? problems : [\"unreadable schema\"]);\n }\n return make<T>(definition);\n },\n};\n\n/**\n * Whether a schema can be sent under a provider's strict mode.\n *\n * False exactly when a `json()` node is somewhere inside it. Strict mode's\n * bargain is that every node constrains its value; an unconstrained one has no\n * spelling there, and sending it anyway is a 400 naming a path.\n *\n * Derived from the tree rather than declared alongside it, because the two\n * would drift: a field added to a tool's input a year from now would need\n * whoever adds it to know that a flag somewhere else describes it. Adding the\n * field is the whole of turning strict off.\n */\nexport function supportsStrict(schema: AnySchema): boolean {\n const definition = definitions.get(schema);\n if (definition) return strictNode(definition.node);\n // A schema built by hand rather than with `s`: `questionSchema` in\n // `ai/Agent.ts`, and the merged one `services/mcp` casts together.\n //\n // Answering `true` here was wrong, and not harmlessly. `McpRegistry`'s\n // `combineSchemas` spreads `meta.input.toJSONSchema()` into its own object,\n // so an `s.json()` field an app declared on an `mcp` route survives into the\n // emitted schema while the *tree* that would have reported it is discarded.\n // Every MCP-projected tool was therefore sent `strict: true` with an empty\n // subschema inside it — a 400 on every turn, from the one path this function\n // exists to get right.\n //\n // So the emitted schema is read instead. It is the same question asked of the\n // artifact rather than the source, which is the only thing a foreign schema\n // has to offer.\n return strictJSONSchema(schema.toJSONSchema());\n}\n\n/**\n * Whether an already-emitted JSON Schema constrains every value it describes.\n *\n * Only for schemas with no definition tree. It answers a narrower question than\n * `strictNode` — it cannot see optionality or a builder's intent, just whether\n * some node says nothing about its value — but that is exactly the property\n * strict mode rejects, and it is visible in the artifact.\n */\nfunction strictJSONSchema(schema: JSONSchema): boolean {\n // `description` is prose, not a constraint. A node carrying only that — which\n // is what `s.json().describe(...)` emits — says nothing about its value.\n const constrained =\n schema.$ref !== undefined ||\n schema.type !== undefined ||\n schema.enum !== undefined ||\n schema.const !== undefined ||\n schema.anyOf !== undefined ||\n schema.properties !== undefined ||\n schema.items !== undefined;\n if (!constrained) return false;\n\n for (const child of Object.values(schema.properties ?? {})) {\n if (!strictJSONSchema(child)) return false;\n }\n if (schema.items && !strictJSONSchema(schema.items)) return false;\n for (const member of schema.anyOf ?? []) {\n if (!strictJSONSchema(member)) return false;\n }\n // A `$ref` is answered for by the `$defs` entry it points at, which is\n // checked here once rather than followed — following it is a cycle.\n for (const definition of Object.values(schema.$defs ?? {})) {\n if (!strictJSONSchema(definition)) return false;\n }\n return true;\n}\n\n/**\n * Enumerated rather than defaulted, so that a node kind added later cannot\n * inherit \"strict\" by omission — which is the failure that shows up as a 400\n * from the provider rather than as a type error here.\n *\n * The one cycle in a definition tree is an `s.recursive` reaching itself, so\n * `seen` holds the cells already being answered for: a body that is strict\n * apart from its references to itself is strict.\n */\nfunction strictNode(node: SchemaNode, seen = new Set<RecursiveCell>()): boolean {\n switch (node.kind) {\n case \"string\":\n case \"number\":\n case \"boolean\":\n case \"literal\":\n case \"enum\":\n return true;\n case \"object\":\n return Object.values(node.shape).every((child) => strictNode(child.node, seen));\n case \"array\":\n return strictNode(node.item.node, seen);\n case \"union\":\n return node.members.every((member) => strictNode(member.node, seen));\n case \"json\":\n return false;\n case \"ref\":\n if (seen.has(node.cell)) return true;\n seen.add(node.cell);\n return strictNode(bodyOf(node.cell).node, seen);\n }\n}\n\n/**\n * Whether `definition` can reach `cell` without an object property or an\n * array item in between — through a union member, or another recursive\n * schema's body. Such a schema describes no finite value (`Self = Self |\n * string` is just `string`), and reading one would recurse forever on a\n * primitive, where no object is there to catch the cycle with.\n */\nfunction reachesUnguarded(\n definition: Definition,\n cell: RecursiveCell,\n seen = new Set<RecursiveCell>(),\n): boolean {\n const node = definition.node;\n if (node.kind === \"union\") {\n return node.members.some((member) => reachesUnguarded(member, cell, seen));\n }\n if (node.kind !== \"ref\") return false;\n if (node.cell === cell) return true;\n if (seen.has(node.cell) || !node.cell.definition) return false;\n seen.add(node.cell);\n return reachesUnguarded(node.cell.definition, cell, seen);\n}\n\nconst RECURSIVE_NAME = /^[A-Za-z_][A-Za-z0-9_-]{0,63}$/;\n\nfunction recursive<T>(\n name: string,\n define: (self: SchemaBuilder<T>) => Schema<T>,\n): SchemaBuilder<T> {\n if (typeof name !== \"string\" || !RECURSIVE_NAME.test(name)) {\n throw new Error(\n `gemi/ai: s.recursive needs a name of letters, digits, \"_\" and \"-\" (starting with a letter or \"_\", at most 64), got ${JSON.stringify(name)}`,\n );\n }\n const cell: RecursiveCell = { name, active: new Set() };\n const reference = (): Definition => leaf({ kind: \"ref\", cell });\n const body = definitionOf(define(make<T>(reference())));\n if (body.optional) {\n throw new Error(\n `gemi/ai: the recursive schema \"${name}\" is optional() as a whole; mark the places that use it optional instead`,\n );\n }\n if (reachesUnguarded(body, cell)) {\n throw new Error(\n `gemi/ai: the recursive schema \"${name}\" refers to itself outside any object or array, so it describes no finite value; nest \\`self\\` in an s.object(...) field or an s.array(...)`,\n );\n }\n cell.definition = body;\n return make<T>(reference());\n}\n"
|
|
5
|
+
"/**\n * The schema layer for tool inputs, tool outputs and structured final answers.\n *\n * Two things have to come out of one declaration: a TypeScript type, so\n * `execute(input)` is typed at the call site and the result is typed in the\n * browser, and a JSON Schema, because that is what the model is actually shown.\n * A phantom `Schema<T>` gives the first and nothing of the second, and a\n * hand-written JSON Schema next to a hand-written type gives both and lets them\n * drift. So the builder below is the single source, and `Infer` reads the type\n * back off it.\n *\n * Everything here is deliberately narrower than JSON Schema. OpenAI's strict\n * structured output only accepts a subset — every property listed in\n * `required`, `additionalProperties: false` on every object, no patterns, no\n * `oneOf` at the root — and a builder that cannot express the rejected parts is\n * better than one that lets you write a schema the API refuses at runtime.\n *\n * `json()` is the one deliberate hole in that, for the formats strict mode\n * cannot describe at all: a record with arbitrary keys, a mixed-type tuple. It\n * does not widen the subset — it turns strict mode off for the schema containing\n * it, which `supportsStrict` reads back off the tree so that no caller has to\n * remember to.\n *\n * A document that nests into itself is NOT one of those: strict mode accepts\n * `$defs` + `$ref`, and `recursive()` emits exactly that (#745).\n */\n\nexport type JSONSchema = {\n type?: string | string[];\n description?: string;\n enum?: readonly (string | number)[];\n const?: string | number | boolean;\n properties?: Record<string, JSONSchema>;\n required?: readonly string[];\n additionalProperties?: false;\n items?: JSONSchema;\n anyOf?: readonly JSONSchema[];\n /**\n * `#/$defs/<name>`, pointing at an entry of the root's `$defs`. Emitted by\n * `s.recursive` and never with a sibling keyword: OpenAI's strict mode\n * refuses `{ $ref, description }`, so a described or nullable reference is\n * wrapped in an `anyOf` instead.\n */\n $ref?: string;\n /** Only ever on the root: every `s.recursive` the schema reaches, by name. */\n $defs?: Record<string, JSONSchema>;\n};\n\n/**\n * Any value JSON can carry. The default output type of `json()`, and the\n * annotation an app reaches for when it hands one of those values on.\n */\nexport type JsonValue =\n | string\n | number\n | boolean\n | null\n | JsonValue[]\n | { [key: string]: JsonValue };\n\ndeclare const OUTPUT: unique symbol;\ndeclare const OPTIONAL: unique symbol;\n\n/**\n * `T` is carried in a phantom property rather than a real one: it exists only\n * for inference, and a real field would show up on the object the app writes.\n */\nexport interface Schema<T> {\n readonly [OUTPUT]: T;\n /** The JSON Schema handed to the provider. */\n toJSONSchema(): JSONSchema;\n /**\n * Parses a value coming back from the model. Tool arguments arrive as a JSON\n * string the model generated, so they are untrusted in exactly the way a\n * request body is: shape-checked before `execute` ever sees them.\n */\n parse(value: unknown): T;\n safeParse(value: unknown): { ok: true; value: T } | { ok: false; errors: string[] };\n}\n\n/**\n * A schema whose key may be left out of the object containing it.\n *\n * Marked with a property rather than detected from the output type, because\n * `undefined extends T` — the obvious test — is true of *everything* when\n * `strictNullChecks` is off, which is how this package and plenty of apps\n * compile. That version made every field of every tool optional, and did it\n * quietly: the JSON Schema was still right, so only the TypeScript types lied.\n */\nexport interface OptionalSchema<T> extends Schema<T | undefined> {\n readonly [OPTIONAL]: true;\n}\n\nexport type AnySchema = Schema<any>;\n\nexport type Infer<S> = S extends Schema<infer T> ? T : never;\n\n/**\n * Collapses a type into one flat object.\n *\n * `ShapeOutput` builds its result as an intersection of two mapped types, one\n * required and one optional, and that intersection is what every hover, every\n * error message and every type assertion would otherwise show. The difference\n * is between an app reading `{ command: string; cwd?: string }` and reading two\n * mapped types joined by an ampersand.\n *\n * It also drops `readonly`, which the mapped types copy from the shape literal\n * — `s.object({ ... })` infers that literal as `const` to keep the keys, and a\n * tool has no reason to receive an immutable input because of how its schema\n * was written down.\n */\ntype Flatten<T> = { -readonly [K in keyof T]: T[K] };\n\ntype ShapeOutput<S extends Record<string, AnySchema>> = Flatten<\n {\n [K in keyof S as S[K] extends OptionalSchema<any> ? never : K]: Infer<S[K]>;\n } & {\n [K in keyof S as S[K] extends OptionalSchema<any> ? K : never]?: Infer<S[K]>;\n }\n>;\n\ninterface SchemaBuilder<T> extends Schema<T> {\n /**\n * The description is not documentation — it is the only prose the model gets\n * about a field, and it is the difference between a tool that is called\n * correctly and one that is not.\n */\n describe(description: string): this;\n /**\n * Strict mode has no notion of an omitted key: every property must appear in\n * `required`. So `optional()` emits a nullable union and the model is told to\n * send `null`, while the TypeScript type says `| undefined` and the parsed\n * value drops the key. The asymmetry is the point — it is what lets an app\n * write ordinary optional fields against an API that forbids them.\n */\n optional(): OptionalSchemaBuilder<T>;\n nullable(): SchemaBuilder<T | null>;\n /**\n * `safeParse` with the failures as structured issues rather than sentences:\n * each one names the path it is about, a JSON Schema keyword as its `code`\n * and the keyword's argument in `params`. For an app that validates a value\n * against a schema itself — a form, a stored record — and wants to word or\n * group the problems per field. All failures are reported, not the first.\n */\n validate(value: unknown): { ok: true; value: T } | { ok: false; issues: SchemaIssue[] };\n}\n\n/**\n * One reason a value failed `validate`.\n *\n * `code` is the JSON Schema keyword the value broke — the same names Ajv puts\n * on its `keyword` — so a mapping written against one reads the other:\n *\n * - `required`: the key is missing (`path` ends in it).\n * - `type`: the wrong kind of value, an integer that isn't whole, or a value\n * that isn't JSON at all.\n * - `const`, `enum`: a literal or a choice that didn't match (`params.allowedValues`).\n * - `minLength`, `maxLength`, `minimum`, `maximum`, `exclusiveMinimum`,\n * `exclusiveMaximum`, `minItems`, `maxItems`: `params.limit` is the bound.\n * - `format`: `params.format` names the format the string failed.\n * - `anyOf`: no union member matched; `message` names the closest one's problems.\n * - `additionalProperties`: a key the object doesn't declare, reported only by\n * a schema built with `s.fromJSONSchema(schema, { unknownKeys: \"error\" })`.\n * `path` ends in the key (Ajv's `instancePath` stops at the object), and\n * `params.additionalProperty` is the key, as in Ajv.\n *\n * `message` is the sentence `safeParse` reports for it, without the path.\n */\nexport type SchemaIssueCode =\n | \"required\"\n | \"type\"\n | \"const\"\n | \"enum\"\n | \"anyOf\"\n | \"minLength\"\n | \"maxLength\"\n | \"minimum\"\n | \"maximum\"\n | \"exclusiveMinimum\"\n | \"exclusiveMaximum\"\n | \"minItems\"\n | \"maxItems\"\n | \"format\"\n | \"additionalProperties\";\n\nexport type SchemaIssue = {\n /** Keys and array indices from the root, `[]` for the root itself. */\n path: (string | number)[];\n code: SchemaIssueCode;\n message: string;\n params: Record<string, unknown>;\n};\n\ninterface OptionalSchemaBuilder<T> extends SchemaBuilder<T | undefined>, OptionalSchema<T> {}\n\n// --- the runtime ---------------------------------------------------------\n\n/**\n * What a builder actually is. `optional` and `nullable` are flags rather than\n * wrapper nodes so that `.nullable().optional()` cannot nest into something\n * whose emitted shape depends on which order they were called in.\n */\ntype Definition = {\n node: SchemaNode;\n description?: string;\n optional: boolean;\n nullable: boolean;\n};\n\n/**\n * The constraints `s.fromJSONSchema` can carry over from a JSON Schema. None of\n * the builders set them; they exist so that a schema read from data validates\n * what it says it does.\n *\n * They are CHECKED, NOT EMITTED as keywords. Strict structured output refuses\n * most of them (`minLength`, `maxLength`, `minimum` on Anthropic; any `format`\n * outside a short list on both), so the model is told them in the field's\n * description instead, and `parse` enforces them — a model that ignores the\n * prose gets an `invalid_tool_input` it can correct, the same as a wrong type.\n */\ntype StringChecks = {\n minLength?: number;\n maxLength?: number;\n format?: { name: string; test: (value: string) => boolean };\n};\n\ntype NumberChecks = {\n integer?: boolean;\n minimum?: number;\n maximum?: number;\n exclusiveMinimum?: number;\n exclusiveMaximum?: number;\n};\n\ntype ArrayChecks = { minItems?: number; maxItems?: number };\n\ntype SchemaNode =\n | { kind: \"string\"; checks?: StringChecks }\n | { kind: \"number\"; checks?: NumberChecks }\n | { kind: \"boolean\" }\n | { kind: \"literal\"; value: string | number | boolean }\n | { kind: \"enum\"; values: readonly string[]; checks?: StringChecks }\n /**\n * `unknownKeys` is what parsing does with a key `shape` doesn't declare:\n * absent is \"strip\", the default and the only thing the builders make. Only\n * `s.fromJSONSchema` sets the others. Emission ignores it: every object is\n * sent with `additionalProperties: false` either way.\n */\n | { kind: \"object\"; shape: Record<string, Definition>; unknownKeys?: \"error\" | \"passthrough\" }\n | { kind: \"array\"; item: Definition; checks?: ArrayChecks }\n | { kind: \"union\"; members: readonly Definition[] }\n /** Constrains nothing. The node strict mode has no spelling for. */\n | { kind: \"json\" }\n /**\n * A use of an `s.recursive` schema — its `self`, or the builder it returned.\n * Emitted as a `$ref` into the root's `$defs`, read by following the cell.\n */\n | { kind: \"ref\"; cell: RecursiveCell };\n\n/**\n * One `s.recursive` declaration. `definition` is filled in once the callback\n * returns; until then `self` is a reference to something that does not exist\n * yet, which is the whole trick.\n *\n * `active` is the set of values being read through this cell right now, the\n * cycle guard for a JavaScript value that contains itself (a tool output an app\n * built). Per cell rather than global, so that one value read through two\n * different recursive schemas in a row is not mistaken for a cycle.\n */\ntype RecursiveCell = {\n name: string;\n definition?: Definition;\n active: Set<object>;\n};\n\nfunction bodyOf(cell: RecursiveCell): Definition {\n if (!cell.definition) {\n throw new Error(\n `gemi/ai: the recursive schema \"${cell.name}\" was used before its definition returned; \\`self\\` can be nested into the schema, but not parsed or emitted inside the callback`,\n );\n }\n return cell.definition;\n}\n\ntype ParseResult = { ok: true; value: unknown } | { ok: false; errors: string[] };\n\ntype Path = (string | number)[];\n\n/** The public interface with the phantoms and the generic taken off. */\ninterface RuntimeSchema {\n toJSONSchema(): JSONSchema;\n parse(value: unknown): unknown;\n safeParse(value: unknown): ParseResult;\n validate(value: unknown): { ok: true; value: unknown } | { ok: false; issues: SchemaIssue[] };\n describe(description: string): RuntimeSchema;\n optional(): RuntimeSchema;\n nullable(): RuntimeSchema;\n}\n\n/**\n * Definitions hang off the builders here rather than on the builders\n * themselves: a property, however obscurely named, is a property an app can\n * see, serialise or accidentally depend on, and `Schema<T>` promises exactly\n * three methods.\n */\nconst definitions = new WeakMap<object, Definition>();\n\n/**\n * Whether `value` is a schema built with `s`. How `HttpRequest` tells an `s`\n * body schema from a map of rules (#711), without a property on the builder.\n */\nexport function isSchema(value: unknown): value is SchemaBuilder<unknown> {\n return typeof value === \"object\" && value !== null && definitions.has(value);\n}\n\nfunction definitionOf(schema: AnySchema): Definition {\n const definition = definitions.get(schema);\n if (!definition) {\n throw new Error(\"gemi/ai: expected a schema built with `s`, got a foreign object\");\n }\n return definition;\n}\n\n// --- emitting ------------------------------------------------------------\n\n/**\n * What one `toJSONSchema()` call collects on its way down: the `$defs` the\n * root will carry, and which cell owns each name in them.\n */\ntype EmitContext = {\n defs: Record<string, JSONSchema>;\n cells: Map<string, RecursiveCell>;\n};\n\n/**\n * The schema as the provider sees it: the tree, plus `$defs` at the root when\n * an `s.recursive` is anywhere in it.\n *\n * A recursive schema used AS the root is inlined there, and its `$defs` entry\n * is a second copy of the same body. Pointing the root at itself with\n * `\"$ref\": \"#\"` would be shorter, and OpenAI accepts it, but `#` means \"the\n * whole document\" — and a document that gets merged into (MCP's\n * `combineSchemas` adds properties to an input's root) would then demand the\n * merged-in fields at every level of the tree.\n */\nfunction emitRoot(definition: Definition): JSONSchema {\n const context: EmitContext = { defs: {}, cells: new Map() };\n let root = definition;\n if (definition.node.kind === \"ref\") {\n const body = bodyOf(definition.node.cell);\n root = {\n ...body,\n ...(definition.description ? { description: definition.description } : {}),\n optional: definition.optional,\n nullable: definition.nullable || body.nullable,\n };\n }\n const schema = emit(root, context);\n return Object.keys(context.defs).length > 0 ? { ...schema, $defs: context.defs } : schema;\n}\n\nfunction emit(definition: Definition, context: EmitContext): JSONSchema {\n // A `json` node already admits every value there is, null included, so\n // widening it would only add an `anyOf` for the model to read past — and one\n // whose second branch is a strictly narrower repeat of its first.\n const widen = (definition.optional || definition.nullable) && definition.node.kind !== \"json\";\n let body = allowNull(emitNode(definition.node, context), widen);\n const description = [definition.description, hint(definition.node)].filter(Boolean).join(\" \");\n // `$ref` takes no siblings under strict mode, so a described reference\n // becomes a one-member `anyOf` that can carry the description beside it.\n if (description && body.$ref !== undefined) body = { anyOf: [body] };\n return description ? { description, ...body } : body;\n}\n\n/**\n * The checks a node carries, in words, for the description — the one place a\n * strict-mode provider lets them through. See `StringChecks`.\n */\nfunction hint(node: SchemaNode): string {\n const said: string[] = [];\n if (node.kind === \"string\" || node.kind === \"enum\") {\n const checks = node.checks;\n if (checks?.format) said.push(`Format: ${checks.format.name}.`);\n if (checks?.minLength !== undefined) said.push(`At least ${checks.minLength} characters.`);\n if (checks?.maxLength !== undefined) said.push(`At most ${checks.maxLength} characters.`);\n } else if (node.kind === \"number\") {\n const checks = node.checks;\n if (checks?.minimum !== undefined) said.push(`Minimum ${checks.minimum}.`);\n if (checks?.exclusiveMinimum !== undefined) {\n said.push(`Greater than ${checks.exclusiveMinimum}.`);\n }\n if (checks?.maximum !== undefined) said.push(`Maximum ${checks.maximum}.`);\n if (checks?.exclusiveMaximum !== undefined) said.push(`Less than ${checks.exclusiveMaximum}.`);\n } else if (node.kind === \"array\") {\n const checks = node.checks;\n if (checks?.minItems !== undefined) said.push(`At least ${checks.minItems} items.`);\n if (checks?.maxItems !== undefined) said.push(`At most ${checks.maxItems} items.`);\n }\n // A `ref` says nothing of its own: its body's hints are in its `$defs` entry.\n return said.join(\" \");\n}\n\nfunction emitNode(node: SchemaNode, context: EmitContext): JSONSchema {\n switch (node.kind) {\n case \"string\":\n return { type: \"string\" };\n case \"number\":\n // `integer` is in the strict subset of every provider gemi speaks to.\n return { type: node.checks?.integer ? \"integer\" : \"number\" };\n case \"boolean\":\n return { type: \"boolean\" };\n // `const` rather than a one-member `enum`, because a boolean literal has no\n // `enum` form and one branch that works for all three beats two that\n // disagree about what a literal is.\n case \"literal\":\n return { type: typeof node.value, const: node.value };\n case \"enum\":\n return { type: \"string\", enum: node.values };\n case \"array\":\n return { type: \"array\", items: emit(node.item, context) };\n case \"object\":\n return {\n type: \"object\",\n properties: Object.fromEntries(\n Object.entries(node.shape).map(([key, child]) => [key, emit(child, context)]),\n ),\n // Every declared property, optional ones included. This is the whole of\n // strict mode's bargain: the model is never allowed to omit a key, so\n // \"may be absent\" has to be spelled as \"may be null\" instead.\n required: Object.keys(node.shape),\n additionalProperties: false,\n };\n case \"union\":\n return { anyOf: node.members.map((member) => emit(member, context)) };\n // The empty schema, which is JSON Schema's own way of saying \"any value\" —\n // no `type` listing all seven, which reads as a constraint the model then\n // has to check itself. What the field actually is gets said in\n // `description`, the one channel a model reads either way.\n case \"json\":\n return {};\n case \"ref\": {\n const { cell } = node;\n const owner = context.cells.get(cell.name);\n if (owner && owner !== cell) {\n throw new Error(\n `gemi/ai: two different recursive schemas are named \"${cell.name}\" in one schema; give each s.recursive(...) its own name`,\n );\n }\n if (!owner) {\n // Claimed BEFORE the body is emitted: the body refers to itself, and\n // that inner reference has to find the name taken and stop here.\n context.cells.set(cell.name, cell);\n context.defs[cell.name] = {};\n context.defs[cell.name] = emit(bodyOf(cell), context);\n }\n return { $ref: `#/$defs/${cell.name}` };\n }\n }\n}\n\n/**\n * Widens a schema to admit `null` — for a `nullable()` field, and for the null\n * an `optional()` field tells the model to send in place of omitting the key.\n */\nfunction allowNull(base: JSONSchema, on: boolean): JSONSchema {\n if (!on) return base;\n // A union is already a list of alternatives; appending to it is flatter than\n // nesting an `anyOf` inside an `anyOf`, and reads the same to the model.\n if (base.anyOf) return { ...base, anyOf: [...base.anyOf, { type: \"null\" }] };\n // `enum` and `const` cannot carry the null themselves — `enum` here is\n // strings and numbers by declaration — so those get wrapped rather than\n // widened.\n if (base.enum || base.const !== undefined) return { anyOf: [base, { type: \"null\" }] };\n if (typeof base.type === \"string\") return { ...base, type: [base.type, \"null\"] };\n return { anyOf: [base, { type: \"null\" }] };\n}\n\n// --- parsing -------------------------------------------------------------\n\nfunction typeName(value: unknown): string {\n if (value === null) return \"null\";\n if (Array.isArray(value)) return \"array\";\n return typeof value;\n}\n\n/**\n * What the value looked like. For a literal or an enum the *type* is usually\n * right and the value is wrong, and \"expected \\\"refund\\\", got string\" tells\n * whoever is reading the failed tool call nothing they did not know.\n */\nfunction saw(node: SchemaNode, value: unknown): string {\n if (typeof value === \"number\" && !Number.isFinite(value)) return String(value);\n if (node.kind === \"literal\" || node.kind === \"enum\") {\n const primitive =\n typeof value === \"string\" || typeof value === \"number\" || typeof value === \"boolean\";\n if (primitive) return JSON.stringify(value);\n }\n return typeName(value);\n}\n\nfunction wanted(definition: Definition): string {\n const node = definition.node;\n const base = (() => {\n switch (node.kind) {\n case \"number\":\n return node.checks?.integer ? \"integer\" : \"number\";\n case \"string\":\n case \"boolean\":\n return node.kind;\n case \"literal\":\n return JSON.stringify(node.value);\n case \"enum\":\n return `one of ${node.values.map((v) => JSON.stringify(v)).join(\" | \")}`;\n case \"array\":\n return \"array\";\n case \"object\":\n return \"object\";\n case \"union\":\n return \"one of the variants\";\n case \"json\":\n return \"a JSON value\";\n case \"ref\":\n return wanted({ ...bodyOf(node.cell), optional: false, nullable: false });\n }\n })();\n return definition.optional || definition.nullable ? `${base} or null` : base;\n}\n\n/** `orders[2].total` — keys joined with dots, indices in brackets. */\nfunction formatPath(path: Path): string {\n let out = \"\";\n for (const segment of path) {\n out += typeof segment === \"number\" ? `[${segment}]` : out ? `.${segment}` : segment;\n }\n return out;\n}\n\n/** `orders[2].total: ` — empty at the root, where a prefix would be noise. */\nfunction at(path: Path): string {\n const text = formatPath(path);\n return text ? `${text}: ` : \"\";\n}\n\n/** The sentence `safeParse` reports for an issue. */\nfunction render(issue: SchemaIssue): string {\n return `${at(issue.path)}${issue.message}`;\n}\n\n/**\n * How well a value matches, used only to pick which union variant to blame.\n * A literal or an enum hit counts for far more than an ordinary field, because\n * that is what a discriminated union turns on: the variant whose `kind` matched\n * is the one the model meant, whatever else it got wrong.\n */\nfunction score(definition: Definition, value: unknown): number {\n if (value === null || value === undefined) {\n return definition.optional || definition.nullable ? 1 : 0;\n }\n const node = definition.node;\n switch (node.kind) {\n case \"string\":\n return typeof value === \"string\" ? 1 : 0;\n case \"number\":\n return typeof value === \"number\" ? 1 : 0;\n case \"boolean\":\n return typeof value === \"boolean\" ? 1 : 0;\n case \"literal\":\n return value === node.value ? 10 : 0;\n case \"enum\":\n return typeof value === \"string\" && node.values.includes(value) ? 10 : 0;\n case \"array\":\n return Array.isArray(value) ? 1 : 0;\n case \"object\": {\n if (typeof value !== \"object\" || Array.isArray(value)) return 0;\n const source = value as Record<string, unknown>;\n let total = 1;\n for (const [key, child] of Object.entries(node.shape)) {\n total += score(child, source[key]);\n }\n return total;\n }\n case \"union\":\n return node.members.reduce((best, member) => Math.max(best, score(member, value)), 0);\n // Matches, because it matches everything — but at the score of a plain\n // scalar, so a sibling variant that pinned its discriminant still wins the\n // blame.\n //\n // Reached only when no member parsed, which for a `json` member means the\n // value is not JSON at all: a function, a bigint, a cycle. Then this is\n // what makes the report name the reason the value was refused rather than\n // the discriminant of a variant the model was never aiming at.\n case \"json\":\n return 1;\n case \"ref\":\n return through(\n node.cell,\n value,\n () => 1,\n () => score(bodyOf(node.cell), value),\n );\n }\n}\n\n/**\n * Runs `walk` with `value` marked as being read through `cell`, or `cycle` when\n * it already is. A value can only meet the same cell again further down by\n * containing itself — `s.recursive` refuses a body that reaches `self` without\n * an object or array in between — so this is exactly the cycle guard, and a\n * value that merely appears twice side by side is read twice.\n */\nfunction through<R>(cell: RecursiveCell, value: unknown, cycle: () => R, walk: () => R): R {\n if (typeof value !== \"object\" || value === null) return walk();\n if (cell.active.has(value)) return cycle();\n cell.active.add(value);\n try {\n return walk();\n } finally {\n cell.active.delete(value);\n }\n}\n\n/** `drop` is a key that should not appear in the parsed object at all. */\ntype Reading = { drop: boolean; value: unknown };\n\nfunction read(definition: Definition, value: unknown, path: Path, issues: SchemaIssue[]): Reading {\n // `optional` is checked before `nullable`, so a schema that is both treats\n // null as \"absent\". They are not distinguishable on the wire: strict mode\n // gives the model one spelling for \"nothing\", and pretending otherwise would\n // mean `.nullable().optional()` silently kept a key the type says is\n // optional. What that trades away is the ability to say \"present and null\" on\n // a field that may also be absent — a distinction no model can express here.\n if (definition.optional && (value === null || value === undefined)) {\n return { drop: true, value: undefined };\n }\n if (definition.nullable && value === null) return { drop: false, value: null };\n return { drop: false, value: readNode(definition, value, path, issues) };\n}\n\nfunction readNode(\n definition: Definition,\n value: unknown,\n path: Path,\n issues: SchemaIssue[],\n): unknown {\n const node = definition.node;\n const fail = () => {\n const code: SchemaIssueCode =\n value === undefined\n ? \"required\"\n : node.kind === \"literal\"\n ? \"const\"\n : node.kind === \"enum\" && typeof value === \"string\"\n ? \"enum\"\n : \"type\";\n const params =\n code === \"const\"\n ? { allowedValue: (node as { value: unknown }).value }\n : code === \"enum\"\n ? { allowedValues: (node as { values: readonly string[] }).values }\n : {};\n issues.push({\n path,\n code,\n message: `expected ${wanted(definition)}, got ${saw(node, value)}`,\n params,\n });\n return undefined;\n };\n\n switch (node.kind) {\n case \"string\":\n if (typeof value !== \"string\") return fail();\n checkString(node.checks, value, path, issues);\n return value;\n case \"number\":\n // NaN and Infinity do not survive `JSON.stringify`, so a tool that\n // returns one produces a body the provider cannot be sent.\n if (typeof value !== \"number\" || !Number.isFinite(value)) return fail();\n if (node.checks?.integer && !Number.isInteger(value)) return fail();\n checkNumber(node.checks, value, path, issues);\n return value;\n case \"boolean\":\n return typeof value === \"boolean\" ? value : fail();\n case \"literal\":\n return value === node.value ? value : fail();\n case \"enum\":\n if (typeof value !== \"string\" || !node.values.includes(value)) return fail();\n checkString(node.checks, value, path, issues);\n return value;\n case \"array\": {\n if (!Array.isArray(value)) return fail();\n const items = value.map((item, index) => {\n const element = read(node.item, item, [...path, index], issues);\n return element.drop ? undefined : element.value;\n });\n const { minItems, maxItems } = node.checks ?? {};\n if (minItems !== undefined && value.length < minItems) {\n issues.push({\n path,\n code: \"minItems\",\n message: `expected at least ${minItems} items, got ${value.length}`,\n params: { limit: minItems },\n });\n }\n if (maxItems !== undefined && value.length > maxItems) {\n issues.push({\n path,\n code: \"maxItems\",\n message: `expected at most ${maxItems} items, got ${value.length}`,\n params: { limit: maxItems },\n });\n }\n return items;\n }\n case \"object\": {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) return fail();\n const source = value as Record<string, unknown>;\n const output: Record<string, unknown> = {};\n for (const [key, child] of Object.entries(node.shape)) {\n const element = read(child, source[key], [...path, key], issues);\n if (!element.drop) output[key] = element.value;\n }\n // By default unknown keys are DROPPED, not rejected. `additionalProperties:\n // false` has already told the model not to send them, so one arriving\n // anyway is a slip rather than an attack, and failing a whole tool call\n // over a stray field costs a turn to fix nothing. Dropping is also what\n // keeps `execute` from ever seeing a field its input type says cannot be\n // there.\n //\n // A schema read from data can ask otherwise (#753): a form submission\n // with a field the form doesn't have is a bot or a stale page, and\n // dropping it loses what the visitor typed without telling them.\n if (node.unknownKeys) {\n for (const key of Object.keys(source)) {\n // `undefined` is absent, the same as for `required`: JSON cannot\n // carry it, and `JSON.stringify` leaves the key out.\n if (Object.hasOwn(node.shape, key) || source[key] === undefined) continue;\n if (node.unknownKeys === \"error\") {\n issues.push({\n path: [...path, key],\n code: \"additionalProperties\",\n message: \"unknown key\",\n params: { additionalProperty: key },\n });\n continue;\n }\n // Kept as it came, checked only for being JSON — there is no schema\n // to read it with. Defined rather than assigned, so that a\n // `__proto__` key from `JSON.parse` stays a key instead of setting\n // the output's prototype.\n checkJson(source[key], [...path, key], issues, new Set());\n Object.defineProperty(output, key, {\n value: source[key],\n enumerable: true,\n writable: true,\n configurable: true,\n });\n }\n }\n return output;\n }\n case \"union\": {\n let best: { issues: SchemaIssue[]; score: number } | undefined;\n for (const member of node.members) {\n const attempt: SchemaIssue[] = [];\n const element = read(member, value, path, attempt);\n if (attempt.length === 0) return element.drop ? undefined : element.value;\n const points = score(member, value);\n if (!best || points > best.score) best = { issues: attempt, score: points };\n }\n // \"no match\" is useless when one field of a five-field variant was wrong.\n // Naming the closest variant and why it stopped is the difference between\n // a debuggable bad tool call and a shrug.\n issues.push({\n path,\n code: \"anyOf\",\n message: `no matching variant; closest: ${best!.issues.map(render).join(\"; \")}`,\n params: { closest: best!.issues },\n });\n return undefined;\n }\n // Passed through by reference, not rebuilt. Two reasons beyond the obvious\n // one: a rebuild would turn a `Date` into `{}` by copying own properties\n // that a `toJSON` was going to replace anyway, and the agent loop signs the\n // *parsed* input and later verifies the signature against it — a parse that\n // is exactly the identity cannot disagree with itself.\n case \"json\":\n if (value === undefined) return fail();\n checkJson(value, path, issues, new Set());\n return value;\n // The reference's own `optional`/`nullable` were settled by `read` above;\n // the body's are its own business, settled by the `read` below.\n case \"ref\":\n return through(\n node.cell,\n value,\n () => {\n issues.push({\n path,\n code: \"type\",\n message: \"expected a finite tree, got a circular reference\",\n params: {},\n });\n return undefined;\n },\n () => read(bodyOf(node.cell), value, path, issues).value,\n );\n }\n}\n\n/**\n * Length in code points, not UTF-16 units — what JSON Schema (and Ajv) count,\n * so an emoji is one character against a `maxLength` either way.\n */\nfunction length(value: string): number {\n let count = 0;\n for (const _ of value) count++;\n return count;\n}\n\nfunction checkString(\n checks: StringChecks | undefined,\n value: string,\n path: Path,\n issues: SchemaIssue[],\n): void {\n if (!checks) return;\n const { minLength, maxLength, format } = checks;\n if (minLength !== undefined || maxLength !== undefined) {\n const size = length(value);\n if (minLength !== undefined && size < minLength) {\n issues.push({\n path,\n code: \"minLength\",\n message: `expected at least ${minLength} characters, got ${size}`,\n params: { limit: minLength },\n });\n }\n if (maxLength !== undefined && size > maxLength) {\n issues.push({\n path,\n code: \"maxLength\",\n message: `expected at most ${maxLength} characters, got ${size}`,\n params: { limit: maxLength },\n });\n }\n }\n if (format) {\n let ok = false;\n try {\n ok = format.test(value) === true;\n } catch {\n // A check that throws has not said yes.\n }\n if (!ok) {\n issues.push({\n path,\n code: \"format\",\n message: `expected a string in format \"${format.name}\"`,\n params: { format: format.name },\n });\n }\n }\n}\n\nfunction checkNumber(\n checks: NumberChecks | undefined,\n value: number,\n path: Path,\n issues: SchemaIssue[],\n): void {\n if (!checks) return;\n const bound = (\n code: SchemaIssueCode,\n limit: number | undefined,\n passes: (limit: number) => boolean,\n words: string,\n ) => {\n if (limit === undefined || passes(limit)) return;\n issues.push({\n path,\n code,\n message: `expected ${words} ${limit}, got ${value}`,\n params: { limit },\n });\n };\n bound(\"minimum\", checks.minimum, (limit) => value >= limit, \"at least\");\n bound(\"exclusiveMinimum\", checks.exclusiveMinimum, (limit) => value > limit, \"more than\");\n bound(\"maximum\", checks.maximum, (limit) => value <= limit, \"at most\");\n bound(\"exclusiveMaximum\", checks.exclusiveMaximum, (limit) => value < limit, \"less than\");\n}\n\n/**\n * Checks that a value is JSON, which is the only check a `json()` node makes.\n *\n * Tool arguments arrive through `JSON.parse`, so this never fires on model\n * input. It fires on a tool *output* or a structured answer an app built, where\n * a `bigint` or a cycle throws inside `JSON.stringify` and a function or a\n * `symbol` is dropped without a word — one turn later, with the provider's\n * request body to debug instead of the value.\n *\n * `undefined` and non-plain objects are deliberately allowed below the root:\n * `JSON.stringify` drops an `undefined` property, writes `null` for an\n * `undefined` element, and calls `toJSON` where there is one. Those are JSON's\n * own answers, and rejecting a `Date` to catch a `Map` is a bad trade.\n *\n * `toJSON` is honoured rather than assumed harmless: the walk checks what it\n * returns and never the object behind it, because that is all `JSON.stringify`\n * will look at.\n */\nfunction checkJson(\n value: unknown,\n path: Path,\n issues: SchemaIssue[],\n seen: Set<object>,\n // False for the value a `toJSON` just returned: `JSON.stringify` applies\n // `toJSON` once per position, and re-applying it is how a pair of them\n // returning each other became an infinite loop.\n applyToJSON = true,\n): void {\n const reject = (what: string) => {\n issues.push({ path, code: \"type\", message: `expected a JSON value, got ${what}`, params: {} });\n };\n\n switch (typeof value) {\n case \"undefined\":\n case \"string\":\n case \"boolean\":\n return;\n case \"number\":\n if (!Number.isFinite(value)) reject(String(value));\n return;\n case \"bigint\":\n return reject(\"a bigint\");\n case \"function\":\n return reject(\"a function\");\n case \"symbol\":\n return reject(\"a symbol\");\n }\n\n if (value === null) return;\n const object = value as object;\n\n // The cycle guard comes FIRST, above `toJSON`, and that ordering is the whole\n // of it: a `toJSON` is arbitrary code that can hand back another object with a\n // `toJSON` of its own, so two of them returning each other is a cycle that\n // `seen` catches and an identity test cannot. Below the guard, that pair hung\n // `safeParse` forever — and a `toJSON` returning a fresh object each time threw\n // `RangeError` out of a function documented to return `{ ok: false, errors }`.\n if (seen.has(object)) return reject(\"a circular reference\");\n seen.add(object);\n try {\n // `JSON.stringify` asks `toJSON` what to write and never looks at the object\n // itself, so that answer is what has to be checked. Without this the walk\n // descended into the wrapper's own fields and refused values `stringify`\n // serializes without complaint — a `toJSON` returning a string off a `bigint`\n // field being the archetype, since writing a `toJSON` is exactly what one\n // does about a field JSON cannot carry. `Date` passed only by having no own\n // enumerable properties to trip over.\n const toJSON = applyToJSON ? (object as { toJSON?: unknown }).toJSON : undefined;\n if (typeof toJSON === \"function\") {\n let replaced: unknown;\n try {\n replaced = (toJSON as (key?: string) => unknown).call(object);\n } catch {\n return reject(\"a toJSON that threw\");\n }\n // `JSON.stringify` applies `toJSON` once per value position, not until it\n // stops changing, so the replacement is checked with it switched off here\n // — its nested values get their own.\n if (replaced === undefined) return reject(\"a toJSON that returns undefined\");\n return checkJson(replaced, path, issues, seen, false);\n }\n if (Array.isArray(value)) {\n value.forEach((item, index) => checkJson(item, [...path, index], issues, seen));\n } else {\n for (const [key, child] of Object.entries(object)) {\n checkJson(child, [...path, key], issues, seen);\n }\n }\n } finally {\n // Removed rather than left in: `seen` is the path currently being walked, and\n // keeping it would call the same object appearing twice side by side — which\n // `JSON.stringify` writes out twice quite happily — a cycle. In a `finally`\n // so the `toJSON` returns above cannot leave it marked.\n seen.delete(object);\n }\n}\n\n/**\n * The one cast in this file, and the reason it has to exist: `OUTPUT` and\n * `OPTIONAL` are `declare const` unique symbols. They have no runtime\n * counterpart — they are inference channels — so no object that can actually be\n * constructed satisfies `Schema<T>` structurally. Funnelling every builder\n * through here means the lie is told once, in one place, and everything else in\n * the module is checked against the real declarations.\n */\nfunction make<T>(definition: Definition): SchemaBuilder<T> {\n return build(definition) as unknown as SchemaBuilder<T>;\n}\n\n/**\n * Builders are immutable: `describe`, `optional` and `nullable` each build a\n * fresh one from a copied definition. Mutating in place is the obvious\n * implementation and it is wrong — `const id = s.string()` reused in two\n * objects, described in one of them, would carry that description into the\n * other, and the only symptom is a model being told the wrong thing about a\n * field somewhere else.\n */\nfunction build(definition: Definition): RuntimeSchema {\n const runtime: RuntimeSchema = {\n toJSONSchema: () => emitRoot(definition),\n parse(value) {\n const issues: SchemaIssue[] = [];\n const result = read(definition, value, [], issues);\n if (issues.length > 0) throw new Error(issues.map(render).join(\"; \"));\n return result.drop ? undefined : result.value;\n },\n safeParse(value) {\n const issues: SchemaIssue[] = [];\n const result = read(definition, value, [], issues);\n if (issues.length > 0) return { ok: false, errors: issues.map(render) };\n return { ok: true, value: result.drop ? undefined : result.value };\n },\n validate(value) {\n const issues: SchemaIssue[] = [];\n const result = read(definition, value, [], issues);\n if (issues.length > 0) return { ok: false, issues };\n return { ok: true, value: result.drop ? undefined : result.value };\n },\n describe: (description) => build({ ...definition, description }),\n optional: () => build({ ...definition, optional: true }),\n // Clearing `optional` is not tidiness. `nullable()` returns a\n // `SchemaBuilder`, not an `OptionalSchemaBuilder`, so the key it describes\n // is required again in `ShapeOutput` — and a parse that still dropped it\n // would hand back an object missing a key its own type declares.\n nullable: () => build({ ...definition, nullable: true, optional: false }),\n };\n definitions.set(runtime, definition);\n return runtime;\n}\n\nfunction leaf(node: SchemaNode): Definition {\n return { node, optional: false, nullable: false };\n}\n\n// --- reading a JSON Schema ---------------------------------------------------\n\n/**\n * How `s.fromJSONSchema` checks a `format`. `true` accepts any string (a format\n * that is only a hint, like `markdown`); a `RegExp` or a function decides.\n */\nexport type JSONSchemaFormat = true | RegExp | ((value: string) => boolean);\n\nexport type FromJSONSchemaOptions = {\n /**\n * The formats the schema may name. A `format` not listed here is refused, not\n * ignored: gemi ships no format checks of its own, and a format that quietly\n * checked nothing would be a constraint that only looks enforced.\n */\n formats?: Record<string, JSONSchemaFormat>;\n /**\n * Keywords to skip as annotations, on top of the ones always skipped:\n * `title`, `$schema`, `$id`, `$comment`, `examples`, `default`,\n * `deprecated`, `readOnly`, `writeOnly`, and every `x-` keyword.\n */\n ignoreKeywords?: readonly string[];\n /**\n * What `parse`, `safeParse` and `validate` do with a key an object of the\n * schema doesn't declare, at every depth:\n *\n * - `\"strip\"` (the default): drop it from the parsed value, silently.\n * - `\"error\"`: fail with an `additionalProperties` issue whose `path` ends in\n * the key and whose `params.additionalProperty` is the key.\n * - `\"passthrough\"`: keep it in the parsed value as it came (it is only\n * checked for being JSON).\n *\n * Every object is closed in `s`, so this applies whether or not the object\n * says `additionalProperties: false`, and the emitted schema still says\n * `additionalProperties: false` (strict mode requires it). It applies to\n * this schema's objects only: an `s.object` it is nested into keeps\n * stripping.\n */\n unknownKeys?: \"strip\" | \"error\" | \"passthrough\";\n};\n\nconst UNKNOWN_KEYS = [\"strip\", \"error\", \"passthrough\"] as const;\n\n/**\n * Thrown by `s.fromJSONSchema` for a schema outside the subset `s` models.\n * `problems` lists every one found, each starting with the path into the\n * schema (`properties.price.type: ...`), so a schema written by a user or a\n * model can be sent back with all of them at once.\n */\nexport class JSONSchemaError extends Error {\n readonly problems: string[];\n constructor(problems: string[]) {\n super(\n `gemi/ai: s.fromJSONSchema cannot model this schema:\\n${problems.map((p) => `- ${p}`).join(\"\\n\")}`,\n );\n this.name = \"JSONSchemaError\";\n this.problems = problems;\n }\n}\n\nconst ANNOTATIONS = new Set([\n \"title\",\n \"$schema\",\n \"$id\",\n \"$comment\",\n \"examples\",\n \"default\",\n \"deprecated\",\n \"readOnly\",\n \"writeOnly\",\n]);\n\n/** The keywords each type may carry, beyond `type`, `description`, `enum` and `const`. */\nconst KEYWORDS: Record<string, readonly string[]> = {\n string: [\"minLength\", \"maxLength\", \"format\"],\n number: [\"minimum\", \"maximum\", \"exclusiveMinimum\", \"exclusiveMaximum\"],\n integer: [\"minimum\", \"maximum\", \"exclusiveMinimum\", \"exclusiveMaximum\"],\n boolean: [],\n object: [\"properties\", \"required\", \"additionalProperties\"],\n array: [\"items\", \"minItems\", \"maxItems\"],\n};\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/**\n * Reads a JSON Schema into a definition, collecting every problem rather than\n * stopping at the first. Returns `undefined` where a node could not be read;\n * the caller throws once the walk is done.\n */\nfunction fromJSON(\n schema: unknown,\n options: FromJSONSchemaOptions,\n where: string,\n problems: string[],\n): Definition | undefined {\n const problem = (message: string, at = where) => {\n problems.push(at ? `${at}: ${message}` : message);\n return undefined;\n };\n const child = (key: string) => (where ? `${where}.${key}` : key);\n if (!isPlainObject(schema)) return problem(\"expected a schema object\");\n\n const ignored = new Set(options.ignoreKeywords ?? []);\n const skip = (key: string) => ANNOTATIONS.has(key) || key.startsWith(\"x-\") || ignored.has(key);\n\n // `type: [T, \"null\"]`, `enum` with a null in it and an `anyOf` with a\n // `{ type: \"null\" }` member all mean the same: T, nullable.\n let nullable = false;\n let type = schema.type;\n if (Array.isArray(type)) {\n const rest = type.filter((t) => t !== \"null\");\n if (rest.length !== 1) {\n return problem(\n `type ${JSON.stringify(type)} is not supported; only one type, optionally with \"null\". Use anyOf for alternatives`,\n child(\"type\"),\n );\n }\n nullable = rest.length < type.length;\n type = rest[0];\n }\n if (type !== undefined && (typeof type !== \"string\" || !(type in KEYWORDS))) {\n return problem(\n `type ${JSON.stringify(type)} is not supported; expected one of ${Object.keys(KEYWORDS).join(\", \")}`,\n child(\"type\"),\n );\n }\n\n const allowed = new Set([\n \"type\",\n \"description\",\n \"enum\",\n \"const\",\n \"anyOf\",\n ...(type ? KEYWORDS[type as string] : []),\n ]);\n let unknown = false;\n for (const key of Object.keys(schema)) {\n if (allowed.has(key) || skip(key)) continue;\n unknown = true;\n const owner = Object.entries(KEYWORDS).find(([, keys]) => keys.includes(key));\n problem(\n owner && owner[0] !== type\n ? `\"${key}\" applies to type ${owner[0]}, and this schema is ${type ? `type ${type}` : \"untyped\"}`\n : `\"${key}\" is not supported by s.fromJSONSchema`,\n child(key),\n );\n }\n if (unknown) return undefined;\n\n if (schema.description !== undefined && typeof schema.description !== \"string\") {\n return problem(\"expected a string\", child(\"description\"));\n }\n const description = schema.description as string | undefined;\n const finish = (node: SchemaNode): Definition => ({\n node,\n optional: false,\n nullable,\n ...(description ? { description } : {}),\n });\n\n if (schema.anyOf !== undefined) {\n if (type !== undefined || schema.enum !== undefined || schema.const !== undefined) {\n return problem(\"anyOf cannot be combined with type, enum or const here\", child(\"anyOf\"));\n }\n if (!Array.isArray(schema.anyOf) || schema.anyOf.length === 0) {\n return problem(\"expected a non-empty array\", child(\"anyOf\"));\n }\n const members: Definition[] = [];\n let failed = false;\n schema.anyOf.forEach((member, index) => {\n if (isPlainObject(member) && member.type === \"null\" && Object.keys(member).length === 1) {\n nullable = true;\n return;\n }\n const read = fromJSON(member, options, child(`anyOf[${index}]`), problems);\n if (read) members.push(read);\n else failed = true;\n });\n if (failed) return undefined;\n if (members.length === 0) return problem(\"anyOf has only null in it\", child(\"anyOf\"));\n if (members.length === 1) {\n const only = members[0]!;\n return {\n ...only,\n nullable: only.nullable || nullable,\n ...(description ? { description } : {}),\n };\n }\n return finish({ kind: \"union\", members });\n }\n\n if (schema.const !== undefined) {\n const value = schema.const;\n if (typeof value !== \"string\" && typeof value !== \"number\" && typeof value !== \"boolean\") {\n return problem(\"only a string, number or boolean const is supported\", child(\"const\"));\n }\n if (type !== undefined && typeof value !== (type === \"integer\" ? \"number\" : type)) {\n return problem(`const ${JSON.stringify(value)} is not of type ${type}`, child(\"const\"));\n }\n return finish({ kind: \"literal\", value });\n }\n\n let stringChecks: StringChecks | undefined;\n if (type === \"string\") {\n stringChecks = readStringChecks(schema, options, child, problems);\n if (stringChecks === null) return undefined;\n }\n\n if (schema.enum !== undefined) {\n if (!Array.isArray(schema.enum) || schema.enum.length === 0) {\n return problem(\"expected a non-empty array\", child(\"enum\"));\n }\n const values = schema.enum.filter((value) => value !== null);\n if (values.length < schema.enum.length) nullable = true;\n const bad = values.find(\n (value) =>\n !(typeof value === \"string\" || typeof value === \"number\" || typeof value === \"boolean\") ||\n (type !== undefined && typeof value !== (type === \"integer\" ? \"number\" : type)),\n );\n if (bad !== undefined || values.length === 0) {\n return problem(\n type\n ? `every value must be of type ${type}${values.length === 0 ? \", and there must be one\" : `; ${JSON.stringify(bad)} is not`}`\n : \"only strings, numbers and booleans are supported\",\n child(\"enum\"),\n );\n }\n if (values.every((value) => typeof value === \"string\")) {\n return finish({\n kind: \"enum\",\n values: [...new Set(values as string[])],\n ...(stringChecks ? { checks: stringChecks } : {}),\n });\n }\n const literals = [...new Set(values as (string | number | boolean)[])];\n if (literals.length === 1) return finish({ kind: \"literal\", value: literals[0]! });\n return finish({\n kind: \"union\",\n members: literals.map((value) => leaf({ kind: \"literal\", value })),\n });\n }\n\n switch (type) {\n case undefined:\n return problem(\"a schema needs a type, an enum, a const or an anyOf\");\n case \"string\":\n return finish({ kind: \"string\", ...(stringChecks ? { checks: stringChecks } : {}) });\n case \"number\":\n case \"integer\": {\n const checks: NumberChecks = type === \"integer\" ? { integer: true } : {};\n let failed = false;\n for (const key of KEYWORDS.number!) {\n const value = schema[key];\n if (value === undefined) continue;\n if (typeof value !== \"number\" || !Number.isFinite(value)) {\n problem(\"expected a number\", child(key));\n failed = true;\n continue;\n }\n checks[key as \"minimum\"] = value;\n }\n if (failed) return undefined;\n return finish({ kind: \"number\", ...(Object.keys(checks).length > 0 ? { checks } : {}) });\n }\n case \"boolean\":\n return finish({ kind: \"boolean\" });\n case \"array\": {\n if (!isPlainObject(schema.items)) {\n return problem(\n 'an array needs \"items\" to be one schema (tuples are not supported)',\n child(\"items\"),\n );\n }\n const checks: ArrayChecks = {};\n let failed = false;\n for (const key of [\"minItems\", \"maxItems\"] as const) {\n const value = schema[key];\n if (value === undefined) continue;\n if (typeof value !== \"number\" || !Number.isInteger(value) || value < 0) {\n problem(\"expected a non-negative integer\", child(key));\n failed = true;\n continue;\n }\n checks[key] = value;\n }\n const item = fromJSON(schema.items, options, child(\"items\"), problems);\n if (!item || failed) return undefined;\n return finish({ kind: \"array\", item, ...(Object.keys(checks).length > 0 ? { checks } : {}) });\n }\n case \"object\": {\n const properties = schema.properties ?? {};\n if (!isPlainObject(properties)) return problem(\"expected an object\", child(\"properties\"));\n if (schema.additionalProperties !== undefined && schema.additionalProperties !== false) {\n return problem(\n \"only false is supported; a record with arbitrary keys has no strict-mode form (use s.json())\",\n child(\"additionalProperties\"),\n );\n }\n const required = schema.required ?? [];\n if (!Array.isArray(required) || !required.every((key) => typeof key === \"string\")) {\n return problem(\"expected an array of property names\", child(\"required\"));\n }\n const missing = required.filter((key) => !Object.hasOwn(properties, key));\n if (missing.length > 0) {\n return problem(\n `lists properties the schema doesn't have: ${missing.join(\", \")}`,\n child(\"required\"),\n );\n }\n const shape: Record<string, Definition> = {};\n let failed = false;\n for (const [key, value] of Object.entries(properties)) {\n const read = fromJSON(value, options, child(`properties.${key}`), problems);\n if (!read) {\n failed = true;\n continue;\n }\n // Not in `required` is \"may be left out\", which is `optional()`: the\n // model is told to send null, and a parse drops the key.\n shape[key] = required.includes(key) ? read : { ...read, optional: true };\n }\n if (failed) return undefined;\n const unknownKeys = options.unknownKeys;\n return finish({\n kind: \"object\",\n shape,\n ...(unknownKeys === \"error\" || unknownKeys === \"passthrough\" ? { unknownKeys } : {}),\n });\n }\n }\n return undefined;\n}\n\n/** `null` when a problem was reported. */\nfunction readStringChecks(\n schema: Record<string, unknown>,\n options: FromJSONSchemaOptions,\n child: (key: string) => string,\n problems: string[],\n): StringChecks | undefined | null {\n const checks: StringChecks = {};\n let failed = false;\n for (const key of [\"minLength\", \"maxLength\"] as const) {\n const value = schema[key];\n if (value === undefined) continue;\n if (typeof value !== \"number\" || !Number.isInteger(value) || value < 0) {\n problems.push(`${child(key)}: expected a non-negative integer`);\n failed = true;\n continue;\n }\n checks[key] = value;\n }\n if (schema.format !== undefined) {\n const name = schema.format;\n const format = typeof name === \"string\" ? options.formats?.[name] : undefined;\n if (typeof name !== \"string\") {\n problems.push(`${child(\"format\")}: expected a string`);\n failed = true;\n } else if (!format || !Object.hasOwn(options.formats!, name)) {\n problems.push(\n `${child(\"format\")}: unknown format ${JSON.stringify(name)}; pass a check for it in the formats option`,\n );\n failed = true;\n } else {\n checks.format = { name, test: formatTest(format) };\n }\n }\n if (failed) return null;\n return Object.keys(checks).length > 0 ? checks : undefined;\n}\n\nfunction formatTest(format: JSONSchemaFormat): (value: string) => boolean {\n if (format === true) return () => true;\n if (format instanceof RegExp) {\n // A `g` or `y` regex keeps `lastIndex` between calls, so the second value\n // tested would start halfway in. Reset it every time.\n return (value) => {\n format.lastIndex = 0;\n return format.test(value);\n };\n }\n return format;\n}\n\nexport const s: {\n string(): SchemaBuilder<string>;\n number(): SchemaBuilder<number>;\n boolean(): SchemaBuilder<boolean>;\n literal<const L extends string | number | boolean>(value: L): SchemaBuilder<L>;\n /** Modelled as a JSON Schema `enum`, which strict mode does support. */\n enum<const L extends readonly [string, ...string[]]>(values: L): SchemaBuilder<L[number]>;\n object<const S extends Record<string, AnySchema>>(shape: S): SchemaBuilder<ShapeOutput<S>>;\n array<const S extends AnySchema>(item: S): SchemaBuilder<Infer<S>[]>;\n /**\n * `anyOf` of object schemas, discriminated by a literal member. Left in\n * because tool outputs are frequently a success/failure pair, and modelling\n * that as one object with everything optional is worse for the model.\n */\n union<const S extends readonly [AnySchema, AnySchema, ...AnySchema[]]>(\n members: S,\n ): SchemaBuilder<Infer<S[number]>>;\n /**\n * Any JSON value, constrained by nothing — for a format the rest of this\n * builder cannot describe: a record with arbitrary keys, a mixed-type tuple,\n * a document whose shape is not known in advance. (A document that nests\n * into itself has a strict spelling: `s.recursive`.)\n *\n * A schema containing one cannot be sent under strict mode, so a tool whose\n * input uses it is sent with `strict: false` automatically. That is not an\n * option to pass anywhere; it is read back off the schema by\n * `supportsStrict`. The rest of the tool is unaffected, and so is streaming:\n * partial arguments are parsed from the raw text, never through a schema.\n *\n * `T` is an assertion, not a guarantee. The emitted schema constrains\n * nothing, so nothing checks the model's output against `T` — only that it is\n * JSON. Validate it in `execute` and hand the model back an error it can fix,\n * the way it would any other bad argument. `describe()` is where you tell it\n * the format; with no constraints to read, that prose is all it gets.\n *\n * TWO CALL SIGNATURES, NOT A DEFAULT TYPE PARAMETER, and that is load-bearing.\n * Written `json<T = JsonValue>()`, the default lost to the surrounding\n * contextual type in the position this is actually used: `s.object`'s shape is\n * constrained to `Record<string, AnySchema>` — `Schema<any>` — which supplies\n * `any` as an inference candidate, and a candidate beats a default. So\n * `s.object({ definition: s.json() })` inferred `{ definition: any }`, which is\n * type checking switched off around exactly the field this exists for, and the\n * opposite of what the default was written to prevent. An overload with no type\n * parameter has nothing to infer, so `s.json()` is `JsonValue` wherever it is\n * written.\n *\n * `ai:generate-client` maps it to the native `JSONValue` and says nothing about\n * it. `JsonValue` is a union of every JSON shape, so it used to reach the\n * generator's \"a union that is not told apart by one string member\" warning —\n * true, and a misdescription of a field that is free-form on purpose. The\n * extractor recognises it now.\n */\n json(): SchemaBuilder<JsonValue>;\n json<T>(): SchemaBuilder<T>;\n /**\n * A schema that contains itself — a tree of UI nodes, a comment thread, a\n * folder listing — and stays strict-mode safe, unlike `s.json()`.\n *\n * ```ts\n * type Node = { tag: string; text?: string; children: Node[] };\n *\n * const node = s.recursive<Node>(\"Node\", (self) =>\n * s.object({\n * tag: s.enum([\"section\", \"heading\", \"text\"]),\n * text: s.string().optional(),\n * children: s.array(self),\n * }),\n * );\n * const output = s.object({ title: s.string(), root: node });\n * ```\n *\n * Emitted the way OpenAI's strict structured output spells recursion: the\n * body once under the root's `$defs[name]`, and `{ \"$ref\": \"#/$defs/<name>\" }`\n * wherever it is used. Used as the root itself, the body is also inlined at\n * the root, since a tool's parameters and an agent's output must be an\n * object there. `parse`, `safeParse` and `validate` follow the reference to\n * any depth.\n *\n * `T` has to be written out: TypeScript cannot infer a type from a value\n * that mentions itself. The callback's schema is checked against it, so a\n * field the type has and the schema lacks (or the reverse) is a type error.\n *\n * Rules, each an error when the schema is built:\n *\n * - `name` is the `$defs` key: letters, digits, `_` and `-`. Two different\n * recursive schemas in one tool or output need different names.\n * - `self` must be nested inside an `s.object` field or an `s.array` — a\n * body that is `self` again through a union describes no finite value.\n * - The body cannot be `optional()`; make the uses optional instead\n * (`children: s.array(self).optional()`, `next: self.optional()`).\n *\n * Strict mode limits the rest as usual: every node of the body is in the\n * strict subset or the whole schema is sent non-strict (`supportsStrict`).\n */\n recursive<T>(name: string, define: (self: SchemaBuilder<T>) => Schema<T>): SchemaBuilder<T>;\n /**\n * A schema read from a JSON Schema at runtime — for a shape that comes from\n * data rather than code, like a collection whose items a user defined.\n *\n * Only the subset `s` itself models is accepted, so the result stays\n * strict-mode safe and can be a tool's `inputSchema` like any other:\n *\n * - `type`: `string`, `number`, `integer`, `boolean`, `object`, `array`,\n * or one of them with `\"null\"` (`[\"string\", \"null\"]`).\n * - `enum` (strings become `s.enum`, numbers and booleans a union of\n * literals; a `null` in it makes the field nullable), `const`, `anyOf`.\n * - strings: `minLength`, `maxLength`, `format` (checked with\n * `options.formats`). Numbers: `minimum`, `maximum`, `exclusiveMinimum`,\n * `exclusiveMaximum`. Arrays: `items` (one schema), `minItems`, `maxItems`.\n * - objects: `properties`, `required`, `additionalProperties: false`. A\n * property not in `required` is `optional()`.\n * - `description`; annotations (`title`, `default`, `examples`, `$schema`,\n * `x-*`, … and `options.ignoreKeywords`) are skipped.\n *\n * Anything else — `pattern`, `oneOf`, `allOf`, `$ref`, a tuple, an open\n * `additionalProperties`, an unknown `format` — throws a `JSONSchemaError`\n * listing every problem with its path.\n *\n * The length, range, item-count and format constraints are enforced by\n * `parse`/`safeParse`/`validate` and told to the model in the field's\n * description, because strict structured output does not accept them as\n * keywords. By default an unknown key in an object is dropped from the\n * parsed value rather than reported; pass `unknownKeys: \"error\"` to report\n * it as an `additionalProperties` issue (as Ajv does), or `\"passthrough\"`\n * to keep it.\n *\n * The output type is `JsonValue` (or the `T` you assert). Validate a value\n * with `.validate(value)` for per-path issues, or `.safeParse(value)`.\n */\n fromJSONSchema(schema: unknown, options?: FromJSONSchemaOptions): SchemaBuilder<JsonValue>;\n fromJSONSchema<T>(schema: unknown, options?: FromJSONSchemaOptions): SchemaBuilder<T>;\n} = {\n string: () => make<string>(leaf({ kind: \"string\" })),\n number: () => make<number>(leaf({ kind: \"number\" })),\n boolean: () => make<boolean>(leaf({ kind: \"boolean\" })),\n literal: (value) => make<typeof value>(leaf({ kind: \"literal\", value })),\n enum: (values) => make<(typeof values)[number]>(leaf({ kind: \"enum\", values })),\n object: (shape) =>\n make<ShapeOutput<typeof shape>>(\n leaf({\n kind: \"object\",\n shape: Object.fromEntries(\n Object.entries(shape).map(([key, child]) => [key, definitionOf(child)]),\n ),\n }),\n ),\n array: (item) => make<Infer<typeof item>[]>(leaf({ kind: \"array\", item: definitionOf(item) })),\n // A union is legal wherever a property is, but not as the root of a tool's\n // input or an agent's structured output: the provider wants an object there.\n // `s` cannot know where a schema will be used, so `AgentTool.create` and\n // `Agent.create` are what reject it at the root.\n union: (members) =>\n make<Infer<(typeof members)[number]>>(\n leaf({ kind: \"union\", members: members.map(definitionOf) }),\n ),\n json: <T>() => make<T>(leaf({ kind: \"json\" })),\n recursive,\n fromJSONSchema: <T>(schema: unknown, options: FromJSONSchemaOptions = {}) => {\n const problems: string[] = [];\n if (\n options.unknownKeys !== undefined &&\n !(UNKNOWN_KEYS as readonly unknown[]).includes(options.unknownKeys)\n ) {\n throw new Error(\n `gemi/ai: s.fromJSONSchema's unknownKeys option must be one of ${UNKNOWN_KEYS.map((v) => JSON.stringify(v)).join(\", \")}, got ${JSON.stringify(options.unknownKeys)}`,\n );\n }\n const definition = fromJSON(schema, options, \"\", problems);\n if (!definition || problems.length > 0) {\n throw new JSONSchemaError(problems.length > 0 ? problems : [\"unreadable schema\"]);\n }\n return make<T>(definition);\n },\n};\n\n/**\n * Whether a schema can be sent under a provider's strict mode.\n *\n * False exactly when a `json()` node is somewhere inside it. Strict mode's\n * bargain is that every node constrains its value; an unconstrained one has no\n * spelling there, and sending it anyway is a 400 naming a path.\n *\n * Derived from the tree rather than declared alongside it, because the two\n * would drift: a field added to a tool's input a year from now would need\n * whoever adds it to know that a flag somewhere else describes it. Adding the\n * field is the whole of turning strict off.\n */\nexport function supportsStrict(schema: AnySchema): boolean {\n const definition = definitions.get(schema);\n if (definition) return strictNode(definition.node);\n // A schema built by hand rather than with `s`: `questionSchema` in\n // `ai/Agent.ts`, and the merged one `services/mcp` casts together.\n //\n // Answering `true` here was wrong, and not harmlessly. `McpRegistry`'s\n // `combineSchemas` spreads `meta.input.toJSONSchema()` into its own object,\n // so an `s.json()` field an app declared on an `mcp` route survives into the\n // emitted schema while the *tree* that would have reported it is discarded.\n // Every MCP-projected tool was therefore sent `strict: true` with an empty\n // subschema inside it — a 400 on every turn, from the one path this function\n // exists to get right.\n //\n // So the emitted schema is read instead. It is the same question asked of the\n // artifact rather than the source, which is the only thing a foreign schema\n // has to offer.\n return strictJSONSchema(schema.toJSONSchema());\n}\n\n/**\n * Whether an already-emitted JSON Schema constrains every value it describes.\n *\n * Only for schemas with no definition tree. It answers a narrower question than\n * `strictNode` — it cannot see optionality or a builder's intent, just whether\n * some node says nothing about its value — but that is exactly the property\n * strict mode rejects, and it is visible in the artifact.\n */\nfunction strictJSONSchema(schema: JSONSchema): boolean {\n // `description` is prose, not a constraint. A node carrying only that — which\n // is what `s.json().describe(...)` emits — says nothing about its value.\n const constrained =\n schema.$ref !== undefined ||\n schema.type !== undefined ||\n schema.enum !== undefined ||\n schema.const !== undefined ||\n schema.anyOf !== undefined ||\n schema.properties !== undefined ||\n schema.items !== undefined;\n if (!constrained) return false;\n\n for (const child of Object.values(schema.properties ?? {})) {\n if (!strictJSONSchema(child)) return false;\n }\n if (schema.items && !strictJSONSchema(schema.items)) return false;\n for (const member of schema.anyOf ?? []) {\n if (!strictJSONSchema(member)) return false;\n }\n // A `$ref` is answered for by the `$defs` entry it points at, which is\n // checked here once rather than followed — following it is a cycle.\n for (const definition of Object.values(schema.$defs ?? {})) {\n if (!strictJSONSchema(definition)) return false;\n }\n return true;\n}\n\n/**\n * Enumerated rather than defaulted, so that a node kind added later cannot\n * inherit \"strict\" by omission — which is the failure that shows up as a 400\n * from the provider rather than as a type error here.\n *\n * The one cycle in a definition tree is an `s.recursive` reaching itself, so\n * `seen` holds the cells already being answered for: a body that is strict\n * apart from its references to itself is strict.\n */\nfunction strictNode(node: SchemaNode, seen = new Set<RecursiveCell>()): boolean {\n switch (node.kind) {\n case \"string\":\n case \"number\":\n case \"boolean\":\n case \"literal\":\n case \"enum\":\n return true;\n case \"object\":\n return Object.values(node.shape).every((child) => strictNode(child.node, seen));\n case \"array\":\n return strictNode(node.item.node, seen);\n case \"union\":\n return node.members.every((member) => strictNode(member.node, seen));\n case \"json\":\n return false;\n case \"ref\":\n if (seen.has(node.cell)) return true;\n seen.add(node.cell);\n return strictNode(bodyOf(node.cell).node, seen);\n }\n}\n\n/**\n * Whether `definition` can reach `cell` without an object property or an\n * array item in between — through a union member, or another recursive\n * schema's body. Such a schema describes no finite value (`Self = Self |\n * string` is just `string`), and reading one would recurse forever on a\n * primitive, where no object is there to catch the cycle with.\n */\nfunction reachesUnguarded(\n definition: Definition,\n cell: RecursiveCell,\n seen = new Set<RecursiveCell>(),\n): boolean {\n const node = definition.node;\n if (node.kind === \"union\") {\n return node.members.some((member) => reachesUnguarded(member, cell, seen));\n }\n if (node.kind !== \"ref\") return false;\n if (node.cell === cell) return true;\n if (seen.has(node.cell) || !node.cell.definition) return false;\n seen.add(node.cell);\n return reachesUnguarded(node.cell.definition, cell, seen);\n}\n\nconst RECURSIVE_NAME = /^[A-Za-z_][A-Za-z0-9_-]{0,63}$/;\n\nfunction recursive<T>(\n name: string,\n define: (self: SchemaBuilder<T>) => Schema<T>,\n): SchemaBuilder<T> {\n if (typeof name !== \"string\" || !RECURSIVE_NAME.test(name)) {\n throw new Error(\n `gemi/ai: s.recursive needs a name of letters, digits, \"_\" and \"-\" (starting with a letter or \"_\", at most 64), got ${JSON.stringify(name)}`,\n );\n }\n const cell: RecursiveCell = { name, active: new Set() };\n const reference = (): Definition => leaf({ kind: \"ref\", cell });\n const body = definitionOf(define(make<T>(reference())));\n if (body.optional) {\n throw new Error(\n `gemi/ai: the recursive schema \"${name}\" is optional() as a whole; mark the places that use it optional instead`,\n );\n }\n if (reachesUnguarded(body, cell)) {\n throw new Error(\n `gemi/ai: the recursive schema \"${name}\" refers to itself outside any object or array, so it describes no finite value; nest \\`self\\` in an s.object(...) field or an s.array(...)`,\n );\n }\n cell.definition = body;\n return make<T>(reference());\n}\n",
|
|
6
|
+
"import type { ServiceToken } from \"../container/Container\";\nimport { app } from \"../foundation/app\";\n\n/**\n * Base for the facades that front a container binding. A subclass names the\n * service it proxies with `getFacadeAccessor()` and reaches the live instance\n * through `this.getFacadeRoot()`, so the binding is resolved per call against\n * the Application for the current async context — never captured at module\n * load, which is what makes a facade swappable in tests.\n *\n * Two deliberate divergences from `Illuminate\\Support\\Facades\\Facade`:\n *\n * 1. No `__callStatic`. TypeScript has no typed equivalent, and a Proxy would\n * erase the very signatures that make these facades worth having. Subclasses\n * therefore declare explicit statics that forward to `getFacadeRoot()`.\n *\n * 2. `getFacadeAccessor()` is public, not protected. `getFacadeRoot()` types\n * its `this` structurally in order to infer the service type from the\n * accessor's return, and a protected static is not structurally assignable\n * to that.\n *\n * Facades that resolve nothing from the container — Cookie, Redirect, Url,\n * Meta — do not extend this class.\n */\nexport abstract class Facade {\n static getFacadeAccessor(): ServiceToken<any> {\n throw new Error(\n `Facade [${this.name}] does not implement getFacadeAccessor().`,\n );\n }\n\n static getFacadeRoot<T>(this: {\n getFacadeAccessor(): ServiceToken<T>;\n }): T {\n return app(this.getFacadeAccessor());\n }\n}\n",
|
|
7
|
+
"import type { LogEntry, LogLevel } from \"./types\";\n\n/**\n * How the console sink writes an entry.\n *\n * - `\"text\"`: one readable line, `2026-10-11T09:00:00.000Z ERROR Payment failed {\"orderId\":1}`.\n * - `\"json\"`: one JSON object per line, `{\"timestamp\":…,\"level\":\"error\",\"message\":…,\"orderId\":1}`,\n * which platform log viewers (Railway, Fly, Datadog, …) parse into structured fields.\n */\nexport type LogConsoleFormat = \"text\" | \"json\";\n\n/**\n * A request field an entry carries only when the app opts in with\n * `requestFields`.\n *\n * - `\"url\"`: the full URL, query string included.\n * - `\"headers\"`: the request headers as a plain object, with the\n * `redactHeaders` ones replaced by `\"[redacted]\"`.\n */\nexport type LogRequestField = \"url\" | \"headers\";\n\n/**\n * Headers whose value never reaches a log entry, whatever `redactHeaders`\n * says: they carry sessions and credentials.\n */\nexport const DEFAULT_REDACTED_HEADERS = [\n \"cookie\",\n \"set-cookie\",\n \"authorization\",\n \"proxy-authorization\",\n \"x-api-key\",\n];\n\n// Config key: `log`. Derived from `LoggingServiceProvider`.\nexport interface LogConfig {\n maxFileSize?: number;\n\n /**\n * Also write every entry to the process's stdout (`debug`, `info`, `notice`)\n * or stderr (`warning` and above), so platform log collectors pick it up.\n *\n * `true` writes every level, a level writes that level and above, `false`\n * turns the sink off. Default: `true` when `NODE_ENV` is `\"development\"`\n * (`gemi dev`), `false` otherwise.\n */\n console?: boolean | LogLevel;\n\n /**\n * Line format of the console sink. Default: `\"text\"` in development,\n * `\"json\"` otherwise.\n */\n consoleFormat?: LogConsoleFormat;\n\n /**\n * Request fields added to an entry logged inside a request, on top of the\n * ones it always carries: `method`, `path`, `userAgent` and, when the\n * request has an `x-request-id` header, `requestId`. Default: `[]`.\n *\n * Applies to the file sink and `onLogCreated`. The console sink only ever\n * gets `method` and `path`.\n */\n requestFields?: LogRequestField[];\n\n /**\n * Header names (any case) redacted when `requestFields` includes\n * `\"headers\"`, in addition to `cookie`, `set-cookie`, `authorization`,\n * `proxy-authorization` and `x-api-key`, which are always redacted.\n */\n redactHeaders?: string[];\n\n onLogFileClosed?: (file: File) => void | Promise<void>;\n onLogCreated?: (logEntry: LogEntry) => void | Promise<void>;\n}\n\nexport function defineLogConfig(config: LogConfig): LogConfig {\n return config;\n}\n\nexport function logConfigDefaults(): Required<LogConfig> {\n const development = process.env.NODE_ENV === \"development\";\n return {\n maxFileSize: 1024 * 1024 * 10, // 10MB\n console: development,\n consoleFormat: development ? \"text\" : \"json\",\n requestFields: [],\n redactHeaders: [],\n onLogFileClosed: () => {},\n onLogCreated: () => {},\n };\n}\n",
|
|
8
|
+
"import type { FileSink } from \"bun\";\nimport { mkdir, readdir, access } from \"fs/promises\";\n\nasync function exists(path: string): Promise<boolean> {\n try {\n await access(path);\n return true;\n } catch {\n return false;\n }\n}\nimport { RequestContext } from \"../../http/requestContext\";\nimport { projectRoot } from \"../../support/discover\";\nimport { DEFAULT_REDACTED_HEADERS, type LogConfig } from \"./config\";\nimport { consoleThreshold, writeConsoleLine } from \"./consoleSink\";\nimport type { LogEntry, LogLevel } from \"./types\";\n\nexport class LogManager {\n static token = \"log\";\n\n writer: FileSink;\n isReady: boolean = false;\n\n private flushTimeout: Timer;\n private fileSize: number = 0;\n private writerSize: number = 0;\n private isCreatingFile: boolean = false;\n private bootPromise: Promise<void> | null = null;\n public currentLogFilePath: string;\n\n /**\n * Computed per read, not once in the constructor: `Server.start` awaits\n * `waitForBoot()` — where `LogServiceProvider.boot()` builds this directory —\n * and only *then* imports the http layer that sets `ROOT_DIR`. A field\n * initializer (or any `process.env.ROOT_DIR` read here) resolves to\n * `undefined/storage/logs` at boot, which is how every `Log.info()` ended up\n * throwing on an undefined writer. `projectRoot()` is the same rule\n * `httpProd` sets `ROOT_DIR` from, a moment later.\n */\n private get logsDirPath(): string {\n return `${projectRoot()}/storage/logs`;\n }\n\n private readonly consoleThreshold: number;\n private readonly redactedHeaders: Set<string>;\n\n constructor(public config: Required<LogConfig>) {\n this.consoleThreshold = consoleThreshold(config.console);\n this.redactedHeaders = new Set(\n [...DEFAULT_REDACTED_HEADERS, ...(config.redactHeaders ?? [])].map((h) =>\n h.toLowerCase(),\n ),\n );\n }\n\n /**\n * What an entry logged inside a request says about it. An allow-list: the\n * headers carry the session cookie and `Authorization`, and log files and\n * `onLogCreated` transports are read by more people than the app's secrets\n * should be, so anything beyond method, path, user agent and request id is\n * opt-in, and redacted headers stay redacted even then.\n */\n private requestMetadata(request: Request): Record<string, unknown> {\n const url = new URL(request.url);\n const metadata: Record<string, unknown> = {\n method: request.method,\n path: url.pathname,\n userAgent: request.headers.get(\"user-agent\") ?? undefined,\n };\n const requestId = request.headers.get(\"x-request-id\");\n if (requestId) {\n metadata.requestId = requestId;\n }\n const fields = this.config.requestFields ?? [];\n if (fields.includes(\"url\")) {\n metadata.url = request.url;\n }\n if (fields.includes(\"headers\")) {\n const headers: Record<string, string> = {};\n request.headers.forEach((value, name) => {\n headers[name] = this.redactedHeaders.has(name) ? \"[redacted]\" : value;\n });\n metadata.headers = headers;\n }\n return metadata;\n }\n\n /**\n * Idempotent. `LogServiceProvider.boot()` calls this so the storage\n * directory exists before the first request; a lazy first `log()` triggers\n * it too, so the manager still works when it is resolved on its own.\n */\n boot(): Promise<void> {\n if (!this.bootPromise) {\n this.bootPromise = this.createStorage()\n .catch((err) => {\n // A logger that rejects turns every `Log.info()` into the caller's\n // error. Report the storage failure once and carry on without a file\n // sink — `log()` still feeds `onLogCreated`.\n console.error(\"Log storage unavailable, file logging disabled\", err);\n })\n .then(() => {\n this.isReady = true;\n });\n }\n return this.bootPromise;\n }\n\n private async createStorage() {\n const storageDirPath = `${projectRoot()}/storage`;\n if (!(await exists(storageDirPath))) {\n await mkdir(storageDirPath);\n }\n if (!(await exists(this.logsDirPath))) {\n await mkdir(this.logsDirPath);\n }\n await this.newLogFile();\n }\n\n async newLogFile() {\n if (!(await exists(this.logsDirPath))) {\n await mkdir(this.logsDirPath);\n }\n this.isCreatingFile = true;\n if (this.currentLogFilePath) {\n this.writer.flush();\n this.writer.end();\n this.writer = null;\n const file = new File(\n [await Bun.file(this.currentLogFilePath).arrayBuffer()],\n this.currentLogFilePath.split(\"/\").pop(),\n { type: \"text/plain\" },\n );\n this.config.onLogFileClosed(file);\n this.fileSize = 0;\n this.writerSize = 0;\n }\n\n const logFiles = await readdir(this.logsDirPath);\n\n const lastLogFile = logFiles.sort().reverse()[0];\n\n if (lastLogFile) {\n const _file = Bun.file(`${this.logsDirPath}/${lastLogFile}`);\n if (_file.size < this.config.maxFileSize) {\n this.currentLogFilePath = `${this.logsDirPath}/${lastLogFile}`;\n\n this.writer = _file.writer();\n this.writer.write(await _file.text());\n this.writer.write(\"\\n\");\n this.writer.flush();\n this.fileSize = _file.size;\n }\n }\n\n if (!this.writer) {\n const logFileName =\n `${new Date(Date.now()).toISOString()}.log`.replaceAll(\":\", \"-\");\n this.currentLogFilePath = `${this.logsDirPath}/${logFileName}`;\n const file = Bun.file(`${this.logsDirPath}/${logFileName}`);\n this.writer = file.writer();\n this.fileSize = 0;\n this.writerSize = 0;\n }\n this.isCreatingFile = false;\n }\n\n async log(\n level: LogLevel,\n message: string,\n metadata: Record<string, any> = {},\n ) {\n if (!this.isReady) {\n await this.boot();\n }\n\n const reqCtx = RequestContext.getStore();\n let requestMetadata = {};\n // The console sink gets the request's method and path only: platform logs\n // are read by more people than the log files, and the headers carry the\n // session cookie and `Authorization`.\n let consoleRequestMetadata = {};\n if (reqCtx) {\n consoleRequestMetadata = {\n method: reqCtx.req.rawRequest.method,\n path: new URL(reqCtx.req.rawRequest.url).pathname,\n };\n requestMetadata = this.requestMetadata(reqCtx.req.rawRequest);\n }\n\n const logObject: LogEntry = {\n timestamp: new Date(Date.now()).toISOString(),\n env: process.env.NODE_ENV,\n level,\n message,\n metadata: { ...requestMetadata, ...metadata },\n };\n\n if (this.consoleThreshold !== -1) {\n writeConsoleLine(\n {\n timestamp: logObject.timestamp,\n level,\n message,\n metadata: { ...consoleRequestMetadata, ...metadata },\n },\n { threshold: this.consoleThreshold, format: this.config.consoleFormat },\n );\n }\n\n let log = \"\";\n try {\n log = JSON.stringify(logObject);\n } catch (err) {\n console.log(\"Error parsing log object\", err);\n }\n // Contained, because this is an app-supplied hook and every facade method\n // calls `log()` without awaiting it: a hook that throws would otherwise\n // leave a floating `Log.info()` as an unhandled rejection, which is the\n // failure this method exists to not have. A rejected promise from an async\n // hook is the same thing arriving later, so it is caught too — what is not\n // done is *awaiting* it, which would put the app's transport in front of\n // the file write.\n try {\n const handled = this.config.onLogCreated(logObject);\n if (handled instanceof Promise) {\n handled.catch((err) => console.error(\"Error in onLogCreated\", err));\n }\n } catch (err) {\n console.error(\"Error in onLogCreated\", err);\n }\n\n // No writer means `createStorage` failed (or a rotation is mid-flight);\n // either way the entry has already been handed to `onLogCreated`, so drop\n // the file copy rather than throwing at the call site.\n if (!this.writer) {\n return;\n }\n\n this.writerSize += log.length;\n this.fileSize += log.length;\n\n try {\n this.writer.write(log);\n this.writer.write(\"\\n\");\n this.tryFlush();\n } catch (err) {\n console.error(\"Error writing log\", err);\n // Do something\n }\n }\n\n async tryFlush() {\n if (this.fileSize > this.config.maxFileSize) {\n if (!this.isCreatingFile) {\n await this.newLogFile();\n }\n }\n if (this.writerSize > this.config.maxFileSize / 2) {\n await this.writer.flush();\n this.writerSize = 0;\n await this.newLogFile();\n } else {\n clearTimeout(this.flushTimeout);\n this.flushTimeout = setTimeout(async () => {\n await this.writer.flush();\n this.writerSize = 0;\n }, 100);\n }\n }\n}\n",
|
|
9
|
+
"import type { LogConsoleFormat } from \"./config\";\nimport type { LogLevel } from \"./types\";\n\nconst LEVELS: LogLevel[] = [\n \"debug\",\n \"info\",\n \"notice\",\n \"warning\",\n \"error\",\n \"critical\",\n \"alert\",\n \"emergency\",\n];\n\nconst STDERR_FROM = LEVELS.indexOf(\"warning\");\n\n/**\n * The lowest level index the console sink writes, or `-1` when it is off.\n * An unknown string is treated as `true` rather than silently dropping every\n * entry: a typo in the config should not hide the logs.\n */\nexport function consoleThreshold(option: boolean | LogLevel | undefined) {\n if (!option) {\n return -1;\n }\n if (option === true) {\n return 0;\n }\n const index = LEVELS.indexOf(option);\n return index === -1 ? 0 : index;\n}\n\nexport type ConsoleLogLine = {\n timestamp: string;\n level: LogLevel;\n message: string;\n /** Only what the caller passed, plus `method` and `path` inside a request. */\n metadata: Record<string, unknown>;\n};\n\n/**\n * `JSON.stringify` replacer for log metadata: an `Error` becomes its name,\n * message and stack (it stringifies to `{}` otherwise), a `bigint` its string,\n * and a repeated object `\"[Circular]\"`.\n */\nfunction metadataReplacer() {\n const seen = new WeakSet<object>();\n return function (this: unknown, _key: string, value: unknown) {\n if (typeof value === \"bigint\") {\n return value.toString();\n }\n if (value instanceof Error) {\n const out: Record<string, unknown> = {\n name: value.name,\n message: value.message,\n stack: value.stack,\n };\n for (const key of Object.keys(value)) {\n out[key] = (value as any)[key];\n }\n if (value.cause !== undefined) {\n out.cause = value.cause;\n }\n return out;\n }\n if (value !== null && typeof value === \"object\") {\n if (seen.has(value)) {\n return \"[Circular]\";\n }\n seen.add(value);\n }\n return value;\n };\n}\n\nfunction stringify(value: unknown) {\n try {\n return JSON.stringify(value, metadataReplacer());\n } catch {\n return '\"[Unserializable]\"';\n }\n}\n\nexport function formatConsoleLine(\n line: ConsoleLogLine,\n format: LogConsoleFormat,\n): string {\n if (format === \"json\") {\n // Metadata is spread first so the three fields platforms key on cannot be\n // overwritten by a metadata key of the same name.\n return stringify({\n ...line.metadata,\n timestamp: line.timestamp,\n level: line.level,\n message: line.message,\n });\n }\n const hasMetadata = Object.keys(line.metadata).length > 0;\n return `${line.timestamp} ${line.level.toUpperCase()} ${line.message}${\n hasMetadata ? ` ${stringify(line.metadata)}` : \"\"\n }`;\n}\n\n/**\n * Writes one entry to stdout or stderr. Never throws: a closed pipe must not\n * become the caller's error.\n */\nexport function writeConsoleLine(\n line: ConsoleLogLine,\n options: { threshold: number; format: LogConsoleFormat },\n) {\n const index = LEVELS.indexOf(line.level);\n if (options.threshold === -1 || index < options.threshold) {\n return;\n }\n try {\n const text = formatConsoleLine(line, options.format) + \"\\n\";\n if (index >= STDERR_FROM) {\n process.stderr.write(text);\n } else {\n process.stdout.write(text);\n }\n } catch {\n // Nowhere left to report it.\n }\n}\n",
|
|
10
|
+
"import { LogManager } from \"../services/logging/LogManager\";\nimport { Facade } from \"./Facade\";\n\nexport class Log extends Facade {\n static getFacadeAccessor() {\n return LogManager;\n }\n\n static debug(message: string, metadata?: Record<string, any>) {\n this.getFacadeRoot().log(\"debug\", message, metadata);\n }\n\n static info(message: string, metadata?: Record<string, any>) {\n this.getFacadeRoot().log(\"info\", message, metadata);\n }\n\n static notice(message: string, metadata?: Record<string, any>) {\n this.getFacadeRoot().log(\"notice\", message, metadata);\n }\n\n static warning(message: string, metadata?: Record<string, any>) {\n this.getFacadeRoot().log(\"warning\", message, metadata);\n }\n\n static error(message: string, metadata?: Record<string, any>) {\n this.getFacadeRoot().log(\"error\", message, metadata);\n }\n\n static critical(message: string, metadata?: Record<string, any>) {\n this.getFacadeRoot().log(\"critical\", message, metadata);\n }\n\n static alert(message: string, metadata?: Record<string, any>) {\n this.getFacadeRoot().log(\"alert\", message, metadata);\n }\n\n static emergency(message: string, metadata?: Record<string, any>) {\n this.getFacadeRoot().log(\"emergency\", message, metadata);\n }\n}\n"
|
|
6
11
|
],
|
|
7
|
-
"mappings": ";AAmRA,SAAS,CAAM,CAAC,EAAiC,CAC/C,GAAI,CAAC,EAAK,WACR,MAAU,MACR,kCAAkC,EAAK,sIACzC,EAEF,OAAO,EAAK,WAwBd,IAAM,EAAc,IAAI,QAMjB,SAAS,EAAQ,CAAC,EAAiD,CACxE,OAAO,OAAO,IAAU,UAAY,IAAU,MAAQ,EAAY,IAAI,CAAK,EAG7E,SAAS,CAAY,CAAC,EAA+B,CACnD,IAAM,EAAa,EAAY,IAAI,CAAM,EACzC,GAAI,CAAC,EACH,MAAU,MAAM,iEAAiE,EAEnF,OAAO,EAyBT,SAAS,CAAQ,CAAC,EAAoC,CACpD,IAAM,EAAuB,CAA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