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

CLAUDE.md

252 lines15.3 KB

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