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

README.md

605 lines29.7 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 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- `maker` (`string | null`): the maker as the host names it (#710).
168 `null` with a `factSources.maker` of `path: "unstated"` when the host's
169 page lists the model and names no maker; `null` with no
170 `factSources.maker` when the page does not list the model (or no maker
171 source is read for that provider). Sources: Groq `owned_by` on
172 `GET /openai/v1/models`; BytePlus the Provider column of the
173 [model list](https://docs.byteplus.com/en/docs/ModelArk/1330310);
174 Mistral an overview Summary that opens "A third-party ... model from
175 Z.ai" ([models.md](https://docs.mistral.ai/models.md)), copied onto the
176 listing's alias group; Gemini the Authors line of the
177 [Gemma 4 card](https://ai.google.dev/gemma/docs/core/model_card_4), which
178 also fills `openWeights` and `weightsUrl` for the sizes it binds. Never
179 read from an id prefix and never copied from another provider; resolving
180 the maker to a catalog row is `sameAs`. The name can be the host's own
181 company (`ByteDance`, `Google DeepMind`). Telling a host's own models
182 from hosted ones is decidable from this field on Mistral and Gemini
183 only.
184- `requiredRequestHeaders` (`array | null`): the client-supplied entries of
185 the provider connect profile `requiredHeaders` (`name` plus the rule for
186 the value). A constant header, such as `anthropic-version`, stays on
187 `GET /v1/openapi/{provider}` as `schema.const` and is not copied here.
188 Null when the provider publishes none. OpenCode Go lists
189 `x-opencode-session` and `User-Agent`
190 ([Go docs](https://opencode.ai/docs/console/go/), "Where can I use it?"). The
191 same headers are parameters on each Go operation.
192- `trainsOnRequestData` (`true | null`): true when that model's own source
193 states it trains on request data. OpenCode Go reads `go.training` on
194 `GET https://opencode.ai/inference/go/v1/models` (the boolean the console
195 privacy view shows). An id that list does not name can still be true from
196 that id's probe record. Null when `go.training` is false, or no source
197 states it. Never inferred from an id suffix or from a retention period.
198​
199`knowledgeCutoff` and `openWeights` are null on every row until provider
200adapters fill them. A row's first `releasedAt`, first `providerMetadata`
201and first `maker` (or its first stated silence) are written without a
202`model.updated` change; a later change emits one.
203​
204A `model.updated` event is written only when a fact changed.
205`payload.changed` lists those field paths, for example `contextWindow` or
206`pricing.tables.rate.base.input_tokens`, and is never empty. A source hash,
207an extract time, the operand order of `+`, and the order of an input's
208`values` are not facts: a poll that only moves them writes no row and no
209event. The stored `source` then says when the price last changed.
210`model.added` and `model.removed` are unchanged. `GET /v1/status` adds
211`updateStorm` while one poll updated more than half of a provider's live
212rows (and at least 20). The updates are still written; the field only
213marks them, and the next quieter poll clears it.
214​
215### API stability (`/v1`)
216​
217The model row is typed field by field in [openapi.json](./openapi.json)
218(`Model`, `ModelList`, `ProviderModelList`, `ModelDetail`, `ExportModel`),
219and `@modelschemas/client` types its responses from it.
220​
221- **Additive changes** keep `/v1`: a new field, a new key in a map, a new
222 enum value or change type. Ignore keys you do not know, and handle an
223 enum value you do not know.
224- **Any change to the row shape** (additive or not: a field added,
225 removed, renamed, retyped or moved to another field) bumps
226 `MODEL_ROW_SHAPE.version` in `src/server/row-shape.ts` and ships with a
227 `@modelschemas/client` changeset. `row-shape.test.ts` hashes the row
228 schemas (descriptions and the emitter's spelling excluded) and fails
229 until the record matches, so a shape change cannot merge without one. A
230 hash that moves with no served change (a zod bump respelling the same
231 schema) is re-recorded under the same version and announces nothing.
232- **The feed announces it.** The first models poll after the deploy
233 (within 15 minutes) writes one `catalog.shape_changed` change per
234 provider, `subjectId: "model-row"`, with
235 `payload: { version, contentHash, previousHash, notes }`, and webhooks
236 deliver it. Watch for it with `GET /v1/changes?type=catalog.shape_changed`.
237 The rows of one announcement share `payload.contentHash`: dedupe on it
238 when you read across providers. A provider added later gets the current
239 shape's row on its first poll.
240- A change that is not additive is also recorded in
241 [docs/api-changes.md](docs/api-changes.md).
242​
243### Generation OpenAPI (`GET /v1/openapi/{provider}`)
244​
245One operation per endpoint. A response that can be JSON or a stream lists
246`application/json` (or `text/plain`) and `text/event-stream` under one
247`200`, as OpenAI's own spec does. Each schema's `$defs` are hoisted into
248`components.schemas`, so every `$ref` resolves within the document;
249identical definitions share one name, and a name two endpoints define
250differently gets a content-hash suffix. An upstream `#stream` path key
251(Mistral transcriptions) is merged into its base operation: the request
252body is `anyOf` both variants (`stream: false` / `stream: true`). A
253document that would still hold an unresolved `$ref` is refused with
254`500 unresolved_refs`, naming the ref and where it sits; twins that list
255one media type with different schemas are refused with
256`500 schema_conflict`.
257​
258**Breaking:** the `{path}#stream` SSE twins are gone. hey-api 0.99.0 types
259a JSON-or-SSE response as JSON only and returns the stream as one string
260([hey-api/hey-api#4482](https://github.com/hey-api/hey-api/issues/4482)),
261so a hey-api client loses typed streaming until that is fixed. Kubb v5
262handles it: the response is a union keyed by content type, and
263`toEventStream()` yields typed events.
264​
265## Examples
266​
267Three TanStack Start apps in [`examples/`](./examples) exercise the
268packages end-to-end: **schema-studio** (`@modelschemas/vite` pulls →
269generative UI from JSON Schemas), **image-dimensions** (live image-model
270discovery, supported dimensions drawn to scale), and **video-composer**
271(request builder restricted to each video schema's allowed
272model/aspect-ratio/duration values). `pnpm install`, then `pnpm run dev`
273inside any example.
274​
275## Development
276​
277Node.js 24 or newer (`package.json` `engines`). pnpm 11.9 (`packageManager`).
278​
279```bash
280pnpm install
281pnpm run dev # dev server on http://localhost:3100
282pnpm run test # vitest: unit + workers-pool projects
283pnpm run lint
284pnpm run typecheck
285pnpm run build
286```
287​
288Local data setup:
289​
290```bash
291pnpm run db:migrate # apply migrations to wrangler's local D1
292pnpm run seed # seed the 8 providers
293pnpm run dev # then, in another shell:
294curl -X POST http://localhost:3100/v1/admin/sync/openrouter -H "X-Admin-Key: $ADMIN_KEY"
295```
296​
297Secrets live in `.env.local` (see CLAUDE.md). Pull them from Doppler:
298​
299```bash
300pnpm run secrets:pull # Doppler `dev` → .env.local (strips DOPPLER_*)
301```
302​
303`ADMIN_KEY` gates `POST /v1/admin/sync/{provider}`,
304`POST /v1/admin/extract/fal`, and `GET /v1/admin/export` (the whole
305catalog in one streamed response, for the git mirror). Useful scripts:
306`pnpm run agent-roundtrip` (agent-auth end-to-end),
307`pnpm run client-smoke` (typed client), `pnpm run check:client`
308(client/spec drift), `pnpm run emit-skill` (regenerate SKILL.md),
309`pnpm run rederive -- <provider>` (re-derive schema hashes from the
310upstream spec, no service needed).
311​
312PostHog browser and API analytics use `VITE_PUBLIC_POSTHOG_PROJECT_TOKEN`
313and `VITE_PUBLIC_POSTHOG_HOST`. Store these in the relevant Doppler config
314and pull them into `.env.local` for development. These are public SDK
315configuration values, not personal API credentials. Keep personal API keys
316out of `VITE_PUBLIC_*` variables, which are included in the browser bundle.
317The existing `POSTHOG_PROJECT_KEY` Worker secret separately captures ingest
318signals.
319​
320Vite reads the public variables at build time. Configure both variables in
321the Cloudflare Workers Builds environment before building production, or
322build locally with `pnpm run secrets:build` (defaults to Doppler `prd`;
323use `pnpm run secrets:build --config dev` for another config). This injects
324only `VITE_PUBLIC_*` values from Doppler into the build process without
325writing them to disk.
326`secrets:push` only supplies Worker runtime bindings; it does not configure
327the browser bundle, and skips `VITE_*` bindings. A build without these variables disables the new
328analytics integration in production; development reports missing
329configuration with an error.
330​
331## Production setup
332​
3331. Create resources and put their IDs in `wrangler.jsonc`:
334​
335 ```bash
336 pnpm exec wrangler d1 create modelschemas # → d1_databases[0].database_id
337 pnpm exec wrangler kv namespace create SCHEMA_CACHE # → kv_namespaces[0].id
338 ```
339​
3402. Apply migrations and seed:
341​
342 ```bash
343 pnpm run db:migrate:remote
344 pnpm run seed -- --remote
345 ```
346​
3473. Secrets (`wrangler secret put <NAME>`): `BETTER_AUTH_SECRET` (32+ random
348 bytes), `ADMIN_KEY`, and optionally provider keys — `OPENAI_API_KEY`,
349 `ANTHROPIC_API_KEY`, `GEMINI_API_KEY`, `XAI_API_KEY`,
350 `ELEVENLABS_API_KEY`, `FAL_KEY`, `ARK_API_KEY`. Providers without keys are
351 skipped with a recorded warning (OpenRouter needs none; Anthropic's spec
352 sync is also keyless). `ARK_API_KEY` is the exception: it is optional and
353 only upgrades BytePlus's model catalog from the embedded one to Ark's live
354 listing — BytePlus still serves schemas and a catalog without it.
355 `GITHUB_TOKEN` is optional too. When set, `api.github.com` requests send
356 `Authorization: Bearer` (the Cloudflare AI Gateway catalog listing). A
357 classic personal access token with no scopes is enough to leave the
358 anonymous 60-requests-per-hour quota that shared Worker egress exhausts.
359 `raw.githubusercontent.com` fetches, including the BytePlus Go SDK, stay
360 unauthenticated, and both polls still run when the token is absent. Set
361 the `BETTER_AUTH_URL` var in `wrangler.jsonc` to the deployed origin
362 (agent JWT audiences are origin-bound).
363​
364 Rather than setting them one at a time, reconcile against Doppler:
365​
366 ```bash
367 pnpm run secrets:check # Doppler prd ↔ Worker (names only)
368 pnpm run secrets:push # apply (one wrangler secret bulk call)
369 ```
370​
371 It runs locally against your existing Doppler and wrangler logins, so no
372 token goes near CI. Doppler is the source of truth: every name in the
373 config is pushed except the remove list (`DOPPLER_*` context vars, and
374 `BETTER_AUTH_URL` which is already a wrangler `vars` binding, and
375 `VITE_*` build-time configuration).
376 Secrets are written into a new Worker version rather
377 than the live one (the live API refuses while an undeployed preview
378 version exists); the next deploy inherits them. Nothing is ever deleted.
379 Deliberately NOT a CI job: that would need a long-lived Doppler service
380 token plus a Cloudflare API token in GitHub, turning repo write access
381 into full production compromise.
382​
3834. Deploy and warm:
384​
385 ```bash
386 pnpm run deploy
387 curl https://<worker-url>/v1/status
388 curl -X POST https://<worker-url>/v1/admin/sync/openrouter -H "X-Admin-Key: ..."
389 ```
390​
391Cron triggers start automatically on deploy: `*/15 * * * *` (models poll +
392webhook drain), four spec-sync shards (`0/10/20/30 5 * * *`) — each shard
393is its own invocation with its own subrequest/CPU budgets, FAL alone in
394shard 0, the rest of the registry round-robined across the other three
395(`SPEC_SYNC_SHARD_CRONS` in `src/server/ingest/sync.ts`) — a daily
396`0 4 * * *` firing for Vercel `/endpoints` price ranges
397(`VERCEL_PRICING_EXTRACT_CRON`; rows with `varies_by_provider` only) —
398and six hourly
399firings `0 6-11 * * *` for the FAL per-endpoint `llms.txt` rate-card
400extract (`FAL_PRICING_EXTRACT_CRONS`), each covering ~250 endpoints so the
401whole FAL roster is walked in one calendar day. Most Pricing sections are a
402single unit rate and compile with no model call; only the multi-rate ones
403go to the extract model, once per distinct Pricing-section hash. Force one
404shard's worth with `POST /v1/admin/extract/fal`;
405`POST /v1/admin/sync/fal` stays spec-only.
406​
407The extract model runs through Cloudflare AI Gateway on Unified Billing,
408so its cost lands on the Cloudflare bill and needs no provider key: the
409Worker's `AI` binding calls the gateway named by the `AI_GATEWAY_ID` var
410in `wrangler.jsonc` (TanStack AI `chat()` with the Anthropic adapter over
411`cloudflareBindingFetch` from `@tanstack/ai-cloudflare`). Create that gateway in the dashboard (AI →
412AI Gateway) and load credits on the account. Without them every
413leftover fails and the cursor rewinds, as it does for any extract
414error. Re-pick the model with `pnpm run compare-fal --`.
415​
416### Continuous deploys (Source CI)
417​
418Pushes to `main` deploy through `.source/workflows/deploy.ts` on TanStack
419Source. The job runs only as a protected run in the `production` CI
420environment: with no branch rule on `main`, or no `CLOUDFLARE_API_TOKEN`
421in `production`, it is skipped, not failed. Check `src run list` after a
422merge. To deploy `main` again with no new commit, run
423`src workflow run deploy`: a rerun of a skipped run stays skipped.
424​
425Steps:
426​
427- **Check variables:** fails when `CLOUDFLARE_ACCOUNT_ID` or a
428 `VITE_PUBLIC_POSTHOG_*` CI variable is unset.
429- **Build:** `pnpm run build`
430- **Deploy:** `pnpm run deploy:ci` — applies pending D1 migrations
431 (`wrangler d1 migrations apply modelschemas --remote`, by database name so
432 a binding rename can't retarget it) and then `wrangler deploy`, which
433 follows the build-emitted redirect (`.wrangler/deploy/config.json`) to the
434 real worker config at `dist/server/wrangler.json`. Deploying the repo-root
435 `wrangler.jsonc` directly will not work.
436​
437Only `main` deploys: preview versions would share the production D1
438binding, so migrations must never run from another branch.
439​
440`pnpm run deploy` remains the manual/emergency path (build + the same
441migrate-then-deploy).
442​
443A green CI run is not a deploy. Before debugging a production symptom a
444merged PR should have fixed, confirm the merge is live:
445​
446```bash
447CLOUDFLARE_ACCOUNT_ID=<account> pnpm exec wrangler deployments list --name modelschemas | tail
448```
449​
450The newest `Created:` must postdate the merge. If it does not, the Builds
451connection is broken (the move to `TanStack/modelschemas` dropped it —
452#553 — and #557 stayed undeployed for two days while every FAL extract kept
453failing on the old model id, #552). Reconnect it, or deploy by hand with
454the production browser config:
455​
456```bash
457DOPPLER_PROJECT=modelschemas CLOUDFLARE_ACCOUNT_ID=<account> \
458 pnpm run secrets:build && pnpm run deploy:ci
459```
460​
461`DOPPLER_PROJECT` is needed because the secrets scripts pass no
462`--project`; `CLOUDFLARE_ACCOUNT_ID` because wrangler cannot pick between
463two authorised accounts non-interactively.
464​
465## Releasing on npm
466​
467Non-additive API changes are recorded in [docs/api-changes.md](docs/api-changes.md).
468​
469Five public packages (`0.1.0` is on the registry; `@modelschemas/rate-card` from its bootstrap; `0.2.0` is the next release):
470​
471| Package | Directory |
472| ------------------------------ | -------------------- |
473| `@modelschemas/client` | `packages/client` |
474| `@modelschemas/codegen` | `packages/codegen` |
475| `@modelschemas/rate-card` | `packages/rate-card` |
476| `@modelschemas/vite` | `packages/vite` |
477| `modelschemas` (CLI, unscoped) | `packages/cli` |
478​
479CI **never** holds an npm token. `.github/workflows/publish.yml` packs
480with `pnpm run npm:pack` (pins `workspace:*`), then `npm stage publish`
481over GitHub OIDC. A human 2FA-approves each staged version before it is
482installable.
483​
484### Bootstrap (done 2026-08-21)
485​
486`npm trust` and `npm stage publish` require the package to already exist,
487so the first version of each name was a laptop `npm publish` with 2FA,
488then stage-only trusted publishers. Repeat that only when adding a **new
489package name**.
490​
491Trusted-publisher config on every package must match. Trusted publishing
492is bound to the repo path, so the `modelschemas/modelschemas` publisher
493does not survive the move: re-run this for every `@modelschemas/*` package
494and for unscoped `modelschemas`.
495​
496```bash
497npm install -g npm@11.19.0 # trust/stage need >= 11.15; npm 12 wants Node 24.15+
498npm trust github <name> \
499 --file publish.yml \
500 --repo TanStack/modelschemas \
501 --env npm \
502 --allow-stage-publish
503```
504​
505Each package: **Settings → Publishing access → Require two-factor
506authentication and disallow tokens**. GitHub Environment `npm`: required
507reviewer; deployment branches limited to `main` and tags `v*`.
508​
509### Ongoing releases
510​
5111. A PR that changes a published package adds a changeset
512 (`pnpm exec changeset`). The five packages share one version. MAJOR.MINOR
513 must equal `RATE_CARD_LANGUAGE` in `packages/rate-card/src/card.ts`
514 (a test checks it): a release that changes what a card can say bumps
515 both (minor), and a release that does not is a patch.
5162. On main, the Publish workflow keeps a **Version Packages** PR open
517 that applies the pending changesets (versions + CHANGELOGs). Merge it.
5183. That merge's Publish run sees no changesets and a version npm lacks,
519 so it runs CI, packs, then (after the `npm` environment approval)
520 `npm stage publish`. Inspect the tarball artifacts on the run. Pushing
521 a `vX.Y.Z` tag still works as a manual trigger.
5224. On [npmjs.com](https://www.npmjs.com) → **Staged Packages**, 2FA-approve
523 in the same order as bootstrap. Until you approve, `npm install` cannot
524 see the version.
525​
526Dry-run the pipeline without staging:
527​
528```bash
529# Actions → Publish → Run workflow, leave dry_run checked
530# or locally:
531pnpm run npm:pack -- --pack-dir dist/npm
532```
533​
534Do not add `NPM_TOKEN` / `NODE_AUTH_TOKEN` to GitHub Secrets. Token
535`npm publish` is not used for releases.
536​
537## Runbook: a provider sync is failing
538​
5391. `GET /v1/status` — the failing provider shows `status: "degraded"` and a
540 stale `lastSyncedAt`/`lastPolledAt`.
5412. Tail logs during a manual sync (`observability.enabled` is on, so the
542 dashboard's Workers Logs works too):
543​
544 ```bash
545 pnpm exec wrangler tail modelschemas --format pretty
546 # in another shell:
547 curl -X POST https://<worker-url>/v1/admin/sync/<provider> -H "X-Admin-Key: ..."
548 ```
549​
550 Cron handlers log structured JSON lines:
551 `{"job":"models-poll"|"spec-sync"|"webhooks", outcomes:[{providerId, error?, skipped?, ...}]}`.
552​
5533. Interpret the outcome:
554 - `skipped: "<provider>: X_API_KEY not set"` → set the secret
555 (`wrangler secret put X_API_KEY`) or ignore if intentional.
556 - `error: "fetch failed: <url> → 4xx/5xx"` → the upstream spec/models URL
557 moved or is down; check `providers.spec_source_url` (seeded from
558 `src/db/seed-providers.ts`) against the provider's docs.
559 - Anthropic `403 forbidden` or Gemini
560 `User location is not supported` on the models poll, or an OpenAI
561 `docsFailures` entry `403 Forbidden … hkg1::` → the host refused the
562 caller's region. Their listing calls (and Anthropic's and OpenAI's
563 docs pages) go through the `US_EGRESS`
564 Durable Object (`src/server/providers/us-egress.ts`), created with
565 `locationHint: 'enam'`. The hint is best effort and an object never
566 moves, so if this persists, change its name (`provider-egress`) so
567 a fresh object is created under the hint.
568 - Dangling-`$ref` warnings → the upstream spec changed shape; see
569 `src/server/ingest/bundle.ts`.
570 - `docsFailing` on a `/v1/status` provider (a `docs` marker on the home
571 page) → a docs page stopped loading or changed shape. Polls go on and
572 `status` stays as it was; the docs-derived facts are frozen at their
573 stored values. `sources` and `error` name the page: fix its parser in
574 the provider's adapter. The next poll that reports no docs failures
575 clears it, including one whose adapter no longer loads docs. A
576 skipped listing leaves it.
577 - `priceClearsRefused` on a `/v1/status` provider (a `prices` marker) →
578 a poll asked to clear `refused` of `priced` stored prices and none was
579 cleared. Either the adapter misreads a reshaped listing (fix it), or
580 the prices really are gone (null the stale cards by hand in D1). The
581 next poll that refuses nothing clears it.
582 - `updateStorm` on a `/v1/status` provider (an `updates` marker) → one
583 poll wrote `model.updated` for more than half of the live rows, and
584 at least 20. The events were written. A new kind of non-fact is the
585 usual cause; a real catalog-wide repricing looks the same. The next
586 poll under that line clears it.
587 - Those records are written and cleared only by a poll whose listing
588 loads. While the listing itself fails (`lastPolledAt` stalls) they stay
589 as last written, with an old `lastAt`.
590 - `completeness.score` null for every provider and
591 `completenessComputedAt` null → no score is stored, as after a deploy
592 that changes the scorer. The 15-minute poll cron computes it; trigger
593 that cron to force a recompute. A failed computation logs
594 `{"job":"completeness","error":…}` and keeps the previous scores.
5954. One provider failing never sinks the run (per-provider isolation); fix
596 and re-trigger with the admin sync endpoint. Schema history is preserved
597 across failures — superseded versions stay queryable via
598 `?version=<contentHash>`.
599​
600## Architecture
601​
602See `CLAUDE.md` for the operational map. `PLAN.md` is the completed build
603log (not the backlog). Borrows the provider-registry,
604activity-grouping, and `$defs`-bundling design from TanStack AI PR #622,
605re-implemented as a runtime service (no codegen) on Workers.