Skip to content
Source
Sign inSign up
TanStack/schemas
Open History to see the last commit

README.md

555 lines27.3 KB

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; model lists include it by default (`?provenance=0` explicitly omits it).
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​
148A `model.updated` event is written only when a fact changed.
149`payload.changed` lists those field paths, for example `contextWindow` or
150`pricing.tables.rate.base.input_tokens`, and is never empty. A source hash,
151an extract time, the operand order of `+`, and the order of an input's
152`values` are not facts: a poll that only moves them writes no row and no
153event. The stored `source` then says when the price last changed.
154`model.added` and `model.removed` are unchanged. `GET /v1/status` adds
155`updateStorm` while one poll updated more than half of a provider's live
156rows (and at least 20). The updates are still written; the field only
157marks them, and the next quieter poll clears it.
158​
159### API stability (`/v1`)
160​
161The model row is typed field by field in [openapi.json](./openapi.json)
162(`Model`, `ModelList`, `ProviderModelList`, `ModelDetail`, `ExportModel`),
163and `@modelschemas/client` types its responses from it.
164​
165- **Additive changes** keep `/v1`: a new field, a new key in a map, a new
166 enum value or change type. Ignore keys you do not know, and handle an
167 enum value you do not know.
168- **Any change to the row shape** (additive or not: a field added,
169 removed, renamed, retyped or moved to another field) bumps
170 `MODEL_ROW_SHAPE.version` in `src/server/row-shape.ts` and ships with a
171 `@modelschemas/client` changeset. `row-shape.test.ts` hashes the row
172 schemas (descriptions excluded) and fails until the record matches, so a
173 shape change cannot merge without one.
174- **The feed announces it.** The first models poll after the deploy
175 (within 15 minutes) writes one `catalog.shape_changed` change per
176 provider, `subjectId: "model-row"`, with
177 `payload: { version, contentHash, previousHash, notes }`, and webhooks
178 deliver it. Watch for it with `GET /v1/changes?type=catalog.shape_changed`.
179 The rows of one announcement share `payload.contentHash`: dedupe on it
180 when you read across providers. A provider added later gets the current
181 shape's row on its first poll.
182- A change that is not additive is also listed as **Breaking** under
183 "Releasing on npm" below.
184​
185## Examples
186​
187Three TanStack Start apps in [`examples/`](./examples) exercise the
188packages end-to-end: **schema-studio** (`@modelschemas/vite` pulls →
189generative UI from JSON Schemas), **image-dimensions** (live image-model
190discovery, supported dimensions drawn to scale), and **video-composer**
191(request builder restricted to each video schema's allowed
192model/aspect-ratio/duration values). `bun install`, then `bun run dev`
193inside any example.
194​
195## Development
196​
197```bash
198bun install
199bun run dev # dev server on http://localhost:3100 (NOT --bun)
200bun run test # vitest: unit + workers-pool projects (NOT --bun)
201bun --bun run lint
202bun run typecheck
203bun --bun run build
204```
205​
206Local data setup:
207​
208```bash
209bun run db:migrate # apply migrations to wrangler's local D1
210bun run seed # seed the 8 providers
211bun run dev # then, in another shell:
212curl -X POST http://localhost:3100/v1/admin/sync/openrouter -H "X-Admin-Key: $ADMIN_KEY"
213```
214​
215Secrets live in `.env.local` (see CLAUDE.md). Pull them from Doppler:
216​
217```bash
218bun run secrets:pull # Doppler `dev` → .env.local (strips DOPPLER_*)
219```
220​
221`ADMIN_KEY` gates `POST /v1/admin/sync/{provider}`,
222`POST /v1/admin/extract/fal`, and `GET /v1/admin/export` (the whole
223catalog in one streamed response, for the git mirror). Useful scripts:
224`bun scripts/agent-roundtrip.ts` (agent-auth end-to-end),
225`bun scripts/client-smoke.ts` (typed client), `bun run check:client`
226(client/spec drift), `bun scripts/emit-skill.ts` (regenerate SKILL.md),
227`bun scripts/rederive.ts <provider>` (re-derive schema hashes from the
228upstream spec, no service needed).
229​
230PostHog browser and API analytics use `VITE_PUBLIC_POSTHOG_PROJECT_TOKEN`
231and `VITE_PUBLIC_POSTHOG_HOST`. Store these in the relevant Doppler config
232and pull them into `.env.local` for development. These are public SDK
233configuration values, not personal API credentials. Keep personal API keys
234out of `VITE_PUBLIC_*` variables, which are included in the browser bundle.
235The existing `POSTHOG_PROJECT_KEY` Worker secret separately captures ingest
236signals.
237​
238Vite reads the public variables at build time. Configure both variables in
239the Cloudflare Workers Builds environment before building production, or
240build locally with `bun run secrets:build` (defaults to Doppler `prd`;
241use `bun run secrets:build --config dev` for another config). This injects
242only `VITE_PUBLIC_*` values from Doppler into the build process without
243writing them to disk.
244`secrets:push` only supplies Worker runtime bindings; it does not configure
245the browser bundle, and skips `VITE_*` bindings. A build without these variables disables the new
246analytics integration in production; development reports missing
247configuration with an error.
248​
249## Production setup
250​
2511. Create resources and put their IDs in `wrangler.jsonc`:
252​
253 ```bash
254 bunx wrangler d1 create modelschemas # → d1_databases[0].database_id
255 bunx wrangler kv namespace create SCHEMA_CACHE # → kv_namespaces[0].id
256 ```
257​
2582. Apply migrations and seed:
259​
260 ```bash
261 bun run db:migrate:remote
262 bun run seed -- --remote
263 ```
264​
2653. Secrets (`wrangler secret put <NAME>`): `BETTER_AUTH_SECRET` (32+ random
266 bytes), `ADMIN_KEY`, and optionally provider keys — `OPENAI_API_KEY`,
267 `ANTHROPIC_API_KEY`, `GEMINI_API_KEY`, `XAI_API_KEY`,
268 `ELEVENLABS_API_KEY`, `FAL_KEY`, `ARK_API_KEY`. Providers without keys are
269 skipped with a recorded warning (OpenRouter needs none; Anthropic's spec
270 sync is also keyless). `ARK_API_KEY` is the exception: it is optional and
271 only upgrades BytePlus's model catalog from the embedded one to Ark's live
272 listing — BytePlus still serves schemas and a catalog without it.
273 `GITHUB_TOKEN` is optional too. When set, `api.github.com` requests send
274 `Authorization: Bearer` (the Cloudflare AI Gateway catalog listing). A
275 classic personal access token with no scopes is enough to leave the
276 anonymous 60-requests-per-hour quota that shared Worker egress exhausts.
277 `raw.githubusercontent.com` fetches, including the BytePlus Go SDK, stay
278 unauthenticated, and both polls still run when the token is absent. Set
279 the `BETTER_AUTH_URL` var in `wrangler.jsonc` to the deployed origin
280 (agent JWT audiences are origin-bound).
281​
282 Rather than setting them one at a time, reconcile against Doppler:
283​
284 ```bash
285 bun run secrets:check # Doppler prd ↔ Worker (names only)
286 bun run secrets:push # apply (one wrangler secret bulk call)
287 ```
288​
289 It runs locally against your existing Doppler and wrangler logins, so no
290 token goes near CI. Doppler is the source of truth: every name in the
291 config is pushed except the remove list (`DOPPLER_*` context vars, and
292 `BETTER_AUTH_URL` which is already a wrangler `vars` binding, and
293 `VITE_*` build-time configuration).
294 Secrets are written into a new Worker version rather
295 than the live one (the live API refuses while an undeployed preview
296 version exists); the next deploy inherits them. Nothing is ever deleted.
297 Deliberately NOT a CI job: that would need a long-lived Doppler service
298 token plus a Cloudflare API token in GitHub, turning repo write access
299 into full production compromise.
300​
3014. Deploy and warm:
302​
303 ```bash
304 bun run deploy
305 curl https://<worker-url>/v1/status
306 curl -X POST https://<worker-url>/v1/admin/sync/openrouter -H "X-Admin-Key: ..."
307 ```
308​
309Cron triggers start automatically on deploy: `*/15 * * * *` (models poll +
310webhook drain), four spec-sync shards (`0/10/20/30 5 * * *`) — each shard
311is its own invocation with its own subrequest/CPU budgets, FAL alone in
312shard 0, the rest of the registry round-robined across the other three
313(`SPEC_SYNC_SHARD_CRONS` in `src/server/ingest/sync.ts`) — and six hourly
314firings `0 6-11 * * *` for the FAL per-endpoint `llms.txt` rate-card
315extract (`FAL_PRICING_EXTRACT_CRONS`), each covering ~250 endpoints so the
316whole FAL roster is walked in one calendar day. Most Pricing sections are a
317single unit rate and compile with no model call; only the multi-rate ones
318go to the extract model, once per distinct Pricing-section hash. Force one
319shard's worth with `POST /v1/admin/extract/fal`;
320`POST /v1/admin/sync/fal` stays spec-only.
321​
322### Continuous deploys (Workers Builds)
323​
324Pushes to `main` deploy via Cloudflare Workers Builds (dashboard → Workers
325& Pages → `modelschemas` → Settings → Build → connect the GitHub repo).
326Settings:
327​
328- **Build command:** `bun run build`
329- **Deploy command:** `bun run deploy:ci` — applies pending D1 migrations
330 (`wrangler d1 migrations apply modelschemas --remote`, by database name so
331 a binding rename can't retarget it) and then `wrangler deploy`, which
332 follows the build-emitted redirect (`.wrangler/deploy/config.json`) to the
333 real worker config at `dist/server/wrangler.json`. Deploying the repo-root
334 `wrangler.jsonc` directly will not work.
335- **Non-production branch deploy command:** leave as the default
336 `npx wrangler versions upload` — preview versions share the production D1
337 binding, so migrations must never run from non-production branches.
338​
339`bun run deploy` remains the manual/emergency path (build + the same
340migrate-then-deploy).
341​
342## Releasing on npm
343​
344**Breaking (0.1.x):** `capabilities` is a map of booleans, not a list of
345flag names: `["tools", "reasoning"]` is now `{ "tools": true, "reasoning":
346true }`, and a flag the provider states the model does not support is
347`false`. Replace `capabilities.includes('tools')` with
348`capabilities?.tools === true`. A missing key is unknown, not `false`. The
349provider-native objects five providers kept in `capabilities` (fal
350`{ category }`, BytePlus, ElevenLabs, Replicate, Reactor) moved to the new
351`providerMetadata` field, so `capabilities` is a boolean map or `null` on
352every row. `?capability=` matches a flag set to `true` by exact name; it
353was a substring match over the stored JSON, so `?capability=text-to-image`
354(a fal category) no longer matches anything. Use `?activity=` or read
355`providerMetadata.category`.
356​
357**Added (0.1.x):** model rows gain `releasedAt`, `knowledgeCutoff`,
358`openWeights`, `weightsUrl` and `providerMetadata`, all nullable
359("Capability flags, dates and provider metadata" above).
360​
361Both need D1 migrations `0013` (columns) and `0014` (stored capability
362lists become maps; native objects move to `provider_metadata`). Migrate
363first, then deploy: `bun run deploy:ci` does both in that order.
364​
365**Breaking (0.1.x):** `reasoning.mode` gains `toggle` (an on/off thinking
366switch and nothing else), and `reasoning.mandatory` is `boolean | null`.
367`null` means the provider's source does not say whether thinking can be
368turned off. It must NOT be read as `false`: `if (!reasoning.mandatory)`
369now misreads it, so test `reasoning.mandatory === false` before offering
370an off option. `efforts` is never present on `toggle`, a `toggle` row
371always has a stated `mandatory`, and a `switch (mode)` needs a `toggle`
372case. `true` means the provider states thinking cannot be turned off —
373but rows written before this rule also store `true` when a level list
374merely has no `none`. Until those adapters are converted, treat `true` as
375"inferred" on `openai`, `vercel`, `amazon-bedrock` (effort rows),
376`mistral`, `groq`, `grok`, `moonshotai-cn`, `baseten`, `byteplus`,
377`fal`, and on the `effort` rows of `gemini` and `google-vertex`.
378​
379**Breaking (0.1.x):** `models.pricing` is a RateCard or `null`, not an
380OpenRouter `{ prompt, completion, … }` blob. List rows carry a summary of
381the stored card — `{ per: 'token', inputPerMillion, outputPerMillion }` at
382the base rate (`tiered: true` when long prompts re-quote), or
383`{ per: 'second' | 'character' | 'image' | 'request' }` for a card billed
384by unit — so `null` on a list row always means no card. `GET
385/v1/models?pricing=1` and model detail return the full card, and
386`GET /v1/status` counts `priced` models per provider. Together all-zero placeholders are
387`null`. `POST /v1/estimate` evaluates a stored card.
388​
389**Breaking (0.1.x):** `opencode-go` endpoint ids moved from `v1/<tail>` to
390the documented `inference/go/<protocol>/v1/<tail>` (#393), e.g.
391`/v1/schemas/opencode-go/chat/inference/go/openai/v1/chat/completions`.
392The next spec sync emits `endpoint.removed` for the old ids. Until it runs,
393polls leave Go models unbound; run `POST /v1/admin/sync/opencode-go` after
394deploy.
395​
396**Currencies:** rate cards may be in a currency other than USD.
397`moonshotai-cn` and `minimax-cn` are priced in CNY. A USD card is unchanged;
398a card in another currency wraps its price as
399`{ "currency": ["CNY", <expression>] }` (ISO 4217), and that wrapper is the
400only place the currency is stated. `price()` returns an amount in the
401card's currency. **`@modelschemas/rate-card` 0.1.0 cannot read non-USD
402cards: it rejects them at parse and `price()` throws `unknown-op`, so it
403refuses rather than report yuan as dollars. 0.2.0 reads them.**
404`/v1/estimate` and `estimate_cost` return `{ amount, currency }`; `usd` is
405present only for USD cards and is deprecated. List summaries always include
406`currency`. Nothing is converted, so amounts in different currencies never
407compare.
408​
409Cards come from each host's own source — the OpenRouter, Together and xAI
410listings (`listing`), and the OpenAI, Anthropic and Gemini pricing pages
411(`docs-derived`); `factSources.pricing` says which. Token models carry
412their cache, media-token and long-prompt rates; models billed by the
413second, the minute, the character, the image or the request carry a
414`quantity × rate[size]` card instead. What a source does not state, a card
415does not guess: an unrecognised surcharge, a rate keyed on something the
416request cannot express, or an alias the pricing page never names leaves the
417model with no card rather than a partial one. A card is re-read when its
418source text changes, or once the `expiresAt` of a dated price change has
419passed.
420​
421**Breaking (`@modelschemas/rate-card` 0.2.0):** the package ships built
422JS and .d.ts, not TypeScript source. `zod` is an optional peer
423dependency: install it to import the package root (`rateCardSchema`).
424`@modelschemas/rate-card/evaluator` (`evaluateCard`, `price`,
425`normalizeUsage`) imports no package and runs on edge runtimes.
426​
427Five public packages (`0.1.0` is on the registry; `@modelschemas/rate-card` from its bootstrap; `0.2.0` is the next release):
428​
429| Package | Directory |
430| ------------------------------ | -------------------- |
431| `@modelschemas/client` | `packages/client` |
432| `@modelschemas/codegen` | `packages/codegen` |
433| `@modelschemas/rate-card` | `packages/rate-card` |
434| `@modelschemas/vite` | `packages/vite` |
435| `modelschemas` (CLI, unscoped) | `packages/cli` |
436​
437CI **never** holds an npm token. `.github/workflows/publish.yml` packs
438with Bun (rewrites `workspace:*`), then `npm stage publish` over GitHub
439OIDC. A human 2FA-approves each staged version before it is installable.
440​
441### Bootstrap (done 2026-08-21)
442​
443`npm trust` and `npm stage publish` require the package to already exist,
444so the first version of each name was a laptop `npm publish` with 2FA,
445then stage-only trusted publishers. Repeat that only when adding a **new
446package name**.
447​
448Trusted-publisher config on every package must match:
449​
450```bash
451npm install -g npm@11.19.0 # trust/stage need >= 11.15; npm 12 wants Node 24.15+
452npm trust github <name> \
453 --file publish.yml \
454 --repo modelschemas/modelschemas \
455 --env npm \
456 --allow-stage-publish
457```
458​
459Each package: **Settings → Publishing access → Require two-factor
460authentication and disallow tokens**. GitHub Environment `npm`: required
461reviewer; deployment branches limited to `main` and tags `v*`.
462​
463### Ongoing releases
464​
4651. A PR that changes a published package adds a changeset
466 (`bunx changeset`). The five packages share one version. MAJOR.MINOR
467 must equal `RATE_CARD_LANGUAGE` in `packages/rate-card/src/card.ts`
468 (a test checks it): a release that changes what a card can say bumps
469 both (minor), and a release that does not is a patch.
4702. On main, the Publish workflow keeps a **Version Packages** PR open
471 that applies the pending changesets (versions + CHANGELOGs). Merge it.
4723. That merge's Publish run sees no changesets and a version npm lacks,
473 so it runs CI, packs, then (after the `npm` environment approval)
474 `npm stage publish`. Inspect the tarball artifacts on the run. Pushing
475 a `vX.Y.Z` tag still works as a manual trigger.
4764. On [npmjs.com](https://www.npmjs.com) → **Staged Packages**, 2FA-approve
477 in the same order as bootstrap. Until you approve, `npm install` cannot
478 see the version.
479​
480Dry-run the pipeline without staging:
481​
482```bash
483# Actions → Publish → Run workflow, leave dry_run checked
484# or locally:
485bun scripts/npm-pack.ts --pack-dir dist/npm
486```
487​
488Do not add `NPM_TOKEN` / `NODE_AUTH_TOKEN` to GitHub Secrets. `bun publish`
489is token-auth only and is not used for releases.
490​
491## Runbook: a provider sync is failing
492​
4931. `GET /v1/status` — the failing provider shows `status: "degraded"` and a
494 stale `lastSyncedAt`/`lastPolledAt`.
4952. Tail logs during a manual sync (`observability.enabled` is on, so the
496 dashboard's Workers Logs works too):
497​
498 ```bash
499 bunx wrangler tail modelschemas --format pretty
500 # in another shell:
501 curl -X POST https://<worker-url>/v1/admin/sync/<provider> -H "X-Admin-Key: ..."
502 ```
503​
504 Cron handlers log structured JSON lines:
505 `{"job":"models-poll"|"spec-sync"|"webhooks", outcomes:[{providerId, error?, skipped?, ...}]}`.
506​
5073. Interpret the outcome:
508 - `skipped: "<provider>: X_API_KEY not set"` → set the secret
509 (`wrangler secret put X_API_KEY`) or ignore if intentional.
510 - `error: "fetch failed: <url> → 4xx/5xx"` → the upstream spec/models URL
511 moved or is down; check `providers.spec_source_url` (seeded from
512 `src/db/seed-providers.ts`) against the provider's docs.
513 - Anthropic `403 forbidden` or Gemini
514 `User location is not supported` on the models poll → the provider
515 refused the caller's region. Their listing calls go through the `US_EGRESS`
516 Durable Object (`src/server/providers/us-egress.ts`), created with
517 `locationHint: 'enam'`. The hint is best effort and an object never
518 moves, so if this persists, change its name (`provider-egress`) so
519 a fresh object is created under the hint.
520 - Dangling-`$ref` warnings → the upstream spec changed shape; see
521 `src/server/ingest/bundle.ts`.
522 - `docsFailing` on a `/v1/status` provider (a `docs` marker on the home
523 page) → a docs page stopped loading or changed shape. Polls go on and
524 `status` stays as it was; the docs-derived facts are frozen at their
525 stored values. `sources` and `error` name the page: fix its parser in
526 the provider's adapter. The next poll whose docs all load clears it.
527 - `priceClearsRefused` on a `/v1/status` provider (a `prices` marker) →
528 a poll asked to clear `refused` of `priced` stored prices and none was
529 cleared. Either the adapter misreads a reshaped listing (fix it), or
530 the prices really are gone (null the stale cards by hand in D1). The
531 next poll that refuses nothing clears it.
532 - `updateStorm` on a `/v1/status` provider (an `updates` marker) → one
533 poll wrote `model.updated` for more than half of the live rows, and
534 at least 20. The events were written. A new kind of non-fact is the
535 usual cause; a real catalog-wide repricing looks the same. The next
536 poll under that line clears it.
537 - Those records are written and cleared only by a poll whose listing
538 loads. While the listing itself fails (`lastPolledAt` stalls) they stay
539 as last written, with an old `lastAt`.
540 - `completeness.score` null for every provider and
541 `completenessComputedAt` null → no score is stored, as after a deploy
542 that changes the scorer. The 15-minute poll cron computes it; trigger
543 that cron to force a recompute. A failed computation logs
544 `{"job":"completeness","error":…}` and keeps the previous scores.
5454. One provider failing never sinks the run (per-provider isolation); fix
546 and re-trigger with the admin sync endpoint. Schema history is preserved
547 across failures — superseded versions stay queryable via
548 `?version=<contentHash>`.
549​
550## Architecture
551​
552See `CLAUDE.md` for the operational map. `PLAN.md` is the completed build
553log (not the backlog). Borrows the provider-registry,
554activity-grouping, and `$defs`-bundling design from TanStack AI PR #622,
555re-implemented as a runtime service (no codegen) on Workers.