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

PLAN.md

1,154 lines77.9 KB

1# modelschemas — Live AI Model Schema Service
2​
3> Historical build log (phases 0–18 complete). New work is GitHub issues.
4> Live map: `CLAUDE.md`.
5​
6A Cloudflare Workers service that gives agents live, validated access to AI model schemas
7(request/response JSON Schemas per provider endpoint, plus model metadata), with
8react-query-style server-side caching: persistent, stale-while-revalidate, auto-refreshed
9when providers ship new models or API revisions.
10​
11Borrows directly from TanStack AI PR #622 (`@tanstack/ai-schemas`):
12​
13- **Provider registry pattern** — a `ProviderConfig` per provider (`fetch` → `load` →
14 activity-categorised merged specs). Providers: OpenAI, Anthropic, Gemini, xAI Grok,
15 ElevenLabs, OpenRouter, FAL.
16- **Activity grouping** — `chat | image | video | audio | embeddings | moderation`;
17 platform/admin endpoints classify to `null` and are dropped.
18- **Endpoint-id-keyed schema maps** with self-contained JSON Schemas (`$ref` closures
19 bundled under `$defs`).
20- **Spec-source tricks** — e.g. Anthropic's spec URL resolved from the Stainless
21 `.stats.yml`; FAL's `expand=openapi-3.0` param; Gemini Discovery→OpenAPI conversion.
22​
23Key difference from the PR: no codegen, no Zod, no npm package. We extract and bundle
24JSON Schemas at runtime (pure JSON manipulation — portable to Workers) and serve them
25over HTTP. Zod codegen stays in the npm package world; this service is the live API.
26​
27---
28​
29## Loop protocol (completed)
30​
31This plan was executed by an autonomous loop. Each iteration:
32​
331. Read this file. Find the first unchecked `- [ ]` task, top to bottom.
342. Implement exactly that task. Stay inside its scope; if you discover necessary
35 side-work, add it as a new task in the right phase instead of doing it now.
363. Verify against the task's acceptance criteria. Every task that adds or changes
37 behaviour must ship with tests covering it — write them as part of the task, not
38 later. Run `bun run test` (plain `bun run`, not `--bun` — bun's ws shim can't
39 start the cloudflare vitest pool), `bun --bun run lint`, and `bun run typecheck`;
40 all must be green (lefthook enforces lint/format/typecheck on commit — never
41 commit with `--no-verify`). For route/API tasks, exercise the endpoint against
42 `bun --bun run dev` (vite cloudflare plugin provides local D1/KV bindings —
43 note the plugin is skipped under vitest; Workers-runtime tests need
44 `@cloudflare/vitest-pool-workers`, see task 0.3).
454. Check the task off (`- [x]`), append a one-line note under it if anything
46 non-obvious happened, and commit with a conventional message
47 (`feat(api): ...`, `chore(db): ...`).
485. **Phase boundary:** when the task just completed is the last task of its phase,
49 run the full test suite and lint one more time — everything green is a hard gate
50 before starting the next phase. Make a phase-closing commit
51 (`chore: complete phase N`) even if the last task was already committed, and
52 confirm CI (task 0.0) passes on that commit. Do not begin the next phase with a
53 dirty tree, failing tests, or red CI.
546. If blocked (missing secret, upstream outage, ambiguous requirement), check the task
55 off as `- [x] ~BLOCKED:` with the reason, move on to the next task, and surface the
56 blocker in the iteration summary.
577. Stop the loop when every task is checked.
58​
59Rules:
60​
61- No task is done without tests: new behaviour gets new tests, and the whole suite
62 passes before the task is checked off.
63- Never edit `src/routeTree.gen.ts` by hand.
64- All times stored as unix epoch integers; all ids lowercase kebab/slug.
65- Every API response is JSON (errors included: `{ error: { code, message } }`).
66- No secrets in code. Local: `.env.local` / `.dev.vars`. Prod: `wrangler secret put`.
67​
68---
69​
70## Architecture decisions (settled during the build)
71​
72- **D1 is the source of truth**, not KV. We need relational queries (models by
73 provider/activity/capability), versioned schema history, diffs, auth tables, and
74 webhook subscriptions — that's SQL. **KV is the hot cache** in front of D1 for
75 schema blobs (read-heavy, immutable-per-version), keyed by content hash.
76- **Two-tier refresh loop** (Cloudflare Cron Triggers):
77 - _Fast tier, every 15 min_: poll each provider's cheap model-list endpoint
78 (`/v1/models` etc.). New/removed model → update D1, record a change event,
79 fire webhooks. This is what catches "new model just dropped".
80 - _Slow tier, daily 05:00 UTC_: full OpenAPI spec sync per provider (port of the
81 PR #622 fetch+merge+bundle pipeline, minus codegen). Content-hash each bundled
82 endpoint schema; changed hash → new schema version row + change event.
83- **SWR semantics** (the "server-side react query"): every cached entity carries
84 `fetchedAt` + `staleTime`. Reads always serve immediately; if stale, a background
85 revalidation runs via `ctx.waitUntil`. Cron is the backstop, SWR is the accelerator.
86 Responses expose `ETag`, `Last-Modified`, and `X-Stale-At` so agents can build their
87 own cache layers on top.
88- **Auth**: Better Auth on D1 (drizzle adapter) with the **agent-auth plugin**
89 (`@better-auth/agent-auth`) as the primary flow — the standard agent protocol:
90 discovery at `/.well-known/agent-configuration`, `POST /agent/register`, capability
91 grants, short-lived signed JWTs (replay-protected, audience-bound) verified in our
92 routes via `verifyAgentRequest`. Capabilities are derived from our own
93 `openapi.json` with `createFromOpenAPI` where possible, hand-declared otherwise.
94 The **api-key plugin** stays as a low-friction alternative for simple bearer access.
95 Anonymous read access allowed at a low rate limit; authenticated agents get higher
96 limits + webhooks. Reads stay public — auth gates rates, subscriptions, and any
97 future write surface, not schema access.
98- **Validation**: `@cfworker/json-schema` (built for Workers; ajv's codegen trips CSP/
99 eval restrictions).
100- **Worker entry**: `wrangler.jsonc` currently points at
101 `@tanstack/react-start/server-entry`. Replace with a thin `src/worker.ts` that
102 re-exports the Start fetch handler and adds `scheduled` (cron) — and later `queue`
103 if we adopt Queues. Webhook delivery starts with `waitUntil` + a retry table drained
104 by cron (no paid-plan Queues dependency).
105​
106---
107​
108## Phase 0 — Platform foundation
109​
110- [x] **0.0 CI pipeline.** GitHub Actions workflow (`.github/workflows/ci.yml`)
111 running on push to `main` and on pull requests: `oven-sh/setup-bun`,
112 `bun install --frozen-lockfile`, `bun --bun run check`, `bun --bun run lint`,
113 `bun run typecheck`, `bun --bun run test`, `bun --bun run build`. This is the
114 gate the loop protocol's
115 phase-boundary step checks against. _Accepts:_ workflow file is valid (passes
116 `actionlint` or a dry-run push) and the run is green on the commit that adds it.
117 - Note: actionlint not installable in the sandbox; validated via YAML parse + all five
118 commands green locally, then confirmed green on GitHub Actions (run 27326004002 on
119 commit 320c2b0, the phase 0 closing commit). checkout bumped v4→v5 (node20
120 deprecation). Standing permission from Tom to push origin/main each iteration.
121- [x] **0.1 Move the database to D1.** Add a `d1_databases` binding (`DB`) to
122 `wrangler.jsonc`; switch `src/db/index.ts` to `drizzle-orm/d1` reading the binding
123 from the Cloudflare env (expose a `getDb(env)` helper — Workers have no module-scope
124 env); update `drizzle.config.ts` to the `d1-http` driver for remote, keep local
125 migrations working against wrangler's local D1 (`bun run db:generate` +
126 `wrangler d1 migrations apply DB --local`). Remove `better-sqlite3` and the demo
127 `todos` table. _Accepts:_ dev server boots, a trivial query against D1 works locally.
128 - Note: dev server only boots under `bun run dev` (node runtime) — `bun --bun run dev`
129 hangs before vite's ready banner (pre-existing, ws-related). Vite binds IPv6-only
130 (`http://[::1]:3000`). `db:migrate` script now applies migrations to local D1 via
131 wrangler; `db:migrate:remote` added. `@cloudflare/workers-types` added (type-only,
132 drizzle optional peer).
133- [x] **0.2 Custom worker entry with cron support.** Create `src/worker.ts` exporting
134 `{ fetch }` from the TanStack Start server entry plus a `scheduled(controller, env, ctx)`
135 handler that dispatches on `controller.cron`. Point `wrangler.jsonc` `main` at it and
136 declare two crons: `*/15 * * * *` (models poll) and `0 5 * * *` (spec sync).
137 _Accepts:_ `wrangler dev --test-scheduled` + `curl /__scheduled?cron=*/15+*+*+*+*`
138 hits the handler; normal SSR routes still render.
139 - Note: on wrangler 4.99 the test endpoint is `/cdn-cgi/handler/scheduled?cron=…`
140 (`/__scheduled` 404s); verified against the built worker
141 (`wrangler dev --test-scheduled -c dist/server/wrangler.json`) and under vite dev —
142 both crons dispatch, SSR home renders in both. Entry-module named exports must be
143 handlers only (workerd rejects exported constants), so cron strings stay module-local.
144- [x] **0.3 KV namespace + helpers.** Add `kv_namespaces` binding (`SCHEMA_CACHE`).
145 Write `src/server/kv.ts` with typed get/put wrapping JSON + content-hash keys.
146 The cloudflare vite plugin is incompatible with vitest (it is skipped under
147 `VITEST` in `vite.config.ts`), so set up `@cloudflare/vitest-pool-workers`
148 (or a miniflare test harness) here for tests that need real KV/D1 bindings.
149 _Accepts:_ round-trip test passes under `bun run test` with a real KV binding.
150 - Note: pool-workers 0.16 (vitest 4) replaced `defineWorkersConfig` with a
151 `cloudflareTest()` vite plugin — config split into vitest.config.ts +
152 unit/workers project files (`*.worker.test.ts` runs in workerd). Tests MUST run
153 via plain `bun run test`: under `--bun`, bun's ws shim can't start the pool
154 runner (hangs after "Timeout starting cloudflare-pool runner"); ci.yml,
155 CLAUDE.md, and the loop protocol updated accordingly. Miniflare bindings are
156 declared inline (not via wrangler.jsonc configPath) so the pool doesn't try to
157 load the TanStack Start worker entry.
158- [x] **0.4 Better Auth on D1.** Wire `src/lib/auth.ts` to the drizzle adapter over D1,
159 add the `agent-auth` (`@better-auth/agent-auth`), `api-key`, and `bearer` plugins,
160 generate auth tables into `src/db/schema.ts` via `bunx --bun @better-auth/cli generate`
161 (agent-auth adds `agent`, `host`, `grant`, `approval`), migrate. Keep email/password
162 enabled (it backs delegated-mode approvals and the dashboard later). Minimal
163 `agentAuth({...})` config for now — providerName/description, `modes:
164['autonomous', 'delegated']`, empty capabilities (filled in Phase 5). _Accepts:_
165 sign-up + session retrieval works through the existing `/api/auth/$` catch-all
166 locally; auth tables present in local D1.
167 - Note: better-auth 1.6 moved `apiKey` to `@better-auth/api-key` (added as a dep);
168 the option is `providerDescription`, not `description`. Auth is a `createAuth(db)`
169 factory in `src/lib/auth.ts` (CLI-loadable via `scripts/better-auth-config.ts`);
170 the runtime instance in `src/server/auth.ts` builds from `cloudflare:workers` env
171 and passes `tanstackStartCookies()` via `extraPlugins` — that plugin can't be in
172 the factory (vite-only `#tanstack-router-entry` imports break the workers test
173 pool). Worker tests apply drizzle migrations via the pool's
174 TEST_MIGRATIONS/applyD1Migrations pattern. Curl-verified sign-up + get-session
175 (needs an `Origin` header, else 403 MISSING_OR_NULL_ORIGIN).
176​
177## Phase 1 — Data model
178​
179- [x] **1.1 Core tables** in `src/db/schema.ts` (drizzle, sqlite dialect):
180 - `providers` — id, displayName, specSourceUrl, modelsEndpoint, authEnvVar,
181 lastPolledAt, lastSyncedAt, status.
182 - `models` — id (slug), providerId, rawId, activity, displayName, contextWindow,
183 maxOutput, modalities (json), pricing (json), capabilities (json), firstSeenAt,
184 lastSeenAt, deprecatedAt nullable.
185 - `endpoints` — id, providerId, activity, method, path, description.
186 - `schema_versions` — id, endpointId, kind (`input`|`output`), contentHash,
187 schema (json text, $defs-bundled), specRevision, createdAt, supersededAt nullable.
188 - `changes` — id, type (`model.added`|`model.removed`|`model.updated`|
189 `schema.added`|`schema.updated`|`endpoint.added`|`endpoint.removed`),
190 providerId, subjectId, summary, payload (json diff), createdAt. This is the
191 public changelog feed.
192 _Accepts:_ migration generated and applied locally; drizzle types compile.
193 - Note: migration drizzle/0001_sweet_zeigeist.sql; `activities`/`changeTypes` exported
194 as const arrays (drizzle text enums are type-level only). Worker tests cover insert +
195 relational query across all five tables and FK enforcement.
196- [x] **1.2 Cache + delivery tables:**
197 - `cache_meta` — key, fetchedAt, staleTime, lastError, refreshing flag.
198 - `subscriptions` — id, agentId (auth user), url, secret, events (json array),
199 providerFilter nullable, active, createdAt.
200 - `webhook_deliveries` — id, subscriptionId, changeId, attempt, nextAttemptAt,
201 status (`pending`|`ok`|`failed`), lastResponseCode.
202 _Accepts:_ migration applies; FK relations defined.
203 - Note: migration drizzle/0002_violet_lionheart.sql; deliveries indexed on
204 (status, nextAttemptAt) for the cron drain. Worker tests cover cache_meta
205 round-trip, subscription→user/delivery→change relations, and FK enforcement.
206- [x] **1.3 Seed script.** `scripts/seed.ts` inserting the 7 providers with their spec
207 source config (port the constants/URLs from PR #622's `scripts/providers/*`:
208 Anthropic `.stats.yml` resolution, FAL `expand=openapi-3.0` note, Gemini discovery
209 URL, etc.). Runnable via `bun run seed` against local D1. _Accepts:_ `providers`
210 table populated locally.
211 - Note: seed data lives in `src/db/seed-providers.ts` (typed `$inferInsert`, unit
212 tested, reusable by the Phase 2 registry); `scripts/seed.ts` upserts via
213 `wrangler d1 execute --file` (idempotent, preserves runtime columns; `--remote`
214 flag for prod). URLs/env-vars ported from PR #622 @ 276e808.
215​
216## Phase 2 — Ingestion pipeline (the refresh loop)
217​
218- [x] **2.1 Provider registry.** `src/server/providers/types.ts` +
219 `src/server/providers/{openai,anthropic,gemini,grok,elevenlabs,openrouter,fal}.ts`.
220 Port PR #622's `ProviderConfig` shape, adapted to Workers: `fetchSpec(env)` returns
221 parsed spec objects (no filesystem), `listModels(env)` hits the provider's models
222 endpoint, `classify(path, op)` → `Activity | null`. Providers needing keys are
223 skipped with a recorded warning when the secret is absent. _Accepts:_ unit tests
224 for `classify` per provider using small spec fixtures.
225 - Note: listModels also normalises to the ModelInfo shape (providers own their API
226 mapping; 2.4 just diffs). FAL activity rides on a fetch-time per-operation marker
227 (category-derived; non-taxonomy targets like 3d/json classify to null for now);
228 OpenRouter's video synthesis + embeddings lift ported as exported, unit-tested
229 helpers; Anthropic's resolved spec URL doubles as specRevision. `yaml` dep added
230 for OpenAI/Anthropic YAML specs.
231- [x] **2.2 Schema extraction + bundling.** `src/server/ingest/bundle.ts`: given a
232 merged OpenAPI spec and an endpoint, extract the input schema (request body —
233 handle `application/json` and `multipart/form-data`, per the PR's multipart fix)
234 and output schema (`post-200` strategy, plus FAL's `sibling-get`), then inline the
235 `$ref` closure under `$defs` so every schema is self-contained. Stable
236 stringify → SHA-256 content hash. _Accepts:_ unit tests with fixture specs prove
237 self-containment (no dangling `$ref`s — port the PR's dedup-rename lesson as a test).
238 - Note: content hashing reuses `stableStringify`/`contentHash` from src/server/kv.ts
239 (task 0.3). Improvement over the PR: refs back to the root schema rewrite to `#`
240 instead of dangling in $defs; `findDanglingRefs` exported as the self-containment
241 checker (used by tests, reusable as a sync-time sanity check). Inline (ref-less)
242 body schemas are bundled too, not skipped.
243- [x] **2.3 Sync engine.** `src/server/ingest/sync.ts`: per provider —
244 fetch spec → classify endpoints → bundle schemas → diff content hashes against
245 `schema_versions` → insert new versions, mark superseded, upsert `endpoints`,
246 write `changes` rows, warm KV with new blobs. Idempotent; per-provider try/catch so
247 one provider's outage doesn't sink the run; record outcome on `providers`.
248 _Accepts:_ integration test with a fixture spec: first run inserts, second run
249 no-ops, mutated fixture produces exactly one `schema.updated` change.
250 - Note: endpoint db ids are `${providerId}/${path-minus-slash}`. Vanished endpoints
251 keep their rows + version history; an `endpoint.removed` change is written once
252 (deduped against prior changes). Failed providers get status='degraded', successful
253 syncs set lastSyncedAt + status='active'. Injectable clock for tests. D1 persists
254 across tests in one isolate — worker tests use per-test provider ids.
255- [x] **2.4 Model poller.** `src/server/ingest/poll-models.ts`: per provider, call
256 `listModels`, normalise to the `models` shape, diff against D1 → `model.added` /
257 `model.removed` / `model.updated` changes, bump `lastSeenAt`. _Accepts:_ fixture
258 test covering add/remove/no-change.
259 - Note: normalisation lives in each provider's listModels (task 2.1); the poller
260 diffs. "Removed" = deprecatedAt set (row kept), recorded once; reappearance clears
261 deprecation via model.updated with a before/after payload. Model db ids are
262 `${providerId}-${slugified rawId}`.
263- [x] **2.5 Wire crons.** `scheduled` dispatch: 15-min cron → `pollAllModels(env, ctx)`,
264 daily cron → `syncAllSchemas(env, ctx)`. Stagger providers with `ctx.waitUntil` and
265 keep each provider's work sequential to respect subrequest limits. _Accepts:_
266 `--test-scheduled` run against live providers (no key required: OpenRouter) writes
267 real rows locally.
268 - Note: live run wrote 338 OpenRouter models + changes locally; second trigger
269 idempotent (0 added); keyed providers skipped with recorded warnings. Surfaced a
270 0.4 regression: betterAuth() can't construct at module scope in the built worker
271 (workerd forbids global-scope I/O/random) — src/server/auth.ts now lazy-inits via
272 getAuth(). Use `wrangler dev -c dist/server/wrangler.json --persist-to
273.wrangler/state` so the built worker shares the root local D1.
274- [x] **2.6 Manual trigger + status.** `POST /v1/admin/sync/{provider}` (admin-key
275 gated) and `GET /v1/status` (public: per-provider lastPolledAt/lastSyncedAt/counts).
276 _Accepts:_ curl both locally.
277 - Note: admin key via X-Admin-Key or Bearer (fails closed without ADMIN_KEY; local
278 value in .env.local). Logic split into testable `src/server/{admin,status}.ts`.
279 routeTree.gen.ts must be regenerated by the dev server, not `tsr generate` (the
280 pinned router-cli 1.132 emits a format without the `server` route option). Live
281 curl: status shows per-provider counts; admin sync of OpenRouter ingested 21
282 endpoints / 41 schema versions with zero dangling-ref warnings.
283​
284## Phase 3 — SWR cache layer ("server-side react query")
285​
286- [x] **3.1 `src/server/cache.ts`** — `swr(env, ctx, key, fetcher, { staleTime, hardTtl })`:
287 KV hit + fresh → return; KV hit + stale → return AND `ctx.waitUntil(revalidate)`
288 guarded by the `cache_meta.refreshing` flag (cheap cross-isolate dedupe; a stuck
289 flag older than 2× staleTime is ignored); miss → fetch inline, persist to KV +
290 `cache_meta`. _Accepts:_ unit tests for all three paths and the stuck-flag case.
291 - Note: signature is `swr(deps, key, fetcher, opts)` with deps = {db, kv, waitUntil,
292 now?} (injectable clock + collected waitUntil promises make the tests
293 deterministic). Result carries fetchedAt/staleAt/revalidating for task 3.2's
294 header helper. Failed background revalidation records cache_meta.lastError and
295 keeps serving the stale value. 6 worker tests.
296- [x] **3.2 HTTP cache semantics.** Response helper adding `ETag` (content hash),
297 `Last-Modified`, `Cache-Control: public, max-age=60, stale-while-revalidate=600`,
298 `X-Fetched-At`, `X-Stale-At`; honour `If-None-Match` → 304. Apply to all schema/model
299 read endpoints in Phase 4. _Accepts:_ test asserts 304 on matching ETag.
300 - Note: `cachedJson(request, value, opts)` in src/server/http-cache.ts — etag
301 computed from the body unless a stored content hash is passed; If-None-Match
302 handles lists, weak validators, and `*`. X-Fetched-At/X-Stale-At are epoch
303 seconds, matching SwrResult from 3.1.
304​
305## Phase 4 — Public API (agent-first)
306​
307All under `/v1`, JSON-only, TanStack Start server-route handlers. Design for an LLM
308consumer: every list response includes `_links` to drill deeper, errors carry remedies.
309​
310- [x] **4.1 Discovery surface.** `GET /v1` (service description + endpoint index),
311 `GET /llms.txt` (markdown usage guide for agents), `GET /openapi.json` (the
312 service's own OpenAPI doc, hand-maintained in `src/server/openapi.ts`). _Accepts:_
313 all three render; openapi.json validates against OpenAPI 3.1 meta-schema in a test.
314 - Note: meta-schema (2022-10-07) vendored in src/server/fixtures, validated with
315 @cfworker/json-schema (added now, reused by 4.4); a second test enforces unique
316 camelCase operationIds (the 5.1/7.4 contract). llms.txt content lives in
317 src/server/llms-txt.ts for reuse by /docs (7.3) and the skill (7.6). Dotted
318 filenames use `[.]` escaping (`openapi[.]json.ts`); the router plugin rewrites
319 the createFileRoute id itself on dev-server regeneration.
320- [x] **4.2 Catalog endpoints.**
321 - `GET /v1/providers` — list with sync status.
322 - `GET /v1/providers/{provider}/models` — models for one provider.
323 - `GET /v1/models?activity=&provider=&capability=&q=` — cross-provider catalog,
324 filterable; this is the headline "what can I use right now" endpoint.
325 - `GET /v1/models/{provider}/{modelId}` — full metadata + `_links.schemas`.
326 _Accepts:_ curl each against seeded/synced local data; filters covered by tests.
327 - Note: query logic in src/server/catalog.ts (worker-tested; routes thin). Deprecated
328 models hidden unless `?deprecated=true`; model detail resolves slug OR raw id;
329 invalid `?activity=` → 400 listing valid values. Curl-verified against live local
330 data (q=claude → 20 OpenRouter models, capability=tools → 252, encoded raw-id
331 lookup, 404s with remediation). All reads use the 3.2 cachedJson helper.
332- [x] **4.3 Schema endpoints.**
333 - `GET /v1/schemas/{provider}` — activities + endpoint ids.
334 - `GET /v1/schemas/{provider}/{activity}` — endpoint-id-keyed map (current versions),
335 mirroring the PR's `endpoint-schema-map` shape.
336 - `GET /v1/schemas/{provider}/{activity}/{endpointId}?kind=input|output&version=` —
337 single self-contained JSON Schema; defaults to current input schema.
338 All via the SWR layer + ETag helper. _Accepts:_ schemas served byte-identical to D1
339 content; 304s work; unknown ids → structured 404 with valid-id hints.
340 - Note: endpoint ids contain slashes, so the single-schema route is a splat
341 (`$activity/$.ts`); clients URL-encode (`chat%2Fcompletions`). `waitUntil` comes
342 straight from `cloudflare:workers` (added to the local module declaration).
343 Versioned (content-addressed) reads cache with staleTime 86400, current reads 300;
344 single-schema ETag is the stored contentHash. Live-verified on synced OpenRouter
345 data including a 304 round-trip; byte-identity asserted in worker tests.
346- [x] **4.4 Validation endpoint.** `POST /v1/validate` with
347 `{ provider, endpointId, kind?, payload }` → `{ valid, errors: [{ path, message, keyword }] }`
348 using `@cfworker/json-schema`. _Accepts:_ test with one valid + one invalid
349 Anthropic messages payload.
350 - Note: worker tests use a trimmed Anthropic messages fixture (valid + invalid with
351 $defs-ref'd errors); also live-verified against the REAL synced Anthropic spec
352 (keyless sync: 5 endpoints / 10 versions) — valid payload passes, bad payload
353 yields structured required/enum errors. Response includes the schema contentHash
354 so agents know which version judged them.
355- [x] **4.5 Changes feed.** `GET /v1/changes?since=&provider=&type=` (cursor-paginated)
356 — the polling-friendly alternative to webhooks. _Accepts:_ cursor pagination test.
357 - Note: opaque (createdAt, id) keyset cursor (base64), newest first, stable under
358 concurrent inserts, tie-break tested on equal timestamps; limit clamped to 200;
359 `_links.next` carries the ready-made next-page URL. Live-verified against real
360 sync-generated change rows.
361​
362## Phase 5 — Agent signup & access control
363​
364Built on Better Auth's agent-auth plugin (https://better-auth.com/docs/plugins/agent-auth):
365discovery → register → request capability grants → execute with short-lived JWTs.
366​
367- [x] **5.1 Agent Auth provider surface.** Expose the discovery document at
368 `/.well-known/agent-configuration` (route handler calling
369 `auth.api.getAgentConfiguration()`). Declare capabilities in `agentAuth({...})`:
370 derive the read/validate operations from our own `src/server/openapi.ts` doc via
371 `createFromOpenAPI` (every Phase 4 operation has an `operationId`), and hand-declare
372 `manage_subscriptions`. Autonomous mode is the default path (no human in the loop);
373 delegated mode + approvals kept enabled but not required for any current capability.
374 _Accepts:_ discovery doc renders; `POST /agent/register` → capability request →
375 `POST /capability/execute` round-trips `get_schema` locally.
376 - Note: full round-trip verified live by `bun scripts/agent-roundtrip.ts` (Ed25519
377 keys via jose; agent JWT: iss=hostId, sub=agentId, aud=default_location; execute
378 response wraps results in `{data}`). Required `allowDynamicHostRegistration: true`
379 (open signup) and a `resolveAutonomousUser` virtual identity (autonomous agents
380 have no human owner). Admin op (syncProvider) filtered out of capabilities;
381 capabilities are at `/capability/list`, not inline in the discovery doc.
382- [x] **5.2 JWT verification on owned routes.** For agent-authed access to our native
383 `/v1/*` routes (as opposed to the `/capability/execute` proxy), add a
384 `requireAgent(request)` helper wrapping `verifyAgentRequest(request, auth)` +
385 grant check, used by subscriptions (Phase 6) and `/v1/agents/me`. _Accepts:_ test
386 hits a protected route with a valid agent JWT (200) and without (401).
387 - Note: signature is `requireAgent(auth, request, {capability?})` returning a
388 principal or a ready-made 401/403 Response. verifyAgentRequest builds its session
389 URL without the basePath, so the helper retries with `/api/auth` appended. Agent
390 JWT jtis are replay-protected — a fresh token per request. /v1/agents/me created
391 minimal here (5.5 enriches it); 200/401/403 covered by worker tests + the live
392 round-trip script.
393- [x] **5.3 API-key fallback.** `POST /v1/agents/register-key` `{ name, email? }` →
394 Better Auth user + api-key plugin key, returned once; `Authorization: Bearer <key>`
395 accepted everywhere `requireAgent` is — for agents that don't speak the agent-auth
396 protocol. _Accepts:_ register → authed call with the key succeeds.
397 - Note: requireAgent now returns a Principal union (agent | api-key); non-JWT bearer
398 values and X-Api-Key are treated as keys; api-key principals pass capability
399 checks (full-access fallback). The plugin's key owner field is `referenceId`.
400 Emails are pre-checked in D1 (better-auth's duplicate throw leaves a floating
401 rejection). Live-verified: register → Bearer key on /v1/agents/me → 200.
402- [x] **5.4 Rate limiting.** Per-agent/per-key and per-IP (anonymous) limits via
403 Workers Rate Limiting binding (fallback: fixed-window counter in KV). Anonymous:
404 60 req/h; authenticated: 5k req/h. 429s include `Retry-After`. _Accepts:_ test
405 exhausts the anonymous window and sees 429.
406 - Note: KV fixed-window used (the Workers binding can't express hourly windows);
407 enforced centrally in src/worker.ts fetch for /v1/* (admin-keyed requests exempt).
408 API keys are verified for their bucket; agent JWTs bucket by *decoded\* sub — full
409 verification would consume the replay-protected jti before the route's own auth.
410 Eventual-consistency drift accepted (abuse mitigation, not billing). Acceptance
411 test exhausts 60 anon requests → 429 with Retry-After; keyed bucket independent.
412- [x] **5.5 Usage endpoint.** `GET /v1/agents/me` — agent identity, grants, limits,
413 current usage. _Accepts:_ curl with agent JWT and with API key.
414 - Note: usage reads the live KV rate counter (non-incrementing readRateUsage).
415 Curl-verified with both credential types. Also hardened 5.4 per security review:
416 agent JWT buckets now require a signature+expiry check against the agent's stored
417 key (jti untouched) — forged subs can no longer mint 5k/h windows (tested with
418 rotating spoofed subs).
419​
420## Phase 6 — Push notifications
421​
422- [x] **6.1 Subscriptions CRUD.** `POST|GET|DELETE /v1/subscriptions` (authed):
423 url + events filter (+ optional provider filter). Secret generated server-side,
424 returned once. _Accepts:_ CRUD round-trip test.
425 - Note: gated on the manage*subscriptions capability; autonomous agents' virtual
426 identities are materialised as user rows on first write (FK integrity); 10
427 subscriptions/owner cap; whsec*-prefixed 32-byte secrets; list never echoes
428 secrets; ownership enforced on delete. Live curl round-trip verified.
429- [x] **6.2 Webhook delivery.** On new `changes` rows, enqueue `webhook_deliveries`;
430 deliver via `ctx.waitUntil` with HMAC-SHA256 signature header
431 (`X-ModelSchemas-Signature`), JSON body `{ event, change, _links }`. Failures →
432 exponential backoff via `nextAttemptAt`, drained by the 15-min cron; 8 failures →
433 subscription auto-paused + recorded. _Accepts:_ integration test with a local
434 receiver route capturing the signed payload.
435 - Note: fan-out runs off a cache_meta checkpoint (changes.createdAt high-water mark)
436 so enqueue is idempotent without coupling sync/poll code; the 15-min cron runs
437 runWebhookTick (enqueue + drain) inside the same waitUntil as the poll. Backoff is
438 60s·2^attempt; signature is `sha256=<hex HMAC>` over the exact body, verified by
439 recomputation in the receiver test. Injectable fetcher = the "local receiver".
440​
441## Phase 7 — Clients, MCP + DX polish
442​
443The service's own `openapi.json` (task 4.1, every operation has an `operationId`) is
444the single source for three consumer surfaces: the generated TS client, the CLI, and
445the agent-auth capability list (5.1). Spec drift breaks a CI check, not a user.
446​
447- [x] **7.1 MCP server endpoint** at `/mcp` (streamable HTTP, Workers-native) exposing
448 tools: `list_models`, `get_model`, `get_schema`, `validate_payload`,
449 `recent_changes`. Reuse the Phase 4 service functions directly. _Accepts:_ MCP
450 inspector (or a scripted client) lists tools and round-trips `get_schema`.
451 - Note: hand-rolled stateless streamable-HTTP (JSON responses, no SSE session —
452 the MCP SDK transports are node/DO-centric); handles initialize/ping/tools/\*,
453 202s notifications, 405s GET, JSON-RPC errors for unknown methods. Live scripted
454 client listed 5 tools and round-tripped the real Anthropic messages schema.
455- [x] **7.2 Minimal human dashboard.** `/` route: provider sync status, model counts,
456 latest changes, docs links. Tailwind + shadcn; no auth needed (read-only).
457 _Accepts:_ renders against local data.
458 - Note: data via a createServerFn loader reusing getServiceStatus + listChanges
459 (already worker-tested); plain Tailwind shadcn-style cards/badges (no new deps).
460 Full SSR verified against local data (provider table + change feed in the HTML —
461 note: ugrep chokes on the single-line SSR output, use python/sed to inspect).
462- [x] **7.3 Docs page** `/docs`: quickstart for agents (register → fetch schema →
463 validate → subscribe), rendered from the same content as `llms.txt`. _Accepts:_
464 renders; links resolve.
465 - Note: renders the llmsTxt module verbatim via streamdown (already a dep) — zero
466 drift by construction; a content-contract test pins the sections/paths the page
467 and the future skill depend on. All 7 nav links curl-resolved 200 live.
468- [x] **7.4 Generated TS client (`@modelschemas/client`).** Convert the repo to bun
469 workspaces (`workspaces: ["packages/*"]`); add `packages/client` generated by
470 `@hey-api/openapi-ts` (pin the version — PR #622 pinned 0.97.2 for a reason) from
471 our spec: add `bun run openapi:emit` (writes `openapi.json` from
472 `src/server/openapi.ts`) and `bun run generate:client`. Fetch-based client, typed
473 per operation, pluggable auth (API key header or agent JWT). CI-style check script:
474 regenerate → `git diff --exit-code` so the committed client never drifts from the
475 spec. _Accepts:_ client compiles; smoke test against local dev lists providers and
476 fetches one schema, fully typed.
477 - Note: root devDependency `@modelschemas/client: workspace:*` makes bun link the
478 package (workspaces alone don't symlink into the root). Generated code lives in
479 packages/client/src/generated (eslint-ignored; typechecked by the root tsconfig);
480 hand-written entry adds createModelschemasClient with bearer auth. `check:client`
481 wired into CI. Smoke: bun scripts/client-smoke.ts listed 7 providers + fetched the
482 Anthropic schema typed.
483- [x] **7.5 CLI (`packages/cli`, bin: `modelschemas`).** Thin command layer over the
484 generated client. `modelschemas login` runs agent-auth registration (autonomous
485 mode by default; `--delegated` walks the device-authorization approval flow and
486 polls until granted; `--api-key` falls back to `/v1/agents/register-key`), storing
487 credentials in `~/.config/modelschemas/credentials.json` (0600). Commands:
488 `models list|get`, `schema get <provider> <endpointId>`, `validate <endpointId> <file>`,
489 `changes [--since]`, `subscribe <url> [--events]`, `whoami`. `--json` everywhere
490 (default when not a TTY) so the CLI is itself agent-friendly. _Accepts:_
491 `bun packages/cli login` against local dev creates an agent; `models list` then
492 succeeds authenticated; `validate` returns non-zero exit on invalid payload.
493 - Note: all commands live-verified (login → active autonomous agent, 0600 creds,
494 MODELSCHEMAS_CONFIG_DIR override for tests; whoami; models list/get; schema get
495 auto-resolves activity from the provider index; validate exits 2 on invalid;
496 changes; subscribe). validate takes `<provider/endpointId>`. Surfaced + fixed a
497 5.1 bug: defaultHostCapabilities derived from the raw spec included the excluded
498 syncProvider op, 400-ing capability-less registrations — now the filtered list.
499- [x] **7.6 Distributable agent skill.** `skill/modelschemas/SKILL.md` (frontmatter:
500 `name`, `description` with trigger phrases like "model schema", "what models
501 support X", "validate this provider payload") teaching the full workflow:
502 discovery (`/.well-known/agent-configuration`, `llms.txt`) → auth via
503 `modelschemas login` (or raw HTTP for keyless reads) → fetch/validate schemas →
504 watch `/v1/changes`. Generate the endpoint reference section from the same source
505 as `llms.txt` to avoid drift. Serve it: `GET /skill` returns the SKILL.md, linked
506 from `/docs` and `llms.txt`. _Accepts:_ frontmatter valid; installing the dir into
507 `.claude/skills/` and asking for an Anthropic chat schema produces a correct
508 CLI/HTTP call sequence.
509 - Note: SKILL.md generated from src/server/skill.ts (bun scripts/emit-skill.ts);
510 a test pins the committed file to the module and validates frontmatter +
511 trigger phrases; the reference section embeds llms.txt verbatim. Served at
512 GET /skill, linked from /docs and llms.txt. The taught call sequences are the
513 live-verified ones (schema get anthropic v1/messages; encoded HTTP path).
514​
515## Phase 8 — Ship
516​
517- [x] **8.1 Production setup.** Create real D1 + KV resources, set IDs in
518 `wrangler.jsonc`; `wrangler secret put` for `BETTER_AUTH_SECRET`, provider keys
519 (`FAL_KEY`, `ELEVENLABS_API_KEY`, …), `ADMIN_KEY`. Document in README. _Accepts:_
520 `bun run deploy` succeeds; `/v1/status` live.
521 - Done 2026-06-11 after Tom's "deploy it": D1 557c12a0… + KV 8c8f93fc… created, IDs
522 wired, remote migrations + seed applied, secrets set (BETTER_AUTH_SECRET,
523 ADMIN_KEY — prod value in .env.local as PROD_ADMIN_KEY; provider keys still
524 unset → those providers skip). Live at https://modelschemas.openstory.workers.dev
525 with both crons. Deploy script fixed to use the vite-built config
526 (wrangler deploy -c dist/server/wrangler.json); BETTER_AUTH_URL var set to the
527 deployed origin.
528- [x] **8.2 First production sync.** Trigger admin sync for all providers; verify
529 `/v1/models?activity=chat` returns real multi-provider data in prod. _Accepts:_
530 spot-check Anthropic + OpenRouter schemas served with ETags.
531 - Done: admin sync of OpenRouter (21 endpoints/41 versions) + Anthropic (5/10) in
532 prod, outcomes identical to local; /v1/models serves live multi-provider data
533 (cron poll already fired); Anthropic messages schema served with the same
534 contentHash as local, 304 on If-None-Match verified.
535- [x] **8.3 Observability.** `wrangler.jsonc` `observability.enabled`, structured
536 `console.log` JSON lines in cron handlers (provider, duration, changes count),
537 README runbook for "a provider sync is failing". _Accepts:_ logs visible via
538 `wrangler tail` during a manual sync.
539 - Note: observability.enabled set, worker renamed `modelschemas`, cron handlers
540 already log structured JSON lines (provider/outcomes), README rewritten with the
541 runbook + production setup. The wrangler-tail acceptance can only run post-deploy
542 (8.1) — everything tail-able is in place. Post-deploy: wrangler tail captured both
543 manual sync invocations (request events, outcome ok).
544- [x] ~BLOCKED~ **8.4 Publish client + CLI.** npm publish `@modelschemas/client` and the
545 `modelschemas` CLI (changesets or manual version bump); install instructions in
546 README, `/docs`, and the skill. _Accepts:_ `bunx modelschemas@latest whoami`
547 works against prod.
548 - BLOCKED 2026-06-11: npm publish is irreversible and needs Tom's npm account +
549 scope decision (@modelschemas org availability unverified) + a deployed prod URL
550 (8.1). Packages are publish-shaped (files/bin/exports set).
551 - 2026-08-21 (#48): scope kept as `@modelschemas` (CLI unscoped).
552 `0.1.0` could not go through Actions (`npm trust` / `npm stage` need
553 an existing package). Laptop bootstrap landed 2026-08-21 (org,
554 `npm publish`, stage-only `npm trust`, tokens disallowed). Ongoing:
555 OIDC `npm stage publish` from `.github/workflows/publish.yml` (no
556 `NPM_TOKEN`; provenance on future Actions stages).
557- [x] **8.5 Update CLAUDE.md** with the new architecture (D1/KV bindings, cron
558 entry point, ingest pipeline layout, workspace packages, API map) replacing the
559 starter description. _Accepts:_ CLAUDE.md matches reality.
560 - Note: full rewrite — commands (bun/--bun split, db/codegen scripts), worker entry
561 - ingest/API/auth/webhook architecture, workspace packages, route-tree-regen and
562 module-scope-auth gotchas, API map. README rewritten alongside (8.1 docs + 8.3
563 runbook).
564​
565## Phase 9 — Human users + site polish
566​
567Requested by Tom 2026-06-11: a human-facing surface alongside the agent one.
568The production domain is **modelschemas.com**.
569​
570- [x] **9.1 Custom domain.** Attach `modelschemas.com` to the deployed worker
571 (Cloudflare custom domain on this account's zone; `routes` in
572 `wrangler.jsonc` with `custom_domain: true`), set the
573 `BETTER_AUTH_URL` var to `https://modelschemas.com` (agent JWT
574 audiences are origin-bound), redeploy, and confirm the workers.dev URL
575 still serves (or document the canonical-host choice). _Accepts:_
576 `https://modelschemas.com/v1/status` live. If the zone is not in the
577 OpenStory account, mark BLOCKED with what Tom needs to do.
578 - First attempt 2026-06-11 failed: the modelschemas.com zone is not in the
579 OpenStory Cloudflare account (PUT …/domains/records rejected). Prereq for Tom:
580 add modelschemas.com as a zone (dashboard → Add site → point registrar
581 nameservers at Cloudflare). The loop should retry this task first each
582 iteration and skip forward while the zone is absent. Route was reverted so
583 deploys stay green; service stays on modelschemas.openstory.workers.dev
584 meanwhile. NOTE: 9.2's email sender verification ALSO depends on this zone.
585- [x] **9.2 Email OTP sign-in for humans.** Add better-auth's `emailOTP`
586 plugin to `createAuth` with a mail abstraction in
587 `src/server/email.ts` built on **Cloudflare Email Workers** — a
588 `send_email` binding (`EMAIL`) in `wrangler.jsonc` using the
589 structured `env.EMAIL.send({to, from, subject, text})` API, sender
590 `login@modelschemas.com`. Until the zone is verified (9.1), and in
591 local dev, every send falls back to a structured console line
592 (`{"job":"email",...}`) so the OTP stays observable — never silently
593 drop a sign-in. The sender is injectable so worker tests capture OTPs.
594 Build a minimal `/login` page (email → code → session) with the
595 email-otp client plugin, plus a signed-in indicator + sign-out. Keep
596 email/password enabled (delegated-mode approvals depend on it).
597 Regenerate worker-configuration.d.ts after adding the binding.
598 _Accepts:_ worker test issues + verifies an OTP via an injected
599 sender; live dev sign-in works end to end using the logged code.
600 - Note: live-verified — the vite plugin SIMULATES the send_email binding locally
601 and writes messages to a temp .txt (path printed in dev output), so the dev
602 fallback log rarely fires; the OTP was read from the simulator file and the full
603 send→sign-in→session flow passed. better-auth's withSpan telemetry leaves a
604 floating APIError rejection on failed sign-ins — filtered via vitest's root
605 onUnhandledError (APIError only). Production email needs Email Routing enabled
606 on the modelschemas.com zone (sender verification) — covered in 9.5.
607- [x] **9.3 Human API-key management.** `/account` page for signed-in users:
608 list, create (name + optional expiry), and revoke their API keys via
609 the better-auth api-key plugin's session-authed endpoints; the key
610 value is shown exactly once on creation, with copy-paste usage snippet
611 (`Authorization: Bearer …`). The page explains what keys unlock (5k
612 req/h + subscriptions). _Accepts:_ live flow — sign in, create key,
613 key authenticates `/v1/agents/me`, revoke, key 401s; worker tests for
614 the session-scoped key lifecycle.
615 - Note: list endpoint returns {apiKeys: []}, not a bare array. Live flow verified
616 end to end (OTP sign-in → session-cookie key create → key 200s /v1/agents/me →
617 revoke → 401); worker tests cover the lifecycle plus cross-user isolation
618 (Bob can't see/revoke Alice's key).
619- [x] **9.4 Frontend overhaul (use the /frontend-design:frontend-design
620 skill).** Make the site look hot while staying agent-first: redesign
621 the landing page (`/`) with a hero that pitches the service, a
622 prominent "for agents" section (copy-paste curl + CLI + MCP + skill
623 install examples, llms.txt/discovery links), the live provider status + latest-changes data, and nav to /docs, /login, /account. Restyle
624 /docs, /login, /account to match. No regression to any agent surface
625 (JSON endpoints untouched). _Accepts:_ pages render with the new
626 design against local data; all links resolve; existing tests stay
627 green.
628 - Note: direction = "machine registry" — dark instrument panel (phosphor green /
629 amber on near-black), Instrument Serif display + IBM Plex Mono data + Instrument
630 Sans body, terminal-chrome cards, pulsing status dots, scanline overlay, staggered
631 hero reveal (reduced-motion safe). Shared chrome in src/components/site.tsx;
632 landing hero features a real schema fragment + etag, a 4-card FOR AGENTS section
633 (curl/validate/MCP/discovery+skill), live provider table and log-line change feed.
634 All 9 routes/surfaces curl-verified; agent JSON untouched; 128 tests green.
635- [x] **9.5 Ship the human surface.** Deploy to production and verify on
636 the live origin (modelschemas.com once 9.1 lands, else workers.dev):
637 OTP sign-in (real email via the send*email binding when the zone is
638 verified; logged code via `wrangler tail` otherwise), key creation,
639 the key authenticating `/v1/agents/me`, and the redesigned landing
640 page rendering. \_Accepts:* live production walkthrough recorded in
641 the note.
642​
643## Phase 10 — Agent-readiness audit (isitagentready.com)
644​
645Tom pasted the audit 2026-06-11. Fixes target https://modelschemas.com; each
646lands as a route/header served by the worker so they stay correct on every
647deploy. Re-verify on production at the end.
648​
649- [x] **10.1 Sitemap + robots.** `GET /sitemap.xml` (canonical pages: `/`,
650 `/docs`, `/login`, `/account`, plus `/llms.txt`, `/openapi.json`,
651 `/skill`), generated dynamically (origin from BETTER*AUTH_URL, lastmod
652 from the latest change row) so it is always current on publish;
653 `GET /robots.txt` allowing all and referencing the sitemap. \_Accepts:*
654 both render locally with correct content types; sitemap validates
655 against the sitemaps.org shape (urlset/url/loc).
656 - Note: a scaffold public/robots.txt static asset was shadowing the route
657 (assets win over worker routes) — removed. lastmod derives from the newest
658 change row; worker tests cover both surfaces.
659- [x] **10.2 Link headers (RFC 8288).** Add `Link` response headers on HTML
660 pages (via the worker fetch wrapper): `</.well-known/api-catalog>;
661rel="api-catalog"`, `</openapi.json>; rel="service-desc"`, `</docs>;
662rel="service-doc"`, `</llms.txt>; rel="describedby"`. _Accepts:_ curl -I
663 of `/` shows the Link header; JSON endpoints unaffected.
664- [x] **10.3 Discovery trio.** `/.well-known/api-catalog`
665 (`application/linkset+json` per RFC 9727: anchor + service-desc/
666 service-doc/status), `/.well-known/mcp/server-card.json` (SEP-1649:
667 serverInfo, transport endpoint `/mcp`, capabilities/tools), and
668 `/.well-known/agent-skills/index.json` (Agent Skills Discovery RFC
669 v0.2.0: $schema + skills[] with name/type/description/url/sha256 — the
670 digest computed from the live SKILL.md content). _Accepts:_ all three
671 render with correct content types; sha256 in the index matches the
672 served /skill body.
673- [x] **10.4 Auth discovery.** `/.well-known/oauth-protected-resource`
674 (RFC 9728: resource, authorization*servers, scopes_supported = public
675 capability names), `/.well-known/oauth-authorization-server` (RFC 8414
676 fields we genuinely have: issuer, registration via agent-auth, the
677 device-authorization endpoint, jwks where applicable) including the
678 auth.md `agent_auth` block (register_uri, identity/credential types),
679 and `/auth.md` — markdown registration instructions for agents
680 (agent-auth protocol + register-key fallback), generated from the same
681 sources as llms.txt where possible. Honest metadata only — no fake
682 OAuth endpoints. \_Accepts:* all three render; agent_auth.register_uri
683 round-trips against the real register endpoint locally.
684- [x] **10.5 Markdown negotiation.** Requests with `Accept: text/markdown`
685 on HTML pages return markdown with `Content-Type: text/markdown`
686 (worker wrapper): `/docs` → llms.txt content, `/skill` already
687 markdown, `/` → a markdown landing summary (hero pitch + agent
688 quickstart + live links); browsers keep HTML. The audit saw a 500 —
689 must return 200. _Accepts:_ curl with the Accept header gets markdown
690 200s on `/`, `/docs`; plain requests still get HTML.
691- [x] **10.6 WebMCP.** On the landing page, feature-detect
692 `navigator.modelContext` and `provideContext()` with tools wrapping the
693 public API: `list_models`, `get_schema`, `validate_payload` (fetch
694 wrappers with JSON Schema inputs). No-op when the API is absent.
695 _Accepts:_ guarded registration code ships on `/` without console
696 errors in normal browsers; tool definitions match the MCP tool shapes.
697- [x] **10.7 DNS-AID (+ ship + reverify).** Attempt to publish
698 `_index._agents.modelschemas.com` ServiceMode HTTPS/SVCB records (alpn
699 h2, target the apex) via the Cloudflare API; DNSSEC needs zone signing + a DS record at the registrar — document for Tom if the API token
700 lacks DNS scope. Then deploy everything and re-verify each Phase 10
701 surface on https://modelschemas.com. _Accepts:_ production curls for
702 10.1–10.5 all pass; DNS-AID either resolves or is marked BLOCKED with
703 exact records for Tom.
704 **Deployed + reverified 2026-06-11: production curls for 10.1–10.5 all
705 pass** (sitemap/robots, Link header HTML-only, discovery trio with
706 sha256 match, auth trio with live register_uri, markdown negotiation).
707 **DNS-AID: BLOCKED on Tom** — wrangler's OAuth token has no DNS scope
708 (and harvesting it was denied anyway). To publish, in the Cloudflare
709 dashboard (zone modelschemas.com → DNS) add an HTTPS record:
710 name `_index._agents`, priority `1`, target `modelschemas.com.`,
711 params `alpn="h2"` (zone-file form:
712 `_index._agents 3600 IN HTTPS 1 modelschemas.com. alpn="h2"`), then
713 enable DNSSEC (DNS → Settings) and add the DS record at the registrar.
714​
715## Phase 11 — Agents API ergonomics (Tom, 2026-06-11)
716​
717Agents consume APIs differently from programmers. Keep the DX surface
718(`/openapi.json`, typed client) separate from the agent experience (AX)
719surface; these tasks build the AX layer.
720​
721- [x] **11.1 HAL self-description.** Add `_links` (HAL) to `/v1` and every
722 `/v1/*` JSON read response, extended per link with `method`,
723 `contentType`, and an inline `example` (HAL doesn't carry these —
724 agents need them). Keep payload shapes backwards-compatible (additive
725 only); document the extension in llms.txt. _Accepts:_ `GET /v1` and
726 `GET /v1/models` responses carry `_links` whose hrefs all resolve 200
727 locally (worker test walks them); openapi.json regenerated without
728 breaking `check:client`.
729- [x] **11.2 Narrative API root.** Make a JSON-accepting `GET /`
730 (`Accept: application/json`, plus the `GET /v1` self link) return the equivalent of
731 MCP default instructions: narrative description, workflow, inline
732 examples, and HAL links — the same content an MCP `initialize`
733 instructions field would carry, generated from the llms.txt source.
734 _Accepts:_ JSON `GET /` returns the narrative document with `_links`;
735 HTML browsers still get the landing page; MCP initialize instructions
736 and the root narrative share one source.
737- [x] **11.3 `?wait=` long-poll.** Support `?wait=<seconds>` (cap 60s, also
738 accepts `60s` form) on `/v1/changes` and `/v1/status`: hold the
739 request until new data exists or the window expires (poll D1 every
740 ~2s), returning whatever is current at expiry. Agents rarely have a
741 sleep tool — this gives them one. Document on the endpoints + llms.txt;
742 ensure Workers runtime limits are respected (use ctx.waitUntil-safe
743 timers within the request, no cron dependency). _Accepts:_ worker test
744 proves `?wait=2` returns early when a change lands mid-wait and at
745 ~wait expiry otherwise; rate limiter counts the call once.
746​
747## Phase 12 — Build-time schema pulls: typegen + vite plugin (Tom, 2026-06-12)
748​
749Design settled with Tom (don't relitigate):
750​
751- **Generated files on disk, committed.** No virtual modules. Dev-time
752 fetch only: the vite dev server (or explicit CLI command) fetches and
753 writes; production builds touch zero network and fail with remediation if
754 files are missing. `.manifest.json` in the out dir is the lockfile
755 (endpoint → contentHash) and records the selection, so `update` needs no
756 separate config.
757- **Tree-shakeable, no barrel index.** One pure `.ts` module per
758 endpoint+kind (schema const + generated types), zero imports, zero side
759 effects, descriptive export names (`anthropicV1MessagesRequestSchema`,
760 `AnthropicV1MessagesRequest`). Users import directly from the file. The
761 schema const is annotated with an exported structural `JsonSchema` alias
762 (exported so `declaration: true` consumers don't hit TS4025) — never
763 `as const` (literal-typing megabyte schemas kills tsc).
764- **Server-side typegen, dependency-free emitter.** No
765 json-schema-to-typescript (prettier dep + bundle weight in workerd);
766 we own a small deterministic emitter. Generated lazily at request time
767 via `?format=types` on the existing schema route, SWR-cached, ETag =
768 contentHash + emitter version. tsconfig variance handled by emitting
769 flag-agnostic declaration-only types plus one knob:
770 `optional=exact|undefined` (default `exact`: `foo?: T` — JSON has no
771 undefined). Always `unknown`, never `any`. Index signatures only when
772 `additionalProperties` is explicitly truthy (jstt's always-on
773 `[k: string]: unknown` poisons DX).
774- **Formatting belongs to the user.** The pull core runs the user's own
775 prettier (dynamic `import('prettier')` + `resolveConfig`) over generated
776 files when present; otherwise the server's canonical formatting stands.
777 Files carry a `// @generated` banner (source URL + contentHash + emitter
778 version, no timestamp — output stays byte-deterministic).
779- **Selection grammar** maps 1:1 onto the API:
780 `provider[/endpointId][#request|response]` with `*` globs expanded via
781 the catalog (`request`/`response` are the user-facing aliases for
782 kind=`input`/`output`; filenames use them too:
783 `anthropic/v1-messages.request.ts`).
784- **Auth:** anonymous fine (a dev boot is ~1 request thanks to the
785 manifest); `MODELSCHEMAS_API_KEY` lifts to the credentialed tier.
786- **Packages:** `@modelschemas/codegen` (pull core: grammar, catalog
787 expansion, ETag fetch, manifest, file writer, prettier pass),
788 `@modelschemas/vite` (thin plugin), CLI gains `pull`/`update` on the
789 same core.
790​
791- [x] **12.1 TypeScript emitter.** `src/server/typegen.ts`: JSON Schema →
792 self-contained `.ts` module text (banner, `JsonSchema` alias, schema
793 const, root interface/type, named `$defs` as exported declarations,
794 JSDoc from descriptions). Handles type arrays, OpenAPI `nullable`,
795 enum/const, anyOf/oneOf unions, allOf intersections, tuples,
796 `$ref → #/$defs/*` (circular-safe via named declarations), name
797 collisions via numeric suffix. Deterministic output;
798 `TYPEGEN_VERSION` exported for ETags. _Accepts:_ unit tests cover the
799 subset + a real bundled fixture; generated text compiles clean under
800 `strict` with `exactOptionalPropertyTypes` both on and off (in-memory
801 tsc program in the test).
802- [x] **12.2 `?format=types` on the schema route.** Extend
803 `/v1/schemas/{p}/{activity}/{endpointId}` with `format=json|types`
804 (+ `optional=exact|undefined`): types responses are
805 `text/typescript; charset=utf-8`, SWR-cached per
806 `contentHash+TYPEGEN_VERSION+optional`, ETag/304 preserved.
807 openapi.json + generated client regenerated (additive). Documented in
808 llms.txt. _Accepts:_ worker test fetches types for a synced fixture
809 endpoint, gets compilable TS, 304 on If-None-Match replay;
810 `check:client` passes.
811 - Note: deviated from "SWR-cached emitted text" — the module is emitted
812 inline from the already-SWR-cached schema (pure CPU, cheaper than a
813 second KV read); the ETag (`typesEtag` = hash+TYPEGEN_VERSION+optional)
814 still fully keys the body. Verified live: real Anthropic v1/messages →
815 186KB module, 0 tsc diagnostics under strict+exactOptionalPropertyTypes,
816 304 replay, 400s on bad format/optional. SKILL.md re-emitted (it embeds
817 llms.txt).
818- [x] **12.3 `@modelschemas/codegen` pull core.** `packages/codegen`:
819 selection parsing/expansion, conditional fetch (If-None-Match from
820 manifest), atomic file writes, manifest read/write, optional local
821 prettier pass, `pull()`/`checkUpdates()`/`verify()`. `checkUpdates`
822 is one `/v1/changes?since=` call per provider filtered to selected
823 endpoints. _Accepts:_ unit tests with a mocked fetch cover grammar
824 (provider, globs, #kind), 304 short-circuit, manifest round-trip,
825 verify failure messaging.
826- [x] **12.4 `@modelschemas/vite` plugin.** `packages/vite`: on `serve`,
827 pull missing files then log (never auto-rewrite) upstream updates
828 from `checkUpdates`; on `build`, `verify()` only — zero network —
829 erroring with "run `modelschemas pull`" remediation. _Accepts:_ unit
830 tests drive the plugin hooks both modes; a fixture project under the
831 test proves generated modules are import-clean (no side effects, no
832 barrel).
833- [x] **12.5 CLI `pull`/`update`.** `modelschemas pull` taking selections
834 plus `--out` and `--no-types` flags, and `modelschemas update --out`
835 (selection read from the manifest) on the codegen core; help text
836 updated. _Accepts:_ unit tests for arg parsing; roundtrip exercised
837 in 12.6.
838- [x] **12.6 E2E + docs + ship.** `bun scripts/pull-roundtrip.ts`: against
839 the local dev server, pull a real selection, typecheck the generated
840 files, mutate one upstream schema (admin sync fixture or direct D1
841 write), prove `update` rewrites exactly that file. README + docs page + llms.txt get the vite-plugin/CLI quickstart. Deploy; verify
842 `?format=types` on production. _Accepts:_ roundtrip script green
843 locally; production curl returns compilable TS with correct
844 content-type and ETag.
845 - Note: roundtrip green against local dev (pull → tsc-clean module → 304
846 no-op → staled manifest entry rewritten exactly); upstream mutation done
847 by staling the lockfile entry rather than a D1 write — same code path,
848 no SWR-staleness flake. CLI pull/update smoked end-to-end. Docs: README
849 quickstart; /docs + llms.txt already carry the 12.2 section.
850 **Deployed + verified 2026-06-12** (Tom approved): production curl →
851 200 `text/typescript` with `<hash>-types-v1-exact` ETag (and the
852 `optional=undefined` variant keyed separately); full
853 `bun scripts/pull-roundtrip.ts https://modelschemas.com` green —
854 pull → tsc-clean → 304 no-op → staled-entry rewrite, all against prod.
855- [x] ~BLOCKED on Tom~ **12.7 Deploy on push via Workers Builds.** Tom
856 chose Cloudflare Workers Builds over a CI deploy job (no tokens in
857 GitHub). Connecting the repo needs interactive GitHub auth in the
858 Cloudflare dashboard, so the setup is Tom's: dashboard → Workers &
859 Pages → `modelschemas` → Settings → Build → Connect → GitHub repo
860 `modelschemas/modelschemas` (moved from `tombeckenham/modelschemas`
861 2026-06), production branch `main`, then:
862 - Build command: `bun run build` (the build image auto-runs
863 `bun install` from bun.lock)
864 - Deploy command:
865 `bunx wrangler d1 migrations apply DB --remote && bunx wrangler deploy -c dist/server/wrangler.json`
866 (migrations are idempotent; the emitted config under dist/server is the
867 real worker config — NOT the repo-root wrangler.jsonc)
868 - Root directory: `/`; leave non-production branch builds enabled if PR
869 preview versions are wanted (wrangler versions upload).
870 Once connected, manual `bun run deploy` becomes the emergency path
871 only. _Accepts:_ a push to main produces a dashboard build that
872 deploys; /v1/status on prod reflects the new version.
873​
874## Phase 13 — Backdate firstSeenAt to real release dates (Tom, 2026-07-14; issue #1)
875​
876- [x] **13.1 Backdate `models.firstSeenAt` per provider.** `ModelInfo` gains
877 optional `releasedAt` (epoch s); listModels populates it — OpenAI/xAI/
878 OpenRouter `created`, Anthropic `created_at` (ISO), FAL `metadata.date`
879 (ISO), Gemini/ElevenLabs from a curated map in
880 `src/server/providers/release-dates.ts` (+ Gemini `MM-YYYY` preview-id
881 suffix fallback). The 15-min poll applies it continuously: on insert
882 `firstSeenAt = releasedAt` when sane-and-earlier than now; existing
883 rows backdate in place when upstream reports an earlier date —
884 SILENTLY (no `model.updated` event: the fleet-wide first pass would
885 flood the changes feed + webhook fan-out; converges once per row so
886 the bulk clean-path perf note above still holds). Backdates write in
887 30-row CASE-chunked bulk UPDATEs — each D1 query is a subrequest
888 against the invocation's 1,000 budget, and the ~1,900-row first pass
889 as one-per-row writes would exhaust it mid-poll (and starve the
890 webhook drain sharing the invocation). Never forward-dates;
891 bogus timestamps (< 2015-01-01) ignored. `PollOutcome.backdated`
892 counts corrections for cron observability. _Accepts:_ live listModels
893 shows date coverage openai 129/129, anthropic 10/10, grok 10/10,
894 openrouter 344/344, fal 1399/1399; worker test walks insert/backdate/
895 never-forward/update-compose cycles.
896​
897## Phase 14 — BytePlus provider (2026-08-11)
898​
899- [x] **14.1 BytePlus as the 8th provider — fully static, keyless.** BytePlus
900 publishes no machine-readable spec (its OpenAPI docs live behind the
901 console's API explorer) and the Ark data-plane `GET /models` needs a
902 region-bound key AND is documented non-exhaustive, so both surfaces are
903 embedded, ported from TanStack AI's `@tanstack/ai-byteplus` adapter
904 (whose wire types are hand-written, test-pinned, and probe-verified
905 against the ap-southeast host on 2026-07-31):
906 `src/server/providers/byteplus-spec.ts` synthesizes two OpenAPI 3.1
907 documents — Ark (`/chat/completions` OpenAI-compatible + thinking/
908 reasoning*effort/repetition_penalty/service_tier extensions,
909 `/images/generations` Seedream, `/contents/generations/tasks` Seedance
910 async task API whose 200 is just the `{id}` ack, post-200 precedent per
911 OpenRouter/ElevenLabs job acks) and Seed Speech (`/tts/create`,
912 `/auc/bigmodel/recognize/flash` — separate host and `X-Api-Key` product
913 key). `byteplus.ts` classifies by exact path and serves the curated
914 32-model catalog (18 chat / 7 video / 5 image / 2 speech) with context
915 windows, modalities, probed structured-output capabilities, and
916 `releasedAt` from the `-YYMMDD` id suffix
917 (`byteplusIdSuffixDate` in release-dates.ts). Provenance: sources point
918 at the human docs, hashes are `contentHash` of the built documents (FAL
919 embedded-spec precedent), so content changes only land through edits
920 here and version like any upstream change. NOTE the HMAC
921 `BYTEPLUS_ACCESS_KEY`/`SECRET_KEY` pair in the old providers-to-add
922 table only guards the control plane — never needed. \_Accepts:*
923 byteplus.test.ts walks classifyAndBundle over the embedded specs (5
924 endpoints, zero warnings, no dangling refs, deterministic hashes) and
925 the catalog counts; registry/seed tests updated to 8.
926​
927## Phase 15 — BytePlus spec generated from the Go SDK (2026-08-12)
928​
929- [x] **15.1 Generate the Ark spec from BytePlus's Go SDK at sync time.**
930 Probing the Ark data plane with a real `ARK_API_KEY` confirmed there is
931 no fetchable OpenAPI document (`/openapi.json`, `/swagger.json`,
932 `/docs`, `/models/{id}` all answer 200 with an EMPTY body). But
933 BytePlus's official Go SDK declares the whole Ark data plane as
934 `json:"…"`-tagged structs, and — unlike the Python SDK's Pydantic
935 models, which need a Python runtime to introspect — Go structs are
936 plain text. So `go-struct-parser.ts` (Workers-safe, pure string
937 parsing) turns them into component schemas and `byteplus-ark-build.ts`
938 maps them onto paths, letting `fetchSpec` regenerate the Ark document
939 from `raw.githubusercontent.com/byteplus-sdk/byteplus-go-sdk-v2` on the
940 daily cron. No codegen step, no committed artifact, no CI drift check —
941 upstream SDK releases flow in and the content-hash diff versions them
942 like any other provider's spec change.
943 Two deliberate seams: (a) the endpoint→type map is hand-maintained,
944 because the model package has no notion of HTTP paths and paths change
945 far more slowly than field sets; (b) an explicit curated overlay
946 re-applies the request fields the SDK omits (`reasoning_effort`,
947 `top_k`, `seed` on chat; `stream` on images; `output_format` on video)
948 and the hand-written descriptions carrying probe findings that a type
949 declaration cannot state. The overlay is an explicit list rather than a
950 blanket merge of the old document, so a field genuinely REMOVED
951 upstream disappears instead of being resurrected forever.
952 Falls back to the embedded document (with a warning on the sync
953 outcome, via the new `SpecFetchResult.warnings`) when GitHub is
954 unreachable or the SDK outgrows the parser — degraded freshness, not a
955 degraded service. Seed Speech stays hand-written: it appears in no
956 BytePlus SDK in any language.
957 _Accepts:_ generated-vs-hand-port diff loses ZERO fields and gains
958 three (`function_call`, image-response `tools`, task-response
959 `safety_identifier`); live end-to-end against GitHub bundles all 5
960 endpoints with no warnings and no dangling refs; parser unit tests
961 cover primitives/pointers/omitempty-requiredness, const-block enums,
962 slices/maps/interface{}/[]byte, `json:"-"` and embedded fields,
963 aliases and named composites, doc comments, closure-only emission, and
964 graceful degradation on unmapped types.
965​
966- [x] **15.2 Per-endpoint schema provenance (`derivation` + `verifiedAt`).**
967 Surfaces how each schema's content was arrived at so agents can weigh
968 how far to trust it — and so a hand-written corner going stale is
969 visible rather than invisible. A four-rung trust ladder on
970 `provenance.derivation`: `upstream-spec` (extracted from a document the
971 provider publishes and we re-fetch every sync — the seven original
972 providers), `generated` (re-derived each sync from a provider artifact
973 that is not a spec — BytePlus Ark from the Go SDK), `probe-verified`
974 (hand-written but confirmed against live calls on `verifiedAt` —
975 BytePlus TTS, 2026-08-12) and `docs-derived` (hand-written, never
976 confirmed — BytePlus ASR, blocked on a Seed ASR account grant). The
977 first two self-heal; the last two are point-in-time claims.
978 Providers declare `defaultDerivation`, and any operation may override
979 it with an `x-modelschemas-provenance` marker (the FAL activity-marker
980 trick) — which is how the BytePlus Ark document downgrades itself from
981 `generated` to `probe-verified`/2026-07-31 when it falls back to the
982 embedded copy. A malformed marker falls back to the provider default
983 rather than throwing. Stored on `schema_versions` beside the existing
984 sourceUrl/sourceHash/extractorVersion provenance (nullable, additive
985 migration 0004), so it versions per schema version and can improve over
986 time as endpoints get probed. _Accepts:_ worker tests assert the
987 columns persist and the API surfaces them (including null for rows
988 synced before the field existed); byteplus tests pin all five endpoint
989 grades and the fallback downgrade; openapi.json, the typed client and
990 SKILL.md regenerated.
991​
992## Phase 16 — Full provider roster + system-wide schema discovery (2026-08-14)
993​
994- [x] **16.1 Registry is the source of truth for provider listings.** The
995 landing page and `/v1/status`/`/v1/providers` only showed providers
996 whose rows happened to exist in D1, and the sync/poll engines only ever
997 UPDATE provider rows — so the adapter providers added in #18–#37 never
998 appeared in prod without a manual `bun run seed`. Two fixes, both
999 self-healing: `getServiceStatus` merges `providerRegistry` (code) over
1000 the DB rows, surfacing never-synced providers as a new `pending` status
1001 with zero counts (blue dot on the site; enum added to the OpenAPI
1002 ServiceStatus schema); and `ensureProviderRow` (sync.ts) upserts the
1003 seed row — `seedForProvider`: hand-written row for the original 8,
1004 `seedFromAdapter` otherwise, no-op for configs without a
1005 `specSourceUrl` (test stubs) — at the top of every syncProvider/
1006 pollProviderModels run, matching scripts/seed.ts semantics (config
1007 columns refresh, runtime state preserved). _Accepts:_
1008 status.worker.test asserts every registry provider surfaces as
1009 `pending` on an unseeded DB; sync/poll worker tests unchanged.
1010​
1011- [x] **16.2 `GET /v1/schemas` — the system-wide schema index.**
1012 `getSystemSchemaIndex` groups every endpoint into provider → activity →
1013 endpoint-id lists (one D1 query, SWR-cached under `schema-index:all`,
1014 ETag like every read). Discovery wiring: `_links.schemaIndex` on
1015 `GET /v1`, an `/v1/schemas` path in openapi.ts (client + SKILL.md
1016 regenerated), llms.txt quickstart step 3, and a `list_schemas` MCP tool
1017 (optional `provider` arg narrows to the per-provider index) mirrored
1018 into the WebMCP tool list. llms.txt no longer hard-codes the original
1019 7-provider list.
1020​
1021- [x] **16.3 `/schemas` — the human-browsable index.** New route modeled on
1022 `/models`: the flattened endpoint list with provider/activity/q filters
1023 (client-side; the whole index is one loader payload), capped at 300
1024 rows with a pointer to the API, readable/json ViewToggle serving the
1025 `/v1/schemas` body verbatim. Nav gains a `schemas` link; the landing
1026 hero gains a `GET /v1/schemas` button; provider-table schema counts
1027 link to `/schemas?provider=…`.
1028​
1029- [x] **16.4 schema-studio browses every schema live.** The example keeps
1030 its four vite-plugin-pinned, offline-verified schemas as instant
1031 entries and adds a live rail: fetch `/v1/schemas` on mount, pick a
1032 provider, fetch any input schema on demand and render the generated
1033 form. Same-origin on the zone; from a local dev server it hits prod —
1034 which works because the worker now serves CORS-open reads
1035 (`Access-Control-Allow-Origin: *` + OPTIONS preflight) on GET/HEAD for
1036 `/v1/*` (admin excluded), `/openapi.json` and `/llms.txt` — a public
1037 keyless JSON API browsers can actually call.
1038​
1039## Phase 17 — sync scalability (the FAL degradation)
1040​
1041- [x] **17.1 Root-cause FAL's stuck `degraded` status.** Production D1
1042 showed the daily 05:00 spec sync dying mid-FAL every day since
1043 Aug 1: fal + the four biggest core providers flapping degraded, and
1044 every provider after fal in the registry (byteplus + all adapters)
1045 with `last_synced_at` NULL — never synced once. Cause: the sync did
1046 2 D1 `findFirst` round trips per endpoint (+1 per vanished endpoint,
1047 forever) and FAL is ~1,400 endpoints — past the invocation's
1048 1,000-subrequest budget and most of its wall clock, so a full
1049 successful sync (the only thing that resets status to `active`)
1050 could never complete. Fix mirrors poll-models' batching: one joined
1051 query for the provider's current versions, one for the
1052 endpoint.removed set; degraded-status write is best-effort so budget
1053 exhaustion inside the catch can't sink the rest of the run. FAL's
1054 paginated crawl also now retries 5xx/408/timeouts/network errors
1055 (not just 429), honors Retry-After, 5 attempts.
1056- [x] **17.2 Shard the spec-sync cron.** One shared invocation meant one
1057 provider's blowup starved everyone behind it (and uncatchable
1058 CPU/memory kills took out the rest of the registry silently). The
1059 daily sync now fires four crons (05:00/05:10/05:20/05:30 UTC), each
1060 a fresh invocation with its own budgets: shard 0 is FAL alone, the
1061 rest round-robin (`specSyncShard`; keep `SPEC_SYNC_SHARD_CRONS` in
1062 lockstep with wrangler.jsonc — a unit test enforces it).
1063 `limits.cpu_ms` raised to 300s (ceiling, not floor) for FAL's
1064 1,400-spec parse+hash. Models poll unchanged: it's already batched,
1065 time-sensitive (15-min freshness), and carries the webhook drain.
1066​
1067## Phase 18 — grain=provider model activity + route binding (issue #50)
1068​
1069- [x] **18.1 Activity + displayName on grain=provider catalog rows.** Grok
1070 and OpenAI `/models` payloads are `id` + `created` only, so every row
1071 listed `activity: null` and `GET /v1/models?provider=grok&activity=image`
1072 returned empty. Derive activity from the raw id (Grok Imagine
1073 image/video/voice vs chat; OpenAI `gpt-image`/`sora`/`whisper`/`tts`
1074 before the `gpt-` chat default) and a display name from the id.
1075 Anthropic listed models are `chat`. Persisted by the 15-min poller
1076 like Gemini already was.
1077- [x] **18.2 Bind each model to its generation route schema.** Catalog rows
1078 gain `schemaEndpointId` (and `_links.schema`) pointing at the shared
1079 HTTP route — `v1/images/generations` for Grok Imagine image,
1080 `images/generations` for `gpt-image-2`, `v1/messages` for Anthropic,
1081 Gemini's `:predict` / `:generateContent` / `:predictLongRunning`.
1082 Model-grained FAL falls back to the raw id. `GET /v1/schemas/{p}/{activity}/{rawId}`
1083 aliases onto that route and pins the request `model` field to the one
1084 id so a Run form can be built the same way as for FAL. Validate
1085 accepts the same alias. `?format=types` overlays same-activity catalog
1086 ids (falling back to the full list when activity is still null).
1087 Follow-up on the same PR: OpenRouter activity from
1088 `architecture.output_modalities` (video → synthesised `videos/{id}`;
1089 image-only has no classified route); BFL `v1/{rawId}`; BytePlus
1090 chat/image/video plus Seed Speech TTS vs ASR.
1091- [x] **18.3 Fill contextWindow / maxOutput / modalities / request-feature
1092 capabilities on grain=provider rows (issue #53; pricing is a separate
1093 PR).** Native `/models` payloads publish none of these (OpenAI, xAI)
1094 or only limits plus a capability tree (Anthropic Models API, since
1095 2026-03) or limits + `thinking`/sampling defaults (Gemini). The rest
1096 comes from each provider's own published sources — never a
1097 third-party catalog (a model catalog that mirrors another caps its
1098 accuracy at theirs): OpenAI per-model markdown pages
1099 (`developers.openai.com/api/docs/models/{slug}.md`, fetched only for
1100 the ~65 pages the listed ids resolve to, dated snapshots via their
1101 alias), xAI's `/v1/{language,image-generation,video-generation}-models`
1102 for modalities plus `docs.x.ai/docs/models.md` for context windows.
1103 Adapters: `openAiCompatModelFacts` maps the extension fields
1104 OpenAI-compatible hosts already put on their rows (`context_window` /
1105 `context_length` / `max_context_length`, `max_completion_tokens`,
1106 `input_modalities`, `supports_*` booleans, groq/jina
1107 `supported_features` + `supported_sampling_parameters`, mistral
1108 `capabilities`) — one mapper in `listOpenAiCompatibleModels` covers groq, fireworks,
1109 moonshot, sambanova, hyperbolic, novita (`context_size`, hyphenated
1110 `features`); mistral, jina and cohere (`features`) call it too.
1111 Speech/media hosts (elevenlabs, deepgram, cartesia, stability,
1112 replicate, bfl, fal, byteplus, reactor) keep their own capability
1113 objects — token limits and request params don't apply; deepseek,
1114 cerebras, dashscope, perplexity, together publish bare rows. Output uses OpenRouter's shapes: `file` for documents,
1115 `supported_parameters` names as feature flags (`tools`,
1116 `tool_choice`, `reasoning`, `reasoning_effort`, `temperature`,
1117 `top_p`, `top_k`, `structured_outputs`, `response_format`).
1118 Nothing is inferred: a value is stored only when a provider field or
1119 table cell states it. So Grok has no capabilities (xAI publishes no
1120 feature flags), Gemini has no modalities (not on the row), a lone
1121 image/vision boolean does not produce a modalities object,
1122 `tool_choice` needs its own flag, and Anthropic's tool use, sampling
1123 params and Fable-tier mandatory thinking stay unset (prose only). Those
1124 prose-only facts are the target of the AI docs-extraction follow-up,
1125 which will attach the backing quote to each value. Gemini `capabilities` no longer holds `supportedGenerationMethods`; the
1126 `:predict` vs `:generateContent` decision those methods drive is now
1127 made at list time and stored as `models.schema_endpoint_id`
1128 (migration 0005), which the read path prefers over the config
1129 binding. The config fallback still reads leftover
1130 `supportedGenerationMethods` from `capabilities` so un-repolled
1131 Imagen rows keep `:predict` — first-party data kept, no id-prefix
1132 guessing. Deploy needs
1133 `db:migrate:remote` first (deploys do not run migrations). Docs parses are memoised
1134 in-isolate for 6h and fail closed: zero parsed rows throws and fails
1135 that provider's poll for the tick rather than nulling populated rows
1136 (which would fan out a bogus `model.updated` per model and again on
1137 recovery). Gotcha: the first poll after deploy legitimately emits one
1138 `model.updated` per newly filled row.
1139- [x] **18.4 Bound-schema catalog facts + per-field provenance (issue #53).**
1140 After listing/docs fill, the poller walks the bound generation
1141 _request_ schema (`schemaEndpointId` → current input
1142 `schema_versions`) for OpenRouter `supported_parameters` names and
1143 input modalities. Listing/docs win on a field they stated; the schema
1144 fills remaining flags. `generated` specs are skipped (OpenAI-borrowed
1145 documents must not stamp `tools` onto DeepSeek/DashScope). Host-native
1146 capability objects (FAL/Reactor/…) are left alone. Each stored value
1147 carries `models.fact_sources` (migration 0006): per-field and
1148 per-flag `{ derivation, sourceUrl, endpointId, path }`.
1149 `GET /v1/models/{p}/{id}` always returns `factSources` plus
1150 `discrepancies` against the already-polled OpenRouter catalog (join
1151 `author/rawId`; no extra fetch, no unlabeled OpenRouter copy).
1152 `GET /v1/models?provenance=1` includes `factSources` on list rows.
1153 OpenRouter fill-nulls, pricing, and `docs-extracted` remain later
1154 slices.