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 public GETs on a D1 read session and edge caching (`max-age` of
715 minutes on catalog and current schema reads; a year on
8`?version=<hash>`; purged after an admin sync). Turn on D1 read replication
9(`read_replication.mode: auto`) only after #554 recreates the database
10with a US primary; until then the session still reads the primary.
11Automatic refresh — model lists every 15 minutes, full OpenAPI spec
12syncs daily. KV holds rate-limit counters and the docs cache the crons use.
13
14Surfaces:
15
16- **HTTP API** under `/v1` — catalog, schemas, validation, cost estimate,
17 changes feed (see `GET /v1` or [openapi.json](./openapi.json))
18- **Agent guide** at `/llms.txt`, **agent skill** at `/skill`, **docs** at `/docs`
19- **MCP server** at `/mcp` (streamable HTTP; tools: `list_models`,
20 `get_model`, `get_schema`, `validate_payload`, `estimate_cost`,
21 `recent_changes`)
22- **Agent auth** — agent-auth protocol discovery at
23 `/.well-known/agent-configuration`, plus an API-key fallback
24 (`POST /v1/agents/register-key`)
25- **TS client** `@modelschemas/client` (packages/client, generated from the
26 spec) and the **`modelschemas` CLI** (packages/cli)
27- **Build-time pulls** — `@modelschemas/vite` (packages/vite) +
28 `@modelschemas/codegen` (packages/codegen): commit selected schemas and
29 generated TypeScript into your repo, fetched at dev time only
30
31## Build-time schema pulls (vite plugin + CLI)
32
33Pull self-contained TypeScript modules (JSON Schema const + generated
34interfaces — pure exports, no barrel, tree-shakeable) into your project.
35Files are committed; production builds touch zero network.
36
37```ts
38// vite.config.ts
39import { modelschemas } from '@modelschemas/vite'
40
41export default defineConfig({
42 plugins: [
43 modelschemas({
44 selections: ['anthropic/v1/messages#request', 'openai/chat/*'],
45 outDir: 'src/modelschemas', // default; commit it
46 apiKey: process.env.MODELSCHEMAS_API_KEY, // optional — lifts rate limits
47 }),
48 ],
49})
50```
51
52```ts
53import {
54 anthropicV1MessagesRequestSchema,
55 type AnthropicV1MessagesRequest,
56} from './modelschemas/anthropic/v1-messages.request.ts'
57```
58
59The dev server pulls whatever is missing and _reports_ upstream schema
60drift (it never rewrites existing files); `modelschemas update` is the
61explicit refresh and the git diff is the review. `vite build` only verifies
62files match the `.manifest.json` lockfile — offline, reproducible. Without
63vite: `modelschemas pull 'anthropic/*' --out src/modelschemas`. The raw
64surface behind all of this is `?format=types` on any
65`/v1/schemas/{provider}/{activity}/{endpointId}` read
66(`?optional=undefined` for `exactOptionalPropertyTypes` consumers who
67assign `undefined` explicitly). Verify locally end-to-end with
68`pnpm run pull-roundtrip`.
69
70## Provenance & verification
71
72You don't have to trust that a schema served here matches its upstream —
73every derivation is recorded and reproducible:
74
75- **Provenance on every version.** Each stored schema version records the
76 upstream document it was derived from: `sourceUrl`, `sourceHash`
77 (SHA-256 of the document as fetched — for file-served specs,
78 `curl -s <sourceUrl> | shasum -a 256` reproduces it), `fetchedAt`, and
79 the `extractorVersion` that derived it.
80 `GET /v1/schemas/{provider}/{activity}/{endpointId}` returns all of it
81 alongside the schema.
82- **Content-addressed schemas.** `contentHash` is the SHA-256 of the
83 key-sorted schema JSON; it doubles as the ETag and the
84 `?version=<contentHash>` address, so a pinned version is immutable by
85 construction.
86- **Re-derive the hashes yourself.** The extraction pipeline is this repo;
87 `pnpm run rederive -- <provider>` runs the same
88 fetchSpec → classify → bundle → hash pipeline the sync engine runs
89 (shared code, `classifyAndBundle`) directly against the upstream spec —
90 no service, no database — and prints every endpoint's `contentHash`.
91 Matching hashes prove the served schema is exactly what the upstream
92 document derives to. If they differ, compare `sourceHash` first: the
93 upstream usually moved after the service's last daily sync.
94- **Verify your pulls.** `modelschemas verify` checks committed files
95 against the `.manifest.json` lockfile, then re-fetches every entry at
96 its pinned `?version=<contentHash>` address, recomputes the hash
97 locally, and exits non-zero on any mismatch — so pulled schemas keep
98 matching their content addresses, with each check's provenance telling
99 you which upstream document to audit.
100
101### Same model at another provider
102
103A model row carries `sameAs: { provider, rawId }` when its own provider names
104the upstream model — a gateway id such as `anthropic/claude-opus-4.5`, or
105Azure's OpenAI model ids — and that model has a catalog row. It is a link
106only: the row's price, limits, and other facts stay its own provider's.
107
108- Within the named provider an exact id wins, then a documented alias, then
109 the same with dots read as hyphens (`claude-opus-4.5` → `claude-opus-4-5`).
110- `sameAs` is `null` when no upstream is stated, or the stated one matches no
111 row or more than one. Priced variants such as `:batch` stay unlinked.
112- `factSources.sameAs` records the source when the link is set, with
113 `normalized: true` for a dots-as-hyphens match. Detail responses include
114 it; model lists include it by default (`?provenance=0` explicitly omits it).
115- Links refresh on each model poll (every 15 minutes) and a change emits
116 `model.updated`.
117
118### Aliases at the same provider
119
120An alias id and the model it resolves to are linked both ways when the
121provider states it (#709): the alias row's `aliasOf` is the target's
122`rawId`, and the target's `aliases` lists the alias. The statement comes
123from an OpenAI model page's `Default snapshot` or a Gemini changelog line.
124Mistral's `GET /v1/models` states alias groups only: every member lists
125the others in `aliases`, and none names which id the others resolve to.
126It is never read from an id's shape.
127
128- `aliasOf` is `null` when the provider names no target, or the named
129 target has no live row (the evidence is kept and links again when the
130 row returns).
131- `factSources.aliasOf` is its source. `path: "unstated"` means the
132 source was read and names no target for this id (every grouped Mistral
133 row, Gemini `-latest` ids no changelog line names).
134- With `aliases: null`, `factSources.aliases` with `path: "Snapshots"`
135 means the OpenAI page lists the snapshot and no alias resolves to it;
136 `path: "unstated"` means no docs page names the id.
137- An alias may be a row of its own, so `aliases` can name listed ids.
138
139### Capability flags, dates and provider metadata
140
141`null` means "we do not know" on every model field.
142
143- `capabilities` (`Record<string, boolean> | null`) is a map of flags:
144 `{ "tools": true, "reasoning": false }`. `true`: the provider states the
145 model supports it. `false`: the provider states it does not. Key absent:
146 unknown. Never read a missing key as `false`; test
147 `capabilities?.tools === true` to offer a feature and `=== false` to rule
148 it out. `factSources.capabilities[flag]` is the source of each entry, a
149 `true` and a `false` alike; a `false` whose source has `path: 'unlisted'`
150 comes from the provider publishing the model's whole flag list without
151 that flag. `?capability=tools` matches rows whose map has that flag set
152 to `true` (exact flag name).
153- `providerMetadata` (`object | null`): the provider's own listing object,
154 as published and not normalised (fal `category`, BytePlus Ark features,
155 ElevenLabs languages, Replicate visibility, Reactor pricing name). It is
156 different for every provider and nothing in it is a capability flag.
157- `releasedAt` (epoch seconds `| null`): the provider's own stated release
158 or creation date. `firstSeenAt` still holds that date when there is one
159 and our first observation otherwise; `releasedAt` is how to tell them
160 apart. A row keeps its date when a listing stops stating it.
161- `knowledgeCutoff` (`string | null`): `YYYY-MM`, or `YYYY-MM-DD` when the
162 provider states a day. Never padded.
163- `openWeights` (`boolean | null`) and `weightsUrl` (`string | null`): true
164 only when the provider itself states the weights can be downloaded, with
165 its link; false only when it states they cannot. Never inferred from a
166 model name.
167- `requiredRequestHeaders` (`array | null`): the client-supplied entries of
168 the provider connect profile `requiredHeaders` (`name` plus the rule for
169 the value). A constant header, such as `anthropic-version`, stays on
170 `GET /v1/openapi/{provider}` as `schema.const` and is not copied here.
171 Null when the provider publishes none. OpenCode Go lists
172 `x-opencode-session` and `User-Agent`
173 ([Go docs](https://opencode.ai/docs/console/go/), "Where can I use it?"). The
174 same headers are parameters on each Go operation.
175- `trainsOnRequestData` (`true | null`): true when that model's own source
176 states it trains on request data. OpenCode Go reads `go.training` on
177 `GET https://opencode.ai/inference/go/v1/models` (the boolean the console
178 privacy view shows). An id that list does not name can still be true from
179 that id's probe record. Null when `go.training` is false, or no source
180 states it. Never inferred from an id suffix or from a retention period.
181
182`knowledgeCutoff` and `openWeights` are null on every row until provider
183adapters fill them. A row's first `releasedAt` and first `providerMetadata`
184are written without a `model.updated` change; a later change emits one.
185
186A `model.updated` event is written only when a fact changed.
187`payload.changed` lists those field paths, for example `contextWindow` or
188`pricing.tables.rate.base.input_tokens`, and is never empty. A source hash,
189an extract time, the operand order of `+`, and the order of an input's
190`values` are not facts: a poll that only moves them writes no row and no
191event. The stored `source` then says when the price last changed.
192`model.added` and `model.removed` are unchanged. `GET /v1/status` adds
193`updateStorm` while one poll updated more than half of a provider's live
194rows (and at least 20). The updates are still written; the field only
195marks them, and the next quieter poll clears it.
196
197### API stability (`/v1`)
198
199The model row is typed field by field in [openapi.json](./openapi.json)
200(`Model`, `ModelList`, `ProviderModelList`, `ModelDetail`, `ExportModel`),
201and `@modelschemas/client` types its responses from it.
202
203- **Additive changes** keep `/v1`: a new field, a new key in a map, a new
204 enum value or change type. Ignore keys you do not know, and handle an
205 enum value you do not know.
206- **Any change to the row shape** (additive or not: a field added,
207 removed, renamed, retyped or moved to another field) bumps
208 `MODEL_ROW_SHAPE.version` in `src/server/row-shape.ts` and ships with a
209 `@modelschemas/client` changeset. `row-shape.test.ts` hashes the row
210 schemas (descriptions and the emitter's spelling excluded) and fails
211 until the record matches, so a shape change cannot merge without one. A
212 hash that moves with no served change (a zod bump respelling the same
213 schema) is re-recorded under the same version and announces nothing.
214- **The feed announces it.** The first models poll after the deploy
215 (within 15 minutes) writes one `catalog.shape_changed` change per
216 provider, `subjectId: "model-row"`, with
217 `payload: { version, contentHash, previousHash, notes }`, and webhooks
218 deliver it. Watch for it with `GET /v1/changes?type=catalog.shape_changed`.
219 The rows of one announcement share `payload.contentHash`: dedupe on it
220 when you read across providers. A provider added later gets the current
221 shape's row on its first poll.
222- A change that is not additive is also recorded in
223 [docs/api-changes.md](docs/api-changes.md).
224
225### Generation OpenAPI (`GET /v1/openapi/{provider}`)
226
227One operation per endpoint. A response that can be JSON or a stream lists
228`application/json` (or `text/plain`) and `text/event-stream` under one
229`200`, as OpenAI's own spec does. Each schema's `$defs` are hoisted into
230`components.schemas`, so every `$ref` resolves within the document;
231identical definitions share one name, and a name two endpoints define
232differently gets a content-hash suffix. An upstream `#stream` path key
233(Mistral transcriptions) is merged into its base operation: the request
234body is `anyOf` both variants (`stream: false` / `stream: true`). A
235document that would still hold an unresolved `$ref` is refused with
236`500 unresolved_refs`, naming the ref and where it sits; twins that list
237one media type with different schemas are refused with
238`500 schema_conflict`.
239
240**Breaking:** the `{path}#stream` SSE twins are gone. hey-api 0.99.0 types
241a JSON-or-SSE response as JSON only and returns the stream as one string
242([hey-api/hey-api#4482](https://github.com/hey-api/hey-api/issues/4482)),
243so a hey-api client loses typed streaming until that is fixed. Kubb v5
244handles it: the response is a union keyed by content type, and
245`toEventStream()` yields typed events.
246
247## Examples
248
249Three TanStack Start apps in [`examples/`](./examples) exercise the
250packages end-to-end: **schema-studio** (`@modelschemas/vite` pulls →
251generative UI from JSON Schemas), **image-dimensions** (live image-model
252discovery, supported dimensions drawn to scale), and **video-composer**
253(request builder restricted to each video schema's allowed
254model/aspect-ratio/duration values). `pnpm install`, then `pnpm run dev`
255inside any example.
256
257## Development
258
259Node.js 24 or newer (`package.json` `engines`). pnpm 11.9 (`packageManager`).
260
261```bash
262pnpm install
263pnpm run dev # dev server on http://localhost:3100
264pnpm run test # vitest: unit + workers-pool projects
265pnpm run lint
266pnpm run typecheck
267pnpm run build
268```
269
270Local data setup:
271
272```bash
273pnpm run db:migrate # apply migrations to wrangler's local D1
274pnpm run seed # seed the 8 providers
275pnpm run dev # then, in another shell:
276curl -X POST http://localhost:3100/v1/admin/sync/openrouter -H "X-Admin-Key: $ADMIN_KEY"
277```
278
279Secrets live in `.env.local` (see CLAUDE.md). Pull them from Doppler:
280
281```bash
282pnpm run secrets:pull # Doppler `dev` → .env.local (strips DOPPLER_*)
283```
284
285`ADMIN_KEY` gates `POST /v1/admin/sync/{provider}`,
286`POST /v1/admin/extract/fal`, and `GET /v1/admin/export` (the whole
287catalog in one streamed response, for the git mirror). Useful scripts:
288`pnpm run agent-roundtrip` (agent-auth end-to-end),
289`pnpm run client-smoke` (typed client), `pnpm run check:client`
290(client/spec drift), `pnpm run emit-skill` (regenerate SKILL.md),
291`pnpm run rederive -- <provider>` (re-derive schema hashes from the
292upstream spec, no service needed).
293
294PostHog browser and API analytics use `VITE_PUBLIC_POSTHOG_PROJECT_TOKEN`
295and `VITE_PUBLIC_POSTHOG_HOST`. Store these in the relevant Doppler config
296and pull them into `.env.local` for development. These are public SDK
297configuration values, not personal API credentials. Keep personal API keys
298out of `VITE_PUBLIC_*` variables, which are included in the browser bundle.
299The existing `POSTHOG_PROJECT_KEY` Worker secret separately captures ingest
300signals.
301
302Vite reads the public variables at build time. Configure both variables in
303the Cloudflare Workers Builds environment before building production, or
304build locally with `pnpm run secrets:build` (defaults to Doppler `prd`;
305use `pnpm run secrets:build --config dev` for another config). This injects
306only `VITE_PUBLIC_*` values from Doppler into the build process without
307writing them to disk.
308`secrets:push` only supplies Worker runtime bindings; it does not configure
309the browser bundle, and skips `VITE_*` bindings. A build without these variables disables the new
310analytics integration in production; development reports missing
311configuration with an error.
312
313## Production setup
314
3151. Create resources and put their IDs in `wrangler.jsonc`:
316
317 ```bash
318 pnpm exec wrangler d1 create modelschemas # → d1_databases[0].database_id
319 pnpm exec wrangler kv namespace create SCHEMA_CACHE # → kv_namespaces[0].id
320 ```
321
3222. Apply migrations and seed:
323
324 ```bash
325 pnpm run db:migrate:remote
326 pnpm run seed -- --remote
327 ```
328
3293. Secrets (`wrangler secret put <NAME>`): `BETTER_AUTH_SECRET` (32+ random
330 bytes), `ADMIN_KEY`, and optionally provider keys — `OPENAI_API_KEY`,
331 `ANTHROPIC_API_KEY`, `GEMINI_API_KEY`, `XAI_API_KEY`,
332 `ELEVENLABS_API_KEY`, `FAL_KEY`, `ARK_API_KEY`. Providers without keys are
333 skipped with a recorded warning (OpenRouter needs none; Anthropic's spec
334 sync is also keyless). `ARK_API_KEY` is the exception: it is optional and
335 only upgrades BytePlus's model catalog from the embedded one to Ark's live
336 listing — BytePlus still serves schemas and a catalog without it.
337 `GITHUB_TOKEN` is optional too. When set, `api.github.com` requests send
338 `Authorization: Bearer` (the Cloudflare AI Gateway catalog listing). A
339 classic personal access token with no scopes is enough to leave the
340 anonymous 60-requests-per-hour quota that shared Worker egress exhausts.
341 `raw.githubusercontent.com` fetches, including the BytePlus Go SDK, stay
342 unauthenticated, and both polls still run when the token is absent. Set
343 the `BETTER_AUTH_URL` var in `wrangler.jsonc` to the deployed origin
344 (agent JWT audiences are origin-bound).
345
346 Rather than setting them one at a time, reconcile against Doppler:
347
348 ```bash
349 pnpm run secrets:check # Doppler prd ↔ Worker (names only)
350 pnpm run secrets:push # apply (one wrangler secret bulk call)
351 ```
352
353 It runs locally against your existing Doppler and wrangler logins, so no
354 token goes near CI. Doppler is the source of truth: every name in the
355 config is pushed except the remove list (`DOPPLER_*` context vars, and
356 `BETTER_AUTH_URL` which is already a wrangler `vars` binding, and
357 `VITE_*` build-time configuration).
358 Secrets are written into a new Worker version rather
359 than the live one (the live API refuses while an undeployed preview
360 version exists); the next deploy inherits them. Nothing is ever deleted.
361 Deliberately NOT a CI job: that would need a long-lived Doppler service
362 token plus a Cloudflare API token in GitHub, turning repo write access
363 into full production compromise.
364
3654. Deploy and warm:
366
367 ```bash
368 pnpm run deploy
369 curl https://<worker-url>/v1/status
370 curl -X POST https://<worker-url>/v1/admin/sync/openrouter -H "X-Admin-Key: ..."
371 ```
372
373Cron triggers start automatically on deploy: `*/15 * * * *` (models poll +
374webhook drain), four spec-sync shards (`0/10/20/30 5 * * *`) — each shard
375is its own invocation with its own subrequest/CPU budgets, FAL alone in
376shard 0, the rest of the registry round-robined across the other three
377(`SPEC_SYNC_SHARD_CRONS` in `src/server/ingest/sync.ts`) — a daily
378`0 4 * * *` firing for Vercel `/endpoints` price ranges
379(`VERCEL_PRICING_EXTRACT_CRON`; rows with `varies_by_provider` only) —
380and six hourly
381firings `0 6-11 * * *` for the FAL per-endpoint `llms.txt` rate-card
382extract (`FAL_PRICING_EXTRACT_CRONS`), each covering ~250 endpoints so the
383whole FAL roster is walked in one calendar day. Most Pricing sections are a
384single unit rate and compile with no model call; only the multi-rate ones
385go to the extract model, once per distinct Pricing-section hash. Force one
386shard's worth with `POST /v1/admin/extract/fal`;
387`POST /v1/admin/sync/fal` stays spec-only.
388
389The extract model runs through Cloudflare AI Gateway on Unified Billing,
390so its cost lands on the Cloudflare bill and needs no provider key: the
391Worker's `AI` binding calls the gateway named by the `AI_GATEWAY_ID` var
392in `wrangler.jsonc` (TanStack AI `chat()` with the Anthropic adapter over
393`cloudflareBindingFetch` from `@tanstack/ai-cloudflare`). Create that gateway in the dashboard (AI →
394AI Gateway) and load credits on the account. Without them every
395leftover fails and the cursor rewinds, as it does for any extract
396error. Re-pick the model with `pnpm run compare-fal --`.
397
398### Continuous deploys (Source CI)
399
400Pushes to `main` deploy through `.source/workflows/deploy.ts` on TanStack
401Source. The job runs only as a protected run in the `production` CI
402environment: with no branch rule on `main`, or no `CLOUDFLARE_API_TOKEN`
403in `production`, it is skipped, not failed. Check `src run list` after a
404merge. To deploy `main` again with no new commit, run
405`src workflow run deploy`: a rerun of a skipped run stays skipped.
406
407Steps:
408
409- **Check variables:** fails when `CLOUDFLARE_ACCOUNT_ID` or a
410 `VITE_PUBLIC_POSTHOG_*` CI variable is unset.
411- **Build:** `pnpm run build`
412- **Deploy:** `pnpm run deploy:ci` — applies pending D1 migrations
413 (`wrangler d1 migrations apply modelschemas --remote`, by database name so
414 a binding rename can't retarget it) and then `wrangler deploy`, which
415 follows the build-emitted redirect (`.wrangler/deploy/config.json`) to the
416 real worker config at `dist/server/wrangler.json`. Deploying the repo-root
417 `wrangler.jsonc` directly will not work.
418
419Only `main` deploys: preview versions would share the production D1
420binding, so migrations must never run from another branch.
421
422`pnpm run deploy` remains the manual/emergency path (build + the same
423migrate-then-deploy).
424
425A green CI run is not a deploy. Before debugging a production symptom a
426merged PR should have fixed, confirm the merge is live:
427
428```bash
429CLOUDFLARE_ACCOUNT_ID=<account> pnpm exec wrangler deployments list --name modelschemas | tail
430```
431
432The newest `Created:` must postdate the merge. If it does not, the Builds
433connection is broken (the move to `TanStack/modelschemas` dropped it —
434#553 — and #557 stayed undeployed for two days while every FAL extract kept
435failing on the old model id, #552). Reconnect it, or deploy by hand with
436the production browser config:
437
438```bash
439DOPPLER_PROJECT=modelschemas CLOUDFLARE_ACCOUNT_ID=<account> \
440 pnpm run secrets:build && pnpm run deploy:ci
441```
442
443`DOPPLER_PROJECT` is needed because the secrets scripts pass no
444`--project`; `CLOUDFLARE_ACCOUNT_ID` because wrangler cannot pick between
445two authorised accounts non-interactively.
446
447## Releasing on npm
448
449Non-additive API changes are recorded in [docs/api-changes.md](docs/api-changes.md).
450
451Five public packages (`0.1.0` is on the registry; `@modelschemas/rate-card` from its bootstrap; `0.2.0` is the next release):
452
453| Package | Directory |
454| ------------------------------ | -------------------- |
455| `@modelschemas/client` | `packages/client` |
456| `@modelschemas/codegen` | `packages/codegen` |
457| `@modelschemas/rate-card` | `packages/rate-card` |
458| `@modelschemas/vite` | `packages/vite` |
459| `modelschemas` (CLI, unscoped) | `packages/cli` |
460
461CI **never** holds an npm token. `.github/workflows/publish.yml` packs
462with `pnpm run npm:pack` (pins `workspace:*`), then `npm stage publish`
463over GitHub OIDC. A human 2FA-approves each staged version before it is
464installable.
465
466### Bootstrap (done 2026-08-21)
467
468`npm trust` and `npm stage publish` require the package to already exist,
469so the first version of each name was a laptop `npm publish` with 2FA,
470then stage-only trusted publishers. Repeat that only when adding a **new
471package name**.
472
473Trusted-publisher config on every package must match. Trusted publishing
474is bound to the repo path, so the `modelschemas/modelschemas` publisher
475does not survive the move: re-run this for every `@modelschemas/*` package
476and for unscoped `modelschemas`.
477
478```bash
479npm install -g npm@11.19.0 # trust/stage need >= 11.15; npm 12 wants Node 24.15+
480npm trust github <name> \
481 --file publish.yml \
482 --repo TanStack/modelschemas \
483 --env npm \
484 --allow-stage-publish
485```
486
487Each package: **Settings → Publishing access → Require two-factor
488authentication and disallow tokens**. GitHub Environment `npm`: required
489reviewer; deployment branches limited to `main` and tags `v*`.
490
491### Ongoing releases
492
4931. A PR that changes a published package adds a changeset
494 (`pnpm exec changeset`). The five packages share one version. MAJOR.MINOR
495 must equal `RATE_CARD_LANGUAGE` in `packages/rate-card/src/card.ts`
496 (a test checks it): a release that changes what a card can say bumps
497 both (minor), and a release that does not is a patch.
4982. On main, the Publish workflow keeps a **Version Packages** PR open
499 that applies the pending changesets (versions + CHANGELOGs). Merge it.
5003. That merge's Publish run sees no changesets and a version npm lacks,
501 so it runs CI, packs, then (after the `npm` environment approval)
502 `npm stage publish`. Inspect the tarball artifacts on the run. Pushing
503 a `vX.Y.Z` tag still works as a manual trigger.
5044. On [npmjs.com](https://www.npmjs.com) → **Staged Packages**, 2FA-approve
505 in the same order as bootstrap. Until you approve, `npm install` cannot
506 see the version.
507
508Dry-run the pipeline without staging:
509
510```bash
511# Actions → Publish → Run workflow, leave dry_run checked
512# or locally:
513pnpm run npm:pack -- --pack-dir dist/npm
514```
515
516Do not add `NPM_TOKEN` / `NODE_AUTH_TOKEN` to GitHub Secrets. Token
517`npm publish` is not used for releases.
518
519## Runbook: a provider sync is failing
520
5211. `GET /v1/status` — the failing provider shows `status: "degraded"` and a
522 stale `lastSyncedAt`/`lastPolledAt`.
5232. Tail logs during a manual sync (`observability.enabled` is on, so the
524 dashboard's Workers Logs works too):
525
526 ```bash
527 pnpm exec wrangler tail modelschemas --format pretty
528 # in another shell:
529 curl -X POST https://<worker-url>/v1/admin/sync/<provider> -H "X-Admin-Key: ..."
530 ```
531
532 Cron handlers log structured JSON lines:
533 `{"job":"models-poll"|"spec-sync"|"webhooks", outcomes:[{providerId, error?, skipped?, ...}]}`.
534
5353. Interpret the outcome:
536 - `skipped: "<provider>: X_API_KEY not set"` → set the secret
537 (`wrangler secret put X_API_KEY`) or ignore if intentional.
538 - `error: "fetch failed: <url> → 4xx/5xx"` → the upstream spec/models URL
539 moved or is down; check `providers.spec_source_url` (seeded from
540 `src/db/seed-providers.ts`) against the provider's docs.
541 - Anthropic `403 forbidden` or Gemini
542 `User location is not supported` on the models poll, or an OpenAI
543 `docsFailures` entry `403 Forbidden … hkg1::` → the host refused the
544 caller's region. Their listing calls (and Anthropic's and OpenAI's
545 docs pages) go through the `US_EGRESS`
546 Durable Object (`src/server/providers/us-egress.ts`), created with
547 `locationHint: 'enam'`. The hint is best effort and an object never
548 moves, so if this persists, change its name (`provider-egress`) so
549 a fresh object is created under the hint.
550 - Dangling-`$ref` warnings → the upstream spec changed shape; see
551 `src/server/ingest/bundle.ts`.
552 - `docsFailing` on a `/v1/status` provider (a `docs` marker on the home
553 page) → a docs page stopped loading or changed shape. Polls go on and
554 `status` stays as it was; the docs-derived facts are frozen at their
555 stored values. `sources` and `error` name the page: fix its parser in
556 the provider's adapter. The next poll that reports no docs failures
557 clears it, including one whose adapter no longer loads docs. A
558 skipped listing leaves it.
559 - `priceClearsRefused` on a `/v1/status` provider (a `prices` marker) →
560 a poll asked to clear `refused` of `priced` stored prices and none was
561 cleared. Either the adapter misreads a reshaped listing (fix it), or
562 the prices really are gone (null the stale cards by hand in D1). The
563 next poll that refuses nothing clears it.
564 - `updateStorm` on a `/v1/status` provider (an `updates` marker) → one
565 poll wrote `model.updated` for more than half of the live rows, and
566 at least 20. The events were written. A new kind of non-fact is the
567 usual cause; a real catalog-wide repricing looks the same. The next
568 poll under that line clears it.
569 - Those records are written and cleared only by a poll whose listing
570 loads. While the listing itself fails (`lastPolledAt` stalls) they stay
571 as last written, with an old `lastAt`.
572 - `completeness.score` null for every provider and
573 `completenessComputedAt` null → no score is stored, as after a deploy
574 that changes the scorer. The 15-minute poll cron computes it; trigger
575 that cron to force a recompute. A failed computation logs
576 `{"job":"completeness","error":…}` and keeps the previous scores.
5774. One provider failing never sinks the run (per-provider isolation); fix
578 and re-trigger with the admin sync endpoint. Schema history is preserved
579 across failures — superseded versions stay queryable via
580 `?version=<contentHash>`.
581
582## Architecture
583
584See `CLAUDE.md` for the operational map. `PLAN.md` is the completed build
585log (not the backlog). Borrows the provider-registry,
586activity-grouping, and `$defs`-bundling design from TanStack AI PR #622,
587re-implemented as a runtime service (no codegen) on Workers.