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

README.md

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