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, and Lovable AI Gateway catalogs.
572. Regenerates `packages/ai-openrouter/src/model-meta.ts` and the Vercel Gateway model list.
583. Inserts **new** native-provider models into `packages/ai-openai`, `ai-anthropic`, `ai-gemini`, and `ai-grok`.
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`. Transcription ids stay hand-maintained.
605. Writes a patch changeset for the packages that changed.
61
62Rules the generator follows:
63
64- 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 `_`.
65- Do **not** copy those aliases into native provider files (`ai-openai`, `ai-anthropic`, `ai-gemini`, `ai-grok`). Those adapters only accept the provider's own ids.
66- For a new native-provider model, write id, modalities, and pricing. Infer features from OpenRouter `supported_parameters` when that field exists. Do **not** copy another model's tool list (`computer_use`, `google_search`, `x_search`, and similar).
67- Anthropic first-party ids use dashes (`claude-fable-5-1`). OpenRouter uses dots (`claude-fable-5.1`). The generator hyphenates Anthropic ids on insert. Do not copy the dotted OpenRouter slug into `ai-anthropic`.
68- 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 []`.
69- For new Anthropic models, infer the provider-options mix from the catalog: no sampling parameters → `AnthropicMaxTokensOptions`; `reasoning.mandatory` → `AnthropicAdaptiveOnlyThinkingOptions` plus `AnthropicOutputConfigOptions`.
70- Leave curated tools and flags on existing models alone. Edit those by hand after the sync PR opens.
71
72Do 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.
73
74The 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`.
75
76## Day-to-day commands
77
78All commands are run from the repo root. Nx handles affected detection and caching.
79
80| Goal | Command |
81| ----------------------------- | ------------------- |
82| Run unit tests (affected) | `pnpm test:lib` |
83| Watch unit tests | `pnpm test:lib:dev` |
84| Type-check (affected) | `pnpm test:types` |
85| Lint (affected) | `pnpm test:oxlint` |
86| Verify build artifacts | `pnpm test:build` |
87| Format the repo | `pnpm format` |
88| Build (affected) | `pnpm build` |
89| Build everything | `pnpm build:all` |
90| Run the full CI suite locally | `pnpm test` |
91| Run the affected-PR check | `pnpm test:pr` |
92| E2E suite | `pnpm test:e2e` |
93| E2E with Playwright UI | `pnpm test:e2e:ui` |
94
95Working on a single package? `cd packages/<pkg>` and use its scripts directly (`pnpm test:lib`, `pnpm test:types`, etc.).
96
97### Faster local runs
98
99Root `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.
100
101A single package still uses all cores:
102
103```bash
104cd packages/ai
105pnpm test:lib
106```
107
108Local `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.
109
110```bash
111E2E_PROVIDERS=* pnpm test:e2e # full matrix locally
112E2E_PROVIDERS=grok pnpm test:e2e # one provider
113```
114
115Playwright does not retry or record video locally. CI retries twice and keeps the video of a failed test.
116
117## Coverage
118
119**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.**
120
121The `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.
122
123There 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.
124
125Read 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.
126
127Re-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.
128
129### If the job says coverage fell under 60%
130
131Add 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.
132
133Two known limitations:
134
135- 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.
136- `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.
137
138A **new package that defines `test:coverage`** shows as `new` and cannot fail the comparison. Packages without that script are not measured.
139
140If 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`.
141
142## Generate a React playground
143
144You need a TanStack Start chat app to try a feature. Do not copy `examples/ts-react-chat`. Run the generator.
145
1461. From the repo root, run `pnpm nx g @tanstack/workspace-plugin:react-app <name>`.
1472. Run `pnpm install`.
1483. Copy `examples/<name>/.env.example` to `examples/<name>/.env.local` and add a key.
1494. Run `pnpm --filter <name> dev` (port 3100).
1505. Change the index route for the feature. If the server must change, change `/api/chat`.
151
152Do not commit the new example unless you mean to keep it as a lasting example.
153
154## TypeScript configuration
155
156There 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).
157
158The standardised per-package shape is:
159
160```jsonc
161{
162 "extends": "../../../tsconfig.base.json",
163 "compilerOptions": {
164 "outDir": "dist",
165 // + package-specific overrides only
166 },
167 "include": ["src", "tests"],
168 "exclude": ["node_modules", "dist"],
169}
170```
171
172Tests are included in typecheck. `vite.config.ts` / `vitest.config.ts` are not — they're tooling configs typechecked by the build tools themselves.
173
174## Adding a unit test
175
176- Place tests under `packages/<pkg>/tests/` with the suffix `.test.ts` (or `.test.tsx` for JSX).
177- Vitest's defaults discover anything matching `**/*.{test,spec}.?(c|m)[jt]s?(x)` — no per-package config is needed.
178- Tests are typechecked by `tsc` and linted by oxlint.
179
180## Adding E2E test coverage (required)
181
182**Every feature, bug fix, or behaviour change MUST have E2E coverage.** See `testing/e2e/README.md` for the full guide. Quick reference:
183
184| Change type | What to add |
185| -------------------------------------- | ------------------------------------------------------------------------ |
186| New provider adapter | Add provider to `feature-support.ts` + `test-matrix.ts`. Tests auto-run. |
187| New feature (e.g. new generation type) | Add to types, feature config, support matrix, fixture, spec file. |
188| Chat / streaming bug fix | Test case in `chat.spec.ts` or `tools-test/`. |
189| Tool system change | Scenario in `tools-test-scenarios.ts` + spec. |
190| Middleware change | Test in `middleware.spec.ts`. |
191| Client-side change (useChat etc.) | Test covering the observable behavior change. |
192
193Run the suite locally with `pnpm test:e2e`. Record real LLM fixtures with `OPENAI_API_KEY=sk-... pnpm --filter @tanstack/ai-e2e record`.
194
195## Documentation (required when relevant)
196
197If the change is user-facing, update `docs/` in the same PR. Do not ship the code now and the docs later.
198
199User-facing means a caller can see or do something new or different:
200
201- New or changed public API (exports, types, flags, env vars)
202- New or changed behaviour
203- New adapter capability
204- Changed defaults, errors, or documented contracts
205
206Skip docs only when nothing user-facing changed (CI, internal tests, same-behaviour refactors, agent files). Write that reason in the PR body.
207
208## Changesets (required on the PR)
209
210Any PR that changes a published package MUST include a changeset file on that PR. Run this before you open the PR:
211
212```bash
213pnpm changeset
214```
215
216Pick the affected packages and the bump type:
217
218- **patch**: bug fix, internal refactor, perf, docs in package, no API change.
219- **minor**: new public API, new opt-in behaviour, backwards-compatible enhancement.
220- **major**: breaking change to a published API surface. Coordinate with maintainers first.
221
222Do not add the changeset after review as a follow-up. It belongs in the first push of the PR.
223
224Skip 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.
225
226The defensive `ignore` list in `.changeset/config.json` blocks accidental publication from examples/testing/codemods even if `"private": true` is ever dropped.
227
228## Branches and commits
229
230- Branch off `main`. Name the branch after the change (`fix/openai-streaming-eof`, `feat/anthropic-cache-control`).
231- Conventional Commits aren't strictly enforced, but follow the prefixes you see in `git log`: `feat:`, `fix:`, `docs:`, `refactor:`, `chore:`, `ci:`.
232- Keep commits logical. The repo prefers a few coherent commits over one giant squash.
233
234## Pull request flow
235
2361. Push your branch and open a PR against `main`.
2372. Fill the PR template. Tick **docs** and **changeset** honestly, or say why you skipped them.
2383. 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.
2394. Address review comments.
2405. A maintainer merges. Releases are cut via Changesets. Your changeset entry lands in the next release.
241
242The PR template lists the steps. The `Test plan` section is required — describe how a reviewer can verify your change.
243
244### Automated Grok review
245
246A 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.
247
248The bot sets exactly one of these labels:
249
250- `ai-rejected` — the change is not useful, or it does not fix the claimed bug.
251- `ai-needs-work` — the review listed fixes, but they are not on the branch yet (often a fork with maintainer edits off).
252- `ai-ready` — the bot thinks a maintainer can merge after they Approve.
253
254The bot never GitHub-approves and never merges. The `ready-to-merge` label still means a human approval plus green CI.
255
256If 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.
257
258The 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.
259
260## Adding a new provider adapter
261
262The pattern lives in `packages/ai-openai/`, `packages/ai-anthropic/`, `packages/ai-gemini/`, etc. New core adapters typically:
263
2641. 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`.
2652. Implement tree-shakeable adapter exports under `src/adapters/` (`text.ts`, `embed.ts`, `summarize.ts`, etc.).
2663. Add `model-meta.ts` so per-model type safety works.
2674. Wire the provider into `testing/e2e/feature-support.ts` and `testing/e2e/test-matrix.ts`. Existing provider-coverage tests pick it up automatically.
2685. Record fixtures (`OPENAI_API_KEY=... pnpm --filter @tanstack/ai-e2e record`) — or write deterministic ones by hand. **No real API keys at test time.**
2696. Update `docs/` for the adapter, and add a `pnpm changeset` entry on the same PR.
270
271If you're building a community/third-party adapter that lives outside this repo, follow `docs/community-adapters/guide.md` instead.
272
273## Known gaps
274
275- **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.
276- **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.
277
278## Reporting issues / getting help
279
280- 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.
281- Questions / discussions: [TanStack Discord](https://tlinz.com/discord).
282- Security: follow the disclosure process in `SECURITY.md` (if applicable) or email the maintainers directly.
283
284## Code of Conduct
285
286By participating you agree to abide by our [Code of Conduct](./CODE_OF_CONDUCT.md).