Open History to see the last commit
1# CLAUDE.md
2
3This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
4
5## What this project is
6
7A Cloudflare Workers service giving AI agents live access to model schemas:
8per-endpoint request/response JSON Schemas and model metadata for 8 monitored
9providers (OpenAI, Anthropic, Gemini, xAI Grok, ElevenLabs, OpenRouter, FAL,
10BytePlus),
11with a D1 read session on public GETs (replicas after #554's US
12primary has `read_replication.mode: auto`; the session still hits the
13primary until then), Workers Cache on the `CachedReads` entrypoint
14(`max-age` matched to the 15-minute poll; versioned schemas cached for a
15year; purged after an admin write), and cron-driven auto-refresh.
16KV remains for rate-limit counters and docs caches. Design ported from
17TanStack AI PR #622 (`@tanstack/ai-schemas`), minus codegen — schemas are
18extracted/bundled at runtime and served over HTTP/MCP.
19
20The service is live at https://modelschemas.openstory.workers.dev. `0.1.0`
21is on npm (`@modelschemas/*` plus unscoped `modelschemas`). Further
22versions: OIDC `npm stage publish` via `.github/workflows/publish.yml` —
23README "Releasing on npm".
24
25**`PLAN.md` is a historical build log**, not the backlog. Open it for a
26gotcha or decision from phases 0–18. New work is GitHub issues. This file
27is the live map.
28
29## Commands
30
31pnpm is the package manager (`packages/*`, `examples/*`). Scripts run on Node 24 or newer (`engines.node`).
32
33```bash
34pnpm install # install + link workspace packages
35pnpm run dev # local D1 migrate, then dev server on http://localhost:3100
36pnpm run test # vitest, unit + workers projects
37pnpm run test src/path/to/file.test.ts # single test file
38pnpm run lint # oxlint --type-aware (no-explicit-any + no-unsafe-* are errors)
39pnpm run typecheck # tsc --noEmit (includes packages/*)
40pnpm run format # oxfmt + oxlint --fix
41pnpm run check # oxfmt --check
42pnpm run build # production build (emits dist/server/wrangler.json)
43pnpm run deploy # build + wrangler deploy
44pnpm run npm:pack # pack public packages to dist/npm (no publish)
45```
46
47Database (drizzle-kit generates; wrangler applies):
48
49```bash
50pnpm run db:generate # generate migrations from src/db/schema.ts
51pnpm run db:migrate # apply to wrangler's LOCAL D1
52pnpm run db:migrate:remote # apply to remote D1
53pnpm run seed # seed the 8 providers (--remote for prod)
54```
55
56Generated artifacts (committed; CI fails on drift):
57
58```bash
59pnpm run openapi:emit # src/server/openapi.ts → openapi.json
60pnpm run generate:client # → packages/client/src/generated (hey-api)
61pnpm run check:client # regenerate + git diff --exit-code (CI step)
62pnpm run emit-skill # src/server/skill.ts → skill/modelschemas/SKILL.md
63```
64
65A PR that touches `packages/*` (including the generated client) needs a
66changeset (`pnpm exec changeset`), or `pnpm exec changeset --empty` when nothing
67ships; CI runs `changeset status --since=origin/main` on PRs and fails
68without one. `openapi.json` and `SKILL.md` are oxfmt-ignored (byte-stable
69emitted artifacts). Lefthook pre-commit runs oxfmt/oxlint/typecheck — never
70`--no-verify`. The cloudflare vite plugin is skipped under vitest;
71Workers-binding tests (`*.worker.test.ts`) run in workerd via
72`@cloudflare/vitest-plugin` (config: `vitest.workers.config.ts`,
73migrations auto-applied via TEST_MIGRATIONS).
74
75Local verification flows: `pnpm run agent-roundtrip` (agent-auth
76register→execute), `pnpm run client-smoke` (typed client),
77`pnpm run cli -- <cmd>` (CLI), `pnpm run rederive -- <provider>`
78(re-derive schema content hashes from the upstream spec — no service/db;
79shares `classifyAndBundle` with the sync engine), `pnpm run gap:report -- --table`
80(per-provider score for the chat facts `@tanstack/ai-models` needs; one
81`/v1/models` request; `docs/source-silent/<provider>.md` lists facts a provider does not
82publish; `--check` exits 1 below `--target`). Admin sync:
83`curl -X POST localhost:3100/v1/admin/sync/openrouter -H "X-Admin-Key: $ADMIN_KEY"`.
84
85## Architecture
86
87TanStack Start (React 19, SSR) on Cloudflare Workers via the Cloudflare vite
88plugin + `wrangler.jsonc`. Tailwind v4. Worker entry is `src/worker.ts`:
89rate-limits `/v1/*`, delegates fetch to the Start handler, and runs the
90crons (15-min models poll + webhook drain; daily spec sync sharded across
91four 05:00–05:30 UTC firings — FAL alone in shard 0, the rest round-robin —
92so each shard gets its own invocation budgets; see `SPEC_SYNC_SHARD_CRONS`;
93FAL `llms.txt` rate-card extract hourly 06:00–11:00 UTC —
94`FAL_PRICING_EXTRACT_CRONS`).
95
96Request path: route files in `src/routes/` (server handlers via
97`server.handlers`) → service functions in `src/server/` → drizzle/D1 +
98KV. Bindings come from `import { env, waitUntil } from 'cloudflare:workers'` —
99typed by the committed, wrangler-generated `worker-configuration.d.ts`
100(`pnpm run types` regenerates it; rerun after changing wrangler.jsonc or
101.env.local since secret names are typed into Env). Workers runtime types are
102GLOBAL (KVNamespace, D1Database, …) — do not import from
103@cloudflare/workers-types (removed; its types conflict with the generated
104ones).
105
106- **BytePlus** publishes no OpenAPI document (`/openapi.json` is a catch-all
107 200-empty; the real ones sit behind the console's API Explorer login), so
108 its Ark spec is GENERATED at sync time from BytePlus's official Go SDK:
109 `fetchSpec` pulls `service/arkruntime/model/*.go` from GitHub,
110 `go-struct-parser.ts` turns the `json:"…"`-tagged structs into schemas, and
111 `byteplus-ark-build.ts` maps them onto paths and re-applies curated
112 descriptions plus the few request fields the SDK omits. `byteplus-spec.ts`
113 holds the hand-ported fallback used when that fetch/parse fails, and the
114 Seed Speech document, which no SDK covers. The model catalog is live when
115 `ARK_API_KEY` is set (Ark `GET /models`), with the embedded catalog filling
116 the gaps that listing omits — Seed Speech and unlisted-but-served ids.
117- **Gemini video** (#658) is the Interactions API (`POST /v1beta/interactions`),
118 which the Discovery document lacks. `gemini-video.ts` builds one endpoint
119 per video model at sync time: Google's Interactions OpenAPI request with
120 `model` pinned and `response_format.duration` an enum from the model
121 page's `Output video 3s-15s` limit. The endpoint id is the model id and
122 the path is shared, so `GET /v1/openapi/gemini` merges them into one
123 operation whose body is an `anyOf` of components tagged
124 `x-modelschemas-model` (`mergeModelBodies`). The Models API lists these
125 models like chat models: the poll calls a row `video` only when its docs
126 page states that limit, and keeps the stored activity when the page is
127 unread. Veo is shut down on this API (2026-10-22).
128- **Ingest** (`src/server/providers/` + `src/server/ingest/`): per-provider
129 `ProviderConfig` (fetchSpec/listModels/classify) → `bundle.ts` extracts
130 request/response schemas and inlines `$ref` closures under `$defs` →
131 `sync.ts` content-hash-diffs into `schema_versions` + `changes`;
132 `poll-models.ts` diffs model lists. Keyed providers skip cleanly when the
133 secret is absent. `models.pricing` is a RateCard or null: listings compile
134 at write (`src/server/rate-card.ts`), and OpenAI/Anthropic/Gemini prices
135 are parsed from their pricing pages (`*-pricing.ts`, `openai-model-docs.ts`)
136 — every parser fail-closed, a page that parses nothing throws rather than
137 nulling stored cards. A card is USD unless its price is wrapped
138 as `{ currency: ['CNY', expr] }` (`moonshotai-cn`, `minimax-cn`): the
139 wrapper is the one place a currency is stated, and it is not a core op so
140 pre-currency evaluators refuse the card. Summaries and estimates name the
141 currency; nothing converts or compares across currencies.
142 A listing that omits a price keeps the stored card
143 and logs `pricing_lost`; any other omitted fact is written null once the
144 usual fills are tried (the bound schema for capabilities and modalities,
145 the provider table for the request map). An adapter that knows why says
146 so in `ModelInfo.absent` (`FactAbsence` in `types.ts` has the exact
147 table): `cleared` writes null quietly (Hugging Face hosts that stopped
148 agreeing on a price), `unavailable` keeps the stored value. `cleared` is
149 only for a value the source visibly lacks: an unreadable shape throws,
150 and the poller refuses a poll that would clear 5 or more stored prices
151 and over half of the priced rows the provider lists (`refusesPriceClears`).
152 A refused mass clear repeats every poll until the adapter or the bound
153 changes, or the stale cards are nulled by hand in D1. Wrap a
154 docs load in `tryDocs` (`model-facts.ts`) so its throw marks rows
155 `unavailable(...)` and is reported as `docsFailures` instead of failing
156 the provider's poll; the listing itself is never wrapped. While a
157 provider's docs keep failing, `cache_meta` holds one
158 `docs-failing:<providerId>` row saying since when (`docs-failing.ts`); a
159 refused mass clear holds a `price-clears-refused:<providerId>` row the
160 same way. `GET /v1/status` serves both per provider (`docsFailing`,
161 `priceClearsRefused`), the home page marks the row, and neither changes
162 `status`. `/v1/status` model counts are live rows only (`counts.deprecated`
163 holds the rest), and `completeness` there is the gap-report score:
164 `src/lib/completeness.ts` is the one scorer, shared with
165 `scripts/gap-report.ts`; the Worker bundles `docs/source-silent/*.md`
166 (`source-silent.ts`). The 15-minute cron scores once after the poll
167 (`recordCompleteness`, one `cache_meta` row); requests only read it.
168 BytePlus chat, Seedance, and Seedream cards come
169 from its public ModelArk pricing doc (`byteplus-pricing.ts`; the console
170 pricing view and `arkcli pricing` are login-gated). An id that page
171 names nowhere is `cleared` (the "Retiring models" tables left it on
172 2026-11-12, #646); one it names but no table prices keeps its card. FAL cards come from `extract-fal-pricing.ts`:
173 `fal-unit-rate.ts` compiles the common `$X per <unit>` sections with no
174 model call, leftovers go to one extract model per distinct Pricing-section
175 hash and are copied onto every row sharing it. A priced leftover must
176 become a card (one repair turn, same model); a failed one rewinds the
177 cursor so the next shard retries it once. The prompt states today's
178 date: a promo that has ended is priced at the regular rate the section
179 states (none stated: `unverified`, with the promo end, which the check
180 verifies is past), and a card that arrives already expired is rejected
181 into the repair turn (#552). The model call is TanStack AI
182 `chat()` (`@tanstack/ai-anthropic` over `@tanstack/ai-cloudflare`'s `cloudflareBindingFetch`) on the `AI` binding through AI Gateway (`gatewayChat`, Unified
183 Billing, gateway id `AI_GATEWAY_ID`, catalog id `anthropic/claude-sonnet-5.5`
184 on the wire — `GATEWAY_MODEL_IDS`); `scripts/compare-fal-extract-models.ts`
185 scores candidates through the same code with a stand-in binding, and
186 `pnpm run fal-extract-smoke --` runs one extract through the REAL
187 binding and gateway (Wrangler remote bindings need Node; oven-sh/bun#39247).
188 `models.reasoning` (`{ mode, mandatory, efforts? }`; mode is
189 adaptive/budget/effort/toggle). `mandatory` has one meaning: `true` the
190 source STATES thinking cannot be turned off, `false` it states it can
191 (prose, or an off value in the model's OWN schema or level list), `null`
192 unstated — a shared schema or a list with no `none` states nothing. A
193 `toggle` is never stored with `null`. Full rules on `ModelReasoning` in
194 `providers/types.ts`; `reasoningViolation` gates every poll write
195 (`keepValidReasoning`: a bad object keeps the prior value and emits
196 `ingest_failed`). Older adapters still infer `true` (docs/api-changes.md
197 lists them). `models.reasoning` and
198 `models.serverTools` (provider tool type ids) come from docs: OpenAI and
199 xAI model pages, Gemini model pages + thinking tables, the Anthropic
200 Models API + thinking table; Anthropic tools and sampling support
201 (`temperature`/`top_p`/`top_k`, `false` where the migration guides say 400) are hand-written tables
202 in `anthropic-features.ts` (re-verify on each Claude launch).
203- **Stated facts** (`settleStatedFacts` in `poll-models.ts`; contract in
204 the `FactAbsence` comment in `providers/types.ts`): `models.capabilities`
205 is a yes/no flag map (`src/lib/capabilities.ts`), a boolean map or null
206 on every row. Adapters still emit the list of supported flags, plus
207 `unsupportedCapabilities` for a stated no; `settleCapabilities` is the one
208 place they become the map, and it adds `false` for `exactCapabilities`
209 rows from the flags that provider's exact rows list in the same poll. A
210 provider's native listing object goes in `providerMetadata`, never in
211 `capabilities` (the gate refuses a non-flag value). `models.releasedAt`
212 is the provider's own date (`firstSeenAt` still folds it in), kept when
213 a listing stops stating it. `knowledgeCutoff` (`YYYY-MM[-DD]`) and
214 `openWeights` + `weightsUrl` are null unless the provider states them.
215 A stored row's first `releasedAt` or `providerMetadata` is written with
216 no `model.updated`. Migration `0014` is a drizzle custom migration that
217 converted the stored lists. A fact the provider's docs do not state can
218 still come from a live API check: one file per provider under
219 `src/server/providers/probes/`, derivation `probe-verified`, dated
220 `verifiedAt`. The adapter binds that fact only for the exact model and
221 route the record names. A record older than 90 days stays served;
222 `GET /v1/status` counts it on `staleProbes`. Re-run with
223 `pnpm run probe -- <provider> [--write]` (not CI, not the 15-minute
224 poll). The script reads the provider key from the environment or Doppler
225 and never prints it.
226- **sameAs links** (issue #199, `src/server/ingest/model-identity.ts`): a
227 reseller row links to the upstream row its own provider names — never
228 inferred from a similar name alone, and never a copied fact. Adapters
229 state the upstream with `ProviderConfig.upstreamModelIdentity`
230 (OpenRouter, Vercel, Azure, Perplexity's `anthropic/`-style ids — not
231 OpenCode, whose AI SDK package column names the wire protocol, not the
232 maker); polls store it as evidence
233 (`models.upstream_provider`/`upstream_raw_id`/`upstream_source`), writing
234 only what changed. Names gateways use for a provider (`google` → gemini)
235 are rows in `provider_model_namespaces`, mirrored from
236 `ProviderConfig.modelNamespaces` on each poll by `ensureProviderRow`.
237 `reconcileSameAs` runs once per poll run, across all providers, and
238 resolves evidence to `same_as_model_id`: exact id, then alias, then
239 dots-as-hyphens; ambiguous or missing → null. Each link change emits
240 `model.updated`. The catalog serves the link, with the evidence as
241 `factSources.sameAs`, only while the row's current evidence still names
242 that target. Cloudflare AI Gateway is held until it has its own listing.
243 Migration `0012` is hand-written (in-place `ALTER TABLE`, no rebuild).
244- **API** (`src/routes/v1/`): catalog and schema reads (`getDb(env, { replica: true })`,
245 ETag/304 and `public, max-age` via `http-cache.ts`), `POST /v1/validate`
246 (@cfworker/json-schema), `POST /v1/estimate` (`@modelschemas/rate-card`),
247 cursor-paginated `/v1/changes`, subscriptions.
248 Errors are always `{ error: { code, message } }` with remediation hints.
249- **Spec components from zod**: the RateCard family (`packages/rate-card`)
250 and `CompactPricing`, `PricingRange`, `ModelReasoning`, `ChatRequestMap`
251 (`src/server/api-schemas.ts`) are zod schemas with a `.meta` id; the TS
252 types are inferred from them and `openapi.ts` writes every id'd schema
253 into `components.schemas`. Change the zod schema, not a hand-written
254 component (the rest of `openapi.ts` is still hand-written). A spec change
255 to a served row needs the `MODEL_ROW_SHAPE` bump.
256- **MCP** (`src/server/mcp.ts`, route `/mcp`): stateless streamable-HTTP
257 JSON-RPC wrapping the same service functions.
258- **Auth** (`src/lib/auth.ts` factory → lazy runtime instance in
259 `src/server/auth.ts`; betterAuth CANNOT construct at module scope in
260 workerd): better-auth + agent-auth (capabilities derived from
261 `src/server/openapi.ts`, admin ops excluded), api-key fallback, bearer.
262 `requireAgent` (`src/server/require-agent.ts`) guards native routes; agent
263 JWT jtis are single-use — mint per request. The plugin keeps seen jtis
264 in an in-process cache (no `secondaryStorage`), not in D1. Rate limiting
265 (`src/server/rate-limit.ts`): KV fixed-window, 60/h anon-IP, 5k/h
266 per verified credential. Workers Cache (the `CachedReads` entrypoint in
267 `src/worker.ts`) serves catalog and schema GET hits without running the
268 worker, so those hits are not counted, with or without `Authorization`
269 (the responses are `public`, which is Cloudflare's rule for caching an
270 authenticated request). Only misses are counted.
271- **Webhooks** (`src/server/webhooks.ts`): checkpointed fan-out of `changes`
272 to subscriptions, HMAC-SHA256-signed delivery, exponential backoff,
273 auto-pause after 8 failures; drained by the 15-min cron. Destination URLs
274 are SSRF-guarded (public https only, no redirects).
275- **DB** (`src/db/schema.ts`): better-auth tables + providers/provider_model_namespaces/models/
276 endpoints/schema_versions/changes + cache_meta/subscriptions/
277 webhook_deliveries. Epoch-second integers for our tables; ids are slugs
278 (`provider/path` for endpoints, `provider-rawid-slug` for models).
279- **Workspace packages**: `packages/client` (`@modelschemas/client`,
280 generated + hand-written auth entry), `packages/codegen`,
281 `packages/vite`, `packages/cli` (`modelschemas` bin:
282 login/whoami/models/schema/validate/estimate/changes/subscribe),
283 `packages/rate-card` (`@modelschemas/rate-card`: pricing schema +
284 evaluator + OpenRouter listing compiler; no Workers deps). Its
285 `./evaluator` entry (`evaluateCard`) imports no package. Every public
286 package's npm tarball is `pnpm run build` output (`dist/` JS + .d.ts);
287 `npm-pack` lifts `publishConfig` onto the packed manifest. The CLI
288 `bin` is `dist/index.js`. MAJOR.MINOR equals
289 `RATE_CARD_LANGUAGE` (`card.ts`). The shared estimate cases
290 (`packages/rate-card/src/fixtures/estimate-cases.ts`) run through the package, the packed
291 tarball and `POST /v1/estimate`.
292- **Path aliases**: `#/*` and `@/*` → `./src/*`; `.ts` import extensions
293 allowed. `src/routeTree.gen.ts` is generated by the DEV SERVER (the pinned
294 `tsr` CLI emits an old format) — never edit by hand; boot `pnpm run dev`
295 after adding routes, then typecheck. No tests under `src/routes/` (the
296 router treats them as routes; a `.claude` hook blocks them) — test the
297 `src/server`/`src/lib` code the route calls.
298- **Env**: `.env.local` holds `BETTER_AUTH_SECRET`, `BETTER_AUTH_URL`
299 (http://localhost:3100 — JWT audiences are origin-bound), `ADMIN_KEY`,
300 optional provider keys (`pnpm run secrets:pull` from Doppler `dev`;
301 `DOPPLER_*` is stripped). Prod: `pnpm run secrets:push` or
302 `wrangler secret put`. README has the full production-setup + runbook.
303
304API map: `GET /v1` (index) · `/v1/status` · `/v1/providers[/{p}/models]` ·
305`/v1/models[?activity,provider,capability,q,pricing]` · `/v1/models/{p}/{id}` ·
306`/v1/schemas/{p}[/{activity}[/{endpointId}?kind,version]]` ·
307`POST /v1/validate` · `POST /v1/estimate` · `/v1/changes` · `POST /v1/agents/register-key` ·
308`/v1/agents/me` · `/v1/subscriptions` · `POST /v1/admin/sync/{p}` · `POST /v1/admin/extract/fal` ·
309`/v1/admin/export` · `/openapi.json` · `/llms.txt` · `/skill` · `/docs` · `/mcp` ·
310`/.well-known/agent-configuration`.