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

README.md

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