Open History to see the last commit
1# Contributing to TanStack AI
2
3Thanks for contributing! This guide covers everything you need to get from a fresh clone to a merged PR.
4
5## Before you start
6
7- Search the [open and closed issues](https://github.com/TanStack/ai/issues?q=is%3Aissue) and [open and closed pull requests](https://github.com/TanStack/ai/pulls?q=is%3Apr) before starting work to avoid duplicating an existing report or contribution.
8- Keep each pull request focused on one change or topic. Pull requests that combine unrelated changes will be closed with a request to split them into separately reviewable contributions.
9- Every pull request must follow the [TanStack AI pull request template](.github/pull_request_template.md). Write a concise description that clearly explains what changed and why, and complete the template without removing or bypassing its required sections.
10- You may use AI tools to help generate code, but you remain responsible for understanding, testing, and verifying every submitted change. Do not submit unreviewed, low-quality, or irrelevant generated code.
11- Do not mass-submit unrelated or low-quality AI-generated pull requests. We treat that behavior as spam and may close the pull requests, block the contributor, and report the GitHub account.
12
13## Prerequisites
14
15- **pnpm**: 11.9.0 or newer. Use the version pinned in `packageManager` (`pnpm@11.9.0`).
16 - Recommended: install via [Corepack](https://nodejs.org/api/corepack.html). Run `corepack enable` once and pnpm is managed automatically.
17- **Node**: 24.8.0, the version in `.nvmrc`. On Node 22, Nx fails to load the workspace plugin.
18- **Git**.
19
20## Initial setup
21
22```bash
23git clone https://github.com/TanStack/ai.git
24cd ai
25pnpm install
26pnpm run build:all # build all public packages once so workspace deps resolve
27```
28
29`pnpm install` runs Playwright's chromium download (used by the E2E suite). If you don't need E2E, you can skip it via `PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1 pnpm install`.
30
31## Repository layout
32
33```
34packages/ # Public, published packages (@tanstack/ai, @tanstack/ai-openai, etc.)
35testing/ # Internal test harnesses — NOT published
36 e2e/ # Playwright + aimock E2E suite (mandatory coverage for all changes)
37 panel/ # Stream processor visualisation panel
38examples/ # Example apps (React, Solid, Vue, Svelte, vanilla)
39codemods/ # Internal codemods (not published)
40docs/ # Documentation source
41scripts/ # Repo-level scripts (doc generation, model sync, link verification, maintainer sweep)
42agent-scripts/ # Repo GitHub agents (PR review bot)
43```
44
45- Direct children of `packages/` are public packages (published to npm).
46- Everything under `examples/`, `testing/`, and `codemods/` is `"private": true` and excluded from build/publish.
47- The build system is **Nx** with affected-target detection.
48- The package manager is **pnpm** with workspace + catalog protocols.
49
50For deeper architecture details (adapter system, isomorphic tools, framework integrations), see `CLAUDE.md` at the repo root.
51
52## Syncing model metadata
53
54`pnpm generate:models` is the maintainer command behind the daily **Sync Model Metadata** workflow (branch `automated/sync-models`). It:
55
561. Fetches OpenRouter, Vercel AI Gateway, Lovable AI Gateway, and Neon AI Gateway catalogs.
572. Regenerates `packages/ai-openrouter/src/model-meta.ts` and the Vercel Gateway and Neon model lists.
583. Inserts **new** native-provider models from [modelschemas](https://modelschemas.com) (`@modelschemas/client`) into `ai-openai`, `ai-anthropic`, `ai-gemini`, `ai-grok`, `ai-groq`, `ai-mistral`, and `ai-byteplus`. Native ids, activity, limits, modalities, pricing, and capabilities come from each provider catalog. OpenRouter fills a field only when the native row left it empty. OpenAI, Anthropic, Gemini, and Grok hold an id back until the OpenRouter catalog has a matching row and both prices are known. The log names each held-back id. Groq and Mistral insert even when a price is unknown: the generator leaves that price out (`pricing: {}` when both are unknown) and never writes `0`. BytePlus does not write pricing.
594. Inserts **new** ElevenLabs text-to-speech, music, sound-effect, and voice-design ids from [modelschemas](https://modelschemas.com/v1/schemas/elevenlabs) into `packages/ai-elevenlabs/src/model-meta.ts` (`scripts/sync-elevenlabs-models.ts`, also through `@modelschemas/client`). Text-to-speech ids are catalog rows with `providerMetadata.canDoTextToSpeech`. Music, sound-effect, and voice-design ids are the `model_id` enums of their request schemas. Transcription ids stay hand-maintained.
605. Rewrites each provider package's `./models` catalog (`src/models.ts`) from modelschemas, with `pnpm generate:models:catalogs`. The provider list is `CATALOGS` in `scripts/model-sync/model-catalog.ts`. A value modelschemas does not list stays `undefined`, and a value the script does not know stops the sync. Fix a wrong value upstream in modelschemas, not in the generated file.
616. Writes a patch changeset for the packages that changed.
62
63The sync stops with an error when modelschemas is down, when a catalog is empty, when no row has a `rawId`, `firstSeenAt`, or `deprecatedAt` key, or when an array or type map it must update is missing from a `model-meta.ts`.
64
65Reads against modelschemas work without a key (60 req/h per IP). Set `MODELSCHEMAS_API_KEY` on the workflow when you want the higher limit.
66
67Rules the generator follows:
68
69- Keep OpenRouter routing aliases (ids that start with `~`) in the OpenRouter catalog. Users can pass `chat({ model: '~anthropic/claude-haiku-latest' })`. The generated constant name maps `~` to `_`.
70- Do **not** copy those aliases into native provider files (any of the eight packages above). Those adapters only accept the provider's own ids.
71- For a new native-provider model, write id, modalities, and (where the provider has a `pricing` field) pricing. Infer features from native catalog capabilities (a list of parameter names, or a feature object, as BytePlus sends). Do **not** copy another model's tool list (`computer_use`, `google_search`, `x_search`, and similar). Do **not** copy OpenRouter flags onto a native row that already listed capabilities. BytePlus, Groq, and Mistral insert from the native catalog even when OpenRouter has no row. BytePlus inserts never claim `structured_outputs`: that gate is a live-probed list.
72- ElevenLabs music and voice-design ids are pinned to SDK unions. An id the ElevenLabs SDK does not know yet fails the type-check, so wait for the SDK. BytePlus video and image duration/size tables stay hand-curated.
73- Anthropic first-party ids use dashes (`claude-fable-5-1`). OpenRouter uses dots (`claude-fable-5.1`). The generator takes the modelschemas native id (already hyphenated) and does not copy the dotted OpenRouter slug into `ai-anthropic`. Dated Anthropic snapshots (`claude-haiku-4-5-20251001`) are skipped; the undated alias is the public id.
74- Write a row in the provider's `*ChatModelToolCapabilitiesByName` map for every new chat model, even when `supports.tools` is still `[]`. Missing that row makes `ResolveToolCapabilities` fall back to `readonly []`.
75- For new Anthropic models, infer the provider-options mix from the catalog: no sampling parameters → `AnthropicMaxTokensOptions`; `reasoning.mandatory` → `AnthropicAdaptiveOnlyThinkingOptions` plus `AnthropicOutputConfigOptions`; reasoning params without sampling → adaptive-or-disabled thinking. Every new Claude model gets `AnthropicCacheControlOptions`.
76- `firstSeenAt` is when modelschemas first crawled an id, not its release date. The first sync of a new provider can need a one-off older cutoff in `scripts/.sync-models-last-run`.
77- Leave curated tools and flags on existing models alone. Edit those by hand after the sync PR opens.
78
79Do not rebase or hand-edit `automated/sync-models`. The next scheduled run force-pushes that branch from `main`. Merge generator fixes to `main` first, then let the workflow rebuild the sync PR.
80
81The workflow pushes with `GITHUB_TOKEN`, so GitHub does not start Test / E2E on that push. After a sync, a maintainer with write access can run the PR checks from the Actions tab, or push an empty commit to `automated/sync-models`.
82
83## Day-to-day commands
84
85All commands are run from the repo root. Nx handles affected detection and caching.
86
87| Goal | Command |
88| ----------------------------- | ------------------- |
89| Run unit tests (affected) | `pnpm test:lib` |
90| Watch unit tests | `pnpm test:lib:dev` |
91| Type-check (affected) | `pnpm test:types` |
92| Lint (affected) | `pnpm test:oxlint` |
93| Verify build artifacts | `pnpm test:build` |
94| Format the repo | `pnpm format` |
95| Build (affected) | `pnpm build` |
96| Build everything | `pnpm build:all` |
97| Run the full CI suite locally | `pnpm test` |
98| Run the affected-PR check | `pnpm test:pr` |
99| E2E suite | `pnpm test:e2e` |
100| E2E with Playwright UI | `pnpm test:e2e:ui` |
101
102Working on a single package? `cd packages/<pkg>` and use its scripts directly (`pnpm test:lib`, `pnpm test:types`, etc.).
103
104### Faster local runs
105
106Root `pnpm test`, `pnpm test:pr`, and `pnpm test:lib` set `VITEST_MAX_WORKERS=1`. Nx runs 4 tasks at a time (`nx.json` `parallel`). Together that stops each package from spawning one Vitest worker per CPU core while 15 packages already run in parallel.
107
108A single package still uses all cores:
109
110```bash
111cd packages/ai
112pnpm test:lib
113```
114
115Local `pnpm test:e2e` runs openai, anthropic, and gemini. If none of those providers support a feature, the feature still runs on the providers that do. An explicit `E2E_PROVIDERS` list runs only those providers. CI always runs the full matrix.
116
117```bash
118E2E_PROVIDERS=* pnpm test:e2e # full matrix locally
119E2E_PROVIDERS=grok pnpm test:e2e # one provider
120```
121
122Playwright does not retry or record video locally. CI retries twice and keeps the video of a failed test.
123
124## Coverage
125
126**Coverage runs in CI only. It is not part of `pnpm test`, `pnpm test:pr`, or any git hook, and you are not expected to run it locally.**
127
128The `Coverage` job on every PR measures each affected package that has a `test:coverage` target twice: once on your branch and once on its merge-base with `main`. The job fails only when a metric (statements, branches, functions, lines) is at or above 60% on the merge-base and under 60% on your branch. Other drops are listed, but they do not fail the job. A package that is already under 60% on `main` cannot fail it. Packages your PR didn't affect, and packages without that target, are never measured.
129
130There is no baseline file to keep in sync, and nothing to update when a package is added or removed: both numbers come from the same job on the same runner.
131
132Read the numbers in the PR comment that the `Coverage` job posts. It shows a per-package table with deltas, and the job updates the same comment on each push. A PR from a fork gets no comment, because its token cannot write one. The same table is in the job summary: open the `Coverage` job from the PR's Checks tab.
133
134Re-measuring the merge-base is usually close to free. On every push to `main`, a separate `Coverage` workflow runs `test:coverage` for every package with the same forwarded args as the PR job, and fills the Nx Cloud cache. `test:coverage` declares its `coverage/` directory as a task output, so the base-side run restores the cached summaries and does not run the tests again. If that workflow did not finish for the merge-base commit (for example, a newer push to `main` cancelled it), the base-side tests run again. Keep the `--` args in `coverage.yml` and `pr.yml` identical: Nx hashes them, so any difference causes a cache miss.
135
136### If the job says coverage fell under 60%
137
138Add tests covering the code you changed, so each metric is back at 60% or more. That's the whole remedy — there is no number to override. If you genuinely deleted well-tested code and the drop is expected, say so in the PR and a maintainer can merge past the failing check.
139
140Two known limitations:
141
142- Uncovered `.tsx` files can't be remapped by the coverage provider and are dropped from the report with a `Failed to parse ... Excluding it from coverage` warning. `.tsx` files that tests _do_ load are measured normally, so the UI packages read higher than their real coverage.
143- `preact-ai-devtools`, `react-ai-devtools`, `solid-ai-devtools`, and `svelte-ai-devtools` have no tests, so they have no `test:coverage` script. The collect step fails when a measured package reports 0 statements. Add the script back when the package gets tests.
144
145A **new package that defines `test:coverage`** shows as `new` and cannot fail the comparison. Packages without that script are not measured.
146
147If a package was measured on the base commit and has no summary on this PR, the job fails. A crashing `test:coverage` suite on either side also fails the job. It is not treated as `new`.
148
149## Generate a React playground
150
151You need a TanStack Start chat app to try a feature. Do not copy `examples/ts-react-chat`. Run the generator.
152
1531. From the repo root, run `pnpm nx g @tanstack/workspace-plugin:react-app <name>`.
1542. Run `pnpm install`.
1553. Copy `examples/<name>/.env.example` to `examples/<name>/.env.local` and add a key.
1564. Run `pnpm --filter <name> dev` (port 3100).
1575. Change the index route for the feature. If the server must change, change `/api/chat`.
158
159Do not commit the new example unless you mean to keep it as a lasting example.
160
161## TypeScript configuration
162
163There is a single `tsconfig.base.json` at the repo root with the shared `compilerOptions`. Every package extends it and overrides only what's unique to that package (e.g. `outDir`, JSX runtime, framework lib).
164
165The standardised per-package shape is:
166
167```jsonc
168{
169 "extends": "../../../tsconfig.base.json",
170 "compilerOptions": {
171 "outDir": "dist",
172 // + package-specific overrides only
173 },
174 "include": ["src", "tests"],
175 "exclude": ["node_modules", "dist"],
176}
177```
178
179Tests are included in typecheck. `vite.config.ts` / `vitest.config.ts` are not — they're tooling configs typechecked by the build tools themselves.
180
181## Adding a unit test
182
183- Place tests under `packages/<pkg>/tests/` with the suffix `.test.ts` (or `.test.tsx` for JSX).
184- Vitest's defaults discover anything matching `**/*.{test,spec}.?(c|m)[jt]s?(x)` — no per-package config is needed.
185- Tests are typechecked by `tsc` and linted by oxlint.
186
187## Adding E2E test coverage (required)
188
189**Every feature, bug fix, or behaviour change MUST have E2E coverage.** See `testing/e2e/README.md` for the full guide. Quick reference:
190
191| Change type | What to add |
192| -------------------------------------- | ------------------------------------------------------------------------ |
193| New provider adapter | Add provider to `feature-support.ts` + `test-matrix.ts`. Tests auto-run. |
194| New feature (e.g. new generation type) | Add to types, feature config, support matrix, fixture, spec file. |
195| Chat / streaming bug fix | Test case in `chat.spec.ts` or `tools-test/`. |
196| Tool system change | Scenario in `tools-test-scenarios.ts` + spec. |
197| Middleware change | Test in `middleware.spec.ts`. |
198| Client-side change (useChat etc.) | Test covering the observable behavior change. |
199
200Run the suite locally with `pnpm test:e2e`. Record real LLM fixtures with `OPENAI_API_KEY=sk-... pnpm --filter @tanstack/ai-e2e record`.
201
202## Documentation (required when relevant)
203
204If the change is user-facing, update `docs/` in the same PR. Do not ship the code now and the docs later.
205
206User-facing means a caller can see or do something new or different:
207
208- New or changed public API (exports, types, flags, env vars)
209- New or changed behaviour
210- New adapter capability
211- Changed defaults, errors, or documented contracts
212
213Skip docs only when nothing user-facing changed (CI, internal tests, same-behaviour refactors, agent files). Write that reason in the PR body.
214
215## Changesets (required on the PR)
216
217Any PR that changes a published package MUST include a changeset file on that PR. Run this before you open the PR:
218
219```bash
220pnpm changeset
221```
222
223Pick the affected packages and the bump type:
224
225- **patch**: bug fix, internal refactor, perf, docs in package, no API change.
226- **minor**: new public API, new opt-in behaviour, backwards-compatible enhancement.
227- **major**: breaking change to a published API surface. Coordinate with maintainers first.
228
229Do not add the changeset after review as a follow-up. It belongs in the first push of the PR.
230
231Skip a changeset only when the PR does not change published packages (docs, CI, examples, testing, contributing). Tick the docs/CI/dev-only box on the PR template.
232
233The defensive `ignore` list in `.changeset/config.json` blocks accidental publication from examples/testing/codemods even if `"private": true` is ever dropped.
234
235## Branches and commits
236
237- Branch off `main`. Name the branch after the change (`fix/openai-streaming-eof`, `feat/anthropic-cache-control`).
238- Conventional Commits aren't strictly enforced, but follow the prefixes you see in `git log`: `feat:`, `fix:`, `docs:`, `refactor:`, `chore:`, `ci:`.
239- Keep commits logical. The repo prefers a few coherent commits over one giant squash.
240
241## Pull request flow
242
2431. Push your branch and open a PR against `main`.
2442. Fill the PR template. Tick **docs** and **changeset** honestly, or say why you skipped them.
2453. CI runs: `pnpm test:pr` (sherif workspace check, knip dead-code, docs link verification, oxlint, unit tests, typecheck, build artifacts, build), the `Coverage` regression gate, and the full E2E suite.
2464. Address review comments.
2475. A maintainer merges. Releases are cut via Changesets. Your changeset entry lands in the next release.
248
249The PR template lists the steps. The `Test plan` section is required — describe how a reviewer can verify your change.
250
251### Automated Grok review
252
253A Grok agent reviews non-draft PRs into `main` automatically when they open or sync. The first lines of the bot's comment say it is automated. It is not a maintainer review.
254
255The bot sets exactly one of these labels:
256
257- `ai-rejected` — the change is not useful, or it does not fix the claimed bug.
258- `ai-needs-work` — the review listed fixes, but they are not on the branch yet (often a fork with maintainer edits off).
259- `ai-ready` — the bot thinks a maintainer can merge after they Approve.
260
261The bot never GitHub-approves and never merges. The `ready-to-merge` label still means a human approval plus green CI.
262
263If the bot pushes, it only commits bugs and suggestions the review listed. Roster maintainers can request one run by writing `/ai-review`. Anyone with write access can use Actions (`workflow_dispatch`) on `main`. For a first-time fork contributor, GitHub holds the automatic run. A maintainer writes `/ai-review`, and the bot approves the waiting checks after a clean scan.
264
265The bot checks the PR before Grok starts. It blocks sensitive automation, agent instructions, symlinks, binary files, new executable files, new dependencies, lockfile changes, and incomplete patches. A blocked PR gets a bot comment with the reasons and no verdict label. Grok runs in a disposable Docker container without the bot's GitHub token. The host validates Grok's patch before it applies or pushes any edit.
266
267## Adding a new provider adapter
268
269The pattern lives in `packages/ai-openai/`, `packages/ai-anthropic/`, `packages/ai-gemini/`, etc. New core adapters typically:
270
2711. Create `packages/ai-<provider>/` with `package.json`, `tsconfig.json`, `src/`, `tests/`, `README.md`. Copy structure from an existing adapter. The README must start with the TanStack AI `<picture>` banner from `packages/ai/README.md` (`https://tanstack.com/api/readme/ai.png`). Do not use `media/header_ai.png`.
2722. Implement tree-shakeable adapter exports under `src/adapters/` (`text.ts`, `embed.ts`, `summarize.ts`, etc.).
2733. Add `model-meta.ts` so per-model type safety works.
2744. Wire the provider into `testing/e2e/feature-support.ts` and `testing/e2e/test-matrix.ts`. Existing provider-coverage tests pick it up automatically.
2755. Record fixtures (`OPENAI_API_KEY=... pnpm --filter @tanstack/ai-e2e record`) — or write deterministic ones by hand. **No real API keys at test time.**
2766. Update `docs/` for the adapter, and add a `pnpm changeset` entry on the same PR.
277
278If you're building a community/third-party adapter that lives outside this repo, follow `docs/community-adapters/guide.md` instead.
279
280## Known gaps
281
282- **Vue/Svelte SFCs are not currently linted.** Our linter doesn't yet support `.vue`/`.svelte` parsers in the toolchain we use; the script blocks inside those files rely on TypeScript and tests for safety. If you're touching a `.svelte` or `.vue` file, lean on `tsc` / `svelte-check` / `vue-tsc` and explicit tests.
283- **Build configs (`vite.config.ts`, `vitest.config.ts`) are not in the `tsc` typecheck pass.** They're typechecked at build time by vite/vitest themselves. If you make changes there, run `pnpm build` or `pnpm test:lib` to surface issues.
284
285## Reporting issues / getting help
286
287- Bugs: first search the [open and closed issues](https://github.com/TanStack/ai/issues?q=is%3Aissue), then use the [bug report template](https://github.com/TanStack/ai/issues/new?template=bug_report.yml) with a minimal reproduction if the bug has not already been reported.
288- Questions / discussions: [TanStack Discord](https://tlinz.com/discord).
289- Security: follow the disclosure process in `SECURITY.md` (if applicable) or email the maintainers directly.
290
291## Code of Conduct
292
293By participating you agree to abide by our [Code of Conduct](./CODE_OF_CONDUCT.md).