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