Open History to see the last commit
1# modelschemas
2
3Live AI model schema service on Cloudflare Workers: per-endpoint
4request/response JSON Schemas and model metadata for monitored providers
5(OpenAI, Anthropic, Gemini, xAI Grok, ElevenLabs, OpenRouter, FAL, BytePlus),
6with
7react-query-style server-side caching (D1 source of truth, KV hot cache,
8stale-while-revalidate) and automatic refresh — model lists every 15 minutes,
9full OpenAPI spec syncs daily.
10
11Surfaces:
12
13- **HTTP API** under `/v1` — catalog, schemas, validation, cost estimate,
14 changes feed (see `GET /v1` or [openapi.json](./openapi.json))
15- **Agent guide** at `/llms.txt`, **agent skill** at `/skill`, **docs** at `/docs`
16- **MCP server** at `/mcp` (streamable HTTP; tools: `list_models`,
17 `get_model`, `get_schema`, `validate_payload`, `estimate_cost`,
18 `recent_changes`)
19- **Agent auth** — agent-auth protocol discovery at
20 `/.well-known/agent-configuration`, plus an API-key fallback
21 (`POST /v1/agents/register-key`)
22- **TS client** `@modelschemas/client` (packages/client, generated from the
23 spec) and the **`modelschemas` CLI** (packages/cli)
24- **Build-time pulls** — `@modelschemas/vite` (packages/vite) +
25 `@modelschemas/codegen` (packages/codegen): commit selected schemas and
26 generated TypeScript into your repo, fetched at dev time only
27
28## Build-time schema pulls (vite plugin + CLI)
29
30Pull self-contained TypeScript modules (JSON Schema const + generated
31interfaces — pure exports, no barrel, tree-shakeable) into your project.
32Files are committed; production builds touch zero network.
33
34```ts
35// vite.config.ts
36import { modelschemas } from '@modelschemas/vite'
37
38export default defineConfig({
39 plugins: [
40 modelschemas({
41 selections: ['anthropic/v1/messages#request', 'openai/chat/*'],
42 outDir: 'src/modelschemas', // default; commit it
43 apiKey: process.env.MODELSCHEMAS_API_KEY, // optional — lifts rate limits
44 }),
45 ],
46})
47```
48
49```ts
50import {
51 anthropicV1MessagesRequestSchema,
52 type AnthropicV1MessagesRequest,
53} from './modelschemas/anthropic/v1-messages.request.ts'
54```
55
56The dev server pulls whatever is missing and _reports_ upstream schema
57drift (it never rewrites existing files); `modelschemas update` is the
58explicit refresh and the git diff is the review. `vite build` only verifies
59files match the `.manifest.json` lockfile — offline, reproducible. Without
60vite: `modelschemas pull 'anthropic/*' --out src/modelschemas`. The raw
61surface behind all of this is `?format=types` on any
62`/v1/schemas/{provider}/{activity}/{endpointId}` read
63(`?optional=undefined` for `exactOptionalPropertyTypes` consumers who
64assign `undefined` explicitly). Verify locally end-to-end with
65`bun scripts/pull-roundtrip.ts`.
66
67## Provenance & verification
68
69You don't have to trust that a schema served here matches its upstream —
70every derivation is recorded and reproducible:
71
72- **Provenance on every version.** Each stored schema version records the
73 upstream document it was derived from: `sourceUrl`, `sourceHash`
74 (SHA-256 of the document as fetched — for file-served specs,
75 `curl -s <sourceUrl> | shasum -a 256` reproduces it), `fetchedAt`, and
76 the `extractorVersion` that derived it.
77 `GET /v1/schemas/{provider}/{activity}/{endpointId}` returns all of it
78 alongside the schema.
79- **Content-addressed schemas.** `contentHash` is the SHA-256 of the
80 key-sorted schema JSON; it doubles as the ETag and the
81 `?version=<contentHash>` address, so a pinned version is immutable by
82 construction.
83- **Re-derive the hashes yourself.** The extraction pipeline is this repo;
84 `bun scripts/rederive.ts <provider>` runs the same
85 fetchSpec → classify → bundle → hash pipeline the sync engine runs
86 (shared code, `classifyAndBundle`) directly against the upstream spec —
87 no service, no database — and prints every endpoint's `contentHash`.
88 Matching hashes prove the served schema is exactly what the upstream
89 document derives to. If they differ, compare `sourceHash` first: the
90 upstream usually moved after the service's last daily sync.
91- **Verify your pulls.** `modelschemas verify` checks committed files
92 against the `.manifest.json` lockfile, then re-fetches every entry at
93 its pinned `?version=<contentHash>` address, recomputes the hash
94 locally, and exits non-zero on any mismatch — so pulled schemas keep
95 matching their content addresses, with each check's provenance telling
96 you which upstream document to audit.
97
98### Same model at another provider
99
100A model row carries `sameAs: { provider, rawId }` when its own provider names
101the upstream model — a gateway id such as `anthropic/claude-opus-4.5`, or
102Azure's OpenAI model ids — and that model has a catalog row. It is a link
103only: the row's price, limits, and other facts stay its own provider's.
104
105- Within the named provider an exact id wins, then a documented alias, then
106 the same with dots read as hyphens (`claude-opus-4.5` → `claude-opus-4-5`).
107- `sameAs` is `null` when no upstream is stated, or the stated one matches no
108 row or more than one. Priced variants such as `:batch` stay unlinked.
109- `factSources.sameAs` records the source when the link is set, with
110 `normalized: true` for a dots-as-hyphens match. Detail responses include
111 it; `/v1/models` includes it with `?provenance=1`.
112- Links refresh on each model poll (every 15 minutes) and a change emits
113 `model.updated`.
114
115### Capability flags, dates and provider metadata
116
117`null` means "we do not know" on every model field.
118
119- `capabilities` (`Record<string, boolean> | null`) is a map of flags:
120 `{ "tools": true, "reasoning": false }`. `true`: the provider states the
121 model supports it. `false`: the provider states it does not. Key absent:
122 unknown. Never read a missing key as `false`; test
123 `capabilities?.tools === true` to offer a feature and `=== false` to rule
124 it out. `factSources.capabilities[flag]` is the source of each entry, a
125 `true` and a `false` alike; a `false` whose source has `path: 'unlisted'`
126 comes from the provider publishing the model's whole flag list without
127 that flag. `?capability=tools` matches rows whose map has that flag set
128 to `true` (exact flag name).
129- `providerMetadata` (`object | null`): the provider's own listing object,
130 as published and not normalised (fal `category`, BytePlus Ark features,
131 ElevenLabs languages, Replicate visibility, Reactor pricing name). It is
132 different for every provider and nothing in it is a capability flag.
133- `releasedAt` (epoch seconds `| null`): the provider's own stated release
134 or creation date. `firstSeenAt` still holds that date when there is one
135 and our first observation otherwise; `releasedAt` is how to tell them
136 apart. A row keeps its date when a listing stops stating it.
137- `knowledgeCutoff` (`string | null`): `YYYY-MM`, or `YYYY-MM-DD` when the
138 provider states a day. Never padded.
139- `openWeights` (`boolean | null`) and `weightsUrl` (`string | null`): true
140 only when the provider itself states the weights can be downloaded, with
141 its link; false only when it states they cannot. Never inferred from a
142 model name.
143
144`knowledgeCutoff` and `openWeights` are null on every row until provider
145adapters fill them. A row's first `releasedAt` and first `providerMetadata`
146are written without a `model.updated` change; a later change emits one.
147
148## Examples
149
150Three TanStack Start apps in [`examples/`](./examples) exercise the
151packages end-to-end: **schema-studio** (`@modelschemas/vite` pulls →
152generative UI from JSON Schemas), **image-dimensions** (live image-model
153discovery, supported dimensions drawn to scale), and **video-composer**
154(request builder restricted to each video schema's allowed
155model/aspect-ratio/duration values). `bun install`, then `bun run dev`
156inside any example.
157
158## Development
159
160```bash
161bun install
162bun run dev # dev server on http://localhost:3100 (NOT --bun)
163bun run test # vitest: unit + workers-pool projects (NOT --bun)
164bun --bun run lint
165bun run typecheck
166bun --bun run build
167```
168
169Local data setup:
170
171```bash
172bun run db:migrate # apply migrations to wrangler's local D1
173bun run seed # seed the 8 providers
174bun run dev # then, in another shell:
175curl -X POST http://localhost:3100/v1/admin/sync/openrouter -H "X-Admin-Key: $ADMIN_KEY"
176```
177
178Secrets live in `.env.local` (see CLAUDE.md). Pull them from Doppler:
179
180```bash
181bun run secrets:pull # Doppler `dev` → .env.local (strips DOPPLER_*)
182```
183
184`ADMIN_KEY` gates `POST /v1/admin/sync/{provider}` and
185`POST /v1/admin/extract/fal`. Useful scripts:
186`bun scripts/agent-roundtrip.ts` (agent-auth end-to-end),
187`bun scripts/client-smoke.ts` (typed client), `bun run check:client`
188(client/spec drift), `bun scripts/emit-skill.ts` (regenerate SKILL.md),
189`bun scripts/rederive.ts <provider>` (re-derive schema hashes from the
190upstream spec, no service needed).
191
192## Production setup
193
1941. Create resources and put their IDs in `wrangler.jsonc`:
195
196 ```bash
197 bunx wrangler d1 create modelschemas # → d1_databases[0].database_id
198 bunx wrangler kv namespace create SCHEMA_CACHE # → kv_namespaces[0].id
199 ```
200
2012. Apply migrations and seed:
202
203 ```bash
204 bun run db:migrate:remote
205 bun run seed -- --remote
206 ```
207
2083. Secrets (`wrangler secret put <NAME>`): `BETTER_AUTH_SECRET` (32+ random
209 bytes), `ADMIN_KEY`, and optionally provider keys — `OPENAI_API_KEY`,
210 `ANTHROPIC_API_KEY`, `GEMINI_API_KEY`, `XAI_API_KEY`,
211 `ELEVENLABS_API_KEY`, `FAL_KEY`, `ARK_API_KEY`. Providers without keys are
212 skipped with a recorded warning (OpenRouter needs none; Anthropic's spec
213 sync is also keyless). `ARK_API_KEY` is the exception: it is optional and
214 only upgrades BytePlus's model catalog from the embedded one to Ark's live
215 listing — BytePlus still serves schemas and a catalog without it.
216 `GITHUB_TOKEN` is optional too. When set, `api.github.com` requests send
217 `Authorization: Bearer` (the Cloudflare AI Gateway catalog listing). A
218 classic personal access token with no scopes is enough to leave the
219 anonymous 60-requests-per-hour quota that shared Worker egress exhausts.
220 `raw.githubusercontent.com` fetches, including the BytePlus Go SDK, stay
221 unauthenticated, and both polls still run when the token is absent. Set
222 the `BETTER_AUTH_URL` var in `wrangler.jsonc` to the deployed origin
223 (agent JWT audiences are origin-bound).
224
225 Rather than setting them one at a time, reconcile against Doppler:
226
227 ```bash
228 bun run secrets:check # Doppler prd ↔ Worker (names only)
229 bun run secrets:push # apply (one wrangler secret bulk call)
230 ```
231
232 It runs locally against your existing Doppler and wrangler logins, so no
233 token goes near CI. Doppler is the source of truth: every name in the
234 config is pushed except the remove list (`DOPPLER_*` context vars, and
235 `BETTER_AUTH_URL` which is already a wrangler `vars` binding).
236 Secrets are written into a new Worker version rather
237 than the live one (the live API refuses while an undeployed preview
238 version exists); the next deploy inherits them. Nothing is ever deleted.
239 Deliberately NOT a CI job: that would need a long-lived Doppler service
240 token plus a Cloudflare API token in GitHub, turning repo write access
241 into full production compromise.
242
2434. Deploy and warm:
244
245 ```bash
246 bun run deploy
247 curl https://<worker-url>/v1/status
248 curl -X POST https://<worker-url>/v1/admin/sync/openrouter -H "X-Admin-Key: ..."
249 ```
250
251Cron triggers start automatically on deploy: `*/15 * * * *` (models poll +
252webhook drain), four spec-sync shards (`0/10/20/30 5 * * *`) — each shard
253is its own invocation with its own subrequest/CPU budgets, FAL alone in
254shard 0, the rest of the registry round-robined across the other three
255(`SPEC_SYNC_SHARD_CRONS` in `src/server/ingest/sync.ts`) — and six hourly
256firings `0 6-11 * * *` for the FAL per-endpoint `llms.txt` rate-card
257extract (`FAL_PRICING_EXTRACT_CRONS`), each covering ~250 endpoints so the
258whole FAL roster is walked in one calendar day. Most Pricing sections are a
259single unit rate and compile with no model call; only the multi-rate ones
260go to the extract model, once per distinct Pricing-section hash. Force one
261shard's worth with `POST /v1/admin/extract/fal`;
262`POST /v1/admin/sync/fal` stays spec-only.
263
264### Continuous deploys (Workers Builds)
265
266Pushes to `main` deploy via Cloudflare Workers Builds (dashboard → Workers
267& Pages → `modelschemas` → Settings → Build → connect the GitHub repo).
268Settings:
269
270- **Build command:** `bun run build`
271- **Deploy command:** `bun run deploy:ci` — applies pending D1 migrations
272 (`wrangler d1 migrations apply modelschemas --remote`, by database name so
273 a binding rename can't retarget it) and then `wrangler deploy`, which
274 follows the build-emitted redirect (`.wrangler/deploy/config.json`) to the
275 real worker config at `dist/server/wrangler.json`. Deploying the repo-root
276 `wrangler.jsonc` directly will not work.
277- **Non-production branch deploy command:** leave as the default
278 `npx wrangler versions upload` — preview versions share the production D1
279 binding, so migrations must never run from non-production branches.
280
281`bun run deploy` remains the manual/emergency path (build + the same
282migrate-then-deploy).
283
284## Releasing on npm
285
286**Breaking (0.1.x):** `capabilities` is a map of booleans, not a list of
287flag names: `["tools", "reasoning"]` is now `{ "tools": true, "reasoning":
288true }`, and a flag the provider states the model does not support is
289`false`. Replace `capabilities.includes('tools')` with
290`capabilities?.tools === true`. A missing key is unknown, not `false`. The
291provider-native objects five providers kept in `capabilities` (fal
292`{ category }`, BytePlus, ElevenLabs, Replicate, Reactor) moved to the new
293`providerMetadata` field, so `capabilities` is a boolean map or `null` on
294every row. `?capability=` matches a flag set to `true` by exact name; it
295was a substring match over the stored JSON, so `?capability=text-to-image`
296(a fal category) no longer matches anything. Use `?activity=` or read
297`providerMetadata.category`.
298
299**Added (0.1.x):** model rows gain `releasedAt`, `knowledgeCutoff`,
300`openWeights`, `weightsUrl` and `providerMetadata`, all nullable
301("Capability flags, dates and provider metadata" above).
302
303Both need D1 migrations `0013` (columns) and `0014` (stored capability
304lists become maps; native objects move to `provider_metadata`). Migrate
305first, then deploy: `bun run deploy:ci` does both in that order.
306
307**Breaking (0.1.x):** `reasoning.mode` gains `toggle` (an on/off thinking
308switch and nothing else), and `reasoning.mandatory` is `boolean | null`.
309`null` means the provider's source does not say whether thinking can be
310turned off. It must NOT be read as `false`: `if (!reasoning.mandatory)`
311now misreads it, so test `reasoning.mandatory === false` before offering
312an off option. `efforts` is never present on `toggle`, a `toggle` row
313always has a stated `mandatory`, and a `switch (mode)` needs a `toggle`
314case. `true` means the provider states thinking cannot be turned off —
315but rows written before this rule also store `true` when a level list
316merely has no `none`. Until those adapters are converted, treat `true` as
317"inferred" on `openai`, `vercel`, `amazon-bedrock` (effort rows),
318`mistral`, `groq`, `grok`, `zai`, `moonshotai-cn`, `baseten`, `byteplus`,
319`fal`, and on the `effort` rows of `gemini` and `google-vertex`.
320
321**Breaking (0.1.x):** `models.pricing` is a RateCard or `null`, not an
322OpenRouter `{ prompt, completion, … }` blob. List rows carry a summary of
323the stored card — `{ per: 'token', inputPerMillion, outputPerMillion }` at
324the base rate (`tiered: true` when long prompts re-quote), or
325`{ per: 'second' | 'character' | 'image' | 'request' }` for a card billed
326by unit — so `null` on a list row always means no card. `GET
327/v1/models?pricing=1` and model detail return the full card, and
328`GET /v1/status` counts `priced` models per provider. Together all-zero placeholders are
329`null`. `POST /v1/estimate` evaluates a stored card.
330
331**Currencies:** rate cards may be in a currency other than USD.
332`moonshotai-cn` and `minimax-cn` are priced in CNY. A USD card is unchanged;
333a card in another currency wraps its price as
334`{ "currency": ["CNY", <expression>] }` (ISO 4217), and that wrapper is the
335only place the currency is stated. `price()` returns an amount in the
336card's currency. **`@modelschemas/rate-card` 0.1.0 cannot read non-USD
337cards: it rejects them at parse and `price()` throws `unknown-op`, so it
338refuses rather than report yuan as dollars. Upgrade to read them.**
339`/v1/estimate` and `estimate_cost` return `{ amount, currency }`; `usd` is
340present only for USD cards and is deprecated. List summaries always include
341`currency`. Nothing is converted, so amounts in different currencies never
342compare.
343
344Cards come from each host's own source — the OpenRouter, Together and xAI
345listings (`listing`), and the OpenAI, Anthropic and Gemini pricing pages
346(`docs-derived`); `factSources.pricing` says which. Token models carry
347their cache, media-token and long-prompt rates; models billed by the
348second, the minute, the character, the image or the request carry a
349`quantity × rate[size]` card instead. What a source does not state, a card
350does not guess: an unrecognised surcharge, a rate keyed on something the
351request cannot express, or an alias the pricing page never names leaves the
352model with no card rather than a partial one. A card is re-read when its
353source text changes, or once the `expiresAt` of a dated price change has
354passed.
355
356Five public packages (`0.1.0` is on the registry; `@modelschemas/rate-card` from its bootstrap):
357
358| Package | Directory |
359| ------------------------------ | -------------------- |
360| `@modelschemas/client` | `packages/client` |
361| `@modelschemas/codegen` | `packages/codegen` |
362| `@modelschemas/rate-card` | `packages/rate-card` |
363| `@modelschemas/vite` | `packages/vite` |
364| `modelschemas` (CLI, unscoped) | `packages/cli` |
365
366CI **never** holds an npm token. `.github/workflows/publish.yml` packs
367with Bun (rewrites `workspace:*`), then `npm stage publish` over GitHub
368OIDC. A human 2FA-approves each staged version before it is installable.
369
370### Bootstrap (done 2026-08-21)
371
372`npm trust` and `npm stage publish` require the package to already exist,
373so the first version of each name was a laptop `npm publish` with 2FA,
374then stage-only trusted publishers. Repeat that only when adding a **new
375package name**.
376
377Trusted-publisher config on every package must match:
378
379```bash
380npm install -g npm@11.19.0 # trust/stage need >= 11.15; npm 12 wants Node 24.15+
381npm trust github <name> \
382 --file publish.yml \
383 --repo modelschemas/modelschemas \
384 --env npm \
385 --allow-stage-publish
386```
387
388Each package: **Settings → Publishing access → Require two-factor
389authentication and disallow tokens**. GitHub Environment `npm`: required
390reviewer; deployment branches limited to `main` and tags `v*`.
391
392### Ongoing releases
393
3941. Bump the five `package.json` versions together. Commit.
3952. Tag `vX.Y.Z` matching those versions (or create a GitHub Release
396 whose tag is that name) and push the tag.
3973. Actions runs CI, packs, then (after the `npm` environment approval)
398 `npm stage publish`. Inspect the tarball artifacts on the run.
3994. On [npmjs.com](https://www.npmjs.com) → **Staged Packages**, 2FA-approve
400 in the same order as bootstrap. Until you approve, `npm install` cannot
401 see the version.
402
403Dry-run the pipeline without staging:
404
405```bash
406# Actions → Publish → Run workflow, leave dry_run checked
407# or locally:
408bun scripts/npm-pack.ts --pack-dir dist/npm
409```
410
411Do not add `NPM_TOKEN` / `NODE_AUTH_TOKEN` to GitHub Secrets. `bun publish`
412is token-auth only and is not used for releases.
413
414## Runbook: a provider sync is failing
415
4161. `GET /v1/status` — the failing provider shows `status: "degraded"` and a
417 stale `lastSyncedAt`/`lastPolledAt`.
4182. Tail logs during a manual sync (`observability.enabled` is on, so the
419 dashboard's Workers Logs works too):
420
421 ```bash
422 bunx wrangler tail modelschemas --format pretty
423 # in another shell:
424 curl -X POST https://<worker-url>/v1/admin/sync/<provider> -H "X-Admin-Key: ..."
425 ```
426
427 Cron handlers log structured JSON lines:
428 `{"job":"models-poll"|"spec-sync"|"webhooks", outcomes:[{providerId, error?, skipped?, ...}]}`.
429
4303. Interpret the outcome:
431 - `skipped: "<provider>: X_API_KEY not set"` → set the secret
432 (`wrangler secret put X_API_KEY`) or ignore if intentional.
433 - `error: "fetch failed: <url> → 4xx/5xx"` → the upstream spec/models URL
434 moved or is down; check `providers.spec_source_url` (seeded from
435 `src/db/seed-providers.ts`) against the provider's docs.
436 - Dangling-`$ref` warnings → the upstream spec changed shape; see
437 `src/server/ingest/bundle.ts`.
438 - `docsFailing` on a `/v1/status` provider (a `docs` marker on the home
439 page) → a docs page stopped loading or changed shape. Polls go on and
440 `status` stays as it was; the docs-derived facts are frozen at their
441 stored values. `sources` and `error` name the page: fix its parser in
442 the provider's adapter. The next poll whose docs all load clears it.
443 - `priceClearsRefused` on a `/v1/status` provider (a `prices` marker) →
444 a poll asked to clear `refused` of `priced` stored prices and none was
445 cleared. Either the adapter misreads a reshaped listing (fix it), or
446 the prices really are gone (null the stale cards by hand in D1). The
447 next poll that refuses nothing clears it.
448 - Both records are written and cleared only by a poll whose listing
449 loads. While the listing itself fails (`lastPolledAt` stalls) they stay
450 as last written, with an old `lastAt`.
451 - `completeness.score` null for every provider and
452 `completenessComputedAt` null → no score is stored, as after a deploy
453 that changes the scorer. The 15-minute poll cron computes it; trigger
454 that cron to force a recompute. A failed computation logs
455 `{"job":"completeness","error":…}` and keeps the previous scores.
4564. One provider failing never sinks the run (per-provider isolation); fix
457 and re-trigger with the admin sync endpoint. Schema history is preserved
458 across failures — superseded versions stay queryable via
459 `?version=<contentHash>`.
460
461## Architecture
462
463See `CLAUDE.md` for the operational map. `PLAN.md` is the completed build
464log (not the backlog). Borrows the provider-registry,
465activity-grouping, and `$defs`-bundling design from TanStack AI PR #622,
466re-implemented as a runtime service (no codegen) on Workers.