feat: Introduce OpenRouter adapter #123
main fromrefs/pull/123/head·merged by AlemTuzlak View on GitHub🎯 Changes#
This PR adds an OpenRouter adapter.
Since OpenRouter frequently adds new models, there is no typed list of models. If anyone has suggestions for a better approach, I’d be happy to implement it.
I’m happy to make any changes if needed.
✅ Checklist#
- I have followed the steps in the Contributing guide.
- I have tested this code locally with
pnpm run test:pr.
🚀 Release Impact#
- This change affects published code, and I have generated a changeset.
- This change is docs/CI/dev-only (no release).
Summary by CodeRabbit#
New Features
- OpenRouter integration: text, image, and summarization adapters, plus function and web-search tools with multimodal and streaming support.
Documentation
- Comprehensive OpenRouter docs added covering installation, configuration, models, examples, and usage.
Examples
- Demo apps updated to expose OpenRouter as a provider and new model choices.
Tests
- New tests for text and image adapters covering streaming, multimodal inputs, tool calls, and error handling.
Chores
- New package, build/test config, model-generation script, workspace/dependency and script updates.
- 1
@tanstack/ai
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai@123@tanstack/ai-anthropic
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-anthropic@123@tanstack/ai-client
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-client@123@tanstack/ai-devtools-core
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-devtools-core@123@tanstack/ai-gemini
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-gemini@123@tanstack/ai-grok
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-grok@123@tanstack/ai-ollama
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-ollama@123@tanstack/ai-openai
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-openai@123@tanstack/ai-openrouter
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-openrouter@123@tanstack/ai-preact
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-preact@123@tanstack/ai-react
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-react@123@tanstack/ai-react-ui
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-react-ui@123@tanstack/ai-solid
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-solid@123@tanstack/ai-solid-ui
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-solid-ui@123@tanstack/ai-svelte
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-svelte@123@tanstack/ai-vue
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-vue@123@tanstack/ai-vue-ui
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-vue-ui@123@tanstack/preact-ai-devtools
npm i https://pkg.pr.new/TanStack/ai/@tanstack/preact-ai-devtools@123@tanstack/react-ai-devtools
npm i https://pkg.pr.new/TanStack/ai/@tanstack/react-ai-devtools@123@tanstack/solid-ai-devtools
npm i https://pkg.pr.new/TanStack/ai/@tanstack/solid-ai-devtools@123commit:
422d9fdwould like to see this adapter for python 😄
would like to see this adapter for python 😄
Once the Typescript adapter is finalized and reviewed, I’ll definitely work on adding a Python version as well
Warning
Rate limit exceeded#
@AlemTuzlakhas exceeded the limit for the number of commits that can be reviewed per hour. Please wait 7 minutes and 4 seconds before requesting another review.⌛ How to resolve this issue?
After the wait time has elapsed, a review can be triggered using the
@coderabbitai reviewcommand as a PR comment. Alternatively, push new commits to this PR.We recommend that you space out your commits to avoid hitting the rate limit.
🚦 How do rate limits work?
CodeRabbit enforces hourly rate limits for each developer per organization.
Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.
Please see our FAQ for further information.
📥 Commits
Reviewing files that changed from the base of the PR and between f63453fe0804bf642102908b903c762e983bdc5e and 422d9fd936ecbb71d27bd7a1b61fcddf8aceeaca.
📒 Files selected for processing (2)
packages/typescript/ai-openrouter/src/adapters/text.tspackages/typescript/ai-openrouter/tsconfig.json
📝 Walkthrough
Walkthrough#
Adds a new
@tanstack/ai-openrouterpackage with OpenRouter text (streaming/structured), image, and summarize adapters, model metadata/types, tools converters, client utils, tests, docs, examples, model-generation tooling, and workspace integration. No existing public APIs removed.Changes#
Cohort / File(s) Summary Package & build
packages/typescript/ai-openrouter/package.json,packages/typescript/ai-openrouter/tsconfig.json,packages/typescript/ai-openrouter/vite.config.ts,packages/typescript/ai-openrouter/src/index.tsNew package manifest, tsconfig, vite/test config, and top-level exports exposing adapters, types, utils, and tools. Text adapter (core)
packages/typescript/ai-openrouter/src/adapters/text.tsNew OpenRouterTextAdapter: chatStream, structuredOutput, SSE parsing, tool-call buffering, multimodal message conversion, request mapping, ID generation, env/api-key wiring (large, high-density logic). Image adapter & provider options
packages/typescript/ai-openrouter/src/adapters/image.ts,packages/typescript/ai-openrouter/src/image/image-provider-options.tsImage generation adapter, size↔aspect-ratio mapping, base64 handling, per-model image option typings, and factory helpers. Summarize adapter
packages/typescript/ai-openrouter/src/adapters/summarize.tsSummarization adapter that builds prompts and leverages the text adapter for streaming/non-streaming summarization. Provider options & model meta
packages/typescript/ai-openrouter/src/text/text-provider-options.ts,packages/typescript/ai-openrouter/src/model-meta.ts,packages/typescript/ai-openrouter/src/message-types.tsNew comprehensive provider option types (streaming, reasoning, images, plugins), model metadata types, and per-modality message metadata. Tools / converters
packages/typescript/ai-openrouter/src/tools/function-tool.ts,.../tool-converter.ts,.../web-search-tool.ts,.../index.tsFunctionTool and WebSearchTool types, converters to adapter format, convertToolsToProviderFormat helper, and related exports. Client utils
packages/typescript/ai-openrouter/src/utils/client.ts,packages/typescript/ai-openrouter/src/utils/index.tsOpenRouterClientConfig, env API-key retrieval, generateId, buildHeaders, and re-exports. Model metadata generator
scripts/convert-openrouter-models.ts,packages/typescript/ai-openrouter/src/model-meta.tsNew script to convert OpenRouter model listings into generated TypeScript model-meta and constants; added generate:modelsscript.Tests
packages/typescript/ai-openrouter/tests/openrouter-adapter.test.ts,packages/typescript/ai-openrouter/tests/image-adapter.test.tsUnit tests for text streaming (deltas, tool calls, multimodal), image generation (requests, base64, aspect ratios), and error cases; SDK mocks included. Docs & config
docs/adapters/openrouter.md,docs/config.json,packages/typescript/ai-openrouter/README.mdNew adapter documentation, docs config entry, and README updates with usage/examples. Examples & smoke tests
examples/ts-react-chat/src/routes/api.tanchat.ts,examples/ts-react-chat/src/lib/model-selection.ts,examples/ts-react-chat/package.json,packages/typescript/smoke-tests/adapters/...Integrates openrouter into examples and smoke-tests, updates model options, adapter registry, and workspace deps. Monorepo & deps tweaks
package.json,examples/*/package.json,packages/*/package.json,.claude/settings.local.jsonAdded generate:modelsscript andtsxdevDependency, bumped@tanstack/devtools-utilsin several packages, Claude local settings, and minor typing standardizations in smoke-tests.Sequence Diagram(s)#
sequenceDiagram participant Client participant Adapter as OpenRouter Text Adapter participant SDK as OpenRouter SDK participant Stream as SSE Stream participant Buffer as ToolBuffer Client->>Adapter: chatStream(options: messages, tools, model) Adapter->>Adapter: mapTextOptionsToSDK() Adapter->>SDK: client.chat.completions.create(params) SDK-->>Stream: async iterable (SSE-like) loop per chunk Stream->>Adapter: delta (content / tool_call / error) alt tool_call delta Adapter->>Buffer: accumulate partial tool_call Buffer->>Adapter: complete tool_call Adapter-->>Client: yield tool_call chunk else content delta Adapter-->>Client: yield content chunk else error Adapter-->>Client: yield error chunk end end Adapter-->>Client: yield finish chunk (usage, id, model)Estimated code review effort#
🎯 4 (Complex) | ⏱️ ~60 minutes
Possibly related PRs#
- TanStack/ai#137: Related prior work that introduced the adapter-splitting/module-per-feature structure used here.
Suggested reviewers#
- AlemTuzlak
- jherr
Poem#
🐰 I hopped to OpenRouter's door,
Streams and images and tools galore. I stitched the prompts and models tight, Sent cheerful bytes into the night. 🥕✨
🚥 Pre-merge checks | ✅ 2 | ❌ 1
❌ Failed checks (1 warning)
Check name Status Explanation Resolution Docstring Coverage ⚠️ Warning Docstring coverage is 34.29% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold. ✏️ Tip: You can configure your own custom pre-merge checks in the settings.✅ Passed checks (2 passed)
Check name Status Explanation Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled. Title check ✅ Passed The PR title 'feat: Introduce OpenRouter adapter' clearly and concisely summarizes the primary change: introducing a new OpenRouter adapter to the codebase.
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.
Comment `@coderabbitai help` to get the list of available commands and usage tips.Hold off until adding changes, we have implemented huge breaking changes for adapters internally
Actionable comments posted: 7
🧹 Nitpick comments (9)
packages/typescript/ai-openrouter/live-tests/package.json (1)
1-20: Nice separation for “live” tests; consider making env requirements explicit.These scripts likely require
OPENROUTER_API_KEY(and possibly other vars). Consider adding a short README inlive-tests/(or apretestscript) to fail fast with a clear error if env vars are missing.packages/typescript/ai-openrouter/src/tools/function-tool.ts (1)
13-26: Consider removing the redundant fallback.The
|| {}on Line 23 is redundant sincejsonSchemaalready defaults to{}on Line 16.Apply this diff:
return { type: 'function', function: { name: tool.name, description: tool.description, - parameters: jsonSchema || {}, + parameters: jsonSchema, }, }packages/typescript/ai-openrouter/live-tests/tool-test.ts (1)
7-16: Consider logging environment file errors.The empty catch block silently ignores all errors when reading
.env.local. While this allows the file to be optional, it could hide permission errors or other unexpected issues.Consider logging a debug message:
const envContent = readFileSync(join(__dirname, '.env.local'), 'utf-8') envContent.split('\n').forEach((line) => { const match = line.match(/^([^=]+)=(.*)$/) if (match) { process.env[match[1].trim()] = match[2].trim() } }) -} catch (e) {} +} catch (e) { + // .env.local is optional +}packages/typescript/ai-openrouter/live-tests/web-search-test.ts (1)
6-15: Consider adding a comment for the empty catch block.Similar to tool-test.ts, the empty catch block silently ignores errors. Consider adding a comment to clarify this is intentional.
} }) -} catch {} +} catch { + // .env.local is optional +}packages/typescript/ai-openrouter/live-tests/image-test.ts (1)
6-15: Consider adding a comment for the empty catch block.Consistent with other live tests, consider clarifying the intentional empty catch block.
} }) -} catch {} +} catch { + // .env.local is optional +}packages/typescript/ai-openrouter/src/openrouter-adapter.ts (3)
162-167: Consider usingdeclarefor type-only properties instead of@ts-ignore.The
@ts-ignorecomments suppress TypeScript errors for unassigned properties used only for type inference. Usingdeclaremodifier would be more idiomatic:- // @ts-ignore - We never assign this at runtime and it's only used for types - _modelProviderOptionsByName: OpenRouterChatModelProviderOptionsByName - // @ts-ignore - We never assign this at runtime and it's only used for types - _modelInputModalitiesByName?: OpenRouterModelInputModalitiesByName - // @ts-ignore - We never assign this at runtime and it's only used for types - _messageMetadataByModality?: OpenRouterMessageMetadataByModality + declare _modelProviderOptionsByName: OpenRouterChatModelProviderOptionsByName + declare _modelInputModalitiesByName?: OpenRouterModelInputModalitiesByName + declare _messageMetadataByModality?: OpenRouterMessageMetadataByModality
256-287: Consider adding abort signal support for consistency withchatStream.The
chatStreammethod supportsoptions.request?.signalfor request cancellation, butsummarizedoes not accept any abort mechanism. For long-running summarization requests, users may want the ability to cancel.
376-380: Silent JSON parse failure could hide malformed SSE data.The
catchblock silently continues when JSON parsing fails. While this provides resilience against malformed data, consider logging a warning in debug mode to help diagnose issues.packages/typescript/ai-openrouter/src/text/text-provider-options.ts (1)
309-321: Duplicatetool_choicedefinition.The
tool_choiceproperty is defined identically in bothOpenRouterBaseOptions(lines 245-254) andInternalTextProviderOptions(lines 312-321). SinceInternalTextProviderOptionsextendsExternalTextProviderOptions(which aliasesOpenRouterBaseOptions), this redefinition is redundant.Remove the duplicate definition:
tools?: Array<{ type: 'function' function: { name: string description?: string parameters: Record<string, unknown> } }> - /** - * Controls which (if any) tool the model should use. - */ - tool_choice?: - | 'none' - | 'auto' - | 'required' - | { - type: 'function' - function: { - name: string - } - } }📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📥 Commits
Reviewing files that changed from the base of the PR and between 049eb8acd83e6d566c6040c0c4cb53dbe222d46a and 7616fb904258e072f74537fe108532906b2f3aee.
⛔ Files ignored due to path filters (1)
pnpm-lock.yamlis excluded by!**/pnpm-lock.yaml
📒 Files selected for processing (19)
docs/adapters/openrouter.md(1 hunks)docs/config.json(1 hunks)packages/typescript/ai-openrouter/README.md(2 hunks)packages/typescript/ai-openrouter/live-tests/image-test.ts(1 hunks)packages/typescript/ai-openrouter/live-tests/package.json(1 hunks)packages/typescript/ai-openrouter/live-tests/tool-test.ts(1 hunks)packages/typescript/ai-openrouter/live-tests/web-search-test.ts(1 hunks)packages/typescript/ai-openrouter/package.json(1 hunks)packages/typescript/ai-openrouter/src/index.ts(1 hunks)packages/typescript/ai-openrouter/src/message-types.ts(1 hunks)packages/typescript/ai-openrouter/src/model-meta.ts(1 hunks)packages/typescript/ai-openrouter/src/openrouter-adapter.ts(1 hunks)packages/typescript/ai-openrouter/src/text/text-provider-options.ts(1 hunks)packages/typescript/ai-openrouter/src/tools/function-tool.ts(1 hunks)packages/typescript/ai-openrouter/src/tools/index.ts(1 hunks)packages/typescript/ai-openrouter/src/tools/tool-converter.ts(1 hunks)packages/typescript/ai-openrouter/tests/openrouter-adapter.test.ts(1 hunks)packages/typescript/ai-openrouter/tsconfig.json(1 hunks)packages/typescript/ai-openrouter/vite.config.ts(1 hunks)
🧰 Additional context used
🧬 Code graph analysis (6)
packages/typescript/ai-openrouter/src/message-types.ts (1)
packages/typescript/ai-openrouter/src/index.ts (6)
OpenRouterTextMetadata(12-12)OpenRouterImageMetadata(13-13)OpenRouterAudioMetadata(14-14)OpenRouterVideoMetadata(15-15)OpenRouterDocumentMetadata(16-16)OpenRouterMessageMetadataByModality(17-17)
packages/typescript/ai-openrouter/src/text/text-provider-options.ts (1)
packages/typescript/ai-openrouter/src/index.ts (5)
WebPlugin(20-20)ProviderPreferences(21-21)ReasoningOptions(22-22)StreamOptions(23-23)ImageConfig(24-24)
packages/typescript/ai-openrouter/live-tests/image-test.ts (3)
packages/typescript/ai/src/stream/processor.ts (1)
process(390-413)
packages/typescript/ai-openrouter/src/index.ts (1)
createOpenRouter(3-3)
packages/typescript/ai-openrouter/src/openrouter-adapter.ts (1)
createOpenRouter(674-679)
packages/typescript/ai-openrouter/live-tests/tool-test.ts (3)
packages/typescript/ai/src/stream/processor.ts (1)
process(390-413)
packages/typescript/ai-openrouter/src/index.ts (1)
createOpenRouter(3-3)
packages/typescript/ai-openrouter/src/openrouter-adapter.ts (1)
createOpenRouter(674-679)
packages/typescript/ai-openrouter/src/openrouter-adapter.ts (4)
packages/typescript/ai-openrouter/src/text/text-provider-options.ts (2)
ExternalTextProviderOptions(271-271)InternalTextProviderOptions(273-322)
packages/typescript/ai-openrouter/src/tools/tool-converter.ts (2)
OpenRouterTool(5-5)convertToolsToProviderFormat(7-11)
packages/typescript/ai-openrouter/src/model-meta.ts (2)
OpenRouterChatModelProviderOptionsByName(5-7)OpenRouterModelInputModalitiesByName(9-11)
packages/typescript/ai-openrouter/src/message-types.ts (2)
OpenRouterMessageMetadataByModality(13-19)OpenRouterImageMetadata(3-5)
packages/typescript/ai-openrouter/src/model-meta.ts (2)
packages/typescript/ai-openrouter/src/index.ts (2)
OpenRouterChatModelProviderOptionsByName(8-8)OpenRouterModelInputModalitiesByName(9-9)
packages/typescript/ai-openrouter/src/text/text-provider-options.ts (1)
OpenRouterBaseOptions(110-269)
🪛 Biome (2.1.2)
packages/typescript/ai-openrouter/src/message-types.ts
[error] 1-1: An empty interface is equivalent to {}.
Safe fix: Use a type alias instead.
(lint/suspicious/noEmptyInterface)
[error] 7-7: An empty interface is equivalent to {}.
Safe fix: Use a type alias instead.
(lint/suspicious/noEmptyInterface)
[error] 9-9: An empty interface is equivalent to {}.
Safe fix: Use a type alias instead.
(lint/suspicious/noEmptyInterface)
[error] 11-11: An empty interface is equivalent to {}.
Safe fix: Use a type alias instead.
(lint/suspicious/noEmptyInterface)
🪛 markdownlint-cli2 (0.18.1)
packages/typescript/ai-openrouter/README.md
47-47: Heading levels should only increment by one level at a time Expected: h2; Actual: h3
(MD001, heading-increment)
🔇 Additional comments (31)
docs/config.json (1)
97-120: Confirm docs route matches the OpenRouter doc page id/slug.to: "adapters/openrouter"assumes the OpenRouter docs page resolves to that route, butdocs/adapters/openrouter.mdusesid: openrouter-adapter(which some doc systems treat as the slug). Please verify the link works in the built docs and align either thetoor the doc frontmatter id if needed.packages/typescript/ai-openrouter/README.md (1)
40-46: Copy update looks fine.docs/adapters/openrouter.md (1)
1-57: Doc slug/id vs sidebar route + model examples need verification.- Frontmatter
id: openrouter-adaptermay not match the sidebar route (adapters/openrouter). If your doc system usesidas the slug, consider changing it toopenrouter(or update the sidebar). - The “Available Models” examples look like illustrative model names; please verify they’re valid on OpenRouter (or label them clearly as examples).
packages/typescript/ai-openrouter/vite.config.ts (1)
1-36: Looks reasonable; please verify JSON import works in your Node/Vite setup.import packageJson from './package.json'can be sensitive to Node ESM + TS + tooling config (JSON modules / import assertions). Since this is config-time code, please confirmpnpm -C packages/typescript/ai-openrouter test:libworks in CI and locally.packages/typescript/ai-openrouter/tsconfig.json (1)
1-9: LGTM for a package-local tsconfig.packages/typescript/ai-openrouter/src/tools/index.ts (1)
1-5: LGTM!The barrel exports are clean and follow standard TypeScript module patterns.
packages/typescript/ai-openrouter/tests/openrouter-adapter.test.ts (7)
1-14: LGTM!Test setup and imports are well-structured.
16-35: LGTM!The SSE mock helper correctly simulates the streaming response format.
42-141: LGTM!Comprehensive test coverage for API payload mapping. The test validates all critical fields including provider-specific options like plugins.
143-223: LGTM!Excellent test for streaming behavior, validating incremental content delivery and usage reporting.
225-311: LGTM!Well-designed test for streaming tool calls with proper validation of incremental argument accumulation.
313-366: LGTM!Multimodal test properly validates the transformation of text and image content parts.
368-397: LGTM!Error handling test correctly validates error chunk generation on HTTP errors.
packages/typescript/ai-openrouter/src/tools/tool-converter.ts (1)
1-11: LGTM!Clean converter implementation with good semantic naming via the type alias.
packages/typescript/ai-openrouter/src/tools/function-tool.ts (1)
1-11: LGTM!The FunctionTool interface properly models the OpenRouter function tool format.
packages/typescript/ai-openrouter/src/model-meta.ts (1)
1-11: LGTM!The intentionally empty model array aligns with the PR's approach to avoid maintaining a static model list due to OpenRouter's frequent model additions. The type definitions provide good flexibility for model-specific configuration.
packages/typescript/ai-openrouter/live-tests/tool-test.ts (3)
18-70: LGTM!API key validation and tool definition are well-structured. The extensive argument validation in the execute function is appropriate for a test focused on verifying tool argument passing.
72-142: LGTM!The streaming and tool execution logic is well-implemented with proper error handling for JSON parsing and tool execution.
144-183: LGTM!Comprehensive test validation with clear success/failure criteria and helpful error messages.
packages/typescript/ai-openrouter/live-tests/web-search-test.ts (2)
17-77: LGTM!Clean implementation of web search plugin testing with proper chunk handling for content, done, and error types.
79-100: LGTM!Clear test validation with appropriate success/failure conditions.
packages/typescript/ai-openrouter/live-tests/image-test.ts (4)
17-32: LGTM!API key validation and image URL extraction helper are well-implemented.
34-131: LGTM!Comprehensive test for Gemini image generation with excellent result formatting and validation.
133-228: LGTM!Good coverage for Flux image generation. While there's some duplication with the Gemini test, this is acceptable for test code and improves readability.
230-265: LGTM!Excellent test orchestration with clear result aggregation and reporting.
packages/typescript/ai-openrouter/src/index.ts (1)
1-26: LGTM!The barrel export file is well-organized, correctly using
typefor type-only exports and grouping exports logically by their source modules. The public API surface is clean and appropriately scoped.packages/typescript/ai-openrouter/src/openrouter-adapter.ts (4)
201-203: Throwing inside async generator will be caught correctly.The
throwhere will be caught by the surroundingtry-catchblock (line 247), converting it to an error chunk. This is the expected behavior.
289-299: LGTM!Clear error message explaining the limitation and directing users to appropriate alternatives.
706-717: Environment detection logic is well-structured.The
getEnvironmentfunction properly handles both browser (with injectedwindow.env) and Node.js environments. The fallback chain is appropriate.
444-458: Tool call buffering skip-if-no-id logic is overly defensive but unlikely to cause data loss in practice.The OpenRouter API contract guarantees that
idandfunction.nameare typically present on the first chunk for each tool call;function.argumentsare delivered incrementally across subsequent chunks. The code skips a tool call delta if noidis present and no existing buffer exists (line 451), which means the first chunk must include anidto be buffered. Given the API contract, this edge case—where the first chunk lacks anid—should rarely or never occur. However, if it does happen, the subsequent chunks with theidwill fail to find an existing buffer entry, causing data loss. Consider either: (1) removing theidcheck and buffering bytc.indexalone, since the API guarantees id presence on first chunk anyway, or (2) adding a fallback to buffer incomplete tool calls and merge them when id arrives.packages/typescript/ai-openrouter/src/text/text-provider-options.ts (1)
1-108: Well-documented type definitions.The interfaces are comprehensively documented with JSDoc comments, including default values, value ranges, and links to OpenRouter documentation. This significantly improves developer experience.
@@ -0,0 +22,21 @@22+const stream = chat({23+ adapter,24+ messages: [{ role: "user", content: "Hello!" }],25+ model: "openai/gpt-4o",26+});27+```28+29+## Configuration30+31+```typescript32+import { createOpenRouter, type OpenRouterConfig } from "@tanstack/ai-openrouter";33+34+const config: OpenRouterConfig = {35+ apiKey: process.env.OPENROUTER_API_KEY!,36+ baseURL: "https://openrouter.ai/api/v1", // Optional37+ httpReferer: "https://your-app.com", // Optional, for rankings38+ xTitle: "Your App Name", // Optional, for rankings39+};40+41+const adapter = createOpenRouter(config.apiKey, config);42+```⚠️ Potential issue | 🟠 Major
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash # Find the createOpenRouter function definition and exports find packages/typescript/ai-openrouter -name "*.ts" -o -name "*.tsx" | head -20Repository: TanStack/ai
Length of output: 809
🏁 Script executed:
#!/bin/bash # Search for createOpenRouter function definition rg -n "export.*createOpenRouter|function createOpenRouter" packages/typescript/ai-openrouter -A 5Repository: TanStack/ai
Length of output: 600
🏁 Script executed:
#!/bin/bash # Search for createOpenRouter usage in the codebase rg -n "createOpenRouter\(" --type=ts -B 2 -A 2 | head -100Repository: TanStack/ai
Length of output: 3031
Fix the
createOpenRoutercall in the example—removeapiKeyfrom the config object.The function signature is
createOpenRouter(apiKey: string, config?: Omit<OpenRouterConfig, 'apiKey'>). The second parameter must excludeapiKey, so either:- Pass config without
apiKey:createOpenRouter(config.apiKey, { baseURL: "...", httpReferer: "...", xTitle: "..." }) - Or simplify to:
createOpenRouter(process.env.OPENROUTER_API_KEY!, { baseURL: "...", httpReferer: "...", xTitle: "..." })
The current example passes the full config (with
apiKey), which violates the type signature.🤖 Prompt for AI Agents
In docs/adapters/openrouter.md around lines 31 to 42, the example calls createOpenRouter with a config object that still contains apiKey which violates the function signature; update the call to pass the API key as the first argument and pass a config object that omits apiKey (e.g. call createOpenRouter(process.env.OPENROUTER_API_KEY!, { baseURL: "...", httpReferer: "...", xTitle: "..." }) or extract apiKey then call createOpenRouter(config.apiKey, { baseURL: "...", httpReferer: "...", xTitle: "..." })).packages/typescript/ai-openrouter/package.json lines 1 to 52OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +31,21 @@31+ "test:lib": "vitest run",32+ "test:lib:dev": "pnpm test:lib --watch",33+ "test:types": "tsc"34+ },35+ "keywords": [36+ "ai",37+ "openrouter",38+ "tanstack",39+ "adapter"40+ ],41+ "dependencies": {42+ "@tanstack/ai": "workspace:*"43+ },44+ "devDependencies": {45+ "@vitest/coverage-v8": "4.0.14",46+ "vite": "^7.2.4"47+ },48+ "peerDependencies": {49+ "@tanstack/ai": "workspace:*"50+ }51+}⚠️ Potential issue | 🟡 Minor
🧩 Analysis chain
🏁 Script executed:
ls -la | grep -E "^-" | head -20Repository: TanStack/ai
Length of output: 1376
🏁 Script executed:
git ls-files | grep -E "(release|changeset|publish|vite|tsup|\.npmrc)" | head -20Repository: TanStack/ai
Length of output: 858
🏁 Script executed:
ls -la | head -30Repository: TanStack/ai
Length of output: 1905
🏁 Script executed:
find . -name "vite.config.*" -type f 2>/dev/null | head -10Repository: TanStack/ai
Length of output: 486
🏁 Script executed:
git ls-files | grep -E "^[^/]+$" | sortRepository: TanStack/ai
Length of output: 310
🏁 Script executed:
cat package.json | head -50Repository: TanStack/ai
Length of output: 2651
🏁 Script executed:
[ -d ".changeset" ] && ls -la .changeset/ && cat .changeset/config.json 2>/dev/nullRepository: TanStack/ai
Length of output: 670
🏁 Script executed:
find . -path "*/packages/*/package.json" -type f 2>/dev/null | head -5 | while read f; do echo "=== $f ==="; cat "$f" | jq ".peerDependencies // empty" 2>/dev/null || echo "no peerDep"; doneRepository: TanStack/ai
Length of output: 410
🏁 Script executed:
cat pnpm-workspace.yaml 2>/dev/nullRepository: TanStack/ai
Length of output: 236
🏁 Script executed:
cat pnpm-workspace.yaml 2>/dev/null || echo "Checking package.json workspaces..."Repository: TanStack/ai
Length of output: 236
🏁 Script executed:
ls -laRepository: TanStack/ai
Length of output: 2163
🏁 Script executed:
head -100 package.jsonRepository: TanStack/ai
Length of output: 3234
🏁 Script executed:
cat pnpm-workspace.yaml 2>/dev/null || cat .npmrc 2>/dev/null || echo "checking files..."Repository: TanStack/ai
Length of output: 236
🏁 Script executed:
[ -d ".changeset" ] && cat .changeset/config.json || cat package.json | grep -A 5 '"scripts"'Repository: TanStack/ai
Length of output: 498
🏁 Script executed:
cat package.json | jq '.scripts' 2>/dev/nullRepository: TanStack/ai
Length of output: 2076
🏁 Script executed:
find . -type f -name "*.json" -path "*/.changeset/*" 2>/dev/nullRepository: TanStack/ai
Length of output: 79
🏁 Script executed:
ls -1 && echo "---" && ls -d .*/ 2>/dev/null | head -10Repository: TanStack/ai
Length of output: 369
🏁 Script executed:
find . -maxdepth 2 -type d -name ".changeset" 2>/dev/nullRepository: TanStack/ai
Length of output: 67
🏁 Script executed:
find . -name "package.json" -path "*/packages/*" -type f 2>/dev/null | head -10 | while read f; do echo "=== $f ==="; jq '.peerDependencies' "$f" 2>/dev/null; doneRepository: TanStack/ai
Length of output: 1090
🏁 Script executed:
find . -path "*/packages/*/package.json" -type f 2>/dev/null | head -10Repository: TanStack/ai
Length of output: 535
🏁 Script executed:
cat packages/typescript/ai-openrouter/package.json | jq '.peerDependencies'Repository: TanStack/ai
Length of output: 90
🏁 Script executed:
find packages -maxdepth 2 -type f -name "package.json" 2>/dev/null | xargs grep -l peerDependenciesRepository: TanStack/ai
Length of output: 39
🏁 Script executed:
ls -la packages/typescript/ai-openrouter/ 2>/dev/null | head -20Repository: TanStack/ai
Length of output: 591
🏁 Script executed:
find packages/typescript/ai-openrouter -type f 2>/dev/null | head -20Repository: TanStack/ai
Length of output: 1006
🏁 Script executed:
ls -la packages/typescript/ai-openrouter/ 2>/dev/nullRepository: TanStack/ai
Length of output: 591
🌐 Web query:
vitest run watch flag compatibility💡 Result:
Short answer: Use vitest (or vitest watch) for watch mode and vitest run for a single run. The CLI supports a --watch/-w option, but the documented intent is that "vitest run" is the non-watch single-run command while "vitest" / "vitest watch" (or vitest dev) enter watch mode — so prefer using the matching command rather than combining run + watch. [1][2]
Sources:
- Vitest CLI docs (watch vs run). [1]
- Vitest guide (watch mode details). [2]
References: [1] https://vitest.dev/guide/cli — CLI commands and options. [2] https://vitest.dev/guide/features — Watch mode description.
🌐 Web query:
pnpm workspace:* peerDependencies npm publish handling💡 Result:
Short answer
- When you run pnpm pack / pnpm publish, pnpm rewrites workspace: ranges (including workspace:) in package.json to real semver specs (the target package version for workspace:, or
/^ versions for workspace:/ workspace:^). This applies to dependencies, devDependencies and peerDependencies so the published manifest won’t contain workspace:* tokens. [1][2]
What that means in practice
- Ensure each workspace package has the correct version before publishing (pnpm will substitute that version into any workspace:* peerDependencies). [1]
- Publish order still matters if consumers expect the other packages to exist at the substituted versions on the registry. Use a release flow (publish dependent packages after/updating versions) or a tool that sequences releases.
- You can override fields for the published manifest with publishConfig if you need to change the final package.json that goes to the registry. [3]
Caveats / recent improvements
- pnpm has improved handling for workspace ranges in peerDependencies (allowing wider ranges / workspace in peerDependencies) in recent releases — check your pnpm version if you rely on more advanced workspace range behavior. [4]
- Some pnpm commands (e.g. deploy in some versions) historically didn’t rewrite workspace:* in a copied package.json — test your exact pnpm command/version if you rely on that workflow. [5]
Relevant sources
- pnpm workspaces — publishing behavior (rewrites workspace: ranges on pack/publish). [1]
- pnpm package.json / publishConfig docs. [3]
- pnpm changelog/release notes re: workspace ranges in peerDependencies. [4]
- pnpm GitHub issue about deploy not rewriting workspace:* in package.json (historical caveat). [5]
Sources [1] pnpm — Workspace / Publishing workspace packages. https://pnpm.io/workspaces (see “Publishing workspace packages”). [2] pnpm (older docs) — Workspace publishing explanation. https://pnpm.github.io/ (workspace publishing section). [3] pnpm — package.json / publishConfig. https://pnpm.io/package_json [4] pnpm release notes / changelog (workspace ranges & peerDependencies). https://newreleases.io/project/npm/pnpm/release/10.1.0 [5] pnpm GitHub issue:
pnpm deploydoesn't rewriteworkspace:*dependencies in package.json. https://github.com/pnpm/pnpm/issues/6269If you want, tell me your pnpm version and an example package.json and I’ll show exactly what will be published.
🏁 Script executed:
find . -maxdepth 2 -name "vite.config.*" -type f 2>/dev/nullRepository: TanStack/ai
Length of output: 37
🏁 Script executed:
find . -path "*/.github/workflows/*" -type f 2>/dev/null | head -5Repository: TanStack/ai
Length of output: 145
🏁 Script executed:
ls -la .github/workflows/ 2>/dev/null || echo "No workflows"Repository: TanStack/ai
Length of output: 344
🏁 Script executed:
find .github -type f 2>/dev/null | head -20Repository: TanStack/ai
Length of output: 331
🏁 Script executed:
cat pnpm-workspace.yaml 2>/dev/nullRepository: TanStack/ai
Length of output: 236
🏁 Script executed:
cat package.jsonRepository: TanStack/ai
Length of output: 3234
🏁 Script executed:
find . -type f -name "package.json" -path "*/packages/*" | sort | while read f; do echo "=== $f ==="; jq '.peerDependencies' "$f"; doneRepository: TanStack/ai
Length of output: 2623
🌐 Web query:
workspace protocol peerDependencies npm publish💡 Result:
Short answer
- pnpm and Yarn will rewrite workspace: specifiers (including those in peerDependencies) to real semver ranges when packing/publishing a workspace package. (pnpm.io)
- Lerna-like publishing tools also honor/replace workspace: entries when they pack/publish. (npmjs.com)
- npm’s docs show npm supports running publish in workspaces, but do not document an automatic workspace:→version rewrite the way pnpm/Yarn do; use a pack/dry-run to verify what will be published. (docs.npmjs.com)
Practical implications
- If a package’s peerDependencies use workspace: (e.g. "foo": "workspace:^"), pnpm/Yarn (and many release tools) will replace that with the corresponding version (e.g. "^1.2.3") in the published package.json so consumers see normal semver ranges. (pnpm.io)
- If you build into a dist folder or run publish outside the workspace root, the workspace: rewrite may fail (you’ll get unresolved-workspace-protocol errors) — ensure the package is published from a workspace-aware context or replace workspace: entries before publishing. (github.com)
- Use pnpm pack / npm pack or a publish dry-run to inspect the packaged package.json before publishing to confirm workspace: has been rewritten. (pnpm.io)
If you want, tell me:
- which package manager and publish workflow (npm / pnpm / yarn / lerna / CI) you use, and I’ll give exact commands and a checklist to ensure peerDependencies with workspace: are published correctly.
Citations:
- 1: https://pnpm.io/9.x/workspaces?utm_source=openai
- 2: https://www.npmjs.com/package/%40lerna-lite/publish?utm_source=openai
- 3: https://docs.npmjs.com/cli/v8/commands/npm-publish?utm_source=openai
- 4: https://pnpm.io/9.x/workspaces?utm_source=openai
- 5: https://github.com/pnpm/pnpm/issues/9495?utm_source=openai
- 6: https://pnpm.io/9.x/workspaces?utm_source=openai
🏁 Script executed:
ls -la | grep -E "^\."Repository: TanStack/ai
Length of output: 37
🏁 Script executed:
test -d .changeset && cat .changeset/config.json || echo "no changeset"Repository: TanStack/ai
Length of output: 498
🏁 Script executed:
rg "workspace:\*" 2>/dev/null | head -20Repository: TanStack/ai
Length of output: 974
🏁 Script executed:
find . -type f -name "package.json" | xargs jq '.peerDependencies' 2>/dev/null | grep -v null | head -50Repository: TanStack/ai
Length of output: 1044
🌐 Web query:
vitest run --watch incompatible💡 Result:
You can’t combine the single-run subcommand with watch.
vitest rundoes a one-off run (no watch);--watch/ default behavior is for the mainvitest/vitest watchcommand. Use one of these:- Single run (CI): vitest run. [1]
- Watch mode (dev): vitest or vitest watch (or vitest --watch). [1][2]
If you intended a non-interactive one-off run that exits, remove
--watch(or use--runwhen calling plainvitestto force exit). [2]Sources: Vitest CLI docs. [1][2]
🌐 Web query:
vitest documentation run command watch💡 Result:
Quick summary — commands & watch behavior for Vitest:
- vitest — starts in watch mode by default in a dev (interactive) environment; in CI/non-interactive it runs once. [1]
- vitest watch — explicitly start watch mode (same as vitest). [1]
- vitest run — perform a single (non-watch) run and exit. [1]
- Flags: -w / --watch to enable watch; --standalone to keep Vitest running in background and only run tests when files change; use --run when you want a watch-style command to exit (useful for lint-staged). [1][2]
Sources: Vitest CLI and Watch docs. [1] https://vitest.dev/guide/cli [2] https://vitest.dev/guide/features
🏁 Script executed:
grep -r "vitest" package.json 2>/dev/null | grep -E "version|devDependencies"Repository: TanStack/ai
Length of output: 37
🏁 Script executed:
jq '.devDependencies | keys[]' package.json | grep -i vitestRepository: TanStack/ai
Length of output: 63
🏁 Script executed:
cat package.json | head -200Repository: TanStack/ai
Length of output: 3234
🌐 Web query:
vitest "run" command watch mode documentation💡 Result:
Summary — Vitest watch vs run
- vitest run — performs a single run (no watch). Use when you want the process to exit after tests. [1]
- vitest (or vitest watch / vitest dev) — starts watch mode (re-runs related tests on file changes). Vitest enters watch mode by default in interactive/dev environments and falls back to run mode in CI/non-interactive environments (when CI is set). [1][2]
- --run — commonly used with subcommands (e.g., vitest related --run) to force a single run so the command exits (useful in lint-staged/CI). [1]
- Other useful flag: --standalone keeps Vitest running in background and only runs tests when they change. [2]
Examples
- Single run: vitest run or vitest --run
- Watch mode: vitest or vitest watch or vitest dev
- Force single run for related: vitest related src/foo.ts --run. [1][2]
Sources: Vitest CLI and Features docs. [1] [2]
References [1] Vitest CLI (official docs). [2] Vitest Guide — Watch mode / Features (official docs).
🏁 Script executed:
cat packages/typescript/ai-openrouter/package.json | jq '.scripts'Repository: TanStack/ai
Length of output: 318
🌐 Web query:
vitest 4.0 "run" flag with watch command💡 Result:
Short answer: In Vitest v4 the --run flag makes the process perform a single run (no watch). Use either vitest run or vitest --run (or pass --run to vitest watch/related) to force non-watch behavior so the command exits after running tests (useful in CI or lint-staged). Examples:
- vitest run # explicit single run.
- vitest --run # same as above.
- vitest related --run ... # run related tests and exit.
References: Vitest CLI / watch docs. [1][2][3]
Sources
- Vitest docs — Features / Watch mode. [1]
- Vitest CLI documentation (commands, --run usage, lint-staged tip). [2]
- Vitest config CLI options (watch default / --run). [3]
Fix
test:lib:devwatch mode.The current command
pnpm test:lib --watchexpands tovitest run --watch, butvitest runis incompatible with the--watchflag. Use:- "test:lib:dev": "pnpm test:lib --watch", + "test:lib:dev": "vitest",The
peerDependenciesusingworkspace:*is fine—pnpm (v10.17.0) automatically rewrites workspace protocols to real semver versions when publishing via changesets.🤖 Prompt for AI Agents
In packages/typescript/ai-openrouter/package.json around lines 1 to 51, the script "test:lib:dev": "pnpm test:lib --watch" expands to "vitest run --watch" which is invalid; fix by either invoking vitest in watch mode directly (e.g. set "test:lib:dev" to "vitest --watch") or forward the watch flag to the underlying script by changing "test:lib:dev" to "pnpm test:lib -- --watch" so the --watch reaches vitest correctly.✅ Addressed in commits ef1d19f to 832f7f4
@@ -46,0 +53,21 @@53+**With TanStack Start**, you get a bonus: share implementations between AI tools and server functions with `createServerFnTool`:54+55+```typescript56+import { createServerFnTool } from '@tanstack/ai-react'57+58+// Define once, get AI tool AND server function (TanStack Start only)59+const getProducts = createServerFnTool({60+ name: 'getProducts',61+ inputSchema: z.object({ query: z.string() }),62+ execute: async ({ query }) => db.products.search(query),63+})64+65+// Use in AI chat66+chat({ tools: [getProducts.server] })67+68+// Call directly from components (no API endpoint needed!)69+const products = await getProducts.serverFn({ query: 'laptop' })70+```71+72+No duplicate logic, full type safety, automatic validation. The `serverFn` feature requires TanStack Start. See [docs](https://tanstack.com/ai) for details.73+⚠️ Potential issue | 🟡 Minor
Fix markdown heading level + code sample missing
zimport.- Markdownlint is right: after
# TanStack AI, the next heading level should be##(or drop the heading styling for the “Read the docs” line). - The snippet uses
z.object(...)but doesn’t importz.
-### <a href="https://tanstack.com/ai">Read the docs →</b></a> +## <a href="https://tanstack.com/ai">Read the docs →</b></a> @@ ```typescript import { createServerFnTool } from '@tanstack/ai-react' +import { z } from 'zod'🤖 Prompt for AI Agents
In packages/typescript/ai-openrouter/README.md around lines 49 to 73, adjust the markdown heading to ensure it is a second-level heading (##) immediately after the top-level "# TanStack AI" header (or remove heading styling for the “Read the docs” line) and update the code example to include the missing zod import by adding an import for z (import { z } from 'zod') alongside the existing createServerFnTool import so the z.object usage resolves.@@ -0,0 +1,19 @@1+export interface OpenRouterTextMetadata {}2+3+export interface OpenRouterImageMetadata {4+ detail?: 'auto' | 'low' | 'high'5+}6+7+export interface OpenRouterAudioMetadata {}8+9+export interface OpenRouterVideoMetadata {}10+11+export interface OpenRouterDocumentMetadata {}12+13+export interface OpenRouterMessageMetadataByModality {14+ text: OpenRouterTextMetadata15+ image: OpenRouterImageMetadata16+ audio: OpenRouterAudioMetadata17+ video: OpenRouterVideoMetadata18+ document: OpenRouterDocumentMetadata19+}⚠️ Potential issue | 🟠 Major
Biome “noEmptyInterface” errors: replace empty interfaces with type aliases.
These empty interfaces will fail Biome as configured. Suggested minimal change:
-export interface OpenRouterTextMetadata {} +export type OpenRouterTextMetadata = Record<string, never> @@ -export interface OpenRouterAudioMetadata {} +export type OpenRouterAudioMetadata = Record<string, never> @@ -export interface OpenRouterVideoMetadata {} +export type OpenRouterVideoMetadata = Record<string, never> @@ -export interface OpenRouterDocumentMetadata {} +export type OpenRouterDocumentMetadata = Record<string, never>📝 Committable suggestion
‼️ IMPORTANT Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
Suggested change1-export interface OpenRouterTextMetadata {}2-3-export interface OpenRouterImageMetadata {4- detail?: 'auto' | 'low' | 'high'5-}6-7-export interface OpenRouterAudioMetadata {}8-9-export interface OpenRouterVideoMetadata {}10-11-export interface OpenRouterDocumentMetadata {}12-13-export interface OpenRouterMessageMetadataByModality {14- text: OpenRouterTextMetadata15- image: OpenRouterImageMetadata16- audio: OpenRouterAudioMetadata17- video: OpenRouterVideoMetadata18- document: OpenRouterDocumentMetadata19-}1+export type OpenRouterTextMetadata = Record<string, never>2+3+export interface OpenRouterImageMetadata {4+ detail?: 'auto' | 'low' | 'high'5+}6+7+export type OpenRouterAudioMetadata = Record<string, never>8+9+export type OpenRouterVideoMetadata = Record<string, never>10+11+export type OpenRouterDocumentMetadata = Record<string, never>12+13+export interface OpenRouterMessageMetadataByModality {14+ text: OpenRouterTextMetadata15+ image: OpenRouterImageMetadata16+ audio: OpenRouterAudioMetadata17+ video: OpenRouterVideoMetadata18+ document: OpenRouterDocumentMetadata19+}🧰 Tools
🪛 Biome (2.1.2)
[error] 1-1: An empty interface is equivalent to {}.
Safe fix: Use a type alias instead.
(lint/suspicious/noEmptyInterface)
[error] 7-7: An empty interface is equivalent to {}.
Safe fix: Use a type alias instead.
(lint/suspicious/noEmptyInterface)
[error] 9-9: An empty interface is equivalent to {}.
Safe fix: Use a type alias instead.
(lint/suspicious/noEmptyInterface)
[error] 11-11: An empty interface is equivalent to {}.
Safe fix: Use a type alias instead.
(lint/suspicious/noEmptyInterface)
🤖 Prompt for AI Agents
In packages/typescript/ai-openrouter/src/message-types.ts lines 1-19, Biome's noEmptyInterface linting fails because several interfaces are empty; replace each empty interface with a type alias (e.g., `type OpenRouterTextMetadata = Record<string, never>` and similarly for audio, video, document) and update OpenRouterMessageMetadataByModality to reference those type aliases instead of interfaces; keep OpenRouterImageMetadata as an interface (or convert to a type if you prefer) and preserve the optional `detail` union.@@ -0,0 +559,21 @@559+ prompt += `Keep the summary under ${options.maxLength} tokens. `560+ }561+ return prompt562+ }563+564+ private mapOptions(options: ChatOptions): OpenRouterRequest {565+ const providerOptions = options.providerOptions as566+ | Omit<InternalTextProviderOptions, 'model' | 'messages' | 'tools'>567+ | undefined568+569+ const request: OpenRouterRequest = {570+ model: options.model,571+ messages: this.convertMessages(options.messages),572+ temperature: options.options?.temperature,573+ max_tokens: options.options?.maxTokens,574+ top_p: options.options?.topP,575+ ...providerOptions,576+ tools: options.tools577+ ? convertToolsToProviderFormat(options.tools)578+ : undefined,579+ }⚠️ Potential issue | 🟡 Minor
Spread operator may allow
providerOptionsto override critical fields.The spread
...providerOptions(line 575) occurs after settingmodel,messages,temperature, etc., which means any matching keys inproviderOptionswould override those values. WhileInternalTextProviderOptionsexcludesmodel | messages | tools, the runtime type assertion doesn't enforce this.Consider explicitly excluding known keys or validating the spread doesn't contain restricted properties:
+ const { model: _m, messages: _msg, tools: _t, ...safeProviderOptions } = providerOptions || {} + const request: OpenRouterRequest = { model: options.model, messages: this.convertMessages(options.messages), temperature: options.options?.temperature, max_tokens: options.options?.maxTokens, top_p: options.options?.topP, - ...providerOptions, + ...safeProviderOptions,🤖 Prompt for AI Agents
In packages/typescript/ai-openrouter/src/openrouter-adapter.ts around lines 564 to 579, the current spread of providerOptions into the request can accidentally override critical fields (model, messages, tools, temperature, max_tokens, top_p) at runtime; instead, filter or pick only allowed keys from providerOptions before spreading (or explicitly delete/omit any of the restricted keys if present) so that model/messages/tools and other request fields set earlier cannot be overridden by providerOptions; implement a short runtime whitelist/omit step (or validate and throw) and then merge the sanitized providerOptions into the request.@@ -0,0 +166,21 @@166+ logprobs?: boolean167+ /**168+ * Number of most likely tokens to return at each position (0-20). Requires logprobs: true.169+ */170+ top_logprobs?: number171+ /**172+ * Minimum probability threshold for token sampling.173+ */174+ min_p?: number175+ /**176+ * Consider only top tokens with "top_a" cumulative probability.177+ */178+ top_a?: number179+ /**180+ * Random seed for deterministic sampling. Same seed should produce same results.181+ */182+ seed?: number183+ /**184+ * Force the model to respond in a specific format.185+ */186+ response_format?: { type: 'json_object' }⚠️ Potential issue | 🟠 Major
🧩 Analysis chain
🌐 Web query:
OpenRouter API response_format documentation json_object json_schema💡 Result:
Short summary — how OpenRouter's response_format works (json_object / json_schema)
- Parameter: response_format — a map you pass in the request to force structured outputs. [1][2].
- json_object: set response_format = { "type": "json_object" } to require the model to return any valid JSON object (useful when you only need valid JSON, not a specific schema). Also pair with an explicit system/user instruction to produce JSON. [1][3].
- json_schema (aka structured outputs): set response_format = { "type": "json_schema", "json_schema": { ... } } where json_schema contains name, schema (a JSON Schema object), and optional flags like strict. The model’s output will be validated against that schema; streaming support and model compatibility vary by provider/model. [2][4].
- Behavior/opts: some docs mention a structured_outputs boolean/flag and provider/model compatibility; not all models support response_format or both response_format and tools simultaneously — check the model’s supported parameters. [1][2][4].
- Example shape (conceptual): { "response_format": { "type": "json_schema", "json_schema": { "name": "weather", "strict": true, "schema": { "type":"object", "properties": { "location": {"type":"string"}, "temperature":{"type":"number"} }, "required":["location","temperature"] } } } } (Model returns JSON matching that schema). [2]
Sources
- OpenRouter API parameters / response_format description. [1]
- OpenRouter structured outputs (json_schema) docs and example. [2]
- OpenRouter API reference / compatibility notes. [4]
References: [1] https://openrouter-api.yestool.org/docs/api-reference/parameters [2] https://openrouter.ai/docs/features/structured-outputs [4] https://openrouter.ai/docs/api-reference/overview
🏁 Script executed:
# Check the actual type definition in the file cat -n packages/typescript/ai-openrouter/src/text/text-provider-options.ts | sed -n '180,190p'Repository: TanStack/ai
Length of output: 467
🌐 Web query:
OpenAI API response_format json_schema structured outputs types💡 Result:
Summary — OpenAI Structured Outputs (response_format: json_schema)
What it is: a response_format option that lets you supply a JSON Schema (or SDK types like Pydantic/Zod) so the model returns JSON that adheres to that schema. Use when you want the assistant’s reply itself to be structured (not a function/tool call). [1][2]
How to enable (overview):
- In Responses/Chat APIs set text.format / response_format to type: "json_schema" and include your schema; set strict: true to require schema adherence. SDKs convert Pydantic/Zod to the supported schema automatically. Example usage shown in the OpenAI docs. [1][2][3]
Models that support it: supported on recent GPT‑4o models (examples: gpt-4o-mini, gpt-4o-2024-08-06 / gpt-4o-mini-2024-07-18) and the structured-outputs feature is available alongside function-calling for models that support tools. Check the docs for exact model availability for your account/region. [1][2]
Supported JSON Schema features/types (subset):
- Primitives: string, number, boolean, integer
- Composites: object, array
- Enum and anyOf
- additionalProperties, required, nested objects/arrays are supported as shown in examples. (Structured Outputs supports a subset of JSON Schema — consult docs for exact constraints.) [1]
Behavior & edge cases:
- With strict: true the model’s output will match the schema or return a refusal token if it refuses; otherwise you may get valid JSON that doesn’t match your schema (JSON mode vs Structured Outputs distinction). Handle refusals and interrupted outputs (finish_reason) in your app. [1][2]
References [1] OpenAI — Structured model outputs (docs, supported schemas & examples). [2] OpenAI — Introducing Structured Outputs in the API (blog/announcement, examples). [3] OpenAI — Migrate to the Responses API (notes on text.format vs response_format).
Add support for
json_schemaand expandresponse_formattype definition.The
response_formatfield currently only supports{ type: 'json_object' }, but OpenRouter's API also supports{ type: 'json_schema', json_schema: {...} }for structured outputs. Update the type to:response_format?: | { type: 'json_object' } | { type: 'json_schema'; json_schema: { name: string; schema: Record<string, unknown>; strict?: boolean } }This allows users to leverage OpenRouter's structured output capabilities with schema validation.
🤖 Prompt for AI Agents
In packages/typescript/ai-openrouter/src/text/text-provider-options.ts around lines 184 to 186, the response_format type only allows { type: 'json_object' } but must also support OpenRouter's json_schema form; update the type to a union that includes { type: 'json_object' } OR { type: 'json_schema'; json_schema: { name: string; schema: Record<string, unknown>; strict?: boolean } } so callers can provide schema name, the schema object, and optional strict flag for structured outputs.packages/typescript/ai-openrouter/src/text/text-provider-options.ts lines 334 to 353Resolvedby LuggaPugga(GitHub profile, opens in a new tab)@@ -0,0 +274,21 @@274+ extends ExternalTextProviderOptions {275+ /**276+ * The model ID to use for the request.277+ * https://openrouter.ai/models278+ */279+ model: string280+ /**281+ * The messages to send to the model.282+ */283+ messages: Array<{284+ role: 'user' | 'assistant' | 'system' | 'tool'285+ content:286+ | string287+ | Array<{288+ type: 'text' | 'image_url'289+ text?: string290+ image_url?: {291+ url: string292+ detail?: 'auto' | 'low' | 'high'293+ }294+ }>⚠️ Potential issue | 🟡 Minor
Message content type is narrower than adapter support.
The
InternalTextProviderOptions.messagescontent array only supports'text' | 'image_url'types, but the adapter'sconvertContentPartsmethod (inopenrouter-adapter.ts) handlesaudio_url,video_url, anddocument_urlas well. This type definition doesn't reflect the full capability.Consider extending the content type to match the adapter's actual support:
content: | string | Array<{ - type: 'text' | 'image_url' + type: 'text' | 'image_url' | 'audio_url' | 'video_url' | 'document_url' text?: string image_url?: { url: string detail?: 'auto' | 'low' | 'high' } + audio_url?: { url: string } + video_url?: { url: string } + document_url?: { url: string } }>🤖 Prompt for AI Agents
In packages/typescript/ai-openrouter/src/text/text-provider-options.ts around lines 283 to 294, the message content type is too narrow (only 'text' | 'image_url') while the adapter handles audio_url, video_url and document_url; update the union to include 'audio_url' | 'video_url' | 'document_url' and add corresponding optional fields (e.g., audio_url?: { url: string; detail?: 'auto'|'low'|'high' }, video_url?: { url: string; detail?: 'auto'|'low'|'high' }, document_url?: { url: string; detail?: 'auto'|'low'|'high' }) so the type matches convertContentParts; ensure the updated type is exported/used wherever InternalTextProviderOptions.messages appears.✅ Addressed in commit ebfa0c3
Hold off until adding changes, we have implemented huge breaking changes for adapters internally
Alright, should I resolve the CodeRabbit suggestions now, or should I wait for that as well?
Is this ready to be updated on the new adapter structure?
@LuggaPugga it is, the BaseAdapter should be changed to BaseTextAdapter and if there are other supporting functionalities they should be split
Actionable comments posted: 2
🧹 Nitpick comments (4)
packages/typescript/ai-openrouter/src/adapters/text.ts (1)
410-415: Silent failure on malformed JSON chunks may hide API issues.When JSON parsing fails in the SSE stream, the error is silently swallowed. While this prevents crashes on malformed data, it could mask upstream API issues or protocol changes.
Consider logging or tracking parse failures for observability, at least in development mode.
🔎 Suggested improvement
} else { try { yield { done: false, data: JSON.parse(data) } } catch { - continue + // Consider adding debug logging here for observability + // console.debug('Failed to parse SSE chunk:', data) + continue } }packages/typescript/ai-openrouter/tests/openrouter-adapter.test.ts (1)
297-304: Missing type narrowing before accessingtoolCallproperty.At line 301-303, the code accesses
toolCallChunk.toolCallwithout proper type narrowing. While the filter on line 297 ensures onlytool_callchunks are selected, TypeScript may not infer this correctly.🔎 Suggested improvement for type safety
const toolCallChunks = chunks.filter((c) => c.type === 'tool_call') expect(toolCallChunks.length).toBe(1) const toolCallChunk = toolCallChunks[0] - expect(toolCallChunk.toolCall.function.name).toBe('lookup_weather') - expect(toolCallChunk.toolCall.function.arguments).toBe( - '{"location":"Berlin"}', - ) + if (toolCallChunk && toolCallChunk.type === 'tool_call') { + expect(toolCallChunk.toolCall.function.name).toBe('lookup_weather') + expect(toolCallChunk.toolCall.function.arguments).toBe( + '{"location":"Berlin"}', + ) + }packages/typescript/ai-openrouter/live-tests/web-search-test.ts (1)
7-15: Consider using a library for.envparsing.The manual
.env.localparsing is functional but fragile. It doesn't handle edge cases like quoted values, multiline values, or comments properly.For live tests, this is acceptable, but consider using
dotenvif more robust parsing is needed.packages/typescript/ai-openrouter/src/adapters/summarize.ts (1)
117-136: Code duplication:getEnvironmentand related interfaces are duplicated fromtext.ts.The
EnvObject,WindowWithEnvinterfaces andgetEnvironmentfunction are identical copies fromtext.ts. Consider extracting these to a shared utility module to reduce duplication and ensure consistency.🔎 Suggested refactor
Create a shared utility file:
// packages/typescript/ai-openrouter/src/utils/environment.ts export interface EnvObject { OPENROUTER_API_KEY?: string } interface WindowWithEnv { env?: EnvObject } export function getEnvironment(): EnvObject | undefined { if (typeof globalThis !== 'undefined') { const win = (globalThis as { window?: WindowWithEnv }).window if (win?.env) { return win.env } } if (typeof process !== 'undefined') { return process.env as EnvObject } return undefined }Then import from both adapter files.
📜 Review details
Configuration used: defaults
Review profile: CHILL
Plan: Pro
📥 Commits
Reviewing files that changed from the base of the PR and between 01479fdef4f48397f4723e8e00c2a83125d6b908 and 1507ba5a25d6e61b50e47a64f474c1ef161bc117.
⛔ Files ignored due to path filters (1)
pnpm-lock.yamlis excluded by!**/pnpm-lock.yaml
📒 Files selected for processing (10)
docs/config.jsonpackages/typescript/ai-openrouter/live-tests/image-test.tspackages/typescript/ai-openrouter/live-tests/tool-test.tspackages/typescript/ai-openrouter/live-tests/web-search-test.tspackages/typescript/ai-openrouter/src/adapters/summarize.tspackages/typescript/ai-openrouter/src/adapters/text.tspackages/typescript/ai-openrouter/src/index.tspackages/typescript/ai-openrouter/src/text/text-provider-options.tspackages/typescript/ai-openrouter/src/tools/function-tool.tspackages/typescript/ai-openrouter/tests/openrouter-adapter.test.ts
🚧 Files skipped from review as they are similar to previous changes (3)
- packages/typescript/ai-openrouter/src/text/text-provider-options.ts
- packages/typescript/ai-openrouter/live-tests/tool-test.ts
- packages/typescript/ai-openrouter/live-tests/image-test.ts
🧰 Additional context used
📓 Path-based instructions (5)
**/*.{ts,tsx}
📄 CodeRabbit inference engine (CLAUDE.md)
**/*.{ts,tsx}: Use tree-shakeable adapter architecture for provider implementations - export specialized adapters (text, embedding, summarize, image) as separate imports from/adapterssubpath rather than monolithic adapters Use Zod for runtime schema validation and type inference, particularly for tool input/output definitions withtoolDefinition()and Zod schema inference Implement isomorphic tool system usingtoolDefinition()with.server()and.client()implementations for dual-environment execution Use type-safe per-model configuration with provider options typed based on selected model to ensure compile-time safety Implement stream processing with StreamProcessor for handling chunked responses and support partial JSON parsing for streaming AI responsesFiles:
packages/typescript/ai-openrouter/live-tests/web-search-test.tspackages/typescript/ai-openrouter/src/tools/function-tool.tspackages/typescript/ai-openrouter/tests/openrouter-adapter.test.tspackages/typescript/ai-openrouter/src/adapters/summarize.tspackages/typescript/ai-openrouter/src/adapters/text.tspackages/typescript/ai-openrouter/src/index.ts
**/*.{ts,tsx,js,jsx}
📄 CodeRabbit inference engine (CLAUDE.md)
Use camelCase for function and variable names throughout the codebase
Files:
packages/typescript/ai-openrouter/live-tests/web-search-test.tspackages/typescript/ai-openrouter/src/tools/function-tool.tspackages/typescript/ai-openrouter/tests/openrouter-adapter.test.tspackages/typescript/ai-openrouter/src/adapters/summarize.tspackages/typescript/ai-openrouter/src/adapters/text.tspackages/typescript/ai-openrouter/src/index.ts
**/*.test.ts
📄 CodeRabbit inference engine (CLAUDE.md)
Write unit tests using Vitest alongside source files with
.test.tsnaming conventionFiles:
packages/typescript/ai-openrouter/tests/openrouter-adapter.test.ts
packages/typescript/*/src/adapters/*.ts
📄 CodeRabbit inference engine (CLAUDE.md)
Create individual adapter implementations for each provider capability (text, embed, summarize, image) with separate exports to enable tree-shaking
Files:
packages/typescript/ai-openrouter/src/adapters/summarize.tspackages/typescript/ai-openrouter/src/adapters/text.ts
packages/typescript/*/src/index.ts
📄 CodeRabbit inference engine (CLAUDE.md)
Export tree-shakeable adapters with clear subpath exports in package.json (e.g.,
@tanstack/ai/adapters,@tanstack/ai-openai/adapters) to minimize bundle sizeFiles:
packages/typescript/ai-openrouter/src/index.ts
🧠 Learnings (10)
📓 Common learnings
Learnt from: CR Repo: TanStack/ai PR: 0 File: CLAUDE.md:0-0 Timestamp: 2025-12-13T17:09:09.794Z Learning: Applies to packages/typescript/*/src/adapters/*.ts : Create individual adapter implementations for each provider capability (text, embed, summarize, image) with separate exports to enable tree-shaking📚 Learning: 2025-12-13T17:09:09.794Z
Learnt from: CR Repo: TanStack/ai PR: 0 File: CLAUDE.md:0-0 Timestamp: 2025-12-13T17:09:09.794Z Learning: Applies to **/*.test.ts : Write unit tests using Vitest alongside source files with `.test.ts` naming conventionApplied to files:
packages/typescript/ai-openrouter/live-tests/web-search-test.ts
📚 Learning: 2025-12-13T17:09:09.794Z
Learnt from: CR Repo: TanStack/ai PR: 0 File: CLAUDE.md:0-0 Timestamp: 2025-12-13T17:09:09.794Z Learning: Applies to **/*.{ts,tsx} : Implement isomorphic tool system using `toolDefinition()` with `.server()` and `.client()` implementations for dual-environment executionApplied to files:
packages/typescript/ai-openrouter/src/tools/function-tool.ts
📚 Learning: 2025-12-13T17:09:09.794Z
Learnt from: CR Repo: TanStack/ai PR: 0 File: CLAUDE.md:0-0 Timestamp: 2025-12-13T17:09:09.794Z Learning: Applies to **/*.{ts,tsx} : Use Zod for runtime schema validation and type inference, particularly for tool input/output definitions with `toolDefinition()` and Zod schema inferenceApplied to files:
packages/typescript/ai-openrouter/src/tools/function-tool.ts
📚 Learning: 2025-12-13T17:09:09.794Z
Learnt from: CR Repo: TanStack/ai PR: 0 File: CLAUDE.md:0-0 Timestamp: 2025-12-13T17:09:09.794Z Learning: Applies to packages/typescript/*/src/adapters/*.ts : Create individual adapter implementations for each provider capability (text, embed, summarize, image) with separate exports to enable tree-shakingApplied to files:
packages/typescript/ai-openrouter/src/tools/function-tool.tspackages/typescript/ai-openrouter/tests/openrouter-adapter.test.tspackages/typescript/ai-openrouter/src/adapters/summarize.tspackages/typescript/ai-openrouter/src/adapters/text.tspackages/typescript/ai-openrouter/src/index.ts
📚 Learning: 2025-12-13T17:09:09.794Z
Learnt from: CR Repo: TanStack/ai PR: 0 File: CLAUDE.md:0-0 Timestamp: 2025-12-13T17:09:09.794Z Learning: Applies to **/*.{ts,tsx} : Use tree-shakeable adapter architecture for provider implementations - export specialized adapters (text, embedding, summarize, image) as separate imports from `/adapters` subpath rather than monolithic adaptersApplied to files:
packages/typescript/ai-openrouter/tests/openrouter-adapter.test.tspackages/typescript/ai-openrouter/src/adapters/summarize.tspackages/typescript/ai-openrouter/src/adapters/text.tspackages/typescript/ai-openrouter/src/index.ts
📚 Learning: 2025-12-13T17:09:09.794Z
Learnt from: CR Repo: TanStack/ai PR: 0 File: CLAUDE.md:0-0 Timestamp: 2025-12-13T17:09:09.794Z Learning: Applies to **/*.{ts,tsx} : Implement stream processing with StreamProcessor for handling chunked responses and support partial JSON parsing for streaming AI responsesApplied to files:
packages/typescript/ai-openrouter/tests/openrouter-adapter.test.tspackages/typescript/ai-openrouter/src/adapters/text.ts
📚 Learning: 2025-12-13T17:09:09.794Z
Learnt from: CR Repo: TanStack/ai PR: 0 File: CLAUDE.md:0-0 Timestamp: 2025-12-13T17:09:09.794Z Learning: Applies to packages/typescript/*/src/index.ts : Export tree-shakeable adapters with clear subpath exports in package.json (e.g., `tanstack/ai/adapters`, `tanstack/ai-openai/adapters`) to minimize bundle sizeApplied to files:
packages/typescript/ai-openrouter/tests/openrouter-adapter.test.tspackages/typescript/ai-openrouter/src/adapters/summarize.tspackages/typescript/ai-openrouter/src/adapters/text.tspackages/typescript/ai-openrouter/src/index.ts
📚 Learning: 2025-12-13T17:09:09.794Z
Learnt from: CR Repo: TanStack/ai PR: 0 File: CLAUDE.md:0-0 Timestamp: 2025-12-13T17:09:09.794Z Learning: Applies to packages/typescript/*/src/model-meta.ts : Maintain model metadata files that define provider options and capabilities per model for per-model type safetyApplied to files:
packages/typescript/ai-openrouter/src/adapters/text.tspackages/typescript/ai-openrouter/src/index.ts
📚 Learning: 2025-12-13T17:09:09.794Z
Learnt from: CR Repo: TanStack/ai PR: 0 File: CLAUDE.md:0-0 Timestamp: 2025-12-13T17:09:09.794Z Learning: Applies to **/*.{ts,tsx} : Use type-safe per-model configuration with provider options typed based on selected model to ensure compile-time safetyApplied to files:
packages/typescript/ai-openrouter/src/adapters/text.ts
🧬 Code graph analysis (4)
packages/typescript/ai-openrouter/live-tests/web-search-test.ts (2)
packages/typescript/ai-openrouter/src/adapters/text.ts (1)
createOpenRouterText(712-718)
packages/typescript/ai-openrouter/src/index.ts (1)
createOpenRouterText(8-8)
packages/typescript/ai-openrouter/src/tools/function-tool.ts (4)
packages/typescript/ai-openrouter/src/index.ts (1)
FunctionTool(51-51)
packages/typescript/ai-openrouter/src/tools/index.ts (2)
FunctionTool(4-4)convertFunctionToolToAdapterFormat(5-5)
packages/python/tanstack-ai/src/tanstack_ai/tool_utils.py (1)
tool(12-65)
packages/typescript/ai/src/types.ts (1)
JSONSchema(25-64)
packages/typescript/ai-openrouter/src/adapters/summarize.ts (3)
packages/typescript/ai-openrouter/src/index.ts (5)
OpenRouterSummarizeConfig(19-19)OpenRouterConfig(10-10)OpenRouterSummarizeAdapter(16-16)createOpenRouterSummarize(17-17)openrouterSummarize(18-18)
packages/typescript/ai-openrouter/src/adapters/text.ts (1)
OpenRouterConfig(26-31)
packages/typescript/ai/src/types.ts (1)
StreamChunk(740-748)
packages/typescript/ai-openrouter/src/adapters/text.ts (2)
packages/typescript/ai-openrouter/src/text/text-provider-options.ts (2)
ExternalTextProviderOptions(271-271)InternalTextProviderOptions(273-321)
packages/typescript/ai/src/types.ts (2)
TextOptions(565-650)ContentPart(184-195)
🔇 Additional comments (9)
docs/config.json (1)
135-138: LGTM!The OpenRouter adapter is correctly added to the documentation navigation, maintaining proper alphabetical ordering within the Adapters section.
packages/typescript/ai-openrouter/src/adapters/text.ts (3)
699-710: Dead code:getEnvironmentfunction is defined but never used.The
getEnvironmentfunction and related interfaces (EnvObject,WindowWithEnv) at lines 691-710 are defined but never referenced in this file. TheopenrouterTextfactory function at line 724 callsgetEnvironment(), so this is actually used. Let me re-check.After re-reading:
getEnvironment()is called at line 724 in theopenrouterTextfunction. This is correct and not dead code.
265-334: LGTM!The
structuredOutputmethod correctly implements the tool-forcing pattern for structured JSON extraction with appropriate fallback parsing and clear error messages.
712-734: LGTM!The factory functions provide flexible API key handling with both explicit key and environment-based detection patterns. Error messaging is clear and actionable.
packages/typescript/ai-openrouter/tests/openrouter-adapter.test.ts (1)
1-393: LGTM! Comprehensive test coverage for the adapter.The test suite covers key scenarios including option mapping, streaming responses, tool calls, multimodal input, and error handling. The mock SSE helper is well-designed and tests properly clean up mocked resources.
Consider adding tests for
structuredOutputmethod and reasoning/thinking chunk handling in future iterations.packages/typescript/ai-openrouter/src/tools/function-tool.ts (1)
1-33: LGTM!Clean implementation of the tool format converter. The default schema fallback ensures tools without explicit input schemas still work correctly, and the interface aligns with the OpenRouter/OpenAI function calling specification.
packages/typescript/ai-openrouter/live-tests/web-search-test.ts (1)
24-101: LGTM!The live test provides good coverage of the web search plugin functionality with clear logging, proper error handling, and appropriate exit codes for CI integration.
packages/typescript/ai-openrouter/src/adapters/summarize.ts (1)
88-114: LGTM!The
buildSummarizationPromptmethod provides clear, contextual prompts based on style, focus areas, and length constraints.packages/typescript/ai-openrouter/src/index.ts (1)
1-51: LGTM! Well-organized tree-shakeable exports.The barrel file correctly separates exports by capability (text, summarize) and properly uses the
typekeyword for type-only exports, enabling optimal tree-shaking. This aligns with the coding guidelines for adapter architecture.packages/typescript/ai-openrouter/src/adapters/summarize.ts lines 58 to 87Resolvedby LuggaPugga(GitHub profile, opens in a new tab)@@ -0,0 +51,21 @@51+ let usage = { promptTokens: 0, completionTokens: 0, totalTokens: 0 }52+53+ for await (const chunk of this.textAdapter.chatStream({54+ model: options.model,55+ messages: [{ role: 'user', content: options.text }],56+ systemPrompts: [systemPrompt],57+ maxTokens: options.maxLength,58+ temperature: 0.3,59+ })) {60+ if (chunk.type === 'content') {61+ summary = chunk.content62+ id = chunk.id63+ model = chunk.model64+ }65+ if (chunk.type === 'done' && chunk.usage) {66+ usage = chunk.usage67+ }68+ }69+70+ return { id, model, summary, usage }71+ }⚠️ Potential issue | 🟡 Minor
OpenRouterSummarizeProviderOptions.temperatureis defined but not used.The
OpenRouterSummarizeProviderOptionsinterface definestemperatureandmaxTokensfields (lines 18-22), but thesummarizemethod uses a hardcodedtemperature: 0.3(line 58) instead of reading from provider options.If this is intentional for consistent summarization quality, consider removing the unused options from the interface or documenting this behavior. Otherwise, wire up the provider options.
🔎 Suggested fix to use provider options
for await (const chunk of this.textAdapter.chatStream({ model: options.model, messages: [{ role: 'user', content: options.text }], systemPrompts: [systemPrompt], maxTokens: options.maxLength, - temperature: 0.3, + temperature: options.modelOptions?.temperature ?? 0.3, })) {📝 Committable suggestion
‼️ IMPORTANT Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
Suggested change58+ async summarize(options: SummarizationOptions): Promise<SummarizationResult> {59+ const systemPrompt = this.buildSummarizationPrompt(options)60+61+ // Use the text adapter's streaming and collect the result62+ let summary = ''63+ let id = ''64+ let model = options.model65+ let usage = { promptTokens: 0, completionTokens: 0, totalTokens: 0 }66+67+ for await (const chunk of this.textAdapter.chatStream({68+ model: options.model,69+ messages: [{ role: 'user', content: options.text }],70+ systemPrompts: [systemPrompt],71+ maxTokens: options.maxLength,72+ temperature: options.modelOptions?.temperature ?? 0.3,73+ })) {74+ if (chunk.type === 'content') {75+ summary = chunk.content76+ id = chunk.id77+ model = chunk.model78+ }79+ if (chunk.type === 'done' && chunk.usage) {80+ usage = chunk.usage81+ }82+ }83+84+ return { id, model, summary, usage }85+ }🤖 Prompt for AI Agents
In packages/typescript/ai-openrouter/src/adapters/summarize.ts around lines 44 to 71, the summarize method ignores provider options by hardcoding temperature and may be using the wrong max tokens field; replace the literal temperature: 0.3 with a value taken from the provider options (e.g., temperature: options.temperature ?? 0.3) and ensure the max tokens parameter uses the provider field (e.g., maxTokens: options.maxTokens ?? options.maxLength ?? <sensible default>), or rename/align option names if mismatched so the method respects the configured temperature and maxTokens.✅ Addressed in commit 92524b8
@@ -0,0 +621,21 @@621+ role: 'tool',622+ content:623+ typeof msg.content === 'string'624+ ? msg.content625+ : JSON.stringify(msg.content),626+ tool_call_id: msg.toolCallId,627+ name: msg.name,628+ }629+ }630+631+ const parts = this.convertContentParts(msg.content)632+ const role = msg.role === 'user' ? 'user' : 'assistant'633+ return {634+ role,635+ content:636+ parts.length === 1 && parts[0]?.type === 'text'637+ ? parts[0].text || ''638+ : parts,639+ name: msg.name,640+ }641+ })⚠️ Potential issue | 🟡 Minor
System messages in the messages array are incorrectly converted to assistant role.
If a
ModelMessagewithrole: 'system'is passed in the messages array, it will be converted to an assistant message (line 632). While system prompts are typically passed viasystemPromptsoption, this could cause unexpected behavior if developers pass system messages directly in the messages array.🔎 Suggested fix
const parts = this.convertContentParts(msg.content) - const role = msg.role === 'user' ? 'user' : 'assistant' + const role = msg.role === 'system' ? 'system' : msg.role === 'user' ? 'user' : 'assistant' return { role, content: parts.length === 1 && parts[0]?.type === 'text' ? parts[0].text || '' : parts, name: msg.name, }📝 Committable suggestion
‼️ IMPORTANT Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
Suggested change413+ const parts = this.convertContentParts(msg.content)414+ const role = msg.role === 'system' ? 'system' : msg.role === 'user' ? 'user' : 'assistant'415+ return {416+ role,417+ content:418+ parts.length === 1 && parts[0]?.type === 'text'419+ ? parts[0].text || ''420+ : parts,421+ name: msg.name,422+ }🤖 Prompt for AI Agents
In packages/typescript/ai-openrouter/src/adapters/text.ts around lines 630 to 641, the mapping forces any non-'user' role to 'assistant', which wrongly converts 'system' messages to assistant; update the role mapping to preserve 'system' (and 'assistant') explicitly: set role to 'user' for 'user', to 'assistant' for 'assistant', to 'system' for 'system', and fall back to 'assistant' only for unknown values so system messages remain system messages.Actionable comments posted: 0
♻️ Duplicate comments (1)
packages/typescript/ai-openrouter/src/text/text-provider-options.ts (1)
184-186: Expandresponse_formatto supportjson_schemafor structured outputs.The current type only allows
{ type: 'json_object' }, but OpenRouter's API also supports{ type: 'json_schema', json_schema: {...} }for schema-validated structured outputs. This limitation prevents users from leveraging OpenRouter's full structured output capabilities.🔎 Expand type definition to include json_schema variant
/** * Force the model to respond in a specific format. */ - response_format?: { type: 'json_object' } + response_format?: + | { type: 'json_object' } + | { + type: 'json_schema' + json_schema: { + name: string + schema: Record<string, unknown> + strict?: boolean + } + }Note: This issue was previously flagged but remains unresolved.
🧹 Nitpick comments (1)
packages/typescript/ai-openrouter/src/text/text-provider-options.ts (1)
1-329: Consider Zod schemas for runtime validation and better developer experience.Currently, all types are defined as TypeScript interfaces, which provide compile-time safety but no runtime validation. Using Zod schemas would enable:
- Runtime validation of provider options to catch configuration errors early
- Type inference from schemas (single source of truth)
- Better error messages when invalid options are passed
- Consistency with coding guidelines that recommend Zod for schema validation
This is particularly valuable for complex nested structures like
ProviderPreferencesandOpenRouterBaseOptions.Example: Converting OpenRouterBaseOptions to Zod
import { z } from 'zod' export const openRouterBaseOptionsSchema = z.object({ stop: z.union([z.string(), z.array(z.string())]).optional(), stream: z.boolean().optional(), max_tokens: z.number().optional(), temperature: z.number().min(0).max(2).optional(), // ... additional fields }).strict() export type OpenRouterBaseOptions = z.infer<typeof openRouterBaseOptionsSchema>This approach provides both type safety and runtime validation.
Based on coding guidelines emphasizing Zod for schema validation and type inference.
📜 Review details
Configuration used: defaults
Review profile: CHILL
Plan: Pro
📥 Commits
Reviewing files that changed from the base of the PR and between 1507ba5a25d6e61b50e47a64f474c1ef161bc117 and ebfa0c3ad1f59d2726c48ddc86e19065e2f1a6e5.
📒 Files selected for processing (1)
packages/typescript/ai-openrouter/src/text/text-provider-options.ts
🧰 Additional context used
📓 Path-based instructions (2)
**/*.{ts,tsx}
📄 CodeRabbit inference engine (CLAUDE.md)
**/*.{ts,tsx}: Use tree-shakeable adapter architecture for provider implementations - export specialized adapters (text, embedding, summarize, image) as separate imports from/adapterssubpath rather than monolithic adapters Use Zod for runtime schema validation and type inference, particularly for tool input/output definitions withtoolDefinition()and Zod schema inference Implement isomorphic tool system usingtoolDefinition()with.server()and.client()implementations for dual-environment execution Use type-safe per-model configuration with provider options typed based on selected model to ensure compile-time safety Implement stream processing with StreamProcessor for handling chunked responses and support partial JSON parsing for streaming AI responsesFiles:
packages/typescript/ai-openrouter/src/text/text-provider-options.ts
**/*.{ts,tsx,js,jsx}
📄 CodeRabbit inference engine (CLAUDE.md)
Use camelCase for function and variable names throughout the codebase
Files:
packages/typescript/ai-openrouter/src/text/text-provider-options.ts
🧠 Learnings (6)
📓 Common learnings
Learnt from: CR Repo: TanStack/ai PR: 0 File: CLAUDE.md:0-0 Timestamp: 2025-12-13T17:09:09.794Z Learning: Applies to packages/typescript/*/src/adapters/*.ts : Create individual adapter implementations for each provider capability (text, embed, summarize, image) with separate exports to enable tree-shakingLearnt from: CR Repo: TanStack/ai PR: 0 File: CLAUDE.md:0-0 Timestamp: 2025-12-13T17:09:09.794Z Learning: Applies to **/*.{ts,tsx} : Use tree-shakeable adapter architecture for provider implementations - export specialized adapters (text, embedding, summarize, image) as separate imports from `/adapters` subpath rather than monolithic adaptersLearnt from: CR Repo: TanStack/ai PR: 0 File: CLAUDE.md:0-0 Timestamp: 2025-12-13T17:09:09.794Z Learning: Applies to packages/typescript/*/src/index.ts : Export tree-shakeable adapters with clear subpath exports in package.json (e.g., `tanstack/ai/adapters`, `tanstack/ai-openai/adapters`) to minimize bundle sizeLearnt from: CR Repo: TanStack/ai PR: 0 File: CLAUDE.md:0-0 Timestamp: 2025-12-13T17:09:09.794Z Learning: Applies to **/*.{ts,tsx} : Implement stream processing with StreamProcessor for handling chunked responses and support partial JSON parsing for streaming AI responses📚 Learning: 2025-12-13T17:09:09.794Z
Learnt from: CR Repo: TanStack/ai PR: 0 File: CLAUDE.md:0-0 Timestamp: 2025-12-13T17:09:09.794Z Learning: Applies to packages/typescript/*/src/adapters/*.ts : Create individual adapter implementations for each provider capability (text, embed, summarize, image) with separate exports to enable tree-shakingApplied to files:
packages/typescript/ai-openrouter/src/text/text-provider-options.ts
📚 Learning: 2025-12-13T17:09:09.794Z
Learnt from: CR Repo: TanStack/ai PR: 0 File: CLAUDE.md:0-0 Timestamp: 2025-12-13T17:09:09.794Z Learning: Applies to packages/typescript/*/src/model-meta.ts : Maintain model metadata files that define provider options and capabilities per model for per-model type safetyApplied to files:
packages/typescript/ai-openrouter/src/text/text-provider-options.ts
📚 Learning: 2025-12-13T17:09:09.794Z
Learnt from: CR Repo: TanStack/ai PR: 0 File: CLAUDE.md:0-0 Timestamp: 2025-12-13T17:09:09.794Z Learning: Applies to **/*.{ts,tsx} : Use type-safe per-model configuration with provider options typed based on selected model to ensure compile-time safetyApplied to files:
packages/typescript/ai-openrouter/src/text/text-provider-options.ts
📚 Learning: 2025-12-13T17:09:09.794Z
Learnt from: CR Repo: TanStack/ai PR: 0 File: CLAUDE.md:0-0 Timestamp: 2025-12-13T17:09:09.794Z Learning: Applies to **/*.{ts,tsx} : Use tree-shakeable adapter architecture for provider implementations - export specialized adapters (text, embedding, summarize, image) as separate imports from `/adapters` subpath rather than monolithic adaptersApplied to files:
packages/typescript/ai-openrouter/src/text/text-provider-options.ts
📚 Learning: 2025-12-13T17:09:09.794Z
Learnt from: CR Repo: TanStack/ai PR: 0 File: CLAUDE.md:0-0 Timestamp: 2025-12-13T17:09:09.794Z Learning: Applies to **/*.{ts,tsx} : Use Zod for runtime schema validation and type inference, particularly for tool input/output definitions with `toolDefinition()` and Zod schema inferenceApplied to files:
packages/typescript/ai-openrouter/src/text/text-provider-options.ts
🔇 Additional comments (1)
packages/typescript/ai-openrouter/src/text/text-provider-options.ts (1)
282-301: Content type definitions properly support multimodal inputs.The message content types now correctly include
audio_url,video_url, anddocument_urlalongsidetextandimage_url, with their corresponding field definitions. This properly reflects the adapter's multimodal capabilities.Note: Previous review flagged this section for having too-narrow content types. This has been resolved.
Actionable comments posted: 100
Note
Due to the large number of review comments, Critical severity comments were prioritized as inline comments.
Fix all issues with AI Agents 🤖
In @docs/adapters/gemini.md: - Around line 59-63: Remove the merge conflict markers and normalize the import to use the incoming symbol; replace the conflict block containing chat, toServerSentEventsResponse and toStreamResponse with a single clean import that includes chat and toStreamResponse from "@tanstack/ai" (i.e., remove the <<<<<<<, =======, >>>>>>> lines and ensure only import { chat, toStreamResponse } from "@tanstack/ai"; remains). In @docs/adapters/openai.md: - Around line 59-63: Remove the unresolved merge conflict markers (<<<<<<<, =======, >>>>>>>) in the import block and standardize the import to use toStreamResponse from @tanstack/ai (e.g., import { chat, toStreamResponse } ...). Then update any usages of toServerSentEventsResponse (the example around the previous line 74) to call toStreamResponse instead, ensuring all references and examples consistently use chat and toStreamResponse. In @docs/api/ai.md: - Around line 166-170: There is a merge conflict in the import and usage of the streaming helper: replace the old import and usage of toServerSentEventsResponse with the new toStreamResponse (or vice versa if the new API differs), ensuring the import line and the example call (where toServerSentEventsResponse(stream) is used) both use the same symbol; update the example documentation text to mention toStreamResponse and the expected stream parameter so the chat example (chat and stream variable) matches the consolidated streaming helper API across docs. In @docs/guides/runtime-adapter-switching.md: - Around line 104-108: The file contains unresolved merge markers and inconsistent return choices between toServerSentEventsResponse and toStreamResponse; pick one of these two (e.g., toStreamResponse) and replace every conflicted return (the occurrences around toServerSentEventsResponse/toStreamResponse, including the one passing { abortController }) with the chosen function, remove all Git conflict markers (<<<<<<<, =======, >>>>>>>) and ensure any imports or references for the chosen symbol (toStreamResponse or toServerSentEventsResponse) are present and the unused one is removed so the file is consistent across the three conflict regions. - Around line 16-20: Resolve the Git merge conflict in the import line by removing the conflict markers and keeping the correct export name from @tanstack/ai; replace the conflicting import so it imports the actual function used in this file (either toServerSentEventsResponse or toStreamResponse) alongside chat — based on the adapter split in PR #137 you should likely keep toStreamResponse and remove toServerSentEventsResponse and the conflict markers, ensuring any downstream usages in this file reference the retained symbol. - Around line 66-70: Resolve the merge conflict by removing the conflict markers and keeping a single consistent import statement that matches the other resolved import (use the newer toStreamResponse variant): import { chat, maxIterations, toStreamResponse } from '@tanstack/ai'; ensure you replace the conflicting line that mentions toServerSentEventsResponse and verify the same change was applied to the other identical conflict earlier so both imports are consistent. In @docs/guides/streaming.md: - Around line 33-37: Resolve the merge conflict by choosing a single streaming adapter import and making usage consistent: replace the conflicting import block so it imports chat and the streaming helper you decide to keep (either toServerSentEventsResponse or toStreamResponse) and then update the usage at the referenced call site (the occurrence currently calling toServerSentEventsResponse on line 49) to match that chosen symbol; ensure only one of toServerSentEventsResponse or toStreamResponse is imported and used throughout the file so imports and usage are consistent with the streaming API refactor. In @docs/guides/tool-approval.md: - Around line 60-64: Remove the Git conflict markers and pick the correct import API (replace the conflicted import block with a single clean import); if you adopt the incoming branch API, import toStreamResponse from "@tanstack/ai" alongside chat and update the later usage by replacing toServerSentEventsResponse(stream) with toStreamResponse(stream) so the import and call sites (the import line and the call that currently uses toServerSentEventsResponse) are consistent. In @docs/protocol/sse-protocol.md: - Around line 170-174: Resolve the Git conflict markers in the import block (remove <<<<<<<, =======, >>>>>>>) and make the import consistent by using the new API name: replace the import of toServerSentEventsResponse with toStreamResponse alongside chat; then update all references in the document (including the call site toServerSentEventsResponse(stream) and the descriptive section titled "What `toServerSentEventsResponse()` does") to use toStreamResponse and adjust wording if the behavior or parameters changed to match the new API signature. In @docs/reference/classes/ToolCallManager.md: - Around line 8-12: The docs file has unresolved Git conflict markers around multiple "Defined in" links pointing to tool-calls.ts with differing line numbers; open the source (the TypeScript file that defines ToolCallManager / tool call helpers) to confirm the correct line numbers, remove all conflict markers (<<<<<<<, =======, >>>>>>>) in ToolCallManager.md, and update each "Defined in:" link to the verified single correct line reference for the symbol(s) (e.g., the ToolCallManager and related functions in tool-calls.ts) so the file contains no merge markers and each link points to the authentic line number. - Around line 8-12: The markdown has merge conflict markers and setext-style headings in ToolCallManager.md (around the conflict block referencing activities/chat/tools/tool-calls.ts and at the other listed ranges) which violate the linter; remove the conflict markers and replace the underlined (setext) headings with atx-style headings (use leading # characters) for each affected section (including the blocks at 54-58, 78-82, 141-145, 164-168, 194-198, 214-218) so all headings are consistent with markdownlint-cli2 expectations. In @docs/reference/functions/chat.md: - Around line 12-16: Remove the unresolved merge markers and fix the `Defined in` anchor in docs/reference/functions/chat.md by verifying the actual declaration location in activities/chat/index.ts (check the definition of the exported Chat activity / function referenced) and update the link to the correct line number (either :976 or :945) or, better, point to the symbol location without a hard-coded line (e.g., link to the file or use a commit/anchor that targets the function name) so the conflicting HEAD/Incoming lines are eliminated. In @docs/reference/functions/createChatOptions.md: - Around line 12-16: Remove the leftover Git conflict markers in the "Defined in" link inside createChatOptions.md and update the line number to match the current source; replace the conflict block (the <<<<<<<, =======, >>>>>>> lines) with a single "Defined in: [activities/chat/index.ts:135]" or the correct line number that matches activities/chat/index.ts for the current codebase, ensuring the link points to the actual definition of createChatOptions in activities/chat/index.ts. - Around line 25-39: Resolve the merge conflict markers in the TAdapter/TSchema docs by removing the <<<<<<<, =======, and >>>>>>> lines and keeping a single, correct declaration for each type parameter; specifically update the TAdapter line to a single form (e.g., "TAdapter extends AnyTextAdapter" or "TAdapter extends [`AnyTextAdapter`](../type-aliases/AnyTextAdapter.md)") and update the TSchema block to a single, correct union (either "TSchema extends [`SchemaInput`](../type-aliases/SchemaInput.md) | `undefined` = `undefined`" or the Zod-based form using `ZodType`/`$ZodTypeInternals`), matching the actual types used by the codebase, and remove all conflict markers so the file contains only the chosen wording. In @docs/reference/functions/createSpeechOptions.md: - Around line 20-24: Remove the merge conflict markers and keep the HEAD variant that uses a hyperlink to TTSAdapter instead of plain code; specifically restore the documentation line so it links to the TTSAdapter interface while still showing the generic type parameters string and object (i.e., the linked TTSAdapter with the `<string, object>` generics), ensuring backticks/markdown formatting is valid. In @docs/reference/functions/createSummarizeOptions.md: - Around line 20-24: Resolve the merge markers around the TAdapter doc by removing the conflict tokens and keeping the documentation style consistent with the rest of the file: use the linked reference form for the generic type, i.e., change the conflicted block to `TAdapter` *extends* [`SummarizeAdapter`](../interfaces/SummarizeAdapter.md)\<`string`, `object`\>, ensuring the reference link and generic parameters are intact and no merge markers remain. In @docs/reference/functions/createTranscriptionOptions.md: - Around line 20-24: Remove the Git conflict markers (<<<<<<<, =======, >>>>>>>) around the TAdapter type declaration and leave a single resolved line; specifically update the declaration involving TAdapter and TranscriptionAdapter so it contains a single, clean type reference (e.g., TAdapter extends TranscriptionAdapter<`string`, `object`>) without any conflict markers or duplicated variants. In @docs/reference/functions/createVideoOptions.md: - Around line 20-24: Remove the Git conflict markers and the duplicated lines and render the TAdapter type parameter as a single, correct declaration: "TAdapter extends VideoAdapter with generic parameters string and object", using the linked documentation style for VideoAdapter (i.e., make VideoAdapter a documentation link) and keep the generics as string and object; ensure only that single resolved line remains (no conflict markers). In @docs/reference/functions/generateImage.md: - Around line 22-26: Resolve the Git conflict markers in generateImage.md by removing the <<<<<<<, =======, and >>>>>>> lines and keep the link-style declaration for the type constraint: replace the conflicting block with a single line using the markdown link to ImageAdapter (i.e., `TAdapter` extends [ImageAdapter](../interfaces/ImageAdapter.md)\<`string`, `object`, `any`, `any`\>), ensuring no leftover conflict markers remain and formatting matches surrounding docs. In @docs/reference/functions/generateSpeech.md: - Around line 22-26: Remove the unresolved git conflict markers and keep the HEAD variant: replace the conflict block with the documentation line that states TAdapter extends TTSAdapter using the markdown link (i.e., the version that links to the TTSAdapter docs), ensuring the generic parameters `<string, object>` remain; verify the final line reads the linked form (no conflict markers remaining) so the docs build correctly. In @docs/reference/functions/generateTranscription.md: - Around line 22-26: The file has unresolved git conflict markers around the TAdapter type parameter documentation; remove the conflict markers and choose the canonical form for the repository (prefer the linked interface reference `[TranscriptionAdapter](../interfaces/TranscriptionAdapter.md)<string, object>`), replacing the inline alternative `TranscriptionAdapter<string, object>` and ensure `TAdapter` is documented as extending that linked interface; repeat the same resolution across all other docs with the same pattern so no conflict markers (`<<<<<<<`, `=======`, `>>>>>>>`) remain and the repo can build. In @docs/reference/functions/generateVideo.md: - Around line 27-31: Remove the Git conflict markers (<<<<<<<, =======, >>>>>>>) and resolve the TAdapter line to a single, consistent Markdown form; replace the conflicted block with a single declaration that TAdapter extends VideoAdapter with generics (use the linked interface name VideoAdapter pointing to ../interfaces/VideoAdapter.md and show the generic parameters as inline code/string, e.g., VideoAdapter\<`string`, `object`\>) so the doc contains no conflict markers and matches nearby docs formatting. In @docs/reference/functions/getVideoJobStatus.md: - Around line 32-36: Resolve the unresolved merge conflict in the TAdapter type parameter by removing the git conflict markers and keeping the HEAD version: replace the conflict block with the markdown-linked form `TAdapter` *extends* [`VideoAdapter`](../interfaces/VideoAdapter.md)\<`string`, `object`\>, ensuring the link to the VideoAdapter docs remains and no leftover <<<<<<<, =======, or >>>>>>> markers remain in the file. In @docs/reference/functions/summarize.md: - Around line 22-26: There is an unresolved merge conflict in the TAdapter type parameter; remove the conflict markers and replace the block with the HEAD version that uses a proper markdown link to the SummarizeAdapter docs—i.e., ensure the declaration reads that TAdapter extends the linked SummarizeAdapter with type args string and object (refer to the TAdapter token and SummarizeAdapter symbol to find and fix the text). In @docs/reference/functions/toolDefinition.md: - Around line 12-16: Remove the unresolved git conflict markers (<<<<<<<, =======, >>>>>>>) in the header block and replace the two conflicting "Defined in:" lines with a single correct reference to the exported toolDefinition function; update the documentation link so it points to the actual toolDefinition export location (line 187) in activities/chat/tools/tool-definition.ts and ensure the text references the toolDefinition export name to avoid future ambiguity. - Around line 12-16: Remove the merge conflict markers (<<<<<<<, =======, >>>>>>>) from the "Defined in" line and convert the setext-style heading into an ATX-style heading by prefixing it with a single "#" (e.g., "# Defined in: ...") so the reference to tool-definition.ts (the tool-definition symbol) no longer uses underline-style heading and the Markdown lint rule MD003 is satisfied; pick the correct resolved URL/reference (the one from tool-definition.ts) and keep just that single ATX heading line. In @docs/reference/functions/toStreamResponse.md: - Around line 39-51: The example POST handler calls toStreamResponse with three arguments but the function accepts two, with abortController as an optional property of the second parameter; update the call in the POST function to pass the AbortController as part of the ResponseInit/options object (i.e., replace the third-argument usage with passing { abortController } as the second argument to toStreamResponse), and leave other code (chat, openaiText, messages) unchanged; optionally consider replacing deprecated toStreamResponse with toServerSentEventsStream if applicable. In @docs/reference/index.md: - Around line 36-39: Remove the git conflict markers and reconcile the API reference so it matches the finalized adapter refactor: delete removed adapter entries (e.g., ImageAdapter) and any stale type aliases, keep only the new adapter names and unified type aliases that exist in code (e.g., SummarizeAdapter/TextAdapter vs the new split adapters, TranscriptionAdapter/TTSAdapter/VideoAdapter as applicable, or consolidated AnyTextAdapter/AnyAudioAdapter/AnyVideoAdapter), update all Markdown links to point to the actual interface/type files, and resolve the function name conflict by using the final exported name convertZodToJsonSchema (replace convertSchemaToJsonSchema). Ensure all referenced symbols (ImageAdapter, SummarizeAdapter, TextAdapter, TranscriptionAdapter, TTSAdapter, VideoAdapter, Any*Adapter aliases, convertSchemaToJsonSchema/convertZodToJsonSchema) match the codebase exports and remove leftover conflict markers. In @docs/reference/interfaces/ApprovalRequestedStreamChunk.md: - Around line 8-12: Remove all Git merge markers from ApprovalRequestedStreamChunk.md and replace each conflicting "Defined in: [types.ts:...]" reference with the exact line number where the corresponding type is actually defined in types.ts: open the repository types.ts and locate the declaration for each referenced symbol (e.g., the ApprovalRequestedStreamChunk/type names shown in the file) and update each "Defined in" URL to use that precise line number (apply the same fix for all 8 conflict blocks), then save so no conflict markers remain and all links consistently point to the true locations. In @docs/reference/interfaces/DefaultMessageMetadataByModality.md: - Around line 8-12: The docs contain unresolved git merge conflict markers propagated from the source type file; open the TypeScript source that defines DefaultMessageMetadataByModality (the types.ts entry for that type), remove the conflict markers (<<<<<<<, =======, >>>>>>>), reconcile the conflicting variants into the correct unified definition, ensure no other conflict markers remain in that file (and resolve similar conflicts at the other noted positions), then regenerate the docs by running the project's doc generation command (pnpm generate-docs) so the docs/reference/*.md files are rebuilt without conflict annotations. In @docs/reference/interfaces/DocumentPart.md: - Around line 8-12: Remove all unresolved Git merge conflict markers (<<<<<<<, =======, >>>>>>>) from DocumentPart.md and replace the incorrect reference at the first conflict with the correct location; update the "Defined in" link to point to types.ts:173 where DocumentPart is actually defined, then scan the rest of the file (conflicts at the other markers reported) to resolve and remove any remaining markers so the file is clean and references are consistent. In @docs/reference/interfaces/DoneStreamChunk.md: - Around line 8-12: Remove the Git conflict markers and update all seven "Defined in" references in the docs files to point to the current locations in types.ts (e.g., DoneStreamChunk is at line 708, BaseStreamChunk at line 675) — either regenerate the docs from TypeDoc if available to ensure all anchors/line numbers are correct, or manually replace each conflicting pair with the single correct "Defined in: [types.ts:708]" (or the appropriate symbol's current line) for the properties listed at lines 8-12, 26-30, 40-44, 58-62, 76-80, 94-98, and 112-116 so there are no <<<<<<< / ======= / >>>>>>> markers left. In @docs/reference/interfaces/ErrorStreamChunk.md: - Around line 8-12: This file contains unresolved Git merge conflict markers (e.g., <<<<<<<, =======, >>>>>>>) in ErrorStreamChunk.md; rebase your branch onto the latest adapter-structure changes, remove the conflict markers, and reconcile the two versions by keeping the updated documentation that matches the new adapter split (matching how other docs were resolved), then regenerate the docs (or manually update the definitions referencing the types declaration) and ensure the same fixes are applied to the other reported ranges (26-30, 52-56, 70-74, 88-92, 106-110). In @docs/reference/interfaces/ImageGenerationOptions.md: - Around line 8-12: Resolve the merge conflicts by choosing the post-refactor line references (the cfa7844 offsets) for the ImageGenerationOptions interface and its properties: set the "Defined in" reference for ImageGenerationOptions to types.ts:787, for model to types.ts:791, for prompt to types.ts:793, for numberOfImages to types.ts:795, for size to types.ts:797, and for modelOptions to types.ts:799; update each conflicting "Defined in" block to use these cfa7844 line numbers and remove the conflict markers. In @docs/reference/interfaces/ImagePart.md: - Around line 8-12: The docs file contains unresolved Git conflict markers around the ImagePart reference sections; remove all conflict markers (<<<<<<<, =======, >>>>>>>) in the four affected blocks and replace the incorrect "Defined in" links with the correct line references for the ImagePart interface (use line numbers 137 for the interface and 138, 140, 142 for the type, source, metadata properties) so every occurrence (the blocks at lines ~8–12, ~32–36, ~48–52, ~64–68) points to those updated line numbers and the file contains no merge markers remaining. - Line 8: Remove the leftover merge conflict markers and convert any setext-style headings in ImagePart.md to ATX-style headings (prefix with one or more '#' as appropriate) at the affected locations (around the previously conflicted area and the other flagged spots near lines 32, 48, and 64); ensure there are no underline-style headings or dangling "===" / "---" lines, and keep heading levels consistent with surrounding docs. In @docs/reference/interfaces/SummarizationResult.md: - Around line 8-12: The documentation file SummarizationResult.md contains unresolved merge conflict markers for five "Defined in" references (blocks around lines 8–12, 22–26, 36–40, 50–54, 64–68); inspect the canonical types.ts to determine the correct definition line(s) for the SummarizationResult type and replace each conflict block with a single, consistent "Defined in: [types.ts:NNN](...)" entry using the accurate line numbers (remove all conflict markers <<<<<<<, =======, >>>>>>>), and ensure all five occurrences reference the same validated line number from types.ts. In @docs/reference/interfaces/TextCompletionChunk.md: - Around line 8-12: The TextCompletionChunk.md contains unresolved Git conflict markers; remove all conflict blocks and merge artifacts and update the "Defined in" link to point to types.ts line 765 for the TextCompletionChunk interface, and update the property links to lines 766–775 for id, model, content, role, finishReason, and usage; ensure the final file references the single correct definition (TextCompletionChunk) and properties without any conflict markers or duplicate entries so the docs build cleanly. In @docs/reference/interfaces/ThinkingPart.md: - Around line 8-12: The file contains unresolved git conflict markers in the "Defined in" lines for the ThinkingPart interface; remove the conflict markers and update the three "Defined in" references so they point to the correct lines in packages/typescript/ai/src/types.ts: set the interface definition "Defined in" to line 282, the "type" property reference to line 283, and the "content" property reference to line 284 (ensure no remaining <<<<<<<, =======, >>>>>>> markers remain). In @docs/reference/interfaces/ToolCallPart.md: - Around line 8-12: Resolve the eight "Defined in" merge conflicts in docs/reference/interfaces/ToolCallPart.md by removing the conflict markers and replacing each conflicting link with a single verified reference to the current source location (use types.ts:258 where ToolCallPart is actually defined); ensure all 8 occurrences (lines groups around 8–12, 22–26, 56–60, 70–74, 84–88, 98–102, 114–118, 128–132) consistently point to [types.ts:258] and update the URL to the correct blob/commit path if needed, then run a quick search for other "Defined in" entries to confirm no remaining conflict markers. - Around line 8-12: Resolve and remove the git conflict markers (<<<<<<<, =======, >>>>>>>) in the "Defined in:" blocks, pick the correct target link/version, and convert each setext-style "Defined in: [types.ts:...](...)" heading to an atx-style heading by prefixing it with "# " (ensure you update all occurrences noted: the current block and ranges 22-26, 56-60, 70-74, 84-88, 98-102, 114-118, 128-132), keeping the chosen link text intact and making the heading style consistent with MD003. In @docs/reference/interfaces/ToolCallStreamChunk.md: - Around line 8-12: The docs file ToolCallStreamChunk.md contains unresolved git conflict markers in the "Defined in" metadata (multiple blocks showing differing line numbers like 676 vs 671) which must be removed; resolve by fixing the underlying conflicts in the source types file (types.ts) for the related symbols (e.g., ToolCallStreamChunk and other referenced types), then regenerate the documentation (TypeDoc) so the "Defined in" line-number references are correct, or if you must edit the generated doc manually remove all conflict markers and pick the correct line numbers from the branch you intend to keep (cfa7844), ensuring the final references match the current types.ts. In @docs/reference/interfaces/ToolConfig.md: - Around line 8-12: Remove the unresolved Git conflict markers around the Defined in link in ToolConfig.md, keeping a single correct "Defined in" line; update the URL reference so it points to types.ts at the correct line for the ToolConfig interface (line 444) and ensure there are no leftover <<<<<<<, =======, or >>>>>>> markers in the file; verify the link format remains consistent with other docs entries and commit the cleaned file. - Around line 6-9: Replace the setext-style heading for "Interface: ToolConfig" with an ATX-style heading: change the underlined title into a single line starting with the appropriate number of # (e.g., "# Interface: ToolConfig") and remove the subsequent dash underline so the file complies with MD003; ensure the rest of the file keeps ATX headings consistently and that the merge conflict markers have been resolved. In @docs/reference/interfaces/ToolDefinition.md: - Around line 76-80: This file contains unresolved Git merge conflict markers in ToolDefinition.md for several property blocks (including ranges 76-80, 105-109, 153-157, 215-219, 235-239, 264-268, 284-288); remove the conflict markers (<<<<<<<, =======, >>>>>>>) and pick the correct "Defined in" reference for each property by either regenerating the docs from the post-PR types.ts (which moved symbols during adapter restructuring) or manually selecting the correct branch variant, then update the "Defined in: types.ts:NNN" references to the accurate line numbers or symbol locations and regenerate the documentation to ensure all seven property definitions are consistent. In @docs/reference/interfaces/ToolDefinitionInstance.md: - Around line 52-56: Resolve the seven merge markers in ToolDefinitionInstance.md by updating each "Defined in" reference for the properties description, execute, inputSchema, metadata, name, needsApproval, and outputSchema to the correct line numbers from the merged types.ts (use the incoming branch locations introduced by the adapter-restructure PR if those match the merged file), remove the conflict markers (<<<<<<<, =======, >>>>>>>), and make all "Defined in" references consistent across the file (also update the other ranges noted: 81-85, 129-133, 191-195, 211-215, 240-244, 260-264); after editing, verify each referenced line number points to the actual type declaration in the final merged types.ts and adjust numbers to match exactly. In @docs/reference/interfaces/ToolInputAvailableStreamChunk.md: - Around line 8-12: Resolve the unresolved merge conflicts in the source types file by fixing the two conflict regions: choose and consolidate the correct import for the schema type (pick either StandardJSONSchemaV1 or Zod and remove the conflict markers around the imports) and reconcile the conflicting outputSchema definition/documentation (ensure the ToolInputAvailableStreamChunk-related outputSchema type and its JSDoc are consistent and remove conflict markers). After cleaning those two regions so the file compiles, run pnpm generate-docs to regenerate the docs and clear all autogenerated conflict markers; do not manually edit generated docs. In @docs/reference/interfaces/ToolResultPart.md: - Around line 8-12: The file docs/reference/interfaces/ToolResultPart.md contains six unresolved git merge conflicts showing alternate line references; resolve them by removing all conflict markers and reconciling the competing lines so the documentation consistently references the actual ToolResultPart declaration (interface ToolResultPart) in packages/typescript/ai/src/types.ts at its current location (now starting at line 274 with properties on lines 275-279), update every “Defined in:” and property line links to point to types.ts:274–279, and ensure the final markdown is a single, clean definition matching the ToolResultPart shape. In @docs/reference/interfaces/TranscriptionOptions.md: - Around line 8-12: Resolve the merge conflicts in docs/reference/interfaces/TranscriptionOptions.md by removing all conflict markers (<<<<<<<, =======, >>>>>>>) and ensure the "Defined in" references for TranscriptionOptions and its properties point to the correct TypeScript source line numbers: TranscriptionOptions at types.ts:966, model at types.ts:970, audio at types.ts:972, language at types.ts:974, prompt at types.ts:976, responseFormat at types.ts:978, and modelOptions at types.ts:980; update all seven occurrences accordingly so the file no longer contains conflict markers and all links reference the correct lines. - Around line 8-12: The file contains unresolved git conflict markers (e.g., <<<<<<< HEAD and >>>>>>> cfa7844) inside setext-style heading regions for the "Defined in:" references; remove all conflict markers and convert each affected "Defined in:" reference to an atx-style heading (prefix with "# ") so lines like "Defined in: [types.ts:953]..." become a single line heading starting with "# Defined in: ..." and repeat this fix for the other occurrences mentioned (31-35, 47-51, 63-67, 79-83, 95-99, 111-115). In @docs/reference/interfaces/TranscriptionSegment.md: - Around line 8-12: Resolve the unresolved merge markers in the source types file that generated TranscriptionSegment.md: open packages/typescript/ai/src/types.ts, find the TranscriptionSegment type definition around the conflicting region (near the previous line refs ~968–973) and remove the <<<<<<<, =======, >>>>>>> blocks by selecting the correct variant (or merging the changes) so the type has a single, consistent definition; save and commit that fix, then regenerate docs by running the repository's documentation script (e.g., npm/yarn run generate-docs) so TranscriptionSegment.md is recreated without conflict markers. In @docs/reference/interfaces/VideoJobResult.md: - Around line 8-12: The file docs/reference/interfaces/VideoJobResult.md contains unresolved merge conflict markers in the "Defined in" lines; remove the conflict markers (<<<<<<<, =======, >>>>>>>) and update the three "Defined in" references so they point to the current locations in packages/typescript/ai/src/types.ts: use line 880 for the VideoJobResult interface, line 882 for the jobId property, and line 884 for the model property; ensure all three occurrences are cleaned up and formatted consistently with the other docs entries. In @docs/reference/interfaces/VideoUrlResult.md: - Around line 8-12: Remove all git conflict markers from docs/reference/interfaces/VideoUrlResult.md and update the "Defined in" source references to the correct lines in types.ts: set the interface reference to line 908 and update the property references so jobId points to line 910, url to line 913, and expiresAt to line 916; ensure there are no remaining <<<<<<<, =======, >>>>>>> blocks anywhere in the file and that each "Defined in:" link uses the new types.ts line numbers. In @docs/reference/type-aliases/AgentLoopStrategy.md: - Around line 12-16: Resolve the merge conflict markers in the AgentLoopStrategy doc by removing the HEAD/other-branch conflict lines and leaving a single correct "Defined in" reference; replace the incorrect links pointing to types.ts:560 or :600 with the correct link to types.ts:564 and ensure the line reads "Defined in: [types.ts:564](https://github.com/TanStack/ai/blob/main/packages/typescript/ai/src/types.ts#L564)" so the documentation points to the actual definition of AgentLoopStrategy. In @docs/reference/type-aliases/ConstrainedContent.md: - Around line 15-19: The file docs/reference/type-aliases/ConstrainedContent.md contains unresolved merge conflict markers (<<<<<<<, =======, >>>>>>>) around the "Defined in" source link; remove the conflict markers and replace the two conflicting references with the single correct source link pointing to the actual location of the ConstrainedContent type in the current types.ts (locate the ConstrainedContent definition in types.ts and use that file:line URL), e.g. update the "Defined in:" line to the one matching the current codebase and remove any leftover conflict text so the markdown shows only the accurate reference. In @docs/reference/type-aliases/ConstrainedModelMessage.md: - Around line 12-16: Remove the unresolved merge conflict markers and the two incorrect references, and replace that entire conflict block with the correct single reference for the ConstrainedModelMessage type: "Defined in: [types.ts:313](https://github.com/TanStack/ai/blob/main/packages/typescript/ai/src/types.ts#L313)"; ensure the final line mentions ConstrainedModelMessage so the symbol is clear and no conflict markers (<<<<<<<, =======, >>>>>>>) remain. In @docs/reference/type-aliases/ContentPartForInputModalitiesTypes.md: - Around line 14-18: The markdown contains unresolved git conflict markers for the "Defined in" link for ContentPartForInputModalitiesTypes; remove the conflict markers (<<<<<<<, =======, >>>>>>>) and replace the two conflicting references with a single correct reference pointing to types.ts line 205 (i.e., "Defined in: [types.ts:205](.../types.ts#L205)"); ensure the heading/name ContentPartForInputModalitiesTypes remains intact and that no other conflict remnants remain in the file. In @docs/reference/type-aliases/InferSchemaType.md: - Around line 12-16: Resolve the unresolved merge conflicts in both docs/reference/type-aliases/InferSchemaType.md and the source types file by removing the conflict markers and merging the correct changes; in the source file (types.ts) find the InferSchemaType type export and finish resolving any <<<<<<< / ======= / >>>>>>> sections so the file is clean, then update the "Defined in" link in InferSchemaType.md to point to the actual exported location of InferSchemaType in types.ts (use the final line number or a stable anchor if available) so the documentation no longer references conflicting line numbers. In @docs/reference/type-aliases/InputModalitiesTypes.md: - Around line 12-16: The docs file docs/reference/type-aliases/InputModalitiesTypes.md contains unresolved merge conflict markers at the blocks around lines 12–16, 26–30, and 40–44 caused by PR #137 changing adapter references and line numbers; do not edit the generated file directly—instead resolve the underlying merge in the source (ensure types.ts is merged so the type definition lines are stable around the actual definition near lines ~304–306), then regenerate the docs by running the documentation generator (invoke pnpm run generate-docs which runs scripts/generate-docs.ts using @tanstack/typedoc-config) so the conflict markers and incorrect type links are removed and the references to the correct types.ts line numbers are updated. In @docs/reference/type-aliases/MessagePart.md: - Around line 16-20: Resolve the unresolved merge conflict in the MessagePart docs by removing the conflict markers (<<<<<<<, =======, >>>>>>>) and accepting the HEAD variant so the "Defined in" link points to types.ts:283 (the actual MessagePart definition); update the file to only include the correct reference for MessagePart and ensure no leftover conflict text remains. In @docs/reference/type-aliases/ModalitiesArrayToUnion.md: - Around line 12-16: This doc contains unresolved Git conflict markers around the ModalitiesArrayToUnion reference; remove the conflict markers (<<<<<<<, =======, >>>>>>>) and keep the HEAD variant that points to the correct JSDoc location (the version referencing line 218), deleting the stale competing line that points to line 269 so the file contains a single clean "Defined in: ..." line for ModalitiesArrayToUnion. In @docs/reference/type-aliases/Modality.md: - Around line 12-16: Resolve the merge conflict markers in the "Defined in" reference for the Modality type by removing the <<<<<<<, =======, and >>>>>>> lines and keeping a single correct link; replace the conflicting two links with one link that points to the Modality definition in types.ts (update the reference to the file location where the Modality type is actually defined) so the documentation builds cleanly. In @docs/reference/type-aliases/SchemaInput.md: - Around line 14-18: Remove the leftover git conflict markers in SchemaInput.md around the "Defined in" line and replace the conflicting block with the correct reference text: set the "Defined in:" link to types.ts line 81 (use "Defined in: [types.ts:81](https://github.com/TanStack/ai/blob/main/packages/typescript/ai/src/types.ts#L81)") so the file no longer contains <<<<<<<, =======, or >>>>>>> markers and points to the specified location. In @docs/reference/type-aliases/StreamChunk.md: - Around line 20-24: Remove the unresolved merge conflict markers (<<<<<<<, =======, >>>>>>>) from StreamChunk.md and choose the correct "Defined in" link: verify the current line number of StreamChunk's type in packages/typescript/ai/src/types.ts (after the adapter restructure) and update the reference to that exact line (either types.ts:735 or types.ts:740 as appropriate); ensure only the final resolved line with a single "Defined in" link remains and no conflict markers are left. In @docs/reference/type-aliases/StreamChunkType.md: - Around line 20-24: The file docs/reference/type-aliases/StreamChunkType.md contains unresolved Git merge conflict markers (<<<<<<<, =======, >>>>>>>) around the "Defined in" link; remove the conflict markers and keep the correct "Defined in" reference that matches the current location of StreamChunkType in packages/typescript/ai/src/types.ts (verify the actual line number in that file), then update the Markdown link to the correct line number and commit the cleaned file so the documentation can parse and render properly. In @examples/ts-react-chat/src/routes/api.tanchat.ts: - Around line 6-10: Resolve the unresolved git conflict by removing the conflict markers and keep the cleaner convenience import: replace the conflicted import entry with toServerSentEventsResponse (remove toServerSentEventsStream and the <<<<<<</=======/>>>>>>> markers), ensure the import list is comma-correct and deduplicated, and update any local usages to call toServerSentEventsResponse (it internally uses toServerSentEventsStream and sets SSE headers) so no header duplication remains. - Around line 129-143: Resolve the merge conflict by using the convenience wrapper toServerSentEventsResponse instead of manually creating a ReadableStream and new Response; remove the toServerSentEventsStream/readableStream/Response block and return toServerSentEventsResponse(stream, { abortController }) so headers and stream creation are handled by the existing implementation (keep the existing variables stream and abortController). In @examples/ts-solid-chat/src/routes/api.chat.ts: - Around line 78-92: Resolve the merge conflict by keeping the convenience wrapper call toServerSentEventsResponse instead of manually creating a Response with toServerSentEventsStream; replace the conflicting block so you return toServerSentEventsResponse(stream, { abortController }) and remove the manual creation of readableStream/new Response and the explicit headers, ensuring you still pass the existing stream and abortController variables to the wrapper. - Around line 2-6: Resolve the unresolved git conflict markers in the import line by removing the conflict blocks (<<<<<<<, =======, >>>>>>>) and import the recommended symbol; change the import to use toServerSentEventsResponse (not toServerSentEventsStream) alongside chat and maxIterations so the module imports are consistent with the rest of the code and avoid syntax errors. Ensure any subsequent usage refers to toServerSentEventsResponse if that is what's expected by the surrounding code (e.g., where you call toServerSentEventsResponse(...)); finally run a quick compile to confirm there are no remaining conflict markers or mismatched symbol names. In @examples/ts-svelte-chat/src/routes/api/chat/+server.ts: - Around line 123-134: Remove the Git conflict markers and the old toServerSentEventsResponse call and adopt the new streaming approach: call toServerSentEventsStream(stream, abortController) to get readableStream, then return a new Response(readableStream, { headers: { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache', Connection: 'keep-alive' } }); ensure abortController is passed to toServerSentEventsStream and the obsolete toServerSentEventsResponse reference is deleted. - Around line 5-9: There is an unresolved git merge conflict in the import list around toServerSentEventsResponse / toServerSentEventsStream; remove the conflict markers (<<<<<<, =======, >>>>>>>), delete the toServerSentEventsResponse import, and keep toServerSentEventsStream in the import list; also scan for any usages of toServerSentEventsResponse in this file (e.g., in the handler function) and rename them to toServerSentEventsStream to match the new adapter API (ensure the import and usage names match exactly). In @packages/typescript/ai-anthropic/package.json: - Around line 49-53: The package.json has an unresolved git conflict for the peer dependency "@tanstack/ai" with leftover conflict markers; remove the conflict markers and set the dependency value to "workspace:*" (replace the "<<<<<<<", "=======", and ">>>>>>>", and change any "workspace:^" to "workspace:*") so the JSON is valid and uses the correct workspace protocol. In @packages/typescript/ai-anthropic/src/tools/custom-tool.ts: - Around line 1-6: Remove the Git conflict markers and fix the import lines in custom-tool.ts: delete the <<<<<<<, =======, and >>>>>>> markers and ensure the file imports the used types from '@tanstack/ai' (include JSONSchema, SchemaInput and Tool since SchemaInput is used in the file) and remove the unused 'z' import from 'zod'. In @packages/typescript/ai-client/package.json: - Around line 51-55: The package.json contains unresolved Git conflict markers around the "zod" dependency making the file invalid; open packages/typescript/ai-client/package.json, remove the conflict markers (<<<<<<<, =======, >>>>>>>) and choose the correct "zod" version (replace the conflicted block with a single "zod" entry), likely keeping "zod": "^4.2.0" to match the updated adapter changes so the JSON is valid and installs/builds succeed. In @packages/typescript/ai-gemini/package.json: - Around line 50-54: Remove the unresolved merge conflict markers around the @tanstack/ai dependency in package.json and set the dependency to use the workspace protocol recommended (change the conflicted block to "\"@tanstack/ai\": \"workspace:*\""); ensure you delete the <<<<<<<, =======, and >>>>>>> lines and scan the rest of package.json for any other conflict markers so the file parses correctly. In @packages/typescript/ai-ollama/package.json: - Around line 55-59: Remove the Git conflict markers and accept the incoming change for the @tanstack/ai peerDependency: replace the conflicted block containing "@tanstack/ai": "workspace:^" and the surrounding <<<<<<<, =======, >>>>>>> markers with a single entry using "workspace:*" so the peerDependencies JSON is valid and consistent with the dependencies section; ensure the final package.json has no merge markers and uses "@tanstack/ai": "workspace:*". - Around line 44-47: Remove the git conflict markers (<<<<<<<, =======, >>>>>>>) from the package.json and accept the incoming change that adds the dependency entry "@tanstack/ai": "workspace:*" into the dependencies object; ensure the dependencies object remains valid JSON (proper commas and quoting) after adding the line so the file parses and the workspace:* protocol is used for the internal package reference. In @packages/typescript/ai-ollama/src/adapters/text.ts: - Around line 297-323: Remove the Git conflict markers and keep the incoming change (no type assertion) in the convertToolsToOllamaFormat return mapping: assign parameters: tool.inputSchema ?? { type: 'object', properties: {}, required: [] } (remove the "as OllamaTool['function']['parameters']" cast and delete the HEAD/<<<<<<</>>>>>>> markers), ensuring the resulting object still returns { type: 'function', function: { name: tool.name, description: tool.description, parameters: ... } } as before. In @packages/typescript/ai-openai/package.json: - Around line 50-54: Remove the Git conflict markers and set the peerDependency entry for "@tanstack/ai" to use the workspace:* protocol (replace the conflicted block with "@tanstack/ai": "workspace:*") so package.json is valid and matches the project's internal dependency convention. In @packages/typescript/ai-react/package.json: - Around line 51-56: Resolve the Git conflict markers in package.json devDependencies by removing the conflict lines and merging the two entries so both "vite": "^7.2.7" and "zod": "^4.1.13" appear as valid JSON entries; update the devDependencies object (where "vite" and the added "zod" appear) to include both dependencies and ensure there is a trailing comma only where valid JSON requires it and no <<<<<<<, =======, >>>>>>> markers remain. In @packages/typescript/ai-solid/README.md: - Around line 160-164: There are unresolved merge conflict markers using toServerSentEventsResponse vs toStreamResponse; resolve all occurrences by choosing the new streaming API (replace toServerSentEventsResponse with toStreamResponse), remove all conflict markers (<<<<<<<, =======, >>>>>>>) and ensure the import line (import { chat, toStreamResponse } from '@tanstack/ai') and every usage (e.g., calls to toStreamResponse) are updated consistently across the file (including the other listed locations) so the adapter compiles with the new toStreamResponse API. In @packages/typescript/ai-svelte/package.json: - Around line 58-63: The package.json contains unresolved git conflict markers around the dependencies entry (see the "vite" and "zod" lines) which makes the JSON invalid; remove the conflict markers and merge the entries so dependencies include both "vite": "^7.2.7" and "zod": "^4.1.13" (or keep the intended one if zod was not meant to be added), ensuring the resulting package.json is valid JSON (commas and quoting correct) and run a quick JSON lint or npm install to verify. - Line 62: Remove the unresolved git merge conflict markers (<<<<<<<, =======, >>>>>>>) from package.json and replace the "zod" dependency entry so it is a valid JSON string without conflict artifacts; change the "zod" version to "^4.2.0" to match the monorepo standard, save the file and regenerate/update lockfiles (npm/yarn/pnpm) so all packages are aligned. In @packages/typescript/ai/src/activities/chat/index.ts: - Around line 11-19: Resolve all git conflict markers (<<<<<<<, =======, >>>>>>>) in this file by accepting the incoming Zod-based changes: remove usages/imports of SchemaInput, isStandardSchema, parseWithStandardSchema, and convertSchemaToJsonSchema and replace them with z.ZodType imports/usages and convertZodToJsonSchema; update any parsing/validation code that previously called parseWithStandardSchema to use Zod parsing/validation on z.ZodType schemas; ensure all occurrences of the conflict markers (around imports and the blocks referencing SchemaInput/Standard Schema) are cleaned up and the file consistently uses convertZodToJsonSchema and z.ZodType throughout. In @packages/typescript/ai/src/activities/chat/tools/tool-calls.ts: - Around line 9-20: Remove the Git conflict markers and accept the incoming addition that defines isZodSchema: delete the<<<<<<< HEAD/=======/>>>>>>> cfa7844 markers and keep the import type { z } from 'zod' plus the isZodSchema(schema: SchemaInput | undefined): schema is z.ZodType function; ensure SchemaInput is in scope (or adjust the parameter type) and that any usages of isZodSchema reference the same symbol name, then run TypeScript build to confirm no parsing errors remain. - Around line 16-19: Delete the unused duplicate function isZodSchema from this file (it’s already implemented in zod-converter.ts and not referenced here); remove any now-unused imports (e.g., z) introduced only for that helper, and verify existing code continues to use isStandardSchema where needed (no replacements required in this file since isZodSchema is not called). In @packages/typescript/ai/src/activities/chat/tools/tool-definition.ts: - Around line 1-5: Resolve the merge conflict by removing the conflict markers and keeping both required type imports: add back `import type { StandardJSONSchemaV1 } from '@standard-schema/spec'` and also import `type { z } from 'zod'` (or `import type { ZodType } from 'zod'` if more appropriate) at the top of the file, then ensure `InferToolInput` and `InferToolOutput` still reference `StandardJSONSchemaV1` as used below and any new zod-related types from the incoming branch are used where needed; delete the <<<<<<<, =======, and >>>>>>> lines so the file parses cleanly. In @packages/typescript/ai/src/index.ts: - Around line 62-69: Resolve the leftover merge conflict markers and restore consistent exports: remove the conflict delimiters and export the actual utilities found in stream-to-response.ts (ensure toServerSentEventsResponse and toHttpResponse are exported) while preserving the new toStreamResponse name as either an alias to toServerSentEventsResponse or as an additional export for backward compatibility; update the export list that currently includes toHttpStream to include both toServerSentEventsResponse (or its alias toStreamResponse) and toHttpResponse so consumers of toStreamResponse and existing callers of toServerSentEventsResponse/toHttpResponse continue to work. - Around line 50-56: Resolve the merge conflict by exporting both converters to preserve backward compatibility: keep export of convertZodToJsonSchema (from './activities/chat/tools/zod-converter') and also restore or alias convertSchemaToJsonSchema so existing consumers still work; update the module export block in index.ts to re-export convertZodToJsonSchema and either re-export a convertSchemaToJsonSchema symbol (pointing to the Zod implementation) or import and re-export the original generic converter if it still exists, ensuring both convertZodToJsonSchema and convertSchemaToJsonSchema symbols are present. In @packages/typescript/ai/src/stream-to-response.ts: - Around line 48-57: Resolve the leftover merge conflict markers in the JSDoc for toServerSentEventsStream by removing the conflict lines (<<<<<<<, =======, >>>>>>>) and preserving the intended comment content (including the example block showing usage with chat, openaiText(), model "gpt-4o", and toServerSentEventsStream). Ensure the JSDoc is validly formatted (no leftover markers or duplicated sections) so the file packages/typescript/ai/src/stream-to-response.ts compiles. In @packages/typescript/ai/src/types.ts: - Around line 628-643: Resolve the merge conflict for the TextOptions.outputSchema property by using Zod per project guidelines: change the type to z.ZodType and update the JSDoc to state "Zod schema for structured output"; ensure the code imports z from 'zod' and remove/replace any references to SchemaInput in this type definition so the adapter expects a Zod schema (symbol: outputSchema on the TextOptions type). - Around line 1-5: Remove the Git conflict markers and resolve the import to match the new adapter structure: delete the StandardJSONSchemaV1 import and the conflict markers, and import the zod symbol and BaseTextAdapter instead (e.g., import type { z } from 'zod' and import type { BaseTextAdapter } from the adapter module you now use). Ensure the file exports/types reference z and BaseTextAdapter as needed and that no leftover conflict markers or the old StandardJSONSchemaV1 symbol remain. In @packages/typescript/ai/tests/standard-converter.test.ts: - Around line 3-13: This file contains a git merge conflict that mixed two distinct tests; remove the conflict markers and keep the HEAD version as standard-converter.test.ts that imports convertSchemaToJsonSchema, isStandardJSONSchema, isStandardSchema, parseWithStandardSchema, and validateWithStandardSchema from schema-converter; then create a separate zod-converter.test.ts in the same tests directory that imports convertZodToJsonSchema from zod-converter (so convertZodToJsonSchema tests live separately); ensure no leftover conflict markers remain and each test file only imports the functions it needs. In @packages/typescript/ai/tests/stream-to-response.test.ts: - Around line 4-9: Remove the Git conflict markers and fix the import so it matches what the test actually uses: either import toStreamResponse if the test calls toStreamResponse, or import toServerSentEventsResponse if that is referenced; if both are used, import both. Make the import look like a normal ES import (e.g., "toStreamResponse" or "toServerSentEventsResponse" or both) from '../src/stream-to-response' without any conflict markers. In @testing/panel/package.json: - Around line 35-39: The package.json contains unresolved Git conflict markers around the "zod" dependency which breaks JSON parsing; remove the conflict markers (<<<<<<<, =======, >>>>>>>) and pick the correct version string for "zod" (e.g., replace the conflicted block with a single "zod": "^4.2.0" entry or whichever version your project requires), ensuring surrounding commas and JSON syntax remain valid so the file parses and installs correctly. In @testing/panel/src/routes/api.addon-chat.ts: - Around line 74-88: There is a merge conflict in the response handling: either call toServerSentEventsResponse(stream, { abortController }) which returns a ready Response with proper headers, or use toServerSentEventsStream(stream, abortController) and wrap that readable stream in a new Response with the SSE headers and keep-alive settings; pick one consistent approach, remove the conflict markers and the unused branch, and ensure the chosen branch supplies the abortController to the underlying SSE helper (reference to toServerSentEventsResponse, toServerSentEventsStream, stream, and abortController). - Around line 2-6: Resolve the unresolved Git conflict markers by removing the <<<<<<<, =======, and >>>>>>> lines and pick the new adapter import; replace the conflicted import with a single clean import line that includes chat, maxIterations and the chosen SSE helper—either toServerSentEventsStream (as in the feature branch) or preferably toServerSentEventsResponse (the higher-level helper that wraps toServerSentEventsStream and sets SSE headers automatically); then update any downstream usage to call the chosen helper (update calls referencing toServerSentEventsStream to use toServerSentEventsResponse if you opt for the higher-level helper). In @testing/panel/src/routes/api.chat.ts: - Around line 8-12: The import contains unresolved merge conflict markers and two competing symbols; remove the conflict markers (<<<<<<<, =======, >>>>>>>) and keep only the clean import for toServerSentEventsResponse (drop toServerSentEventsStream), then verify any local references that expect the stream variant use toServerSentEventsResponse instead so SSE headers are handled properly (e.g., update call sites that import or invoke toServerSentEventsStream to use toServerSentEventsResponse).@@ -56,4 +56,8 @@5656 ## Example: Chat Completion57575858 ```typescript59+<<<<<<< HEAD5960 import { chat, toServerSentEventsResponse } from "@tanstack/ai";61+=======62+import { chat, toStreamResponse } from "@tanstack/ai";63+>>>>>>> cfa7844 (feat: split up adapters into functionalities and add generate function (#137))⚠️ Potential issue | 🔴 Critical
Resolve merge conflict markers and update example code.
Unresolved merge conflict markers are present in the example code. Additionally, line 74 still references
toServerSentEventsResponsewhich should be updated totoStreamResponseto match the resolved import.🔎 Proposed fix
-<<<<<<< HEAD -import { chat, toServerSentEventsResponse } from "@tanstack/ai"; -======= -import { chat, toStreamResponse } from "@tanstack/ai"; ->>>>>>> cfa7844 (feat: split up adapters into functionalities and add generate function (#137)) +import { chat, toStreamResponse } from "@tanstack/ai"; import { openaiText } from "@tanstack/ai-openai"; export async function POST(request: Request) { @@ -71,7 +67,7 @@ messages, }); - return toServerSentEventsResponse(stream); + return toStreamResponse(stream); }📝 Committable suggestion
‼️ IMPORTANT Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
Suggested change59-<<<<<<< HEAD60-import { chat, toServerSentEventsResponse } from "@tanstack/ai";61-=======62-import { chat, toStreamResponse } from "@tanstack/ai";63->>>>>>> cfa7844 (feat: split up adapters into functionalities and add generate function (#137))59+import { chat, toStreamResponse } from "@tanstack/ai";60+import { openaiText } from "@tanstack/ai-openai";61+62+export async function POST(request: Request) {63+ const stream = await chat({64+ model: new OpenAIAdapter({65+ apiKey: process.env.OPENAI_API_KEY,66+ }),67+ messages,68+ });69+70+ return toStreamResponse(stream);71+}🤖 Prompt for AI Agents
In @docs/adapters/openai.md around lines 59-63, Remove the unresolved merge conflict markers (<<<<<<<, =======, >>>>>>>) in the import block and standardize the import to use toStreamResponse from @tanstack/ai (e.g., import { chat, toStreamResponse } ...). Then update any usages of toServerSentEventsResponse (the example around the previous line 74) to call toStreamResponse instead, ensuring all references and examples consistently use chat and toStreamResponse.@@ -5,4 +5,8 @@5566 # Class: ToolCallManager778+<<<<<<< HEAD89 Defined in: [activities/chat/tools/tool-calls.ts:42](https://github.com/TanStack/ai/blob/main/packages/typescript/ai/src/activities/chat/tools/tool-calls.ts#L42)10+=======11+Defined in: [activities/chat/tools/tool-calls.ts:51](https://github.com/TanStack/ai/blob/main/packages/typescript/ai/src/activities/chat/tools/tool-calls.ts#L51)12+>>>>>>> cfa7844 (feat: split up adapters into functionalities and add generate function (#137))⚠️ Potential issue | 🔴 Critical
🧩 Analysis chain
🏁 Script executed:
# Check if the markdown file exists and contains merge conflicts if [ -f "docs/reference/classes/ToolCallManager.md" ]; then echo "=== Checking for merge conflict markers in ToolCallManager.md ===" grep -n "^<<<<<<<\|^=======\|^>>>>>>>" "docs/reference/classes/ToolCallManager.md" | head -20 echo "" echo "=== Total merge conflict markers ===" grep -c "^<<<<<<<\|^=======\|^>>>>>>>" "docs/reference/classes/ToolCallManager.md" || echo "No conflicts found" else echo "File does not exist: docs/reference/classes/ToolCallManager.md" fiRepository: TanStack/ai
Length of output: 954
🏁 Script executed:
# Check if the source file exists and examine its structure if [ -f "packages/typescript/ai/src/activities/chat/tools/tool-calls.ts" ]; then echo "=== File exists ===" wc -l "packages/typescript/ai/src/activities/chat/tools/tool-calls.ts" echo "" echo "=== ToolCallManager class definition ===" grep -n "class ToolCallManager" "packages/typescript/ai/src/activities/chat/tools/tool-calls.ts" else echo "Source file does not exist" # Try to find the file echo "=== Searching for tool-calls.ts ===" find . -name "tool-calls.ts" 2>/dev/null | head -5 fiRepository: TanStack/ai
Length of output: 217
🏁 Script executed:
# Check the actual content of a few conflict blocks to verify they are about line number references echo "=== Conflict at lines 8-12 ===" sed -n '8,12p' "docs/reference/classes/ToolCallManager.md" echo "" echo "=== Conflict at lines 54-58 ===" sed -n '54,58p' "docs/reference/classes/ToolCallManager.md" echo "" echo "=== Conflict at lines 78-82 ===" sed -n '78,82p' "docs/reference/classes/ToolCallManager.md"Repository: TanStack/ai
Length of output: 1474
🏁 Script executed:
# Check what's at the disputed line numbers in tool-calls.ts echo "=== Lines 42-52 (dispute between HEAD:42 vs incoming:51) ===" sed -n '42,52p' "packages/typescript/ai/src/activities/chat/tools/tool-calls.ts" | cat -n echo "" echo "=== Lines 46-56 (dispute between HEAD:46 vs incoming:55) ===" sed -n '46,56p' "packages/typescript/ai/src/activities/chat/tools/tool-calls.ts" | cat -n echo "" echo "=== Lines 54-64 (dispute between HEAD:54 vs incoming:63) ===" sed -n '54,64p' "packages/typescript/ai/src/activities/chat/tools/tool-calls.ts" | cat -nRepository: TanStack/ai
Length of output: 1404
Resolve unresolved merge conflicts before merging.
The file contains 7 unresolved Git merge conflicts preventing merge. These appear between HEAD and the incoming branch (cfa7844), with disagreements about line number references in
tool-calls.ts. The incoming branch shifted all references down by 9 lines compared to HEAD, indicating code additions earlier in the file.To resolve:
- Verify the correct line numbers in the actual source file (
packages/typescript/ai/src/activities/chat/tools/tool-calls.ts) - Choose the correct line numbers for each conflict
- Remove all conflict markers and finalize the references
Also applies to: 54-58, 78-82, 141-145, 164-168, 194-198, 214-218
🧰 Tools
🪛 markdownlint-cli2 (0.18.1)
8-8: Heading style Expected: atx; Actual: setext
(MD003, heading-style)
🤖 Prompt for AI Agents
In @docs/reference/classes/ToolCallManager.md around lines 8-12, The docs file has unresolved Git conflict markers around multiple "Defined in" links pointing to tool-calls.ts with differing line numbers; open the source (the TypeScript file that defines ToolCallManager / tool call helpers) to confirm the correct line numbers, remove all conflict markers (<<<<<<<, =======, >>>>>>>) in ToolCallManager.md, and update each "Defined in:" link to the verified single correct line reference for the symbol(s) (e.g., the ToolCallManager and related functions in tool-calls.ts) so the file contains no merge markers and each link points to the authentic line number.@@ -9,4 +9,8 @@99 function chat<TAdapter, TSchema, TStream>(options): TextActivityResult<TSchema, TStream>;1010 ```111112+<<<<<<< HEAD1213 Defined in: [activities/chat/index.ts:976](https://github.com/TanStack/ai/blob/main/packages/typescript/ai/src/activities/chat/index.ts#L976)14+=======15+Defined in: [activities/chat/index.ts:945](https://github.com/TanStack/ai/blob/main/packages/typescript/ai/src/activities/chat/index.ts#L945)16+>>>>>>> cfa7844 (feat: split up adapters into functionalities and add generate function (#137))⚠️ Potential issue | 🔴 Critical
Unresolved merge conflict:
Defined inanchor mismatch.The documentation contains an unresolved merge conflict with two conflicting line number references:
- HEAD:
activities/chat/index.ts:976 - Incoming:
activities/chat/index.ts:945
This must be resolved before the PR can be merged.
🧰 Tools
🪛 markdownlint-cli2 (0.18.1)
12-12: Heading style Expected: atx; Actual: setext
(MD003, heading-style)
🤖 Prompt for AI Agents
In @docs/reference/functions/chat.md around lines 12-16, Remove the unresolved merge markers and fix the `Defined in` anchor in docs/reference/functions/chat.md by verifying the actual declaration location in activities/chat/index.ts (check the definition of the exported Chat activity / function referenced) and update the link to the correct line number (either :976 or :945) or, better, point to the symbol location without a hard-coded line (e.g., link to the file or use a commit/anchor that targets the function name) so the conflicting HEAD/Incoming lines are eliminated.@@ -23,8 +27,18 @@23272428 ### TAdapter252930+<<<<<<< HEAD2631 `TAdapter` *extends* [`AnyTextAdapter`](../type-aliases/AnyTextAdapter.md)27322833 ### TSchema29343035 `TSchema` *extends* [`SchemaInput`](../type-aliases/SchemaInput.md) \| `undefined` = `undefined`36+=======37+`TAdapter` *extends* `AnyTextAdapter`38+39+### TSchema40+41+`TSchema` *extends*42+ \| `ZodType`\<`unknown`, `unknown`, `$ZodTypeInternals`\<`unknown`, `unknown`\>\>43+ \| `undefined` = `undefined`44+>>>>>>> cfa7844 (feat: split up adapters into functionalities and add generate function (#137))⚠️ Potential issue | 🔴 Critical
🧩 Analysis chain
🏁 Script executed:
git ls-files docs/reference/functions/chat.mdRepository: TanStack/ai
Length of output: 87
🏁 Script executed:
# Check if the file exists and view the problematic lines if [ -f "docs/reference/functions/chat.md" ]; then echo "=== File exists, checking lines 30-44 ===" sed -n '20,50p' docs/reference/functions/chat.md else echo "File not found at docs/reference/functions/chat.md" # Try searching for the file find . -name "chat.md" -type f 2>/dev/null | grep -E "(docs|reference)" | head -20 fiRepository: TanStack/ai
Length of output: 1034
🏁 Script executed:
# Search for any merge conflict markers in the repo rg -l "^<<<<<<< HEAD" --type md | head -20Repository: TanStack/ai
Length of output: 818
🏁 Script executed:
# Search for type definitions related to AnyTextAdapter and TSchema rg "TAdapter.*extends.*AnyTextAdapter" --type md --type ts --type tsx -A 3 -B 1 | head -50Repository: TanStack/ai
Length of output: 82
🏁 Script executed:
# Search for type definitions rg "AnyTextAdapter" --type md --type ts | head -30Repository: TanStack/ai
Length of output: 2809
🏁 Script executed:
# Search for SchemaInput type definition rg "SchemaInput" --type md --type ts | head -30Repository: TanStack/ai
Length of output: 3176
🏁 Script executed:
# Look for adapter-related files fd -e ts -e md | grep -i adapter | head -30Repository: TanStack/ai
Length of output: 1417
🏁 Script executed:
# Check if this is a generated documentation file head -20 docs/reference/functions/chat.mdRepository: TanStack/ai
Length of output: 751
🏁 Script executed:
# Check the actual chat function type definition in source sed -n '940,960p' packages/typescript/ai/src/activities/chat/index.tsRepository: TanStack/ai
Length of output: 621
🏁 Script executed:
# Look for ZodType usage in the source rg "ZodType" packages/typescript/ai/src/activities/chat/ -A 2 -B 2Repository: TanStack/ai
Length of output: 4168
🏁 Script executed:
# Check if this documentation is auto-generated rg "generated" docs/reference/functions/chat.mdRepository: TanStack/ai
Length of output: 37
🏁 Script executed:
# Check the actual git history of the merge conflict git log --oneline -1 cfa7844 2>/dev/null || echo "commit not in history"Repository: TanStack/ai
Length of output: 76
🏁 Script executed:
# Check how many merge conflict markers exist in the source rg -c "<<<<<<< HEAD" packages/typescript/ai/src/activities/chat/index.ts docs/reference/functions/chat.mdRepository: TanStack/ai
Length of output: 144
🏁 Script executed:
# Get the actual merge conflict sections from source code sed -n '1,100p' packages/typescript/ai/src/activities/chat/index.ts | rg -A 15 "<<<<<<< HEAD"Repository: TanStack/ai
Length of output: 1962
🏁 Script executed:
# Count total merge conflicts across the repo rg "<<<<<<< HEAD" -l | wc -lRepository: TanStack/ai
Length of output: 58
🏁 Script executed:
# Get a summary of which files have unresolved merge conflicts rg "<<<<<<< HEAD" -lRepository: TanStack/ai
Length of output: 5054
🏁 Script executed:
# Check if the repo is in a merge state cat .git/MERGE_HEAD 2>/dev/null || echo "Not in active merge"Repository: TanStack/ai
Length of output: 74
🏁 Script executed:
# Check the current branch git branch --show-current 2>/dev/null || echo "Unable to determine branch"Repository: TanStack/ai
Length of output: 37
🏁 Script executed:
# Get info about the PR/branch git log --oneline -n 5 2>/dev/null || echo "Git log unavailable"Repository: TanStack/ai
Length of output: 141
🏁 Script executed:
# See which version appears to be more complete in source - check imports sed -n '1,50p' packages/typescript/ai/src/activities/chat/index.ts | cat -ARepository: TanStack/ai
Length of output: 1520
🏁 Script executed:
# Check git status git statusRepository: TanStack/ai
Length of output: 290
🏁 Script executed:
# See what's the current HEAD git log --oneline HEAD -1Repository: TanStack/ai
Length of output: 141
🏁 Script executed:
# Check if there are stashed changes or if this is a completed merge with unresolved conflicts git diff --name-only | head -20Repository: TanStack/ai
Length of output: 37
🏁 Script executed:
# Look at the actual type in the InferSchemaType to understand expected behavior rg "type InferSchemaType" -A 10Repository: TanStack/ai
Length of output: 1766
Unresolved merge conflict spanning 116 files—this PR requires proper conflict resolution, not just documentation updates.
The repository contains widespread unresolved merge conflicts between the current codebase (HEAD) and the incoming changes (cfa7844). The
docs/reference/functions/chat.mdconflict at lines 30-44 is one of many symptoms:HEAD version (current):
TSchemaextendsSchemaInput | undefined(supports Standard JSON Schema or JSON Schema)- Uses
InferSchemaTypeutility that expectsStandardJSONSchemaV1
Incoming version (cfa7844):
TSchemaextendsz.ZodType | undefined(Zod-specific only)- Type inference breaks because
InferSchemaTypeis incompatible withZodType
The incoming branch changed schema handling to Zod-only (aligning with learnings), but the refactoring is incomplete: the
InferSchemaTypeutility and related type infrastructure were not updated to handlez.ZodTypeinference. This creates a broken type system where Zod schemas cannot be properly typed.The PR requires resolving all 116 merge conflicts with a comprehensive refactoring that updates both the schema type constraints AND all dependent type utilities.
🧰 Tools
🪛 markdownlint-cli2 (0.18.1)
35-35: Heading style Expected: atx; Actual: setext
(MD003, heading-style)
39-39: Heading levels should only increment by one level at a time Expected: h2; Actual: h3
(MD001, heading-increment)
@@ -19,4 +19,8 @@19192020 ### TAdapter212122+<<<<<<< HEAD2223 `TAdapter` *extends* [`ImageAdapter`](../interfaces/ImageAdapter.md)\<`string`, `object`, `any`, `any`\>24+=======25+`TAdapter` *extends* `ImageAdapter`\<`string`, `object`, `any`, `any`\>26+>>>>>>> cfa7844 (feat: split up adapters into functionalities and add generate function (#137))⚠️ Potential issue | 🔴 Critical
Resolve unresolved merge conflict.
This file contains unresolved merge conflict markers that must be resolved before merging. The conflict involves two formatting styles for the
TAdaptertype constraint:- Line 23 (HEAD): Uses markdown link syntax with
[ImageAdapter](../interfaces/ImageAdapter.md)— enables reader navigation to the interface definition. - Line 25 (incoming): Uses plain inline code
ImageAdapter— simpler but loses navigation context.
Recommend resolving in favor of the link-style version (line 23) to maintain documentation navigation and consistency with best practices for API reference docs.
🔎 Proposed resolution
-<<<<<<< HEAD -`TAdapter` *extends* [`ImageAdapter`](../interfaces/ImageAdapter.md)\<`string`, `object`, `any`, `any`\> -======= -`TAdapter` *extends* `ImageAdapter`\<`string`, `object`, `any`, `any`\> ->>>>>>> cfa7844 (feat: split up adapters into functionalities and add generate function (#137)) +`TAdapter` *extends* [`ImageAdapter`](../interfaces/ImageAdapter.md)\<`string`, `object`, `any`, `any`\>📝 Committable suggestion
‼️ IMPORTANT Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
Suggested change22-<<<<<<< HEAD23-`TAdapter` *extends* [`ImageAdapter`](../interfaces/ImageAdapter.md)\<`string`, `object`, `any`, `any`\>24-=======25-`TAdapter` *extends* `ImageAdapter`\<`string`, `object`, `any`, `any`\>26->>>>>>> cfa7844 (feat: split up adapters into functionalities and add generate function (#137))22+`TAdapter` *extends* [`ImageAdapter`](../interfaces/ImageAdapter.md)\<`string`, `object`, `any`, `any`\>🧰 Tools
🪛 markdownlint-cli2 (0.18.1)
22-22: Heading style Expected: atx; Actual: setext
(MD003, heading-style)
🤖 Prompt for AI Agents
In @docs/reference/functions/generateImage.md around lines 22-26, Resolve the Git conflict markers in generateImage.md by removing the <<<<<<<, =======, and >>>>>>> lines and keep the link-style declaration for the type constraint: replace the conflicting block with a single line using the markdown link to ImageAdapter (i.e., `TAdapter` extends [ImageAdapter](../interfaces/ImageAdapter.md)\<`string`, `object`, `any`, `any`\>), ensuring no leftover conflict markers remain and formatting matches surrounding docs.@@ -5,4 +5,8 @@5566 # Interface: ImagePart\<TMetadata\>778+<<<<<<< HEAD89 Defined in: [types.ts:133](https://github.com/TanStack/ai/blob/main/packages/typescript/ai/src/types.ts#L133)10+=======11+Defined in: [types.ts:184](https://github.com/TanStack/ai/blob/main/packages/typescript/ai/src/types.ts#L184)12+>>>>>>> cfa7844 (feat: split up adapters into functionalities and add generate function (#137))⚠️ Potential issue | 🔴 Critical
🧩 Analysis chain
🏁 Script executed:
# First, check if the documentation file exists and examine its current content cat docs/reference/interfaces/ImagePart.mdRepository: TanStack/ai
Length of output: 1925
🏁 Script executed:
# Search for ImagePart definition in types.ts to find its actual line number rg "interface ImagePart|type ImagePart" --line-number src/types.tsRepository: TanStack/ai
Length of output: 107
🏁 Script executed:
# Check if merge conflict markers exist in the docs directory find docs -type f -name "*.md" -exec grep -l "^<<<<<<<" {} \;Repository: TanStack/ai
Length of output: 3879
🏁 Script executed:
# Get git status to see if merge is in progress git statusRepository: TanStack/ai
Length of output: 290
🏁 Script executed:
# Find types.ts file in the repository find . -name "types.ts" -type fRepository: TanStack/ai
Length of output: 418
🏁 Script executed:
# List the main source structure to understand the project layout git ls-files | head -30Repository: TanStack/ai
Length of output: 705
🏁 Script executed:
# Search for ImagePart definition in the main types.ts file rg "interface ImagePart|type ImagePart" ./packages/typescript/ai/src/types.ts -n -A 5Repository: TanStack/ai
Length of output: 317
🏁 Script executed:
# Also check the current line count of the types.ts file wc -l ./packages/typescript/ai/src/types.tsRepository: TanStack/ai
Length of output: 97
🏁 Script executed:
# Get context around ImagePart definition to understand the structure head -200 ./packages/typescript/ai/src/types.ts | tail -50Repository: TanStack/ai
Length of output: 1536
🏁 Script executed:
# Check if commit cfa7844 exists in the repository git log --oneline | grep "cfa7844"Repository: TanStack/ai
Length of output: 37
🏁 Script executed:
# Get more context about the merge to understand the conflict situation git log --oneline -10Repository: TanStack/ai
Length of output: 141
🏁 Script executed:
# Check the exact line numbers for ImagePart's properties in types.ts rg "interface ImagePart|type:|source:|metadata\?" ./packages/typescript/ai/src/types.ts -n -B 1 -A 1Repository: TanStack/ai
Length of output: 3723
Resolve unresolved merge conflicts in documentation.
This file contains multiple unresolved Git merge conflict markers that must be removed before the PR can be merged. The conflicts reference outdated line numbers that do not match the current codebase:
- Lines 8–12: Conflict between line 133 (HEAD) and 184 (cfa7844) — both incorrect
- Lines 32–36: Conflict between line 138 (HEAD) and 189 (cfa7844) — both incorrect
- Lines 48–52: Conflict between line 136 (HEAD) and 187 (cfa7844) — both incorrect
- Lines 64–68: Conflict between line 134 (HEAD) and 189 (cfa7844) — both incorrect
The
ImagePartinterface is currently defined at line 137, with its properties at:type: line 138source: line 140metadata: line 142
Remove all merge conflict markers and update line references to
137,138,140, and142respectively across all four conflict sections.Also applies to: 32-36, 48-52, 64-68
🧰 Tools
🪛 markdownlint-cli2 (0.18.1)
8-8: Heading style Expected: atx; Actual: setext
(MD003, heading-style)
🤖 Prompt for AI Agents
In @docs/reference/interfaces/ImagePart.md around lines 8-12, The docs file contains unresolved Git conflict markers around the ImagePart reference sections; remove all conflict markers (<<<<<<<, =======, >>>>>>>) in the four affected blocks and replace the incorrect "Defined in" links with the correct line references for the ImagePart interface (use line numbers 137 for the interface and 138, 140, 142 for the type, source, metadata properties) so every occurrence (the blocks at lines ~8–12, ~32–36, ~48–52, ~64–68) points to those updated line numbers and the file contains no merge markers remaining.@@ -5,4 +5,8 @@5566 # Interface: JSONSchema778+<<<<<<< HEAD89 Defined in: [types.ts:25](https://github.com/TanStack/ai/blob/main/packages/typescript/ai/src/types.ts#L25)10+=======11+Defined in: [types.ts:85](https://github.com/TanStack/ai/blob/main/packages/typescript/ai/src/types.ts#L85)12+>>>>>>> cfa7844 (feat: split up adapters into functionalities and add generate function (#137))⚠️ Potential issue | 🔴 Critical
Pervasive unresolved merge conflicts throughout the file.
This file contains unresolved merge conflicts on every property definition (40+ instances), with "Defined in" references offset by approximately 60 line numbers between HEAD and the incoming branch. This suggests a significant refactoring changed line numbers across types.ts. The entire file must be resolved before it can be merged. Additionally, static analysis flags 40 markdown heading style violations; these should be addressed as part of resolving the merge conflicts.
Also applies to: 31-35, 45-49, 59-63, 73-77, 87-91, 101-105, 115-119, 129-133, 143-147, 157-161, 171-175, 185-189, 199-203, 213-217, 227-231, 241-245, 255-259, 269-273, 283-287, 297-301, 311-315, 325-329, 339-343, 353-357, 367-371, 381-385, 395-399, 409-413, 423-427, 437-441, 451-455, 465-469, 479-483, 493-497, 507-511, 521-525, 535-539
🧰 Tools
🪛 markdownlint-cli2 (0.18.1)
8-8: Heading style Expected: atx; Actual: setext
(MD003, heading-style)
@@ -45,4 +45,8 @@4545 description: string;4646 ```474748+<<<<<<< HEAD4849 Defined in: [types.ts:351](https://github.com/TanStack/ai/blob/main/packages/typescript/ai/src/types.ts#L351)50+=======51+Defined in: [types.ts:400](https://github.com/TanStack/ai/blob/main/packages/typescript/ai/src/types.ts#L400)52+>>>>>>> cfa7844 (feat: split up adapters into functionalities and add generate function (#137))⚠️ Potential issue | 🔴 Critical
Unresolved merge conflicts block this PR from merging.
This file contains 7 unresolved merge conflict markers. All conflicts are in the "Defined in" source references across properties (description, execute, inputSchema, metadata, name, needsApproval, outputSchema). The conflicts are between:
- HEAD: Original line numbers (e.g., 351, 431, 391, 437, 341, 434, 412)
- cfa7844 (feat: split up adapters into functionalities): Refactored line numbers (e.g., 400, 471, 432, 477, 390, 474, 452)
Resolve each conflict by determining which line numbers are correct based on the current state of
packages/typescript/ai/src/types.tsand any other relevant source files. The actual documentation content is consistent between branches and does not require changes—only the line references need resolution.Also applies to: 77-81, 125-129, 187-191, 207-211, 236-240, 256-260
🧰 Tools
🪛 markdownlint-cli2 (0.18.1)
50-50: Heading style Expected: atx; Actual: setext
(MD003, heading-style)
@@ -5,4 +5,8 @@5566 # Interface: ThinkingPart778+<<<<<<< HEAD89 Defined in: [types.ts:278](https://github.com/TanStack/ai/blob/main/packages/typescript/ai/src/types.ts#L278)10+=======11+Defined in: [types.ts:329](https://github.com/TanStack/ai/blob/main/packages/typescript/ai/src/types.ts#L329)12+>>>>>>> cfa7844 (feat: split up adapters into functionalities and add generate function (#137))⚠️ Potential issue | 🔴 Critical
🧩 Analysis chain
🏁 Script executed:
cat -n docs/reference/interfaces/ThinkingPart.mdRepository: TanStack/ai
Length of output: 1522
🏁 Script executed:
rg -n "interface ThinkingPart" packages/typescript/ai/src/types.ts -A 5 -B 2Repository: TanStack/ai
Length of output: 187
Resolve unresolved merge conflicts before merging.
The file contains unresolved merge conflict markers on three sections (lines 8-12, 22-26, 36-40) that must be resolved before the PR can be merged. The conflicting "Defined in" references have outdated line numbers in both versions:
- HEAD version references lines 278, 280, 279
- cfa7844 version references lines 329, 331, 330
The correct line numbers in
packages/typescript/ai/src/types.tsare:- Interface definition: line 282
typeproperty: line 283contentproperty: line 284
Update all three sections with the correct line number (282 for the interface definition).
🧰 Tools
🪛 markdownlint-cli2 (0.18.1)
8-8: Heading style Expected: atx; Actual: setext
(MD003, heading-style)
🤖 Prompt for AI Agents
In @docs/reference/interfaces/ThinkingPart.md around lines 8-12, The file contains unresolved git conflict markers in the "Defined in" lines for the ThinkingPart interface; remove the conflict markers and update the three "Defined in" references so they point to the correct lines in packages/typescript/ai/src/types.ts: set the interface definition "Defined in" to line 282, the "type" property reference to line 283, and the "content" property reference to line 284 (ensure no remaining <<<<<<<, =======, >>>>>>> markers remain).@@ -5,4 +5,8 @@5566 # Interface: ToolCallStreamChunk778+<<<<<<< HEAD89 Defined in: [types.ts:676](https://github.com/TanStack/ai/blob/main/packages/typescript/ai/src/types.ts#L676)10+=======11+Defined in: [types.ts:671](https://github.com/TanStack/ai/blob/main/packages/typescript/ai/src/types.ts#L671)12+>>>>>>> cfa7844 (feat: split up adapters into functionalities and add generate function (#137))⚠️ Potential issue | 🔴 Critical
Resolve unresolved merge conflicts before merging.
This file contains 7 unresolved git merge conflict markers that must be resolved. The conflicts appear in the "Defined in" metadata references, showing two different source line numbers from each branch (e.g., lines 676 vs 671, 664 vs 659, etc.).
This is a blocker and prevents the PR from being merged.
Recommended resolution:
Since these are auto-generated documentation references, the most reliable approach is to:
- Regenerate the documentation from the source code after resolving any code-level conflicts in
types.ts. Run your documentation generation tool (likely TypeDoc) to get the correct line numbers from the current state of the codebase. - If manual resolution is necessary, choose the line numbers from the branch you intend to keep (likely the incoming branch
cfa7844given the PR context about adapter restructuring), then remove the conflict markers.
After resolving, verify the line number references actually match the current
types.tsfile.Also applies to: 26-30, 44-48, 58-62, 76-80, 94-98, 138-142
🧰 Tools
🪛 markdownlint-cli2 (0.18.1)
8-8: Heading style Expected: atx; Actual: setext
(MD003, heading-style)
🤖 Prompt for AI Agents
In @docs/reference/interfaces/ToolCallStreamChunk.md around lines 8-12, The docs file ToolCallStreamChunk.md contains unresolved git conflict markers in the "Defined in" metadata (multiple blocks showing differing line numbers like 676 vs 671) which must be removed; resolve by fixing the underlying conflicts in the source types file (types.ts) for the related symbols (e.g., ToolCallStreamChunk and other referenced types), then regenerate the documentation (TypeDoc) so the "Defined in" line-number references are correct, or if you must edit the generated doc manually remove all conflict markers and pick the correct line numbers from the branch you intend to keep (cfa7844), ensuring the final references match the current types.ts.@@ -5,4 +5,8 @@5566 # Interface: ToolConfig778+<<<<<<< HEAD89 Defined in: [types.ts:440](https://github.com/TanStack/ai/blob/main/packages/typescript/ai/src/types.ts#L440)10+=======11+Defined in: [types.ts:480](https://github.com/TanStack/ai/blob/main/packages/typescript/ai/src/types.ts#L480)12+>>>>>>> cfa7844 (feat: split up adapters into functionalities and add generate function (#137))⚠️ Potential issue | 🔴 Critical
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash # Find the ToolConfig interface definition and its line number rg -n "interface\s+ToolConfig" packages/typescript/ai/src/types.ts -A 5 -B 2Repository: TanStack/ai
Length of output: 191
🏁 Script executed:
#!/bin/bash # Check the actual content of the documentation file to verify merge conflict cat -n docs/reference/interfaces/ToolConfig.md | head -20Repository: TanStack/ai
Length of output: 665
Resolve merge conflict and update incorrect line reference.
This file contains unresolved merge conflict markers (lines 8-12) that must be resolved before merging. Additionally, both conflicting line references are incorrect—the ToolConfig interface is defined at line 444 in types.ts, not line 440 (HEAD) or line 480 (cfa7844 branch). Resolve the conflict and update the reference to the correct line number.
🧰 Tools
🪛 markdownlint-cli2 (0.18.1)
8-8: Heading style Expected: atx; Actual: setext
(MD003, heading-style)
🤖 Prompt for AI Agents
In @docs/reference/interfaces/ToolConfig.md around lines 8-12, Remove the unresolved Git conflict markers around the Defined in link in ToolConfig.md, keeping a single correct "Defined in" line; update the URL reference so it points to types.ts at the correct line for the ToolConfig interface (line 444) and ensure there are no leftover <<<<<<<, =======, or >>>>>>> markers in the file; verify the link format remains consistent with other docs entries and commit the cleaned file.@@ -5,4 +5,8 @@5566 # Interface: TranscriptionWord778+<<<<<<< HEAD89 Defined in: [types.ts:991](https://github.com/TanStack/ai/blob/main/packages/typescript/ai/src/types.ts#L991)10+=======11+Defined in: [types.ts:986](https://github.com/TanStack/ai/blob/main/packages/typescript/ai/src/types.ts#L986)12+>>>>>>> cfa7844 (feat: split up adapters into functionalities and add generate function (#137))⚠️ Potential issue | 🔴 Critical
Resolve all merge conflict markers before merging.
Multiple unresolved merge conflict markers are present throughout this documentation file. These prevent proper parsing and rendering and must be resolved.
🔎 How to resolve
Choose the correct "Defined in" references based on the actual line numbers in
types.tsafter the adapter restructuring changes, then remove all conflict markers. If you need to verify which line numbers are correct, check the current state ofpackages/typescript/ai/src/types.ts.Also applies to: 24-28, 40-44, 56-60
🧰 Tools
🪛 markdownlint-cli2 (0.18.1)
8-8: Heading style Expected: atx; Actual: setext
(MD003, heading-style)
@@ -5,4 +5,8 @@5566 # Interface: UIMessage778+<<<<<<< HEAD89 Defined in: [types.ts:293](https://github.com/TanStack/ai/blob/main/packages/typescript/ai/src/types.ts#L293)10+=======11+Defined in: [types.ts:344](https://github.com/TanStack/ai/blob/main/packages/typescript/ai/src/types.ts#L344)12+>>>>>>> cfa7844 (feat: split up adapters into functionalities and add generate function (#137))⚠️ Potential issue | 🔴 Critical
Resolve merge conflicts before proceeding.
This documentation file contains multiple unresolved merge conflict markers that must be resolved before the PR can be merged. The conflicts appear to originate from the adapter refactoring mentioned in the PR objectives (the breaking changes to adapter architecture with BaseTextAdapter and split functionalities).
The conflicts involve line number references to the source TypeScript file (
types.ts):- HEAD references: lines 293, 294, 295, 296, 297
- Feature branch (cfa7844): lines 344, 345, 346, 347, 348
You'll need to:
- Determine which version reflects the correct line numbers post-adapter refactoring
- Remove the conflict markers (<<<<<<< HEAD / ======= / >>>>>>> cfa7844)
- Keep only the correct line references
Per the PR objectives, AlemTuzlak confirmed the PR should be updated to the new adapter structure. Ensure the resolved line numbers match the refactored adapter implementation.
Also applies to: 25-29, 39-43, 53-57, 67-71
🧰 Tools
🪛 markdownlint-cli2 (0.18.1)
8-8: Heading style Expected: atx; Actual: setext
(MD003, heading-style)
@@ -5,4 +5,8 @@5566 # Interface: VideoUrlResult778+<<<<<<< HEAD89 Defined in: [types.ts:895](https://github.com/TanStack/ai/blob/main/packages/typescript/ai/src/types.ts#L895)10+=======11+Defined in: [types.ts:890](https://github.com/TanStack/ai/blob/main/packages/typescript/ai/src/types.ts#L890)12+>>>>>>> cfa7844 (feat: split up adapters into functionalities and add generate function (#137))⚠️ Potential issue | 🔴 Critical
🧩 Analysis chain
🏁 Script executed:
cat -n docs/reference/interfaces/VideoUrlResult.mdRepository: TanStack/ai
Length of output: 2410
🏁 Script executed:
#!/bin/bash # Find the VideoUrlResult interface and property definitions echo "=== VideoUrlResult interface ===" rg -n "interface VideoUrlResult" --type ts echo -e "\n=== VideoUrlResult and its properties ===" ast-grep --pattern 'interface VideoUrlResult { $$$ }' echo -e "\n=== All VideoUrlResult occurrences in types.ts ===" rg -n "VideoUrlResult" --type ts -B 2 -A 2Repository: TanStack/ai
Length of output: 3639
🏁 Script executed:
sed -n '900,920p' packages/typescript/ai/src/types.tsRepository: TanStack/ai
Length of output: 595
🏁 Script executed:
# Get the full VideoUrlResult interface definition sed -n '908,920p' packages/typescript/ai/src/types.ts | cat -nRepository: TanStack/ai
Length of output: 527
Resolve unresolved merge conflicts in the file.
The file contains 4 unresolved git merge conflict markers that must be resolved before the PR can be merged. These conflicts will block documentation builds and rendering.
Conflicts appear in the "Defined in" source references at:
- Lines 8-12: Interface definition
- Lines 28-32: expiresAt property
- Lines 46-50: jobId property
- Lines 64-68: url property
Update all references to use the correct current line numbers in types.ts:
- Interface: line 908
- jobId property: line 910
- url property: line 913
- expiresAt property: line 916
🤖 Prompt for AI Agents
In @docs/reference/interfaces/VideoUrlResult.md around lines 8-12, Remove all git conflict markers from docs/reference/interfaces/VideoUrlResult.md and update the "Defined in" source references to the correct lines in types.ts: set the interface reference to line 908 and update the property references so jobId points to line 910, url to line 913, and expiresAt to line 916; ensure there are no remaining <<<<<<<, =======, >>>>>>> blocks anywhere in the file and that each "Defined in:" link uses the new types.ts line numbers.@@ -9,4 +9,8 @@99 type AgentLoopStrategy = (state) => boolean;1010 ```111112+<<<<<<< HEAD1213 Defined in: [types.ts:560](https://github.com/TanStack/ai/blob/main/packages/typescript/ai/src/types.ts#L560)14+=======15+Defined in: [types.ts:600](https://github.com/TanStack/ai/blob/main/packages/typescript/ai/src/types.ts#L600)16+>>>>>>> cfa7844 (feat: split up adapters into functionalities and add generate function (#137))⚠️ Potential issue | 🔴 Critical
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash # Check current state of the documentation file echo "=== Checking documentation file ===" cat -n docs/reference/type-aliases/AgentLoopStrategy.md | head -20 echo -e "\n=== Finding AgentLoopStrategy definition in types.ts ===" # Find the AgentLoopStrategy type definition and its context rg -n "type\s+AgentLoopStrategy" packages/typescript/ai/src/types.ts -A 2 -B 2Repository: TanStack/ai
Length of output: 966
Resolve merge conflict in "Defined in" reference.
This documentation file contains unresolved merge conflict markers (lines 12-16) that must be resolved before the PR can be merged. Additionally, both conflicting line references are incorrect: AgentLoopStrategy is defined at line 564 in types.ts, not line 560 or 600 as suggested by the conflict markers.
🤖 Prompt for AI Agents
In @docs/reference/type-aliases/AgentLoopStrategy.md around lines 12-16, Resolve the merge conflict markers in the AgentLoopStrategy doc by removing the HEAD/other-branch conflict lines and leaving a single correct "Defined in" reference; replace the incorrect links pointing to types.ts:560 or :600 with the correct link to types.ts:564 and ensure the line reads "Defined in: [types.ts:564](https://github.com/TanStack/ai/blob/main/packages/typescript/ai/src/types.ts#L564)" so the documentation points to the actual definition of AgentLoopStrategy.@@ -12,4 +12,8 @@1212 | ContentPartForInputModalitiesTypes<TInputModalitiesTypes>[];1313 ```141415+<<<<<<< HEAD1516 Defined in: [types.ts:225](https://github.com/TanStack/ai/blob/main/packages/typescript/ai/src/types.ts#L225)17+=======18+Defined in: [types.ts:276](https://github.com/TanStack/ai/blob/main/packages/typescript/ai/src/types.ts#L276)19+>>>>>>> cfa7844 (feat: split up adapters into functionalities and add generate function (#137))⚠️ Potential issue | 🔴 Critical
Unresolved merge conflict on source reference.
Lines 15–19 contain unresolved merge conflict markers with conflicting source line references (types.ts:225 vs types.ts:276). Resolve this conflict to reflect the correct source location in the current codebase.
🤖 Prompt for AI Agents
In @docs/reference/type-aliases/ConstrainedContent.md around lines 15-19, The file docs/reference/type-aliases/ConstrainedContent.md contains unresolved merge conflict markers (<<<<<<<, =======, >>>>>>>) around the "Defined in" source link; remove the conflict markers and replace the two conflicting references with the single correct source link pointing to the actual location of the ConstrainedContent type in the current types.ts (locate the ConstrainedContent definition in types.ts and use that file:line URL), e.g. update the "Defined in:" line to the one matching the current codebase and remove any leftover conflict text so the markdown shows only the accurate reference.@@ -9,4 +9,8 @@99 type ConstrainedModelMessage<TInputModalitiesTypes> = Omit<ModelMessage, "content"> & object;1010 ```111112+<<<<<<< HEAD1213 Defined in: [types.ts:309](https://github.com/TanStack/ai/blob/main/packages/typescript/ai/src/types.ts#L309)14+=======15+Defined in: [types.ts:360](https://github.com/TanStack/ai/blob/main/packages/typescript/ai/src/types.ts#L360)16+>>>>>>> cfa7844 (feat: split up adapters into functionalities and add generate function (#137))⚠️ Potential issue | 🔴 Critical
🧩 Analysis chain
🏁 Script executed:
cat -n docs/reference/type-aliases/ConstrainedModelMessage.md | head -20Repository: TanStack/ai
Length of output: 166
🏁 Script executed:
rg -n 'type ConstrainedModelMessage' packages/typescript/ai/src/types.ts -A 2 -B 1Repository: TanStack/ai
Length of output: 203
🏁 Script executed:
cat -n docs/reference/type-aliases/ConstrainedModelMessage.md | sed -n '10,20p'Repository: TanStack/ai
Length of output: 586
Resolve unresolved merge conflict and correct the type reference.
The file contains unresolved merge conflict markers (lines 12-16) that must be removed. Both conflicting references are incorrect: the
ConstrainedModelMessagetype is defined attypes.ts:313, not at 309 or 360.Replace the conflict block with:
Defined in: [types.ts:313](https://github.com/TanStack/ai/blob/main/packages/typescript/ai/src/types.ts#L313)🧰 Tools
🪛 markdownlint-cli2 (0.18.1)
12-12: Heading style Expected: atx; Actual: setext
(MD003, heading-style)
🤖 Prompt for AI Agents
In @docs/reference/type-aliases/ConstrainedModelMessage.md around lines 12-16, Remove the unresolved merge conflict markers and the two incorrect references, and replace that entire conflict block with the correct single reference for the ConstrainedModelMessage type: "Defined in: [types.ts:313](https://github.com/TanStack/ai/blob/main/packages/typescript/ai/src/types.ts#L313)"; ensure the final line mentions ConstrainedModelMessage so the symbol is clear and no conflict markers (<<<<<<<, =======, >>>>>>>) remain.@@ -11,4 +11,8 @@1111 }>;1212 ```131314+<<<<<<< HEAD1415 Defined in: [types.ts:201](https://github.com/TanStack/ai/blob/main/packages/typescript/ai/src/types.ts#L201)16+=======17+Defined in: [types.ts:252](https://github.com/TanStack/ai/blob/main/packages/typescript/ai/src/types.ts#L252)18+>>>>>>> cfa7844 (feat: split up adapters into functionalities and add generate function (#137))⚠️ Potential issue | 🔴 Critical
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash # Check the current state of the documentation file echo "=== Current state of ContentPartForInputModalitiesTypes.md ===" cat -n docs/reference/type-aliases/ContentPartForInputModalitiesTypes.md | head -25 echo -e "\n=== Searching for ContentPartForInputModalitiesTypes type definition ===" rg -n 'type\s+ContentPartForInputModalitiesTypes' --type tsRepository: TanStack/ai
Length of output: 1614
🏁 Script executed:
#!/bin/bash # Verify the definition at line 205 in types.ts echo "=== Context around line 205 in types.ts ===" sed -n '203,210p' packages/typescript/ai/src/types.tsRepository: TanStack/ai
Length of output: 427
Resolve unresolved merge conflict before merging.
The file contains unresolved merge conflict markers at lines 14-18. Both conflicting references are outdated—the actual
ContentPartForInputModalitiesTypestype definition is attypes.ts:205, not 201 or 252. Update the "Defined in" reference to the correct line number.Conflict to resolve
<<<<<<< HEAD Defined in: [types.ts:201](https://github.com/TanStack/ai/blob/main/packages/typescript/ai/src/types.ts#L201) ======= Defined in: [types.ts:252](https://github.com/TanStack/ai/blob/main/packages/typescript/ai/src/types.ts#L252) >>>>>>> cfa7844 (feat: split up adapters into functionalities and add generate function (#137))Replace with:
Defined in: [types.ts:205](https://github.com/TanStack/ai/blob/main/packages/typescript/ai/src/types.ts#L205)🤖 Prompt for AI Agents
In @docs/reference/type-aliases/ContentPartForInputModalitiesTypes.md around lines 14-18, The markdown contains unresolved git conflict markers for the "Defined in" link for ContentPartForInputModalitiesTypes; remove the conflict markers (<<<<<<<, =======, >>>>>>>) and replace the two conflicting references with a single correct reference pointing to types.ts line 205 (i.e., "Defined in: [types.ts:205](.../types.ts#L205)"); ensure the heading/name ContentPartForInputModalitiesTypes remains intact and that no other conflict remnants remain in the file.@@ -9,4 +9,8 @@99 type InputModalitiesTypes = object;1010 ```111112+<<<<<<< HEAD1213 Defined in: [types.ts:300](https://github.com/TanStack/ai/blob/main/packages/typescript/ai/src/types.ts#L300)14+=======15+Defined in: [types.ts:351](https://github.com/TanStack/ai/blob/main/packages/typescript/ai/src/types.ts#L351)16+>>>>>>> cfa7844 (feat: split up adapters into functionalities and add generate function (#137))⚠️ Potential issue | 🔴 Critical
🧩 Analysis chain
🏁 Script executed:
# Check if the file exists and examine its current state cat docs/reference/type-aliases/InputModalitiesTypes.mdRepository: TanStack/ai
Length of output: 1411
🏁 Script executed:
# Check for merge conflict markers in the documentation file if grep -q "<<<<<<< HEAD" docs/reference/type-aliases/InputModalitiesTypes.md 2>/dev/null; then echo "=== MERGE CONFLICTS FOUND ===" grep -n "<<<<<<< HEAD\|=======\|>>>>>>>" docs/reference/type-aliases/InputModalitiesTypes.md echo "" echo "=== File context around conflicts ===" cat -n docs/reference/type-aliases/InputModalitiesTypes.md | head -50 else echo "No merge conflicts found" cat -n docs/reference/type-aliases/InputModalitiesTypes.md | head -50 fiRepository: TanStack/ai
Length of output: 2166
🏁 Script executed:
# Examine types.ts around both line ranges mentioned echo "=== Checking types.ts around line 300-302 (HEAD reference) ===" if [ -f "packages/typescript/ai/src/types.ts" ]; then sed -n '295,310p' packages/typescript/ai/src/types.ts | cat -n echo "" echo "=== Checking types.ts around line 351-353 (incoming reference) ===" sed -n '346,360p' packages/typescript/ai/src/types.ts | cat -n else echo "types.ts not found at expected path" find . -name "types.ts" -type f 2>/dev/null | head -5 fiRepository: TanStack/ai
Length of output: 1366
🏁 Script executed:
# Let's precisely verify the line numbers in types.ts echo "=== Exact content at line 300 ===" sed -n '300p' packages/typescript/ai/src/types.ts echo "" echo "=== Exact content at line 351 ===" sed -n '351p' packages/typescript/ai/src/types.ts echo "" echo "=== Context: lines 298-305 ===" sed -n '298,305p' packages/typescript/ai/src/types.ts | cat -n echo "" echo "=== Context: lines 349-356 ===" sed -n '349,356p' packages/typescript/ai/src/types.ts | cat -nRepository: TanStack/ai
Length of output: 913
🏁 Script executed:
# Look for documentation generation scripts or build processes find . -maxdepth 3 -type f \( -name "*.json" -o -name "*.js" -o -name "*.ts" -o -name "*.sh" \) | xargs grep -l "InputModalitiesTypes\|typedoc\|doc.*gen\|generate.*doc" 2>/dev/null | head -10 echo "" echo "=== Check package.json scripts ===" if [ -f "package.json" ]; then cat package.json | jq '.scripts | keys[]' 2>/dev/null | grep -i doc fi echo "" echo "=== Check for tsconfig or docgen config ===" ls -la | grep -E "tsconfig|docgen|doc\.config" ls docs/ 2>/dev/null | head -10Repository: TanStack/ai
Length of output: 406
🏁 Script executed:
# Check for documentation generation configuration find . -maxdepth 2 -name "*.config.*" -o -name "tsconfig*" | head -10 cat package.json 2>/dev/null | jq '.scripts' 2>/dev/nullRepository: TanStack/ai
Length of output: 2190
🏁 Script executed:
# Find the exact line number where InputModalitiesTypes is defined echo "=== Search for InputModalitiesTypes definition ===" rg -n "export type InputModalitiesTypes" packages/typescript/ai/src/types.ts echo "" echo "=== Get context around the actual definition ===" rg -n -A 3 "export type InputModalitiesTypes" packages/typescript/ai/src/types.tsRepository: TanStack/ai
Length of output: 356
🏁 Script executed:
# Examine the generate-docs script head -50 scripts/generate-docs.tsRepository: TanStack/ai
Length of output: 968
Resolve unresolved merge conflicts and regenerate documentation.
This file contains three unresolved merge conflict blocks (lines 12–16, 26–30, and 40–44) that prevent it from rendering correctly. The conflicts stem from PR #137 adapter restructuring and reference incorrect line numbers in
types.tson both sides (HEAD references 300/301/302; incoming references 351/352/353, when the actual definition is at lines 304–306).Since this documentation is auto-generated by
scripts/generate-docs.ts(using@tanstack/typedoc-config), do not manually resolve the conflicts. Instead, regenerate the documentation by runningpnpm run generate-docsafter resolving the underlying merge in the main codebase.Also applies to: 26-30, 40-44
🧰 Tools
🪛 markdownlint-cli2 (0.18.1)
16-16: Heading style Expected: atx; Actual: setext
(MD003, heading-style)
🤖 Prompt for AI Agents
In @docs/reference/type-aliases/InputModalitiesTypes.md around lines 12-16, The docs file docs/reference/type-aliases/InputModalitiesTypes.md contains unresolved merge conflict markers at the blocks around lines 12–16, 26–30, and 40–44 caused by PR #137 changing adapter references and line numbers; do not edit the generated file directly—instead resolve the underlying merge in the source (ensure types.ts is merged so the type definition lines are stable around the actual definition near lines ~304–306), then regenerate the docs by running the documentation generator (invoke pnpm run generate-docs which runs scripts/generate-docs.ts using @tanstack/typedoc-config) so the conflict markers and incorrect type links are removed and the references to the correct types.ts line numbers are updated.@@ -9,4 +9,8 @@99 type ModalitiesArrayToUnion<T> = T[number];1010 ```111112+<<<<<<< HEAD1213 Defined in: [types.ts:218](https://github.com/TanStack/ai/blob/main/packages/typescript/ai/src/types.ts#L218)14+=======15+Defined in: [types.ts:269](https://github.com/TanStack/ai/blob/main/packages/typescript/ai/src/types.ts#L269)16+>>>>>>> cfa7844 (feat: split up adapters into functionalities and add generate function (#137))⚠️ Potential issue | 🔴 Critical
🧩 Analysis chain
🏁 Script executed:
# First, let's check the current state of the file with merge conflicts cat -n docs/reference/type-aliases/ModalitiesArrayToUnion.md | head -20Repository: TanStack/ai
Length of output: 823
🏁 Script executed:
# Find the types.ts file and search for ModalitiesArrayToUnion fd -t f types.tsRepository: TanStack/ai
Length of output: 712
🏁 Script executed:
# Check the definition of ModalitiesArrayToUnion in types.ts rg -n "ModalitiesArrayToUnion" -A 5 -B 5Repository: TanStack/ai
Length of output: 3436
🏁 Script executed:
# Check what's around line 269 in types.ts to understand the other version sed -n '265,275p' packages/typescript/ai/src/types.ts | cat -nRepository: TanStack/ai
Length of output: 452
Resolve unresolved merge conflict in documentation file.
This file contains unresolved merge conflict markers (lines 12-16). The conflict shows two competing line numbers (218 vs 269). The HEAD version pointing to line 218 is correct—it references the JSDoc comment block preceding the type definition. The competing version (line 269) is stale and points to unrelated code.
Accept the HEAD version and remove the merge conflict markers to resolve this blocker.
🧰 Tools
🪛 markdownlint-cli2 (0.18.1)
12-12: Heading style Expected: atx; Actual: setext
(MD003, heading-style)
🤖 Prompt for AI Agents
In @docs/reference/type-aliases/ModalitiesArrayToUnion.md around lines 12-16, This doc contains unresolved Git conflict markers around the ModalitiesArrayToUnion reference; remove the conflict markers (<<<<<<<, =======, >>>>>>>) and keep the HEAD variant that points to the correct JSDoc location (the version referencing line 218), deleting the stale competing line that points to line 269 so the file contains a single clean "Defined in: ..." line for ModalitiesArrayToUnion.@@ -9,4 +9,8 @@99 type Modality = "text" | "image" | "audio" | "video" | "document";1010 ```111112+<<<<<<< HEAD1213 Defined in: [types.ts:108](https://github.com/TanStack/ai/blob/main/packages/typescript/ai/src/types.ts#L108)14+=======15+Defined in: [types.ts:159](https://github.com/TanStack/ai/blob/main/packages/typescript/ai/src/types.ts#L159)16+>>>>>>> cfa7844 (feat: split up adapters into functionalities and add generate function (#137))⚠️ Potential issue | 🔴 Critical
🧩 Analysis chain
🏁 Script executed:
# Check if the documentation file exists and show its contents find . -name "Modality.md" -type fRepository: TanStack/ai
Length of output: 166
🏁 Script executed:
# Search for the Modality type definition in types.ts find . -name "types.ts" -path "*/typescript/ai/src/*" -type fRepository: TanStack/ai
Length of output: 153
🏁 Script executed:
# Search for Modality type definition in types.ts rg -n "type Modality" ./packages/typescript/ai/src/types.tsRepository: TanStack/ai
Length of output: 131
🏁 Script executed:
# Get context around the Modality definition rg -n -B 2 -A 5 "type Modality" ./packages/typescript/ai/src/types.tsRepository: TanStack/ai
Length of output: 341
🏁 Script executed:
# Check the total lines in types.ts wc -l ./packages/typescript/ai/src/types.tsRepository: TanStack/ai
Length of output: 97
🏁 Script executed:
# Search for the documentation file find . -type f -name "*.md" | grep -i modalityRepository: TanStack/ai
Length of output: 160
🏁 Script executed:
# Check the current state of the Modality.md documentation file cat -n ./docs/reference/type-aliases/Modality.mdRepository: TanStack/ai
Length of output: 959
🏁 Script executed:
# Look for merge conflict markers rg -n "<<<<<<<|=======|>>>>>>>" ./docs/reference/type-aliases/Modality.mdRepository: TanStack/ai
Length of output: 180
Resolve unresolved merge conflict in type definition reference.
The "Defined in" reference has conflicting line numbers (108 vs 159) due to adapter restructuring. The merge conflict markers must be resolved to allow documentation to build. The correct line number is 112, where
Modalityis currently defined inpackages/typescript/ai/src/types.ts.🔎 Correct resolution
-<<<<<<< HEAD -Defined in: [types.ts:108](https://github.com/TanStack/ai/blob/main/packages/typescript/ai/src/types.ts#L108) -======= -Defined in: [types.ts:159](https://github.com/TanStack/ai/blob/main/packages/typescript/ai/src/types.ts#L159) ->>>>>>> cfa7844 (feat: split up adapters into functionalities and add generate function (#137)) +Defined in: [types.ts:112](https://github.com/TanStack/ai/blob/main/packages/typescript/ai/src/types.ts#L112)📝 Committable suggestion
‼️ IMPORTANT Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
Suggested change12-<<<<<<< HEAD13-Defined in: [types.ts:108](https://github.com/TanStack/ai/blob/main/packages/typescript/ai/src/types.ts#L108)14-=======15-Defined in: [types.ts:159](https://github.com/TanStack/ai/blob/main/packages/typescript/ai/src/types.ts#L159)16->>>>>>> cfa7844 (feat: split up adapters into functionalities and add generate function (#137))12+Defined in: [types.ts:112](https://github.com/TanStack/ai/blob/main/packages/typescript/ai/src/types.ts#L112)🤖 Prompt for AI Agents
In @docs/reference/type-aliases/Modality.md around lines 12-16, Resolve the merge conflict markers in the "Defined in" reference for the Modality type by removing the <<<<<<<, =======, and >>>>>>> lines and keeping a single correct link; replace the conflicting two links with one link that points to the Modality definition in types.ts (update the reference to the file location where the Modality type is actually defined) so the documentation builds cleanly.@@ -11,4 +11,8 @@1111 | JSONSchema;1212 ```131314+<<<<<<< HEAD1415 Defined in: [types.ts:77](https://github.com/TanStack/ai/blob/main/packages/typescript/ai/src/types.ts#L77)16+=======17+Defined in: [types.ts:129](https://github.com/TanStack/ai/blob/main/packages/typescript/ai/src/types.ts#L129)18+>>>>>>> cfa7844 (feat: split up adapters into functionalities and add generate function (#137))⚠️ Potential issue | 🔴 Critical
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash # Find SchemaInput type definition in types.ts rg -n "type\s+SchemaInput" packages/typescript/ai/src/types.ts -A 5 -B 2Repository: TanStack/ai
Length of output: 374
🏁 Script executed:
#!/bin/bash # Read the specific lines from the documentation file to confirm merge conflict cat -n docs/reference/type-aliases/SchemaInput.md | sed -n '10,25p'Repository: TanStack/ai
Length of output: 911
Resolve merge conflict in SchemaInput.md "Defined in" reference.
Unresolved merge conflict markers at lines 14-18. Remove the conflict markers and update the reference to the correct line number:
Defined in: [types.ts:81](https://github.com/TanStack/ai/blob/main/packages/typescript/ai/src/types.ts#L81).🤖 Prompt for AI Agents
In @docs/reference/type-aliases/SchemaInput.md around lines 14-18, Remove the leftover git conflict markers in SchemaInput.md around the "Defined in" line and replace the conflicting block with the correct reference text: set the "Defined in:" link to types.ts line 81 (use "Defined in: [types.ts:81](https://github.com/TanStack/ai/blob/main/packages/typescript/ai/src/types.ts#L81)") so the file no longer contains <<<<<<<, =======, or >>>>>>> markers and points to the specified location.@@ -17,4 +17,8 @@1717 | ThinkingStreamChunk;1818 ```191920+<<<<<<< HEAD2021 Defined in: [types.ts:740](https://github.com/TanStack/ai/blob/main/packages/typescript/ai/src/types.ts#L740)22+=======23+Defined in: [types.ts:735](https://github.com/TanStack/ai/blob/main/packages/typescript/ai/src/types.ts#L735)24+>>>>>>> cfa7844 (feat: split up adapters into functionalities and add generate function (#137))⚠️ Potential issue | 🔴 Critical
Resolve merge conflict markers before merging.
Unresolved merge conflict markers are present in the documentation. These prevent proper parsing and rendering of the documentation and must be resolved.
🔎 How to resolve
Choose the correct "Defined in" reference based on the actual line number in
types.tsafter the adapter restructuring changes, then remove the conflict markers. If you need to verify which line number is correct, check the current state ofpackages/typescript/ai/src/types.ts.🧰 Tools
🪛 markdownlint-cli2 (0.18.1)
20-20: Heading style Expected: atx; Actual: setext
(MD003, heading-style)
🤖 Prompt for AI Agents
In @docs/reference/type-aliases/StreamChunk.md around lines 20-24, Remove the unresolved merge conflict markers (<<<<<<<, =======, >>>>>>>) from StreamChunk.md and choose the correct "Defined in" link: verify the current line number of StreamChunk's type in packages/typescript/ai/src/types.ts (after the adapter restructure) and update the reference to that exact line (either types.ts:735 or types.ts:740 as appropriate); ensure only the final resolved line with a single "Defined in" link remains and no conflict markers are left.@@ -17,4 +17,8 @@1717 | "thinking";1818 ```191920+<<<<<<< HEAD2021 Defined in: [types.ts:652](https://github.com/TanStack/ai/blob/main/packages/typescript/ai/src/types.ts#L652)22+=======23+Defined in: [types.ts:647](https://github.com/TanStack/ai/blob/main/packages/typescript/ai/src/types.ts#L647)24+>>>>>>> cfa7844 (feat: split up adapters into functionalities and add generate function (#137))⚠️ Potential issue | 🔴 Critical
Resolve merge conflict markers before merging.
Unresolved merge conflict markers are present in the documentation. These prevent proper parsing and rendering of the documentation and must be resolved.
🔎 How to resolve
Choose the correct "Defined in" reference based on the actual line number in
types.tsafter the adapter restructuring changes, then remove the conflict markers. If you need to verify which line number is correct, check the current state ofpackages/typescript/ai/src/types.ts.🧰 Tools
🪛 markdownlint-cli2 (0.18.1)
20-20: Heading style Expected: atx; Actual: setext
(MD003, heading-style)
🤖 Prompt for AI Agents
In @docs/reference/type-aliases/StreamChunkType.md around lines 20-24, The file docs/reference/type-aliases/StreamChunkType.md contains unresolved Git merge conflict markers (<<<<<<<, =======, >>>>>>>) around the "Defined in" link; remove the conflict markers and keep the correct "Defined in" reference that matches the current location of StreamChunkType in packages/typescript/ai/src/types.ts (verify the actual line number in that file), then update the Markdown link to the correct line number and commit the cleaned file so the documentation can parse and render properly.@@ -3,4 +3,8 @@33 chat,44 createChatOptions,55 maxIterations,6+<<<<<<< HEAD67 toServerSentEventsResponse,8+=======9+ toServerSentEventsStream,10+>>>>>>> cfa7844 (feat: split up adapters into functionalities and add generate function (#137))⚠️ Potential issue | 🔴 Critical
Unresolved merge conflict must be resolved.
This file contains unresolved git merge conflict markers that will cause syntax errors. The conflict is between importing
toServerSentEventsResponse(HEAD) vstoServerSentEventsStream(feature branch).Based on the implementation in
packages/typescript/ai/src/stream-to-response.ts,toServerSentEventsResponseis a convenience wrapper that internally callstoServerSentEventsStreamand sets the same SSE headers. UsingtoServerSentEventsResponseis cleaner and avoids duplicating header configuration.Recommended resolution: use toServerSentEventsResponse
import { chat, createChatOptions, maxIterations, -<<<<<<< HEAD - toServerSentEventsResponse, -======= - toServerSentEventsStream, ->>>>>>> cfa7844 (feat: split up adapters into functionalities and add generate function (#137)) + toServerSentEventsResponse, } from '@tanstack/ai'🧰 Tools
🪛 Biome (2.1.2)
[error] 10-10: expected a name for the function in a function declaration, but found none
(parse)
[error] 10-10: Expected a parameter but instead found '#137'.
Expected a parameter here.
(parse)
[error] 10-10: Expected a function body but instead found ')'.
Expected a function body here.
(parse)
🤖 Prompt for AI Agents
In @examples/ts-react-chat/src/routes/api.tanchat.ts around lines 6-10, Resolve the unresolved git conflict by removing the conflict markers and keep the cleaner convenience import: replace the conflicted import entry with toServerSentEventsResponse (remove toServerSentEventsStream and the <<<<<<</=======/>>>>>>> markers), ensure the import list is comma-correct and deduplicated, and update any local usages to call toServerSentEventsResponse (it internally uses toServerSentEventsStream and sets SSE headers) so no header duplication remains.@@ -122,4 +126,18 @@122126 abortController,123127 conversationId,124128 })129+<<<<<<< HEAD125130 return toServerSentEventsResponse(stream, { abortController })131+=======132+ const readableStream = toServerSentEventsStream(133+ stream,134+ abortController,135+ )136+ return new Response(readableStream, {137+ headers: {138+ 'Content-Type': 'text/event-stream',139+ 'Cache-Control': 'no-cache',140+ Connection: 'keep-alive',141+ },142+ })143+>>>>>>> cfa7844 (feat: split up adapters into functionalities and add generate function (#137))⚠️ Potential issue | 🔴 Critical
Unresolved merge conflict in response handling.
This conflict shows two equivalent approaches to returning an SSE response. Since
toServerSentEventsResponsehandles theReadableStreamcreation and header configuration internally (as shown inpackages/typescript/ai/src/stream-to-response.tslines 133-159), prefer the cleaner single-line approach.Recommended resolution: use the convenience wrapper
-<<<<<<< HEAD return toServerSentEventsResponse(stream, { abortController }) -======= - const readableStream = toServerSentEventsStream( - stream, - abortController, - ) - return new Response(readableStream, { - headers: { - 'Content-Type': 'text/event-stream', - 'Cache-Control': 'no-cache', - Connection: 'keep-alive', - }, - }) ->>>>>>> cfa7844 (feat: split up adapters into functionalities and add generate function (#137))🧰 Tools
🪛 Biome (2.1.2)
[error] 129-129: Expected an expression but instead found '<<'.
Expected an expression here.
(parse)
[error] 129-129: Expected an expression but instead found '<<'.
Expected an expression here.
(parse)
[error] 130-130: expected
>but instead foundreturnRemove return
(parse)
[error] 131-131: Expected an expression but instead found '==='.
Expected an expression here.
(parse)
[error] 131-131: Expected an expression but instead found '='.
Expected an expression here.
(parse)
[error] 130-131: Invalid assignment to
toServerSentEventsResponse(stream, { abortController }) ======This expression cannot be assigned to
(parse)
[error] 132-132: Expected an expression, or an assignment but instead found 'const'.
Expected an expression, or an assignment here.
(parse)
[error] 143-143: Expected an expression but instead found '>>>'.
Expected an expression here.
(parse)
[error] 143-143: Expected an expression but instead found '>'.
Expected an expression here.
(parse)
[error] 143-143: expected
,but instead found:Remove :
(parse)
[error] 143-143: expected
,but instead found(Remove (
(parse)
[error] 143-143: Expected an identifier but instead found '137'.
Expected an identifier here.
(parse)
[error] 143-143: Private names are only allowed on the left side of a 'in' expression
(parse)
[error] 143-143: expected
)but instead found137Remove 137
(parse)
[error] 143-143: Expected a semicolon or an implicit semicolon after a statement, but found none
An explicit or implicit semicolon is expected here...
...Which is required to end this statement
(parse)
🤖 Prompt for AI Agents
In @examples/ts-react-chat/src/routes/api.tanchat.ts around lines 129-143, Resolve the merge conflict by using the convenience wrapper toServerSentEventsResponse instead of manually creating a ReadableStream and new Response; remove the toServerSentEventsStream/readableStream/Response block and return toServerSentEventsResponse(stream, { abortController }) so headers and stream creation are handled by the existing implementation (keep the existing variables stream and abortController).@@ -1,2 +1,6 @@11 import { createFileRoute } from '@tanstack/solid-router'2+<<<<<<< HEAD23 import { chat, maxIterations, toServerSentEventsResponse } from '@tanstack/ai'4+=======5+import { chat, maxIterations, toServerSentEventsStream } from '@tanstack/ai'6+>>>>>>> cfa7844 (feat: split up adapters into functionalities and add generate function (#137))⚠️ Potential issue | 🔴 Critical
Unresolved merge conflict must be resolved.
Same issue as in
examples/ts-react-chat/src/routes/api.tanchat.ts— unresolved git conflict markers will cause syntax errors.Recommended resolution: use toServerSentEventsResponse
import { createFileRoute } from '@tanstack/solid-router' -<<<<<<< HEAD -import { chat, maxIterations, toServerSentEventsResponse } from '@tanstack/ai' -======= -import { chat, maxIterations, toServerSentEventsStream } from '@tanstack/ai' ->>>>>>> cfa7844 (feat: split up adapters into functionalities and add generate function (#137)) +import { chat, maxIterations, toServerSentEventsResponse } from '@tanstack/ai'📝 Committable suggestion
‼️ IMPORTANT Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
Suggested change2-<<<<<<< HEAD3-import { chat, maxIterations, toServerSentEventsResponse } from '@tanstack/ai'4-=======5-import { chat, maxIterations, toServerSentEventsStream } from '@tanstack/ai'6->>>>>>> cfa7844 (feat: split up adapters into functionalities and add generate function (#137))2+import { createFileRoute } from '@tanstack/solid-router'3+import { chat, maxIterations, toServerSentEventsResponse } from '@tanstack/ai'🧰 Tools
🪛 Biome (2.1.2)
[error] 3-4: Expected a statement but instead found '======='.
Expected a statement here.
(parse)
[error] 5-6: Expected a statement but instead found '>>>>>>> cfa7844 (feat: split up adapters into functionalities and add generate'.
Expected a statement here.
(parse)
[error] 6-6: expected a name for the function in a function declaration, but found none
(parse)
[error] 6-6: Expected a parameter but instead found '#137'.
Expected a parameter here.
(parse)
[error] 6-6: Expected a function body but instead found ')'.
Expected a function body here.
(parse)
[error] 5-5: Shouldn't redeclare 'chat'. Consider to delete it or rename it.
'chat' is defined here:
(lint/suspicious/noRedeclare)
[error] 5-5: Shouldn't redeclare 'maxIterations'. Consider to delete it or rename it.
'maxIterations' is defined here:
(lint/suspicious/noRedeclare)
🤖 Prompt for AI Agents
In @examples/ts-solid-chat/src/routes/api.chat.ts around lines 2-6, Resolve the unresolved git conflict markers in the import line by removing the conflict blocks (<<<<<<<, =======, >>>>>>>) and import the recommended symbol; change the import to use toServerSentEventsResponse (not toServerSentEventsStream) alongside chat and maxIterations so the module imports are consistent with the rest of the code and avoid syntax errors. Ensure any subsequent usage refers to toServerSentEventsResponse if that is what's expected by the surrounding code (e.g., where you call toServerSentEventsResponse(...)); finally run a quick compile to confirm there are no remaining conflict markers or mismatched symbol names.@@ -71,4 +75,18 @@7175 abortController,7276 })737778+<<<<<<< HEAD7479 return toServerSentEventsResponse(stream, { abortController })80+=======81+ const readableStream = toServerSentEventsStream(82+ stream,83+ abortController,84+ )85+ return new Response(readableStream, {86+ headers: {87+ 'Content-Type': 'text/event-stream',88+ 'Cache-Control': 'no-cache',89+ Connection: 'keep-alive',90+ },91+ })92+>>>>>>> cfa7844 (feat: split up adapters into functionalities and add generate function (#137))⚠️ Potential issue | 🔴 Critical
Unresolved merge conflict in response handling.
Same conflict pattern as the React example. Prefer the convenience wrapper to avoid duplicating header configuration across examples.
Recommended resolution
-<<<<<<< HEAD return toServerSentEventsResponse(stream, { abortController }) -======= - const readableStream = toServerSentEventsStream( - stream, - abortController, - ) - return new Response(readableStream, { - headers: { - 'Content-Type': 'text/event-stream', - 'Cache-Control': 'no-cache', - Connection: 'keep-alive', - }, - }) ->>>>>>> cfa7844 (feat: split up adapters into functionalities and add generate function (#137))📝 Committable suggestion
‼️ IMPORTANT Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
Suggested change78-<<<<<<< HEAD79- return toServerSentEventsResponse(stream, { abortController })80-=======81- const readableStream = toServerSentEventsStream(82- stream,83- abortController,84- )85- return new Response(readableStream, {86- headers: {87- 'Content-Type': 'text/event-stream',88- 'Cache-Control': 'no-cache',89- Connection: 'keep-alive',90- },91- })92->>>>>>> cfa7844 (feat: split up adapters into functionalities and add generate function (#137))78+ return toServerSentEventsResponse(stream, { abortController })🧰 Tools
🪛 Biome (2.1.2)
[error] 78-78: Expected an expression but instead found '<<'.
Expected an expression here.
(parse)
[error] 78-78: Expected an expression but instead found '<<'.
Expected an expression here.
(parse)
[error] 79-79: expected
>but instead foundreturnRemove return
(parse)
[error] 80-80: Expected an expression but instead found '==='.
Expected an expression here.
(parse)
[error] 80-80: Expected an expression but instead found '='.
Expected an expression here.
(parse)
[error] 79-80: Invalid assignment to
toServerSentEventsResponse(stream, { abortController }) ======This expression cannot be assigned to
(parse)
[error] 81-81: Expected an expression, or an assignment but instead found 'const'.
Expected an expression, or an assignment here.
(parse)
[error] 92-92: Expected an expression but instead found '>>>'.
Expected an expression here.
(parse)
[error] 92-92: Expected an expression but instead found '>'.
Expected an expression here.
(parse)
[error] 92-92: expected
,but instead found:Remove :
(parse)
[error] 92-92: expected
,but instead found(Remove (
(parse)
[error] 92-92: Expected an identifier but instead found '137'.
Expected an identifier here.
(parse)
[error] 92-92: Private names are only allowed on the left side of a 'in' expression
(parse)
[error] 92-92: expected
)but instead found137Remove 137
(parse)
[error] 92-92: Expected a semicolon or an implicit semicolon after a statement, but found none
An explicit or implicit semicolon is expected here...
...Which is required to end this statement
(parse)
🤖 Prompt for AI Agents
In @examples/ts-solid-chat/src/routes/api.chat.ts around lines 78-92, Resolve the merge conflict by keeping the convenience wrapper call toServerSentEventsResponse instead of manually creating a Response with toServerSentEventsStream; replace the conflicting block so you return toServerSentEventsResponse(stream, { abortController }) and remove the manual creation of readableStream/new Response and the explicit headers, ensuring you still pass the existing stream and abortController variables to the wrapper.@@ -2,4 +2,8 @@22 chat,33 createChatOptions,44 maxIterations,5+<<<<<<< HEAD56 toServerSentEventsResponse,7+=======8+ toServerSentEventsStream,9+>>>>>>> cfa7844 (feat: split up adapters into functionalities and add generate function (#137))⚠️ Potential issue | 🔴 Critical
Unresolved merge conflict in imports.
The file contains Git merge conflict markers that prevent it from being parsed or executed. Based on the PR context indicating a migration to the new adapter structure, resolve the conflict by accepting the
toServerSentEventsStreamimport.🔎 Proposed fix
-<<<<<<< HEAD - toServerSentEventsResponse, -======= toServerSentEventsStream, ->>>>>>> cfa7844 (feat: split up adapters into functionalities and add generate function (#137))📝 Committable suggestion
‼️ IMPORTANT Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
Suggested change5-<<<<<<< HEAD6- toServerSentEventsResponse,7-=======8- toServerSentEventsStream,9->>>>>>> cfa7844 (feat: split up adapters into functionalities and add generate function (#137))5+ toServerSentEventsStream,🧰 Tools
🪛 Biome (2.1.2)
[error] 9-9: expected a name for the function in a function declaration, but found none
(parse)
[error] 9-9: Expected a parameter but instead found '#137'.
Expected a parameter here.
(parse)
[error] 9-9: Expected a function body but instead found ')'.
Expected a function body here.
(parse)
🤖 Prompt for AI Agents
In @examples/ts-svelte-chat/src/routes/api/chat/+server.ts around lines 5-9, There is an unresolved git merge conflict in the import list around toServerSentEventsResponse / toServerSentEventsStream; remove the conflict markers (<<<<<<, =======, >>>>>>>), delete the toServerSentEventsResponse import, and keep toServerSentEventsStream in the import list; also scan for any usages of toServerSentEventsResponse in this file (e.g., in the handler function) and rename them to toServerSentEventsStream to match the new adapter API (ensure the import and usage names match exactly).@@ -116,4 +120,15 @@116120 abortController,117121 })118122123+<<<<<<< HEAD119124 return toServerSentEventsResponse(stream, { abortController })125+=======126+ const readableStream = toServerSentEventsStream(stream, abortController)127+ return new Response(readableStream, {128+ headers: {129+ 'Content-Type': 'text/event-stream',130+ 'Cache-Control': 'no-cache',131+ Connection: 'keep-alive',132+ },133+ })134+>>>>>>> cfa7844 (feat: split up adapters into functionalities and add generate function (#137))⚠️ Potential issue | 🔴 Critical
Unresolved merge conflict in return statement.
The file contains Git merge conflict markers in the return statement that prevent it from being parsed or executed. Based on the PR's migration to the new streaming architecture, resolve the conflict by accepting the
toServerSentEventsStreamapproach with explicit Response construction.🔎 Proposed fix
-<<<<<<< HEAD - return toServerSentEventsResponse(stream, { abortController }) -======= const readableStream = toServerSentEventsStream(stream, abortController) return new Response(readableStream, { headers: { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache', Connection: 'keep-alive', }, }) ->>>>>>> cfa7844 (feat: split up adapters into functionalities and add generate function (#137))📝 Committable suggestion
‼️ IMPORTANT Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
Suggested change123-<<<<<<< HEAD124- return toServerSentEventsResponse(stream, { abortController })125-=======126- const readableStream = toServerSentEventsStream(stream, abortController)127- return new Response(readableStream, {128- headers: {129- 'Content-Type': 'text/event-stream',130- 'Cache-Control': 'no-cache',131- Connection: 'keep-alive',132- },133- })134->>>>>>> cfa7844 (feat: split up adapters into functionalities and add generate function (#137))123+ const readableStream = toServerSentEventsStream(stream, abortController)124+ return new Response(readableStream, {125+ headers: {126+ 'Content-Type': 'text/event-stream',127+ 'Cache-Control': 'no-cache',128+ Connection: 'keep-alive',129+ },130+ })🧰 Tools
🪛 Biome (2.1.2)
[error] 123-123: Expected an expression but instead found '<<'.
Expected an expression here.
(parse)
[error] 123-123: Expected an expression but instead found '<<'.
Expected an expression here.
(parse)
[error] 124-124: expected
>but instead foundreturnRemove return
(parse)
[error] 125-125: Expected an expression but instead found '==='.
Expected an expression here.
(parse)
[error] 125-125: Expected an expression but instead found '='.
Expected an expression here.
(parse)
[error] 124-125: Invalid assignment to
toServerSentEventsResponse(stream, { abortController }) ======This expression cannot be assigned to
(parse)
[error] 126-126: Expected an expression, or an assignment but instead found 'const'.
Expected an expression, or an assignment here.
(parse)
[error] 134-134: Expected an expression but instead found '>>>'.
Expected an expression here.
(parse)
[error] 134-134: Expected an expression but instead found '>'.
Expected an expression here.
(parse)
[error] 134-134: expected
,but instead found:Remove :
(parse)
[error] 134-134: expected
,but instead found(Remove (
(parse)
[error] 134-134: Expected an identifier but instead found '137'.
Expected an identifier here.
(parse)
[error] 134-134: Private names are only allowed on the left side of a 'in' expression
(parse)
[error] 134-134: expected
)but instead found137Remove 137
(parse)
[error] 134-134: Expected a semicolon or an implicit semicolon after a statement, but found none
An explicit or implicit semicolon is expected here...
...Which is required to end this statement
(parse)
🤖 Prompt for AI Agents
In @examples/ts-svelte-chat/src/routes/api/chat/+server.ts around lines 123-134, Remove the Git conflict markers and the old toServerSentEventsResponse call and adopt the new streaming approach: call toServerSentEventsStream(stream, abortController) to get readableStream, then return a new Response(readableStream, { headers: { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache', Connection: 'keep-alive' } }); ensure abortController is passed to toServerSentEventsStream and the obsolete toServerSentEventsResponse reference is deleted.@@ -46,4 +46,8 @@4646 "@vitest/coverage-v8": "4.0.14"4747 },4848 "peerDependencies": {49+<<<<<<< HEAD4950 "@tanstack/ai": "workspace:^",51+=======52+ "@tanstack/ai": "workspace:*",53+>>>>>>> cfa7844 (feat: split up adapters into functionalities and add generate function (#137))⚠️ Potential issue | 🔴 Critical
Critical: Resolve merge conflict for workspace dependency.
The merge conflict in the
peerDependenciessection will cause JSON parsing to fail, breaking package installation and builds.Based on coding guidelines, the correct resolution is to use
workspace:*(from the incoming branch) rather thanworkspace:^.🔎 Proposed fix
-<<<<<<< HEAD - "@tanstack/ai": "workspace:^", -======= "@tanstack/ai": "workspace:*", ->>>>>>> cfa7844 (feat: split up adapters into functionalities and add generate function (#137))Based on learnings,
workspace:*is the standard protocol for internal package dependencies in this repository.📝 Committable suggestion
‼️ IMPORTANT Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
Suggested change49-<<<<<<< HEAD50- "@tanstack/ai": "workspace:^",51-=======52- "@tanstack/ai": "workspace:*",53->>>>>>> cfa7844 (feat: split up adapters into functionalities and add generate function (#137))49+ "@tanstack/ai": "workspace:*",🧰 Tools
🪛 Biome (2.1.2)
[error] 49-49: unexpected character
<(parse)
[error] 49-49: unexpected character
<(parse)
[error] 49-49: unexpected character
<(parse)
[error] 49-49: unexpected character
<(parse)
[error] 49-49: unexpected character
<(parse)
[error] 49-49: unexpected character
<(parse)
[error] 49-49: String values must be double quoted.
(parse)
[error] 50-50: End of file expected
Use an array for a sequence of values:
[1, 2](parse)
[error] 50-50: End of file expected
Use an array for a sequence of values:
[1, 2](parse)
[error] 50-50: End of file expected
Use an array for a sequence of values:
[1, 2](parse)
[error] 50-51: End of file expected
Use an array for a sequence of values:
[1, 2](parse)
[error] 50-51: unexpected character
=(parse)
[error] 51-51: unexpected character
=(parse)
[error] 51-51: unexpected character
=(parse)
[error] 51-51: unexpected character
=(parse)
[error] 51-51: unexpected character
=(parse)
[error] 51-51: unexpected character
=(parse)
[error] 51-51: unexpected character
=(parse)
[error] 52-52: End of file expected
Use an array for a sequence of values:
[1, 2](parse)
[error] 52-52: End of file expected
Use an array for a sequence of values:
[1, 2](parse)
[error] 52-52: End of file expected
Use an array for a sequence of values:
[1, 2](parse)
[error] 52-53: End of file expected
Use an array for a sequence of values:
[1, 2](parse)
[error] 52-53: unexpected character
>(parse)
[error] 53-53: unexpected character
>(parse)
[error] 53-53: unexpected character
>(parse)
[error] 53-53: unexpected character
>(parse)
[error] 53-53: unexpected character
>(parse)
[error] 53-53: unexpected character
>(parse)
[error] 53-53: unexpected character
>(parse)
[error] 53-53: unexpected character
((parse)
[error] 53-53: unexpected character
((parse)
[error] 53-53: unexpected character
#(parse)
[error] 53-53: End of file expected
Use an array for a sequence of values:
[1, 2](parse)
[error] 53-53: unexpected character
)(parse)
[error] 53-53: unexpected character
)(parse)
🤖 Prompt for AI Agents
In @packages/typescript/ai-anthropic/package.json around lines 49-53, The package.json has an unresolved git conflict for the peer dependency "@tanstack/ai" with leftover conflict markers; remove the conflict markers and set the dependency value to "workspace:*" (replace the "<<<<<<<", "=======", and ">>>>>>>", and change any "workspace:^" to "workspace:*") so the JSON is valid and uses the correct workspace protocol.@@ -1 +1,6 @@1+<<<<<<< HEAD12 import type { JSONSchema, SchemaInput, Tool } from '@tanstack/ai'3+=======4+import type { JSONSchema, Tool } from '@tanstack/ai'5+import type { z } from 'zod'6+>>>>>>> cfa7844 (feat: split up adapters into functionalities and add generate function (#137))⚠️ Potential issue | 🔴 Critical
Unresolved merge conflict markers must be resolved.
The file contains Git merge conflict markers that will cause parse/build failures. Based on the code usage,
SchemaInputis required (used on line 60), while thezimport from zod is unused in this file.🔎 Proposed fix to resolve the merge conflict
-<<<<<<< HEAD -import type { JSONSchema, SchemaInput, Tool } from '@tanstack/ai' -======= -import type { JSONSchema, Tool } from '@tanstack/ai' -import type { z } from 'zod' ->>>>>>> cfa7844 (feat: split up adapters into functionalities and add generate function (#137)) +import type { JSONSchema, SchemaInput, Tool } from '@tanstack/ai'📝 Committable suggestion
‼️ IMPORTANT Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
Suggested change1-<<<<<<< HEAD2-import type { JSONSchema, SchemaInput, Tool } from '@tanstack/ai'3-=======4-import type { JSONSchema, Tool } from '@tanstack/ai'5-import type { z } from 'zod'6->>>>>>> cfa7844 (feat: split up adapters into functionalities and add generate function (#137))1+import type { JSONSchema, SchemaInput, Tool } from '@tanstack/ai'🧰 Tools
🪛 Biome (2.1.2)
[error] 1-1: Expected a statement but instead found '<<<<<<< HEAD'.
Expected a statement here.
(parse)
[error] 2-3: Expected a statement but instead found '======='.
Expected a statement here.
(parse)
[error] 5-6: Expected a statement but instead found '>>>>>>> cfa7844 (feat: split up adapters into functionalities and add generate'.
Expected a statement here.
(parse)
[error] 6-6: expected a name for the function in a function declaration, but found none
(parse)
[error] 6-6: Expected a parameter but instead found '#137'.
Expected a parameter here.
(parse)
[error] 6-6: Expected a function body but instead found ')'.
Expected a function body here.
(parse)
[error] 4-4: Shouldn't redeclare 'JSONSchema'. Consider to delete it or rename it.
'JSONSchema' is defined here:
(lint/suspicious/noRedeclare)
[error] 4-4: Shouldn't redeclare 'Tool'. Consider to delete it or rename it.
'Tool' is defined here:
(lint/suspicious/noRedeclare)
🤖 Prompt for AI Agents
In @packages/typescript/ai-anthropic/src/tools/custom-tool.ts around lines 1-6, Remove the Git conflict markers and fix the import lines in custom-tool.ts: delete the <<<<<<<, =======, and >>>>>>> markers and ensure the file imports the used types from '@tanstack/ai' (include JSONSchema, SchemaInput and Tool since SchemaInput is used in the file) and remove the unused 'z' import from 'zod'.@@ -48,4 +48,8 @@4848 "devDependencies": {4949 "@vitest/coverage-v8": "4.0.14",5050 "vite": "^7.2.7",51+<<<<<<< HEAD5152 "zod": "^4.2.0"53+=======54+ "zod": "^4.1.13"55+>>>>>>> cfa7844 (feat: split up adapters into functionalities and add generate function (#137))⚠️ Potential issue | 🔴 Critical
Resolve the merge conflict.
The Zod dependency has unresolved Git conflict markers, making this JSON file invalid. This blocks all package installation and build operations.
Given the internal adapter changes mentioned in the PR comments, the HEAD version (^4.2.0) likely aligns with the updated adapter architecture. Resolve the conflict by selecting the appropriate version.
🔎 Proposed fix
-<<<<<<< HEAD "zod": "^4.2.0" -======= - "zod": "^4.1.13" ->>>>>>> cfa7844 (feat: split up adapters into functionalities and add generate function (#137))📝 Committable suggestion
‼️ IMPORTANT Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
Suggested change51-<<<<<<< HEAD52- "zod": "^4.2.0"53-=======54- "zod": "^4.1.13"55->>>>>>> cfa7844 (feat: split up adapters into functionalities and add generate function (#137))51+ "zod": "^4.2.0"🧰 Tools
🪛 Biome (2.1.2)
[error] 51-51: unexpected character
<(parse)
[error] 51-51: unexpected character
<(parse)
[error] 51-51: unexpected character
<(parse)
[error] 51-51: unexpected character
<(parse)
[error] 51-51: unexpected character
<(parse)
[error] 51-51: unexpected character
<(parse)
[error] 51-51: String values must be double quoted.
(parse)
[error] 52-52: End of file expected
Use an array for a sequence of values:
[1, 2](parse)
[error] 52-52: End of file expected
Use an array for a sequence of values:
[1, 2](parse)
[error] 52-52: End of file expected
Use an array for a sequence of values:
[1, 2](parse)
[error] 52-53: unexpected character
=(parse)
[error] 53-53: unexpected character
=(parse)
[error] 53-53: unexpected character
=(parse)
[error] 53-53: unexpected character
=(parse)
[error] 53-53: unexpected character
=(parse)
[error] 53-53: unexpected character
=(parse)
[error] 53-53: unexpected character
=(parse)
[error] 54-54: End of file expected
Use an array for a sequence of values:
[1, 2](parse)
[error] 54-54: End of file expected
Use an array for a sequence of values:
[1, 2](parse)
[error] 54-54: End of file expected
Use an array for a sequence of values:
[1, 2](parse)
[error] 54-55: unexpected character
>(parse)
[error] 55-55: unexpected character
>(parse)
[error] 55-55: unexpected character
>(parse)
[error] 55-55: unexpected character
>(parse)
[error] 55-55: unexpected character
>(parse)
[error] 55-55: unexpected character
>(parse)
[error] 55-55: unexpected character
>(parse)
[error] 55-55: String values must be double quoted.
(parse)
[error] 55-55: unexpected character
((parse)
[error] 55-55: String values must be double quoted.
(parse)
[error] 55-55: End of file expected
Use an array for a sequence of values:
[1, 2](parse)
[error] 55-55: unexpected character
((parse)
[error] 55-55: unexpected character
#(parse)
[error] 55-55: End of file expected
Use an array for a sequence of values:
[1, 2](parse)
[error] 55-55: unexpected character
)(parse)
[error] 55-55: unexpected character
)(parse)
🤖 Prompt for AI Agents
In @packages/typescript/ai-client/package.json around lines 51-55, The package.json contains unresolved Git conflict markers around the "zod" dependency making the file invalid; open packages/typescript/ai-client/package.json, remove the conflict markers (<<<<<<<, =======, >>>>>>>) and choose the correct "zod" version (replace the conflicted block with a single "zod" entry), likely keeping "zod": "^4.2.0" to match the updated adapter changes so the JSON is valid and installs/builds succeed.@@ -47,4 +47,8 @@4747 "vite": "^7.2.7"4848 },4949 "peerDependencies": {50+<<<<<<< HEAD5051 "@tanstack/ai": "workspace:^",52+=======53+ "@tanstack/ai": "workspace:*",54+>>>>>>> cfa7844 (feat: split up adapters into functionalities and add generate function (#137))⚠️ Potential issue | 🔴 Critical
Resolve merge conflict markers before merging.
Unresolved merge conflict markers are blocking the package.json from being properly parsed. This is a critical blocker that prevents installation and build processes.
Based on learnings, the
workspace:*protocol should be used for internal package dependencies.🔎 Proposed fix
-<<<<<<< HEAD - "@tanstack/ai": "workspace:^", -======= - "@tanstack/ai": "workspace:*", ->>>>>>> cfa7844 (feat: split up adapters into functionalities and add generate function (#137)) + "@tanstack/ai": "workspace:*",📝 Committable suggestion
‼️ IMPORTANT Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
Suggested change50-<<<<<<< HEAD51- "@tanstack/ai": "workspace:^",52-=======53- "@tanstack/ai": "workspace:*",54->>>>>>> cfa7844 (feat: split up adapters into functionalities and add generate function (#137))50+ "@tanstack/ai": "workspace:*",🧰 Tools
🪛 Biome (2.1.2)
[error] 50-50: unexpected character
<(parse)
[error] 50-50: unexpected character
<(parse)
[error] 50-50: unexpected character
<(parse)
[error] 50-50: unexpected character
<(parse)
[error] 50-50: unexpected character
<(parse)
[error] 50-50: unexpected character
<(parse)
[error] 50-50: String values must be double quoted.
(parse)
[error] 51-51: End of file expected
Use an array for a sequence of values:
[1, 2](parse)
[error] 51-51: End of file expected
Use an array for a sequence of values:
[1, 2](parse)
[error] 51-51: End of file expected
Use an array for a sequence of values:
[1, 2](parse)
[error] 51-52: End of file expected
Use an array for a sequence of values:
[1, 2](parse)
[error] 51-52: unexpected character
=(parse)
[error] 52-52: unexpected character
=(parse)
[error] 52-52: unexpected character
=(parse)
[error] 52-52: unexpected character
=(parse)
[error] 52-52: unexpected character
=(parse)
[error] 52-52: unexpected character
=(parse)
[error] 52-52: unexpected character
=(parse)
[error] 53-53: End of file expected
Use an array for a sequence of values:
[1, 2](parse)
[error] 53-53: End of file expected
Use an array for a sequence of values:
[1, 2](parse)
[error] 53-53: End of file expected
Use an array for a sequence of values:
[1, 2](parse)
[error] 53-54: End of file expected
Use an array for a sequence of values:
[1, 2](parse)
[error] 53-54: unexpected character
>(parse)
[error] 54-54: unexpected character
>(parse)
[error] 54-54: unexpected character
>(parse)
[error] 54-54: unexpected character
>(parse)
[error] 54-54: unexpected character
>(parse)
[error] 54-54: unexpected character
>(parse)
[error] 54-54: unexpected character
>(parse)
[error] 54-54: unexpected character
((parse)
[error] 54-54: unexpected character
((parse)
[error] 54-54: unexpected character
#(parse)
[error] 54-54: End of file expected
Use an array for a sequence of values:
[1, 2](parse)
[error] 54-54: unexpected character
)(parse)
[error] 54-54: unexpected character
)(parse)
🤖 Prompt for AI Agents
In @packages/typescript/ai-gemini/package.json around lines 50-54, Remove the unresolved merge conflict markers around the @tanstack/ai dependency in package.json and set the dependency to use the workspace protocol recommended (change the conflicted block to "\"@tanstack/ai\": \"workspace:*\""); ensure you delete the <<<<<<<, =======, and >>>>>>> lines and scan the rest of package.json for any other conflict markers so the file parses correctly.@@ -41,3 +41,7 @@4141 "adapter"4242 ],4343 "dependencies": {44+<<<<<<< HEAD45+=======46+ "@tanstack/ai": "workspace:*",47+>>>>>>> cfa7844 (feat: split up adapters into functionalities and add generate function (#137))⚠️ Potential issue | 🔴 Critical
Resolve merge conflict in dependencies.
The merge conflict markers make the JSON file invalid and will break the build. Based on the learnings and the new adapter architecture mentioned in the PR objectives, you should accept the incoming changes from the
cfa7844branch that add"@tanstack/ai": "workspace:*"to dependencies.🔎 Proposed fix
-<<<<<<< HEAD -======= - "@tanstack/ai": "workspace:*", ->>>>>>> cfa7844 (feat: split up adapters into functionalities and add generate function (#137)) + "@tanstack/ai": "workspace:*",Based on learnings, the
workspace:*protocol should be used for internal package dependencies.📝 Committable suggestion
‼️ IMPORTANT Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
Suggested change44-<<<<<<< HEAD45-=======46- "@tanstack/ai": "workspace:*",47->>>>>>> cfa7844 (feat: split up adapters into functionalities and add generate function (#137))44+ "@tanstack/ai": "workspace:*",🧰 Tools
🪛 Biome (2.1.2)
[error] 44-44: unexpected character
<(parse)
[error] 44-44: unexpected character
<(parse)
[error] 44-44: unexpected character
<(parse)
[error] 44-44: unexpected character
<(parse)
[error] 44-44: unexpected character
<(parse)
[error] 44-44: unexpected character
<(parse)
[error] 44-44: String values must be double quoted.
(parse)
[error] 44-45: unexpected character
=(parse)
[error] 45-45: unexpected character
=(parse)
[error] 45-45: unexpected character
=(parse)
[error] 45-45: unexpected character
=(parse)
[error] 45-45: unexpected character
=(parse)
[error] 45-45: unexpected character
=(parse)
[error] 45-45: unexpected character
=(parse)
[error] 46-46: End of file expected
Use an array for a sequence of values:
[1, 2](parse)
[error] 46-46: End of file expected
Use an array for a sequence of values:
[1, 2](parse)
[error] 46-46: End of file expected
Use an array for a sequence of values:
[1, 2](parse)
[error] 46-47: End of file expected
Use an array for a sequence of values:
[1, 2](parse)
[error] 46-47: unexpected character
>(parse)
[error] 47-47: unexpected character
>(parse)
[error] 47-47: unexpected character
>(parse)
[error] 47-47: unexpected character
>(parse)
[error] 47-47: unexpected character
>(parse)
[error] 47-47: unexpected character
>(parse)
[error] 47-47: unexpected character
>(parse)
[error] 47-47: unexpected character
((parse)
[error] 47-47: unexpected character
((parse)
[error] 47-47: unexpected character
#(parse)
[error] 47-47: End of file expected
Use an array for a sequence of values:
[1, 2](parse)
[error] 47-47: unexpected character
)(parse)
[error] 47-47: unexpected character
)(parse)
🤖 Prompt for AI Agents
In @packages/typescript/ai-ollama/package.json around lines 44-47, Remove the git conflict markers (<<<<<<<, =======, >>>>>>>) from the package.json and accept the incoming change that adds the dependency entry "@tanstack/ai": "workspace:*" into the dependencies object; ensure the dependencies object remains valid JSON (proper commas and quoting) after adding the line so the file parses and the workspace:* protocol is used for the internal package reference.@@ -41,11 +41,19 @@4141 "adapter"4242 ],4343 "dependencies": {44+<<<<<<< HEAD45+=======46+ "@tanstack/ai": "workspace:*",47+>>>>>>> cfa7844 (feat: split up adapters into functionalities and add generate function (#137))4448 "ollama": "^0.6.3"4549 },4650 "devDependencies": {4751 "@vitest/coverage-v8": "4.0.14",4852 "vite": "^7.2.7"4953 },5054 "peerDependencies": {55+<<<<<<< HEAD5156 "@tanstack/ai": "workspace:^",57+=======58+ "@tanstack/ai": "workspace:*",59+>>>>>>> cfa7844 (feat: split up adapters into functionalities and add generate function (#137))⚠️ Potential issue | 🔴 Critical
Resolve merge conflict in peerDependencies.
The merge conflict markers make the JSON file invalid. You should accept the incoming changes from the
cfa7844branch that use"workspace:*"instead of"workspace:^"for consistency with the dependencies section and monorepo best practices.🔎 Proposed fix
-<<<<<<< HEAD - "@tanstack/ai": "workspace:^", -======= - "@tanstack/ai": "workspace:*", ->>>>>>> cfa7844 (feat: split up adapters into functionalities and add generate function (#137)) + "@tanstack/ai": "workspace:*",Based on learnings, the
workspace:*protocol should be used for internal package dependencies.📝 Committable suggestion
‼️ IMPORTANT Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
Suggested change55-<<<<<<< HEAD56- "@tanstack/ai": "workspace:^",57-=======58- "@tanstack/ai": "workspace:*",59->>>>>>> cfa7844 (feat: split up adapters into functionalities and add generate function (#137))55+ "@tanstack/ai": "workspace:*",🧰 Tools
🪛 Biome (2.1.2)
[error] 55-55: unexpected character
<(parse)
[error] 55-55: unexpected character
<(parse)
[error] 55-55: unexpected character
<(parse)
[error] 55-55: unexpected character
<(parse)
[error] 55-55: unexpected character
<(parse)
[error] 55-55: unexpected character
<(parse)
[error] 55-55: String values must be double quoted.
(parse)
[error] 56-56: End of file expected
Use an array for a sequence of values:
[1, 2](parse)
[error] 56-56: End of file expected
Use an array for a sequence of values:
[1, 2](parse)
[error] 56-56: End of file expected
Use an array for a sequence of values:
[1, 2](parse)
[error] 56-57: End of file expected
Use an array for a sequence of values:
[1, 2](parse)
[error] 56-57: unexpected character
=(parse)
[error] 57-57: unexpected character
=(parse)
[error] 57-57: unexpected character
=(parse)
[error] 57-57: unexpected character
=(parse)
[error] 57-57: unexpected character
=(parse)
[error] 57-57: unexpected character
=(parse)
[error] 57-57: unexpected character
=(parse)
[error] 58-58: End of file expected
Use an array for a sequence of values:
[1, 2](parse)
[error] 58-58: End of file expected
Use an array for a sequence of values:
[1, 2](parse)
[error] 58-58: End of file expected
Use an array for a sequence of values:
[1, 2](parse)
[error] 58-59: End of file expected
Use an array for a sequence of values:
[1, 2](parse)
[error] 58-59: unexpected character
>(parse)
[error] 59-59: unexpected character
>(parse)
[error] 59-59: unexpected character
>(parse)
[error] 59-59: unexpected character
>(parse)
[error] 59-59: unexpected character
>(parse)
[error] 59-59: unexpected character
>(parse)
[error] 59-59: unexpected character
>(parse)
[error] 59-59: unexpected character
((parse)
[error] 59-59: unexpected character
((parse)
[error] 59-59: unexpected character
#(parse)
[error] 59-59: End of file expected
Use an array for a sequence of values:
[1, 2](parse)
[error] 59-59: unexpected character
)(parse)
[error] 59-59: unexpected character
)(parse)
🤖 Prompt for AI Agents
In @packages/typescript/ai-ollama/package.json around lines 55-59, Remove the Git conflict markers and accept the incoming change for the @tanstack/ai peerDependency: replace the conflicted block containing "@tanstack/ai": "workspace:^" and the surrounding <<<<<<<, =======, >>>>>>> markers with a single entry using "workspace:*" so the peerDependencies JSON is valid and consistent with the dependencies section; ensure the final package.json has no merge markers and uses "@tanstack/ai": "workspace:*".@@ -48,4 +48,9 @@4848 "@types/react": "^19.2.7",4949 "@vitest/coverage-v8": "4.0.14",5050 "jsdom": "^27.2.0",51+<<<<<<< HEAD5152 "vite": "^7.2.7"53+=======54+ "vite": "^7.2.7",55+ "zod": "^4.1.13"56+>>>>>>> cfa7844 (feat: split up adapters into functionalities and add generate function (#137))⚠️ Potential issue | 🔴 Critical
Resolve the merge conflict in devDependencies.
The file contains unresolved Git conflict markers, making the JSON invalid and breaking all npm/pnpm operations and builds.
🔎 Proposed fix
-<<<<<<< HEAD - "vite": "^7.2.7" -======= "vite": "^7.2.7", "zod": "^4.1.13" ->>>>>>> cfa7844 (feat: split up adapters into functionalities and add generate function (#137))Keep both dependencies since the
zodaddition supports the new schema conversion utilities mentioned in the PR.📝 Committable suggestion
‼️ IMPORTANT Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
Suggested change51-<<<<<<< HEAD52- "vite": "^7.2.7"53-=======54- "vite": "^7.2.7",55- "zod": "^4.1.13"56->>>>>>> cfa7844 (feat: split up adapters into functionalities and add generate function (#137))51+ "vite": "^7.2.7",52+ "zod": "^4.1.13"🧰 Tools
🪛 Biome (2.1.2)
[error] 51-51: unexpected character
<(parse)
[error] 51-51: unexpected character
<(parse)
[error] 51-51: unexpected character
<(parse)
[error] 51-51: unexpected character
<(parse)
[error] 51-51: unexpected character
<(parse)
[error] 51-51: unexpected character
<(parse)
[error] 51-51: String values must be double quoted.
(parse)
[error] 52-52: End of file expected
Use an array for a sequence of values:
[1, 2](parse)
[error] 52-52: End of file expected
Use an array for a sequence of values:
[1, 2](parse)
[error] 52-52: End of file expected
Use an array for a sequence of values:
[1, 2](parse)
[error] 52-53: unexpected character
=(parse)
[error] 53-53: unexpected character
=(parse)
[error] 53-53: unexpected character
=(parse)
[error] 53-53: unexpected character
=(parse)
[error] 53-53: unexpected character
=(parse)
[error] 53-53: unexpected character
=(parse)
[error] 53-53: unexpected character
=(parse)
[error] 54-54: End of file expected
Use an array for a sequence of values:
[1, 2](parse)
[error] 54-54: End of file expected
Use an array for a sequence of values:
[1, 2](parse)
[error] 54-54: End of file expected
Use an array for a sequence of values:
[1, 2](parse)
[error] 54-54: End of file expected
Use an array for a sequence of values:
[1, 2](parse)
[error] 55-55: End of file expected
Use an array for a sequence of values:
[1, 2](parse)
[error] 55-55: End of file expected
Use an array for a sequence of values:
[1, 2](parse)
[error] 55-55: End of file expected
Use an array for a sequence of values:
[1, 2](parse)
[error] 55-56: unexpected character
>(parse)
[error] 56-56: unexpected character
>(parse)
[error] 56-56: unexpected character
>(parse)
[error] 56-56: unexpected character
>(parse)
[error] 56-56: unexpected character
>(parse)
[error] 56-56: unexpected character
>(parse)
[error] 56-56: unexpected character
>(parse)
[error] 56-56: String values must be double quoted.
(parse)
[error] 56-56: unexpected character
((parse)
[error] 56-56: String values must be double quoted.
(parse)
[error] 56-56: End of file expected
Use an array for a sequence of values:
[1, 2](parse)
[error] 56-56: unexpected character
((parse)
[error] 56-56: unexpected character
#(parse)
[error] 56-56: End of file expected
Use an array for a sequence of values:
[1, 2](parse)
[error] 56-56: unexpected character
)(parse)
[error] 56-56: unexpected character
)(parse)
🤖 Prompt for AI Agents
In @packages/typescript/ai-react/package.json around lines 51-56, Resolve the Git conflict markers in package.json devDependencies by removing the conflict lines and merging the two entries so both "vite": "^7.2.7" and "zod": "^4.1.13" appear as valid JSON entries; update the devDependencies object (where "vite" and the added "zod" appear) to include both dependencies and ensure there is a trailing comma only where valid JSON requires it and no <<<<<<<, =======, >>>>>>> markers remain.@@ -157,4 +157,8 @@157157 2. Use `chat()` to stream responses (with automatic tool execution):158158159159 ```typescript160+<<<<<<< HEAD160161 import { chat, toServerSentEventsResponse } from '@tanstack/ai'162+=======163+import { chat, toStreamResponse } from '@tanstack/ai'164+>>>>>>> cfa7844 (feat: split up adapters into functionalities and add generate function (#137))⚠️ Potential issue | 🔴 Critical
Resolve unresolved merge conflicts across the file.
The file contains 6 unresolved merge conflicts between
toServerSentEventsResponse(HEAD) andtoStreamResponse(incoming branch). These must be resolved before the PR can be merged.Based on the PR context, the incoming changes (
toStreamResponse) represent the new streaming API being introduced in the adapter refactor. Review the conflicts and choose the appropriate version for each location, then remove all conflict markers.Also applies to: 318-322, 363-367, 376-380, 394-398, 408-412
🤖 Prompt for AI Agents
In @packages/typescript/ai-solid/README.md around lines 160-164, There are unresolved merge conflict markers using toServerSentEventsResponse vs toStreamResponse; resolve all occurrences by choosing the new streaming API (replace toServerSentEventsResponse with toStreamResponse), remove all conflict markers (<<<<<<<, =======, >>>>>>>) and ensure the import line (import { chat, toStreamResponse } from '@tanstack/ai') and every usage (e.g., calls to toStreamResponse) are updated consistently across the file (including the other listed locations) so the adapter compiles with the new toStreamResponse API.@@ -6,3 +6,15 @@66 ToolCall,77 ToolResultStreamChunk,88 } from '../../../types'9+<<<<<<< HEAD10+=======11+import type { z } from 'zod'12+13+/**14+ * Check if a value is a Zod schema by looking for Zod-specific internals.15+ */16+function isZodSchema(schema: SchemaInput | undefined): schema is z.ZodType {17+ if (!schema) return false18+ return '_zod' in schema && typeof (schema as any)._zod === 'object'19+}20+>>>>>>> cfa7844 (feat: split up adapters into functionalities and add generate function (#137))⚠️ Potential issue | 🔴 Critical
Critical: Resolve merge conflict.
This merge conflict will cause TypeScript parsing to fail, preventing compilation. The conflict markers must be removed before the PR can be merged.
🔎 Recommended resolution
Accept the incoming changes (lines 11-19) which add the
isZodSchemahelper function:-<<<<<<< HEAD -======= import type { z } from 'zod' /** * Check if a value is a Zod schema by looking for Zod-specific internals. */ function isZodSchema(schema: SchemaInput | undefined): schema is z.ZodType { if (!schema) return false return '_zod' in schema && typeof (schema as any)._zod === 'object' } ->>>>>>> cfa7844 (feat: split up adapters into functionalities and add generate function (#137))However, see the next comment regarding whether this function is actually needed.
📝 Committable suggestion
‼️ IMPORTANT Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
Suggested change9-<<<<<<< HEAD10-=======11-import type { z } from 'zod'12-13-/**14- * Check if a value is a Zod schema by looking for Zod-specific internals.15- */16-function isZodSchema(schema: SchemaInput | undefined): schema is z.ZodType {17- if (!schema) return false18- return '_zod' in schema && typeof (schema as any)._zod === 'object'19-}20->>>>>>> cfa7844 (feat: split up adapters into functionalities and add generate function (#137))9+import type { z } from 'zod'10+11+/**12+ * Check if a value is a Zod schema by looking for Zod-specific internals.13+ */14+function isZodSchema(schema: SchemaInput | undefined): schema is z.ZodType {15+ if (!schema) return false16+ return '_zod' in schema && typeof (schema as any)._zod === 'object'17+}🧰 Tools
🪛 Biome (2.1.2)
[error] 19-20: Expected a statement but instead found '>>>>>>> cfa7844 (feat: split up adapters into functionalities and add generate'.
Expected a statement here.
(parse)
[error] 20-20: expected a name for the function in a function declaration, but found none
(parse)
[error] 20-20: Expected a parameter but instead found '#137'.
Expected a parameter here.
(parse)
[error] 20-20: Expected a function body but instead found ')'.
Expected a function body here.
(parse)
🤖 Prompt for AI Agents
In @packages/typescript/ai/src/activities/chat/tools/tool-calls.ts around lines 9-20, Remove the Git conflict markers and accept the incoming addition that defines isZodSchema: delete the<<<<<<< HEAD/=======/>>>>>>> cfa7844 markers and keep the import type { z } from 'zod' plus the isZodSchema(schema: SchemaInput | undefined): schema is z.ZodType function; ensure SchemaInput is in scope (or adjust the parameter type) and that any usages of isZodSchema reference the same symbol name, then run TypeScript build to confirm no parsing errors remain.@@ -1 +1,5 @@1+<<<<<<< HEAD12 import type { StandardJSONSchemaV1 } from '@standard-schema/spec'3+=======4+import type { z } from 'zod'5+>>>>>>> cfa7844 (feat: split up adapters into functionalities and add generate function (#137))⚠️ Potential issue | 🔴 Critical
Critical: Resolve merge conflict before proceeding.
The file contains unresolved merge conflict markers that prevent it from being parsed or compiled. Both sides of the conflict import different types:
- HEAD:
StandardJSONSchemaV1(used byInferToolInputandInferToolOutputbelow) - Incoming branch:
ztype from zod
Based on the code that follows,
StandardJSONSchemaV1is actively used in type inference (lines 71, 82). The incomingztype import may represent additional Zod-specific typing from PR #137's adapter changes. You may need both imports after resolution.Please resolve this conflict, ensuring all necessary type imports are preserved.
🧰 Tools
🪛 Biome (2.1.2)
[error] 1-1: Expected a statement but instead found '<<<<<<< HEAD'.
Expected a statement here.
(parse)
[error] 2-3: Expected a statement but instead found '======='.
Expected a statement here.
(parse)
[error] 4-5: Expected a statement but instead found '>>>>>>> cfa7844 (feat: split up adapters into functionalities and add generate'.
Expected a statement here.
(parse)
[error] 5-5: expected a name for the function in a function declaration, but found none
(parse)
[error] 5-5: Expected a parameter but instead found '#137'.
Expected a parameter here.
(parse)
[error] 5-5: Expected a function body but instead found ')'.
Expected a function body here.
(parse)
🤖 Prompt for AI Agents
In @packages/typescript/ai/src/activities/chat/tools/tool-definition.ts around lines 1-5, Resolve the merge conflict by removing the conflict markers and keeping both required type imports: add back `import type { StandardJSONSchemaV1 } from '@standard-schema/spec'` and also import `type { z } from 'zod'` (or `import type { ZodType } from 'zod'` if more appropriate) at the top of the file, then ensure `InferToolInput` and `InferToolOutput` still reference `StandardJSONSchemaV1` as used below and any new zod-related types from the incoming branch are used where needed; delete the <<<<<<<, =======, and >>>>>>> lines so the file parses cleanly.- Verify the correct line numbers in the actual source file (
Yeah, I messed up the rebase a bit, so coderabbit reviewed the wrong version 😅 I'm going to turn this into a Draft and finish the migration in the next few days
No worries, I'm also building some architecture around this to enable some cool things on top of openrouter.
@AlemTuzlak I think we have most of it working now. Would you mind double checking and letting me know if you find anything missing?
Will check it out asap, although I think we will switch towards using their sdk /openai sdk instead of calling it directly with a fetch call
Will check it out asap, although I think we will switch towards using their sdk /openai sdk instead of calling it directly with a fetch call
Is there any particular reason for that?
Will check it out asap, although I think we will switch towards using their sdk /openai sdk instead of calling it directly with a fetch call
Is there any particular reason for that?
Yes there is, the first one is that the response is strongly typed, the second is that we can import the types from the library instead of manually writing them ourselves
@LuggaPugga thank you so much for your help with this, I'm personally taking over the PR to push it out soon.
I've gotten in touch with the openrouter team as well and after talking to them I know the direction I'm heading in.
Will be done soon! 🫡
Actionable comments posted: 9
🤖 Fix all issues with AI agents
In @.claude/settings.local.json: - Around line 1-12: Rename the tracked config file from .claude/settings.local.json to .claude/settings.json and update any repository references to it (e.g., CI scripts, docs, or tooling configs) so they point to the new name; ensure you remove the old file path and add the new file path in git (git mv or equivalent) to preserve history, and verify that no developer-specific secrets were accidentally committed before making the rename. In `@examples/ts-react-chat/src/lib/model-selection.ts`: - Around line 50-60: Update the label capitalization for the OpenRouter entries so they read "OpenRouter - ChatGPT 4o Latest" and "OpenRouter - ChatGPT 4o Mini"; locate the objects with provider: 'openrouter' and model: 'openai/chatgpt-4o-latest' and 'openai/chatgpt-4o-mini' and change their label values from "Openrouter - ..." to "OpenRouter - ..." to match branding and other provider capitalization. In `@packages/typescript/ai-openrouter/src/adapters/image.ts`: - Around line 138-158: The loop over responseWithImages.choices reads choice.message.images without guarding for a missing message; update the code to safely handle an optional message by using optional chaining or an explicit null check (e.g., use choice.message?.images or if (choice.message && choice.message.images) before iterating). Apply this change where choiceImages is assigned in the block that iterates choices so the subsequent imgs loop only runs when images exist and avoids null/undefined dereference of choice.message. - Around line 108-111: The catch block currently always wraps the caught error with "Image generation failed:", causing double-wrapping; update the handler so that if the caught value is an Error whose message already startsWith "Image generation failed:" you rethrow the original Error (or return it) instead of wrapping again, otherwise construct a new Error with the prefix and the original message; specifically modify the catch handling around the try-catch in the image generation logic (the catch(error) block that computes message and throws new Error(`Image generation failed: ${message}`)) to check (error instanceof Error && error.message.startsWith('Image generation failed:')) ? throw error : throw new Error(`Image generation failed: ${message}`). In `@packages/typescript/ai-openrouter/src/adapters/text.ts`: - Around line 117-120: The loop over chunk.choices incorrectly inspects chunk.choices[0] instead of the current iteration variable; update the loop body in the for (const choice of chunk.choices) block to check choice?.finishReason and assign lastFinishReason = choice.finishReason (preserving optional chaining) so finish reasons from non-first choices are correctly captured; locate the change around the chunk.choices loop and the lastFinishReason assignment. In `@packages/typescript/ai-openrouter/src/image/image-provider-options.ts`: - Around line 26-38: The type OpenRouterImageModelSizeByName uses mixed Unicode '×' and ASCII 'x' characters causing lookups against SIZE_TO_ASPECT_RATIO in image.ts to fail; update the OpenRouterImageModelSizeByName union so every size string uses the ASCII lowercase 'x' (e.g., '832x1248', '1248x832', etc.) to exactly match the keys used by SIZE_TO_ASPECT_RATIO and ensure aspect ratio lookups in the image handling code (where SIZE_TO_ASPECT_RATIO is used) return the expected values. In `@scripts/convert-openrouter-models.ts`: - Around line 165-179: The generated Pick<> can become empty when model.supported_parameters only contains excluded keys; update the logic that sets perModelProviderOptions[`${constName}.id`] to first compute the filtered list from model.supported_parameters (excluding 'tools', 'reasoning_effort', 'structured_outputs' and mapping 'max_tokens' to 'max_completion_tokens'), then if that filtered list is non-empty build `OpenRouterCommonOptions & Pick<OpenRouterBaseOptions, ...>` using the joined keys, otherwise fall back to `OpenRouterCommonOptions & OpenRouterBaseOptions`; apply this change in the block that assigns perModelProviderOptions[`${constName}.id`] so the resulting type never emits an empty Pick<>. - Around line 4-7: Update the usage instructions in scripts/convert-openrouter-models.ts so both runner references are identical: choose either "ts-node" or "tsx" and replace the other occurrence so the header comment (the Usage steps referencing the `models` variable) and the later example command both use the same runner; ensure any example command string that mentions running the script is changed consistently (e.g., change "npx ts-node scripts/convert-openrouter-models.ts" or "npx tsx scripts/convert-openrouter-models.ts" so both instances match). - Around line 91-135: generateModelMetaString currently uses input_modalities for supports.output and for populating chatModels/imageModels/videoModels, which mislabels models with different output capabilities; change the code to read and map model.architecture.output_modalities (e.g., const outputModalities = model.architecture.output_modalities.map(mapInputModality).filter((m): m is InputModality => m !== null)) and use outputModalities for the supports.output line and for adding to imageModels, videoModels, and chatModels; if a dedicated mapper exists for outputs use that instead of mapInputModality.♻️ Duplicate comments (10)
packages/typescript/ai-devtools/package.json (1)
49-52: Same workspace-protocol check as above for@tanstack/devtools-utils.If it’s a workspace package, prefer
"workspace:*"here as well. Based on learnings, ...packages/typescript/react-ai-devtools/package.json (1)
50-53: Same workspace-protocol check as above for@tanstack/devtools-utils.If it’s a workspace package, prefer
"workspace:*"here as well. Based on learnings, ...packages/typescript/solid-ai-devtools/package.json (1)
49-52: Same workspace-protocol check as above for@tanstack/devtools-utils.If it’s a workspace package, prefer
"workspace:*"here as well. Based on learnings, ...packages/typescript/ai-openrouter/README.md (2)
47-47: Fix markdown heading level.Static analysis correctly flags an MD001 violation: after
# TanStack AI(h1), the next heading should be##(h2), not###(h3).-### <a href="https://tanstack.com/ai">Read the docs →</b></a> +## <a href="https://tanstack.com/ai">Read the docs →</b></a>
55-63: Add missingzimport for Zod usage.The code example uses
z.object(...)but doesn't importzfrom Zod, which would confuse readers.```typescript import { createServerFnTool } from '@tanstack/ai-react' +import { z } from 'zod'packages/typescript/ai-openrouter/package.json (1)
31-33: Fixtest:lib:devwatch mode.The current script
pnpm test:lib --watchexpands tovitest run --watch, butvitest runis incompatible with the--watchflag.Recommended fix
- "test:lib:dev": "pnpm test:lib --watch", + "test:lib:dev": "vitest",docs/adapters/openrouter.md (1)
31-42: Fix thecreateOpenRouterexample to omitapiKeyfrom config (Line 41).The current example passes a config object that still contains
apiKey, which conflicts with the function signature and will fail type-checking.🔧 Proposed doc fix
-const adapter = createOpenRouter(config.apiKey, config); +const { apiKey, ...rest } = config; +const adapter = createOpenRouter(apiKey, rest);packages/typescript/ai-openrouter/src/message-types.ts (1)
1-12: Replace empty interfaces to satisfy BiomenoEmptyInterface.Biome flags the empty interfaces at Line 1, Line 7, Line 9, and Line 11; this will fail lint. Convert them to type aliases.
🧹 Proposed fix
-export interface OpenRouterTextMetadata {} +export type OpenRouterTextMetadata = Record<string, never> export interface OpenRouterImageMetadata { detail?: 'auto' | 'low' | 'high' } -export interface OpenRouterAudioMetadata {} +export type OpenRouterAudioMetadata = Record<string, never> -export interface OpenRouterVideoMetadata {} +export type OpenRouterVideoMetadata = Record<string, never> -export interface OpenRouterDocumentMetadata {} +export type OpenRouterDocumentMetadata = Record<string, never>packages/typescript/ai-openrouter/src/text/text-provider-options.ts (1)
274-276: Extendresponse_formatto includejson_schemastructured outputs.The type only allows
{ type: 'json_object' }. OpenRouter supportsjson_schemastructured outputs, so the type should include it as a union.✅ Suggested type expansion
- response_format?: { type: 'json_object' } + response_format?: + | { type: 'json_object' } + | { + type: 'json_schema' + json_schema: { + name: string + schema: Record<string, unknown> + strict?: boolean + } + }OpenRouter response_format json_schema structured outputs documentationpackages/typescript/ai-openrouter/src/adapters/text.ts (1)
403-439: System messages passed in the messages array are incorrectly converted to assistant role.The
convertMessagesfunction handles'tool'and'user'roles explicitly, but any other role (including'system') falls through to the assistant branch. While system prompts are typically passed viasystemPromptsoption, passing system messages directly in the array will cause unexpected behavior.🔎 Suggested fix
if (msg.role === 'user') { const content = this.convertContentParts(msg.content) return { role: 'user' as const, content: content.length === 1 && content[0]?.type === 'text' ? (content[0] as { type: 'text'; text: string }).text : content, } } + if (msg.role === 'system') { + return { + role: 'system' as const, + content: + typeof msg.content === 'string' + ? msg.content + : msg.content + ? JSON.stringify(msg.content) + : '', + } + } + // assistant role return {🧹 Nitpick comments (4)
packages/typescript/ai-openrouter/src/tools/web-search-tool.ts (1)
17-21: Consider omitting undefined properties for cleaner payloads.Currently, undefined options are still set as properties (e.g.,
max_results: undefined). While JSON serialization ignores undefined, explicitly omitting them produces cleaner objects.♻️ Optional refactor
return { type: 'web_search', - web_search: { - engine: options?.engine, - max_results: options?.maxResults, - search_prompt: options?.searchPrompt, - }, + web_search: { + ...(options?.engine && { engine: options.engine }), + ...(options?.maxResults && { max_results: options.maxResults }), + ...(options?.searchPrompt && { search_prompt: options.searchPrompt }), + }, }packages/typescript/ai-openrouter/package.json (1)
15-20: Consider adding subpath exports for tree-shaking.Based on learnings, the package should expose tree-shakeable adapter exports via subpath exports (e.g.,
@tanstack/ai-openrouter/adapters) similar to other TanStack AI packages. The current single root export bundles everything together.Suggested subpath exports structure
"exports": { ".": { "types": "./dist/esm/index.d.ts", "import": "./dist/esm/index.js" - } + }, + "./adapters": { + "types": "./dist/esm/adapters/index.d.ts", + "import": "./dist/esm/adapters/index.js" + }, + "./tools": { + "types": "./dist/esm/tools/index.d.ts", + "import": "./dist/esm/tools/index.js" + } },packages/typescript/smoke-tests/adapters/src/adapters/index.ts (1)
17-21: PrefercreateOpenRouter*factories to avoid redundant env lookup andanycasts.You already have
apiKey, butopenrouterText/openrouterSummarize/openrouterImagere-read from env and don’t acceptapiKeyin config. Using the explicit factories removes the casts and is clearer.♻️ Suggested refactor
-import { - openrouterImage, - openrouterSummarize, - openrouterText, -} from '@tanstack/ai-openrouter' +import { + createOpenRouterImage, + createOpenRouterSummarize, + createOpenRouterText, +} from '@tanstack/ai-openrouter' @@ return { - textAdapter: openrouterText(OPENROUTER_MODEL as any, { apiKey } as any), - summarizeAdapter: openrouterSummarize( - OPENROUTER_SUMMARY_MODEL as any, - { apiKey } as any, - ), - imageAdapter: openrouterImage( - OPENROUTER_IMAGE_MODEL as any, - { apiKey } as any, - ), + textAdapter: createOpenRouterText(OPENROUTER_MODEL as any, apiKey), + summarizeAdapter: createOpenRouterSummarize( + OPENROUTER_SUMMARY_MODEL as any, + apiKey, + ), + imageAdapter: createOpenRouterImage( + OPENROUTER_IMAGE_MODEL as any, + apiKey, + ), chatModel: OPENROUTER_MODEL, summarizeModel: OPENROUTER_SUMMARY_MODEL, imageModel: OPENROUTER_IMAGE_MODEL, }Also applies to: 207-215
packages/typescript/ai-openrouter/src/adapters/image.ts (1)
83-95: The redundantnandnumberOfImagesproperties appear intentional for provider compatibility.OpenRouter filters unsupported configuration per provider specifications, so sending both parameters is a defensive approach to ensure compatibility across different underlying models. Without evidence that all supported models accept only
n, removingnumberOfImagesrisks breaking requests for providers that expect alternative parameter names. The current implementation is correct; if simplification is desired, first verify that all target models support only thenparameter.📜 Review details
Configuration used: defaults
Review profile: CHILL
Plan: Pro
📥 Commits
Reviewing files that changed from the base of the PR and between ebfa0c3ad1f59d2726c48ddc86e19065e2f1a6e5 and ac1cbb9a187053e66b75292aadf95a68b9ade6fc.
⛔ Files ignored due to path filters (1)
pnpm-lock.yamlis excluded by!**/pnpm-lock.yaml
📒 Files selected for processing (38)
.claude/settings.local.jsondocs/adapters/openrouter.mddocs/config.jsonexamples/ts-react-chat/package.jsonexamples/ts-react-chat/src/lib/model-selection.tsexamples/ts-react-chat/src/routes/api.tanchat.tsexamples/ts-vue-chat/package.jsonpackage.jsonpackages/typescript/ai-devtools/package.jsonpackages/typescript/ai-openrouter/README.mdpackages/typescript/ai-openrouter/package.jsonpackages/typescript/ai-openrouter/src/adapters/image.tspackages/typescript/ai-openrouter/src/adapters/summarize.tspackages/typescript/ai-openrouter/src/adapters/text.tspackages/typescript/ai-openrouter/src/image/image-provider-options.tspackages/typescript/ai-openrouter/src/index.tspackages/typescript/ai-openrouter/src/message-types.tspackages/typescript/ai-openrouter/src/model-meta.tspackages/typescript/ai-openrouter/src/text/text-provider-options.tspackages/typescript/ai-openrouter/src/tools/function-tool.tspackages/typescript/ai-openrouter/src/tools/index.tspackages/typescript/ai-openrouter/src/tools/tool-converter.tspackages/typescript/ai-openrouter/src/tools/web-search-tool.tspackages/typescript/ai-openrouter/src/utils/client.tspackages/typescript/ai-openrouter/src/utils/index.tspackages/typescript/ai-openrouter/tests/image-adapter.test.tspackages/typescript/ai-openrouter/tests/openrouter-adapter.test.tspackages/typescript/ai-openrouter/tsconfig.jsonpackages/typescript/ai-openrouter/vite.config.tspackages/typescript/preact-ai-devtools/package.jsonpackages/typescript/react-ai-devtools/package.jsonpackages/typescript/smoke-tests/adapters/package.jsonpackages/typescript/smoke-tests/adapters/src/adapters/index.tspackages/typescript/smoke-tests/adapters/src/cli.tspackages/typescript/smoke-tests/adapters/src/tool-definition.test.tspackages/typescript/solid-ai-devtools/package.jsonscripts/convert-openrouter-models.tsscripts/openrouter.models.ts
✅ Files skipped from review due to trivial changes (2)
- examples/ts-vue-chat/package.json
- packages/typescript/smoke-tests/adapters/src/tool-definition.test.ts
🚧 Files skipped from review as they are similar to previous changes (5)
- packages/typescript/ai-openrouter/vite.config.ts
- packages/typescript/ai-openrouter/src/tools/function-tool.ts
- packages/typescript/ai-openrouter/src/tools/index.ts
- docs/config.json
- examples/ts-react-chat/src/routes/api.tanchat.ts
🧰 Additional context used
📓 Path-based instructions (6)
**/*.{ts,tsx}
📄 CodeRabbit inference engine (CLAUDE.md)
**/*.{ts,tsx}: Use tree-shakeable adapter architecture for provider implementations - export specialized adapters (text, embedding, summarize, image) as separate imports from/adapterssubpath rather than monolithic adapters Use Zod for runtime schema validation and type inference, particularly for tool input/output definitions withtoolDefinition()and Zod schema inference Implement isomorphic tool system usingtoolDefinition()with.server()and.client()implementations for dual-environment execution Use type-safe per-model configuration with provider options typed based on selected model to ensure compile-time safety Implement stream processing with StreamProcessor for handling chunked responses and support partial JSON parsing for streaming AI responsesFiles:
examples/ts-react-chat/src/lib/model-selection.tspackages/typescript/ai-openrouter/src/utils/index.tspackages/typescript/ai-openrouter/tests/openrouter-adapter.test.tspackages/typescript/ai-openrouter/src/image/image-provider-options.tspackages/typescript/ai-openrouter/tests/image-adapter.test.tspackages/typescript/ai-openrouter/src/adapters/summarize.tspackages/typescript/smoke-tests/adapters/src/adapters/index.tspackages/typescript/ai-openrouter/src/tools/tool-converter.tsscripts/convert-openrouter-models.tspackages/typescript/ai-openrouter/src/utils/client.tspackages/typescript/ai-openrouter/src/text/text-provider-options.tspackages/typescript/ai-openrouter/src/adapters/image.tspackages/typescript/ai-openrouter/src/index.tspackages/typescript/ai-openrouter/src/adapters/text.tspackages/typescript/ai-openrouter/src/tools/web-search-tool.tspackages/typescript/smoke-tests/adapters/src/cli.tspackages/typescript/ai-openrouter/src/message-types.ts
**/*.{ts,tsx,js,jsx}
📄 CodeRabbit inference engine (CLAUDE.md)
Use camelCase for function and variable names throughout the codebase
Files:
examples/ts-react-chat/src/lib/model-selection.tspackages/typescript/ai-openrouter/src/utils/index.tspackages/typescript/ai-openrouter/tests/openrouter-adapter.test.tspackages/typescript/ai-openrouter/src/image/image-provider-options.tspackages/typescript/ai-openrouter/tests/image-adapter.test.tspackages/typescript/ai-openrouter/src/adapters/summarize.tspackages/typescript/smoke-tests/adapters/src/adapters/index.tspackages/typescript/ai-openrouter/src/tools/tool-converter.tsscripts/convert-openrouter-models.tspackages/typescript/ai-openrouter/src/utils/client.tspackages/typescript/ai-openrouter/src/text/text-provider-options.tspackages/typescript/ai-openrouter/src/adapters/image.tspackages/typescript/ai-openrouter/src/index.tspackages/typescript/ai-openrouter/src/adapters/text.tspackages/typescript/ai-openrouter/src/tools/web-search-tool.tspackages/typescript/smoke-tests/adapters/src/cli.tspackages/typescript/ai-openrouter/src/message-types.ts
examples/**
📄 CodeRabbit inference engine (CLAUDE.md)
Examples are not built by Nx and should be run independently from their directories with
pnpm devorpnpm install && pnpm devFiles:
examples/ts-react-chat/src/lib/model-selection.tsexamples/ts-react-chat/package.json
**/*.test.ts
📄 CodeRabbit inference engine (CLAUDE.md)
Write unit tests using Vitest alongside source files with
.test.tsnaming conventionFiles:
packages/typescript/ai-openrouter/tests/openrouter-adapter.test.tspackages/typescript/ai-openrouter/tests/image-adapter.test.ts
packages/typescript/*/src/adapters/*.ts
📄 CodeRabbit inference engine (CLAUDE.md)
Create individual adapter implementations for each provider capability (text, embed, summarize, image) with separate exports to enable tree-shaking
Files:
packages/typescript/ai-openrouter/src/adapters/summarize.tspackages/typescript/ai-openrouter/src/adapters/image.tspackages/typescript/ai-openrouter/src/adapters/text.ts
packages/typescript/*/src/index.ts
📄 CodeRabbit inference engine (CLAUDE.md)
Export tree-shakeable adapters with clear subpath exports in package.json (e.g.,
@tanstack/ai/adapters,@tanstack/ai-openai/adapters) to minimize bundle sizeFiles:
packages/typescript/ai-openrouter/src/index.ts
🧠 Learnings (15)
📓 Common learnings
Learnt from: CR Repo: TanStack/ai PR: 0 File: CLAUDE.md:0-0 Timestamp: 2025-12-13T17:09:09.794Z Learning: Applies to packages/typescript/*/src/adapters/*.ts : Create individual adapter implementations for each provider capability (text, embed, summarize, image) with separate exports to enable tree-shakingLearnt from: CR Repo: TanStack/ai PR: 0 File: CLAUDE.md:0-0 Timestamp: 2025-12-13T17:09:09.794Z Learning: Applies to packages/typescript/*/src/index.ts : Export tree-shakeable adapters with clear subpath exports in package.json (e.g., `tanstack/ai/adapters`, `tanstack/ai-openai/adapters`) to minimize bundle sizeLearnt from: CR Repo: TanStack/ai PR: 0 File: CLAUDE.md:0-0 Timestamp: 2025-12-13T17:09:09.794Z Learning: Applies to **/*.{ts,tsx} : Use tree-shakeable adapter architecture for provider implementations - export specialized adapters (text, embedding, summarize, image) as separate imports from `/adapters` subpath rather than monolithic adapters📚 Learning: 2025-12-13T17:09:09.794Z
Learnt from: CR Repo: TanStack/ai PR: 0 File: CLAUDE.md:0-0 Timestamp: 2025-12-13T17:09:09.794Z Learning: Applies to packages/typescript/*/src/index.ts : Export tree-shakeable adapters with clear subpath exports in package.json (e.g., `tanstack/ai/adapters`, `tanstack/ai-openai/adapters`) to minimize bundle sizeApplied to files:
packages/typescript/ai-devtools/package.jsonpackages/typescript/solid-ai-devtools/package.jsonpackages/typescript/ai-openrouter/src/utils/index.tspackages/typescript/ai-openrouter/tests/openrouter-adapter.test.tspackages/typescript/ai-openrouter/package.jsonpackage.jsonpackages/typescript/smoke-tests/adapters/package.jsonexamples/ts-react-chat/package.jsonpackages/typescript/ai-openrouter/tests/image-adapter.test.tspackages/typescript/preact-ai-devtools/package.jsonpackages/typescript/ai-openrouter/src/adapters/summarize.tspackages/typescript/smoke-tests/adapters/src/adapters/index.tspackages/typescript/ai-openrouter/src/tools/tool-converter.tspackages/typescript/react-ai-devtools/package.jsonpackages/typescript/ai-openrouter/src/adapters/image.tspackages/typescript/ai-openrouter/src/index.tspackages/typescript/ai-openrouter/src/adapters/text.tspackages/typescript/smoke-tests/adapters/src/cli.tspackages/typescript/ai-openrouter/tsconfig.jsonpackages/typescript/ai-openrouter/README.md
📚 Learning: 2025-12-13T17:09:09.794Z
Learnt from: CR Repo: TanStack/ai PR: 0 File: CLAUDE.md:0-0 Timestamp: 2025-12-13T17:09:09.794Z Learning: Applies to packages/*/package.json : Use `workspace:*` protocol for internal package dependencies in package.json (e.g., `"tanstack/ai": "workspace:*"`)Applied to files:
packages/typescript/ai-devtools/package.jsonpackages/typescript/solid-ai-devtools/package.jsonpackages/typescript/ai-openrouter/package.jsonpackages/typescript/smoke-tests/adapters/package.jsonexamples/ts-react-chat/package.jsonpackages/typescript/preact-ai-devtools/package.jsonpackages/typescript/react-ai-devtools/package.json
📚 Learning: 2025-12-13T17:09:09.794Z
Learnt from: CR Repo: TanStack/ai PR: 0 File: CLAUDE.md:0-0 Timestamp: 2025-12-13T17:09:09.794Z Learning: Applies to **/*.{ts,tsx} : Use type-safe per-model configuration with provider options typed based on selected model to ensure compile-time safetyApplied to files:
examples/ts-react-chat/src/lib/model-selection.tspackages/typescript/ai-openrouter/src/image/image-provider-options.tspackages/typescript/ai-openrouter/src/text/text-provider-options.tspackages/typescript/ai-openrouter/src/adapters/text.ts
📚 Learning: 2025-12-13T17:09:09.794Z
Learnt from: CR Repo: TanStack/ai PR: 0 File: CLAUDE.md:0-0 Timestamp: 2025-12-13T17:09:09.794Z Learning: Applies to packages/typescript/*/src/model-meta.ts : Maintain model metadata files that define provider options and capabilities per model for per-model type safetyApplied to files:
examples/ts-react-chat/src/lib/model-selection.tspackages/typescript/ai-openrouter/src/image/image-provider-options.tspackage.jsonscripts/convert-openrouter-models.tspackages/typescript/ai-openrouter/src/text/text-provider-options.tspackages/typescript/ai-openrouter/src/adapters/image.tspackages/typescript/ai-openrouter/src/index.tspackages/typescript/ai-openrouter/src/adapters/text.tspackages/typescript/ai-openrouter/tsconfig.jsonpackages/typescript/ai-openrouter/src/message-types.ts
📚 Learning: 2025-12-13T17:09:09.794Z
Learnt from: CR Repo: TanStack/ai PR: 0 File: CLAUDE.md:0-0 Timestamp: 2025-12-13T17:09:09.794Z Learning: Applies to packages/typescript/*/src/adapters/*.ts : Create individual adapter implementations for each provider capability (text, embed, summarize, image) with separate exports to enable tree-shakingApplied to files:
examples/ts-react-chat/src/lib/model-selection.tspackages/typescript/ai-openrouter/src/utils/index.tspackages/typescript/ai-openrouter/tests/openrouter-adapter.test.tspackages/typescript/ai-openrouter/package.jsonpackages/typescript/ai-openrouter/src/image/image-provider-options.tspackages/typescript/smoke-tests/adapters/package.jsonpackages/typescript/ai-openrouter/tests/image-adapter.test.tspackages/typescript/ai-openrouter/src/adapters/summarize.tspackages/typescript/smoke-tests/adapters/src/adapters/index.tspackages/typescript/ai-openrouter/src/tools/tool-converter.tsscripts/convert-openrouter-models.tspackages/typescript/ai-openrouter/src/text/text-provider-options.tspackages/typescript/ai-openrouter/src/adapters/image.tspackages/typescript/ai-openrouter/src/index.tspackages/typescript/ai-openrouter/src/adapters/text.tspackages/typescript/smoke-tests/adapters/src/cli.tspackages/typescript/ai-openrouter/tsconfig.json
📚 Learning: 2025-12-13T17:09:09.794Z
Learnt from: CR Repo: TanStack/ai PR: 0 File: CLAUDE.md:0-0 Timestamp: 2025-12-13T17:09:09.794Z Learning: Applies to **/*.{ts,tsx} : Use tree-shakeable adapter architecture for provider implementations - export specialized adapters (text, embedding, summarize, image) as separate imports from `/adapters` subpath rather than monolithic adaptersApplied to files:
examples/ts-react-chat/src/lib/model-selection.tspackages/typescript/ai-openrouter/tests/openrouter-adapter.test.tspackages/typescript/smoke-tests/adapters/package.jsonpackages/typescript/ai-openrouter/tests/image-adapter.test.tspackages/typescript/ai-openrouter/src/adapters/summarize.tspackages/typescript/smoke-tests/adapters/src/adapters/index.tspackages/typescript/ai-openrouter/src/tools/tool-converter.tspackages/typescript/ai-openrouter/src/text/text-provider-options.tspackages/typescript/ai-openrouter/src/adapters/image.tspackages/typescript/ai-openrouter/src/index.tspackages/typescript/ai-openrouter/src/adapters/text.tspackages/typescript/smoke-tests/adapters/src/cli.ts
📚 Learning: 2025-12-13T17:09:09.794Z
Learnt from: CR Repo: TanStack/ai PR: 0 File: CLAUDE.md:0-0 Timestamp: 2025-12-13T17:09:09.794Z Learning: Applies to **/*.test.ts : Write unit tests using Vitest alongside source files with `.test.ts` naming conventionApplied to files:
packages/typescript/ai-openrouter/package.jsonpackage.jsonpackages/typescript/ai-openrouter/tsconfig.json
📚 Learning: 2025-12-13T17:09:09.794Z
Learnt from: CR Repo: TanStack/ai PR: 0 File: CLAUDE.md:0-0 Timestamp: 2025-12-13T17:09:09.794Z Learning: Applies to examples/** : Examples are not built by Nx and should be run independently from their directories with `pnpm dev` or `pnpm install && pnpm dev`Applied to files:
packages/typescript/ai-openrouter/package.jsonpackage.json
📚 Learning: 2025-12-13T17:09:09.794Z
Learnt from: CR Repo: TanStack/ai PR: 0 File: CLAUDE.md:0-0 Timestamp: 2025-12-13T17:09:09.794Z Learning: Applies to **/*.{ts,tsx} : Use Zod for runtime schema validation and type inference, particularly for tool input/output definitions with `toolDefinition()` and Zod schema inferenceApplied to files:
packages/typescript/smoke-tests/adapters/package.jsonpackages/typescript/ai-openrouter/src/text/text-provider-options.ts
📚 Learning: 2025-12-13T17:09:09.794Z
Learnt from: CR Repo: TanStack/ai PR: 0 File: CLAUDE.md:0-0 Timestamp: 2025-12-13T17:09:09.794Z Learning: Applies to .eslintrc* : Use ESLint with custom TanStack config for linting all TypeScript and JavaScript filesApplied to files:
packages/typescript/smoke-tests/adapters/package.jsonpackages/typescript/ai-openrouter/tsconfig.jsonpackages/typescript/ai-openrouter/README.md
📚 Learning: 2025-12-13T17:09:09.794Z
Learnt from: CR Repo: TanStack/ai PR: 0 File: CLAUDE.md:0-0 Timestamp: 2025-12-13T17:09:09.794Z Learning: Applies to **/*.{ts,tsx} : Implement isomorphic tool system using `toolDefinition()` with `.server()` and `.client()` implementations for dual-environment executionApplied to files:
packages/typescript/ai-openrouter/src/tools/tool-converter.tspackages/typescript/ai-openrouter/src/index.tspackages/typescript/ai-openrouter/src/tools/web-search-tool.tspackages/typescript/ai-openrouter/README.md
📚 Learning: 2025-12-27T20:22:51.232Z
Learnt from: harry-whorlow Repo: TanStack/ai PR: 117 File: packages/typescript/ai-ollama/src/meta/model-meta-gpt-oss.ts:92-97 Timestamp: 2025-12-27T20:22:51.232Z Learning: In the ai-ollama package's model-meta files (packages/typescript/ai-ollama/src/meta/model-meta-*.ts), capability-related comments follow a standard template format across all files for consistency, even if the comment text doesn't precisely match individual model capabilities. This is an intentional design choice to maintain uniformity across the codebase.Applied to files:
scripts/convert-openrouter-models.tspackages/typescript/ai-openrouter/src/adapters/text.tspackages/typescript/ai-openrouter/src/message-types.ts
📚 Learning: 2025-12-13T17:09:09.794Z
Learnt from: CR Repo: TanStack/ai PR: 0 File: CLAUDE.md:0-0 Timestamp: 2025-12-13T17:09:09.794Z Learning: Applies to **/*.{ts,tsx} : Implement stream processing with StreamProcessor for handling chunked responses and support partial JSON parsing for streaming AI responsesApplied to files:
packages/typescript/ai-openrouter/src/adapters/text.ts
📚 Learning: 2025-12-13T17:09:09.794Z
Learnt from: CR Repo: TanStack/ai PR: 0 File: CLAUDE.md:0-0 Timestamp: 2025-12-13T17:09:09.794Z Learning: Implement framework integrations using the headless `tanstack/ai-client` for state management with framework-specific hooks (useChat) on topApplied to files:
packages/typescript/ai-openrouter/README.md
🧬 Code graph analysis (8)
examples/ts-react-chat/src/lib/model-selection.ts (1)
testing/panel/src/lib/model-selection.ts (1)
Provider(1-1)
packages/typescript/ai-openrouter/tests/openrouter-adapter.test.ts (3)
packages/typescript/ai-openrouter/src/adapters/text.ts (1)
createOpenRouterText(492-498)
packages/typescript/ai-openrouter/src/index.ts (1)
createOpenRouterText(8-8)
packages/typescript/ai/src/types.ts (1)
StreamChunk(740-748)
packages/typescript/ai-openrouter/tests/image-adapter.test.ts (2)
packages/typescript/ai-openrouter/src/adapters/image.ts (1)
createOpenRouterImage(168-174)
packages/typescript/ai-openrouter/src/index.ts (1)
createOpenRouterImage(26-26)
packages/typescript/smoke-tests/adapters/src/adapters/index.ts (4)
packages/typescript/ai-openrouter/src/adapters/text.ts (1)
openrouterText(500-506)
packages/typescript/ai-openrouter/src/index.ts (3)
openrouterText(9-9)openrouterSummarize(18-18)openrouterImage(27-27)
packages/typescript/ai-openrouter/src/adapters/summarize.ts (1)
openrouterSummarize(174-180)
packages/typescript/ai-openrouter/src/adapters/image.ts (1)
openrouterImage(176-182)
packages/typescript/ai-openrouter/src/tools/tool-converter.ts (2)
packages/typescript/ai-openrouter/src/index.ts (2)
OpenRouterTool(80-80)FunctionTool(80-80)
packages/typescript/ai-openrouter/src/tools/function-tool.ts (2)
FunctionTool(3-10)convertFunctionToolToAdapterFormat(17-33)
scripts/convert-openrouter-models.ts (1)
scripts/openrouter.models.ts (2)
OpenRouterModel(1-36)models(37-16260)
packages/typescript/smoke-tests/adapters/src/cli.ts (2)
packages/typescript/smoke-tests/adapters/src/index.ts (1)
TestDefinition(26-26)
packages/typescript/smoke-tests/adapters/src/adapters/index.ts (1)
AdapterDefinition(52-61)
packages/typescript/ai-openrouter/src/message-types.ts (1)
packages/typescript/ai-openrouter/src/index.ts (6)
OpenRouterTextMetadata(45-45)OpenRouterImageMetadata(46-46)OpenRouterAudioMetadata(47-47)OpenRouterVideoMetadata(48-48)OpenRouterDocumentMetadata(49-49)OpenRouterMessageMetadataByModality(50-50)
🪛 Biome (2.1.2)
packages/typescript/ai-openrouter/src/message-types.ts
[error] 1-1: An empty interface is equivalent to {}.
Safe fix: Use a type alias instead.
(lint/suspicious/noEmptyInterface)
[error] 7-7: An empty interface is equivalent to {}.
Safe fix: Use a type alias instead.
(lint/suspicious/noEmptyInterface)
[error] 9-9: An empty interface is equivalent to {}.
Safe fix: Use a type alias instead.
(lint/suspicious/noEmptyInterface)
[error] 11-11: An empty interface is equivalent to {}.
Safe fix: Use a type alias instead.
(lint/suspicious/noEmptyInterface)
🪛 markdownlint-cli2 (0.18.1)
packages/typescript/ai-openrouter/README.md
47-47: Heading levels should only increment by one level at a time Expected: h2; Actual: h3
(MD001, heading-increment)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
- GitHub Check: Test
- GitHub Check: Preview
✏️ Tip: You can disable this entire section by setting `review_details` to `false` in your review settings.🔇 Additional comments (30)
examples/ts-react-chat/src/lib/model-selection.ts (1)
1-7: Address Provider union divergence and label capitalization across example and testing files.The example now includes
'openrouter'in the Provider union (line 7) and model options (lines 50-60), buttesting/panel/src/lib/model-selection.tsstill omits it. If both should support the same providers, update the panel. Additionally, the label capitalization is inconsistent: use "OpenRouter" instead of "Openrouter" on lines 54 and 59 to match other provider labels (OpenAI, Anthropic, Gemini, etc.).Also note:
examples/ts-react-chat/src/routes/api.tanchat.tsuses'openai/gpt-5.2'as the default OpenRouter model (line 97), but the actual available models inMODEL_OPTIONSare'openai/chatgpt-4o-latest'and'openai/chatgpt-4o-mini'. Align the default model or document the discrepancy.⛔ Skipped due to learnings
Learnt from: CR Repo: TanStack/ai PR: 0 File: CLAUDE.md:0-0 Timestamp: 2025-12-13T17:09:09.794Z Learning: Applies to **/*.{ts,tsx} : Use type-safe per-model configuration with provider options typed based on selected model to ensure compile-time safetyLearnt from: CR Repo: TanStack/ai PR: 0 File: CLAUDE.md:0-0 Timestamp: 2025-12-13T17:09:09.794Z Learning: Applies to packages/typescript/*/src/model-meta.ts : Maintain model metadata files that define provider options and capabilities per model for per-model type safetyLearnt from: CR Repo: TanStack/ai PR: 0 File: CLAUDE.md:0-0 Timestamp: 2025-12-13T17:09:09.794Z Learning: Applies to packages/typescript/*/src/adapters/*.ts : Create individual adapter implementations for each provider capability (text, embed, summarize, image) with separate exports to enable tree-shakingpackages/typescript/preact-ai-devtools/package.json (1)
50-53: No changes needed –@tanstack/devtools-utilsis an external dependency.@tanstack/devtools-utilsis not a workspace package and should not use theworkspace:*protocol. The caret version^0.3.0is correct for external npm dependencies. The code as written is already compliant with the monorepo policy.package.json (1)
35-35: LGTM!The new
generate:modelsscript andtsxdevDependency are appropriate additions for the OpenRouter model metadata generation workflow.Also applies to: 69-69
packages/typescript/smoke-tests/adapters/package.json (1)
20-20: LGTM!The
@tanstack/ai-openrouterdependency correctly usesworkspace:*protocol per project conventions, and thetsxversion bump aligns with the root package. Based on learnings, the workspace protocol is the expected pattern for internal package dependencies.Also applies to: 27-27
packages/typescript/ai-openrouter/tsconfig.json (1)
1-9: LGTM!Standard TypeScript configuration that correctly extends the root tsconfig and uses appropriate include/exclude patterns consistent with other adapter packages.
packages/typescript/ai-openrouter/README.md (1)
41-45: Documentation additions look good.The new content clearly documents multimodal support, isomorphic tools, and the TanStack Start integration bonus with a practical code example.
Also applies to: 49-72
packages/typescript/ai-openrouter/src/tools/web-search-tool.ts (1)
1-23: LGTM!Clean implementation with appropriate camelCase function parameters mapping to snake_case wire format. The factory pattern is well-suited for this use case. Per coding guidelines, camelCase is correctly used for function and variable names.
packages/typescript/ai-openrouter/package.json (1)
41-51: Dependencies and peer dependencies look correct.The use of
@openrouter/sdkaligns with the PR discussion recommending the SDK over direct fetch calls. Theworkspace:*protocol for@tanstack/aiis correctly used and will be rewritten to proper semver during publishing.examples/ts-react-chat/package.json (1)
20-20: LGTM!The OpenRouter dependency addition follows the established pattern using
workspace:*protocol, consistent with other TanStack AI packages in this example.packages/typescript/ai-openrouter/src/tools/tool-converter.ts (1)
1-11: LGTM!Clean implementation with proper type re-export for OpenRouter context. The converter function correctly delegates to
convertFunctionToolToAdapterFormatfor each tool.packages/typescript/ai-openrouter/src/image/image-provider-options.ts (1)
6-12: LGTM on base options interface.The
OpenRouterImageProviderOptionsinterface is well-documented with clear comments explaining the resolution mapping.packages/typescript/smoke-tests/adapters/src/cli.ts (3)
117-120: LGTM on type annotation standardization.The change from
T[]toArray<T>syntax improves consistency across the codebase. Both forms are semantically equivalent.
180-184: Consistent type annotations applied.The
runSequentialfunction signature and return type correctly use theArray<T>form.
242-251: Parallel execution types standardized.The
runParallelfunction and local variables (tasks,skippedAdapters) consistently useArray<T>syntax.packages/typescript/ai-openrouter/src/utils/index.ts (1)
1-6: LGTM — clean utility barrel export.packages/typescript/ai-openrouter/tests/image-adapter.test.ts (1)
1-227: Strong coverage for image adapter behavior.packages/typescript/ai-openrouter/tests/openrouter-adapter.test.ts (1)
1-101: Use the correct type name:OpenRouterTextModelOptionsinstead ofOpenRouterTextProviderOptions.The type
OpenRouterTextProviderOptionsdoes not exist in the codebase. The test should useOpenRouterTextModelOptionswhich is exported from../src/adapters/text. Alternatively, you can useExternalTextProviderOptionsfrom../src/text/text-provider-options.🧩 Proposed fix
-import { createOpenRouterText } from '../src/adapters/text' +import { createOpenRouterText, type OpenRouterTextModelOptions } from '../src/adapters/text'Then update line 97:
-const modelOptions: OpenRouterTextProviderOptions = { +const modelOptions: OpenRouterTextModelOptions = {Likely an incorrect or invalid review comment.
packages/typescript/ai-openrouter/src/utils/client.ts (1)
16-56: LGTM — clean env resolution and header construction.scripts/convert-openrouter-models.ts (1)
14-42: LGTM — modality mapping and pricing normalization look good.packages/typescript/ai-openrouter/src/adapters/summarize.ts (2)
65-76: Confirm whetherStreamChunk.contentis a delta; append if so.Currently Line 73 overwrites
summarywith each chunk. IfStreamChunk.contentis a delta, this will drop earlier content. If it’s cumulative, this is fine—please verify and adjust accordingly.🔧 Suggested change if content is delta
- if (chunk.type === 'content') { - summary = chunk.content + if (chunk.type === 'content') { + summary += chunk.content id = chunk.id model = chunk.model }
128-180: LGTM — factory helpers are clean and ergonomic.packages/typescript/ai-openrouter/src/adapters/image.ts (3)
1-23: LGTM!Imports and type definitions are well-structured. The adapter follows the tree-shakeable architecture pattern with separate capability exports as per coding guidelines.
25-40: LGTM!The aspect ratio mapping provides a useful abstraction for common image sizes. The comment correctly notes its usage for Gemini and other models.
168-182: LGTM!Factory functions follow the established pattern with
createOpenRouterImagefor explicit API key andopenrouterImagefor environment-based key resolution.packages/typescript/ai-openrouter/src/adapters/text.ts (5)
1-62: LGTM!Imports and type definitions are comprehensive. The
ToolCallBufferinterface and generic type resolution helpers (ResolveProviderOptions,ResolveInputModalities) provide good type safety.
157-222: LGTM!The
structuredOutputmethod correctly implements tool-based structured output with appropriate fallback to content parsing and proper error handling for aborted requests.
243-359: LGTM!The
processChoicegenerator handles streaming chunks comprehensively—content deltas, reasoning details, tool calls accumulation, refusals, and finish signaling with usage stats are all properly processed.
441-489: LGTM!The
convertContentPartsmethod handles multimodal content types (text, image, audio, video, document) appropriately, with sensible fallbacks for unsupported types like documents.
492-506: LGTM!Factory functions follow the established pattern consistently with the image adapter.
packages/typescript/ai-openrouter/src/index.ts (1)
1-80: LGTM!The barrel file follows the tree-shakeable adapter architecture with clear subpath exports. The organization into sections (Adapters, Types, Utils, Tools) with descriptive comments improves discoverability. This aligns well with the coding guidelines for
packages/typescript/*/src/index.ts.@@ -0,0 +1,12 @@1+{2+ "permissions": {3+ "allow": [4+ "Bash(pnpm install:*)",5+ "Bash(node -e:*)",6+ "Bash(pnpm start:*)",7+ "Bash(pnpm test:lib:*)",8+ "Bash(pnpm typecheck:*)",9+ "Bash(pnpm build:*)",10+ "Bash(find:*)"11+ ]12+ }⚠️ Potential issue | 🟡 Minor
🧩 Analysis chain
🏁 Script executed:
# Check if .claude/settings.local.json is tracked in git git ls-files | grep -E "\.claude/|settings"Repository: TanStack/ai
Length of output: 82
🏁 Script executed:
# Check .gitignore for .local patterns cat .gitignore 2>/dev/null || echo "No .gitignore found"Repository: TanStack/ai
Length of output: 751
🏁 Script executed:
# Search for other .local files in the repository find . -type f -name "*.local.*" 2>/dev/null | head -20Repository: TanStack/ai
Length of output: 84
🏁 Script executed:
# Check .claude directory structure ls -la .claude/ 2>/dev/null || echo ".claude directory not found"Repository: TanStack/ai
Length of output: 234
🏁 Script executed:
# Search for documentation about .claude directory find . -type f \( -name "README*" -o -name "SETTINGS*" -o -name "CONFIG*" \) -exec grep -l "\.claude" {} \;Repository: TanStack/ai
Length of output: 37
Rename
.claude/settings.local.jsonto.claude/settings.jsonto better reflect its intended status as shared configuration.The file is tracked in git and not ignored (unlike per-developer files like
.env.local), so it's clearly meant to be shared. However, the.localsuffix is misleading since similar tool configs in this repo (.cursor/rules,.vscode/settings.json) don't use it. Rename for consistency.🤖 Prompt for AI Agents
In @.claude/settings.local.json around lines 1 - 12, Rename the tracked config file from .claude/settings.local.json to .claude/settings.json and update any repository references to it (e.g., CI scripts, docs, or tooling configs) so they point to the new name; ensure you remove the old file path and add the new file path in git (git mv or equivalent) to preserve history, and verify that no developer-specific secrets were accidentally committed before making the rename.@@ -41,3 +47,14 @@4147 label: 'Gemini 2.5 - Flash',4248 },434950+ // Openrouter51+ {52+ provider: 'openrouter',53+ model: 'openai/chatgpt-4o-latest',54+ label: 'Openrouter - ChatGPT 4o Latest',55+ },56+ {57+ provider: 'openrouter',58+ model: 'openai/chatgpt-4o-mini',59+ label: 'Openrouter - ChatGPT 4o Mini',60+ },⚠️ Potential issue | 🟡 Minor
🧩 Analysis chain
🌐 Web query:
OpenRouter API model catalog "openai/chatgpt-4o-latest" "openai/chatgpt-4o-mini"💡 Result:
Yes — OpenRouter’s model catalog includes OpenAI’s ChatGPT/GPT‑4o entries under the IDs you listed:
- openai/chatgpt-4o-latest — the ChatGPT snapshot of GPT‑4o (used by ChatGPT; 128K context, 16,384 max output tokens). [OpenRouter catalog]. [OpenAI docs]. [1][2]
- openai/chatgpt-4o-mini (aka openai/gpt-4o-mini) — OpenAI’s GPT‑4o mini (small, cost‑efficient multimodal model; 128K context; priced much lower than larger GPT‑4o variants). [OpenAI announcement and docs; OpenRouter listing]. [3][4]
If you want, I can:
- show the exact OpenRouter API call examples for those model IDs, or
- fetch the latest OpenRouter catalog pages or pricing for each model now. Which would you like?
Sources: [1] OpenRouter — ChatGPT-4o model page. [2] OpenAI — ChatGPT-4o model docs. [3] OpenAI — GPT‑4o mini announcement/docs. [4] OpenRouter / third‑party catalogs listing gpt‑4o‑mini.
🏁 Script executed:
# Check the file to see context and other provider capitalization cat -n examples/ts-react-chat/src/lib/model-selection.ts | head -80Repository: TanStack/ai
Length of output: 2264
Standardize label capitalization to "OpenRouter" for consistency.
The OpenRouter model IDs (
openai/chatgpt-4o-latestandopenai/chatgpt-4o-mini) are valid and currently available in OpenRouter's catalog. However, the labels use "Openrouter" (lowercase 'r'), which is inconsistent with other providers in this file (OpenAI, Anthropic, Gemini, Ollama) and the official company branding "OpenRouter".✏️ Capitalization fix
- label: 'Openrouter - ChatGPT 4o Latest', + label: 'OpenRouter - ChatGPT 4o Latest', }, { provider: 'openrouter', model: 'openai/chatgpt-4o-mini', - label: 'Openrouter - ChatGPT 4o Mini', + label: 'OpenRouter - ChatGPT 4o Mini', },📝 Committable suggestion
‼️ IMPORTANT Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
Suggested change50- // Openrouter51- {52- provider: 'openrouter',53- model: 'openai/chatgpt-4o-latest',54- label: 'Openrouter - ChatGPT 4o Latest',55- },56- {57- provider: 'openrouter',58- model: 'openai/chatgpt-4o-mini',59- label: 'Openrouter - ChatGPT 4o Mini',60- },50+ // Openrouter51+ {52+ provider: 'openrouter',53+ model: 'openai/chatgpt-4o-latest',54+ label: 'OpenRouter - ChatGPT 4o Latest',55+ },56+ {57+ provider: 'openrouter',58+ model: 'openai/chatgpt-4o-mini',59+ label: 'OpenRouter - ChatGPT 4o Mini',60+ },🤖 Prompt for AI Agents
In `@examples/ts-react-chat/src/lib/model-selection.ts` around lines 50 - 60, Update the label capitalization for the OpenRouter entries so they read "OpenRouter - ChatGPT 4o Latest" and "OpenRouter - ChatGPT 4o Mini"; locate the objects with provider: 'openrouter' and model: 'openai/chatgpt-4o-latest' and 'openai/chatgpt-4o-mini' and change their label values from "Openrouter - ..." to "OpenRouter - ..." to match branding and other provider capitalization.@@ -0,0 +91,21 @@91+ ? {92+ image_size: modelOptions.image_size,93+ }94+ : {}),95+ },96+ })97+98+ // Check for error in response99+ if ('error' in response && response.error) {100+ const errorMsg =101+ typeof response.error === 'object' && 'message' in response.error102+ ? (response.error as { message: string }).message103+ : String(response.error)104+ throw new Error(`Image generation failed: ${errorMsg}`)105+ }106+107+ return this.transformResponse(model, response)108+ } catch (error) {109+ const message = (error as Error).message || 'Unknown error'110+ throw new Error(`Image generation failed: ${message}`)111+ }⚠️ Potential issue | 🟡 Minor
Error messages may be double-wrapped.
When an error is thrown inside the try block (line 104), it's caught and re-wrapped with the same prefix
"Image generation failed:", resulting in messages like"Image generation failed: Image generation failed: ...".🐛 Proposed fix
} catch (error) { - const message = (error as Error).message || 'Unknown error' - throw new Error(`Image generation failed: ${message}`) + if (error instanceof Error && error.message.startsWith('Image generation failed:')) { + throw error + } + const message = (error as Error).message || 'Unknown error' + throw new Error(`Image generation failed: ${message}`) }🤖 Prompt for AI Agents
In `@packages/typescript/ai-openrouter/src/adapters/image.ts` around lines 108 - 111, The catch block currently always wraps the caught error with "Image generation failed:", causing double-wrapping; update the handler so that if the caught value is an Error whose message already startsWith "Image generation failed:" you rethrow the original Error (or return it) instead of wrapping again, otherwise construct a new Error with the prefix and the original message; specifically modify the catch handling around the try-catch in the image generation logic (the catch(error) block that computes message and throws new Error(`Image generation failed: ${message}`)) to check (error instanceof Error && error.message.startsWith('Image generation failed:')) ? throw error : throw new Error(`Image generation failed: ${message}`).@@ -0,0 +138,21 @@138+ for (const choice of responseWithImages.choices) {139+ const choiceImages = choice.message.images140+ if (choiceImages) {141+ for (const img of choiceImages) {142+ const url = img.image_url.url143+ if (url.startsWith('data:')) {144+ const base64Match = url.match(/^data:image\/[^;]+;base64,(.+)$/)145+ if (base64Match) {146+ images.push({147+ b64Json: base64Match[1],148+ url: url,149+ })150+ } else {151+ images.push({ url })152+ }153+ } else {154+ images.push({ url })155+ }156+ }157+ }158+ }⚠️ Potential issue | 🟠 Major
Potential null pointer dereference on
choice.message.The code accesses
choice.message.imageswithout checking ifchoice.messageexists. The type assertion on lines 126-136 showsmessageis optional, but the access on line 139 doesn't use optional chaining.🐛 Proposed fix
for (const choice of responseWithImages.choices) { - const choiceImages = choice.message.images + const choiceImages = choice.message?.images if (choiceImages) {🤖 Prompt for AI Agents
In `@packages/typescript/ai-openrouter/src/adapters/image.ts` around lines 138 - 158, The loop over responseWithImages.choices reads choice.message.images without guarding for a missing message; update the code to safely handle an optional message by using optional chaining or an explicit null check (e.g., use choice.message?.images or if (choice.message && choice.message.images) before iterating). Apply this change where choiceImages is assigned in the block that iterates choices so the subsequent imgs loop only runs when images exist and avoids null/undefined dereference of choice.message.@@ -0,0 +100,21 @@100+ { signal: options.request?.signal },101+ )102+103+ for await (const chunk of stream) {104+ if (chunk.id) responseId = chunk.id105+ if (chunk.model) currentModel = chunk.model106+107+ if (chunk.error) {108+ yield this.createErrorChunk(109+ chunk.error.message || 'Unknown error',110+ currentModel || options.model,111+ timestamp,112+ String(chunk.error.code),113+ )114+ continue115+ }116+117+ for (const choice of chunk.choices) {118+ if (chunk.choices[0]?.finishReason) {119+ lastFinishReason = chunk.choices[0].finishReason120+ }⚠️ Potential issue | 🟠 Major
Loop iteration checks first choice instead of current choice.
Inside the
for (const choice of chunk.choices)loop, line 118 always checkschunk.choices[0]?.finishReasoninstead of the currentchoice.finishReason. This will miss finish reasons from non-first choices.🐛 Proposed fix
for (const choice of chunk.choices) { - if (chunk.choices[0]?.finishReason) { - lastFinishReason = chunk.choices[0].finishReason + if (choice.finishReason) { + lastFinishReason = choice.finishReason }📝 Committable suggestion
‼️ IMPORTANT Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
Suggested change113- )114- continue115- }116-113+ for (const choice of chunk.choices) {114+ if (choice.finishReason) {115+ lastFinishReason = choice.finishReason116+ }🤖 Prompt for AI Agents
In `@packages/typescript/ai-openrouter/src/adapters/text.ts` around lines 117 - 120, The loop over chunk.choices incorrectly inspects chunk.choices[0] instead of the current iteration variable; update the loop body in the for (const choice of chunk.choices) block to check choice?.finishReason and assign lastFinishReason = choice.finishReason (preserving optional chaining) so finish reasons from non-first choices are correctly captured; locate the change around the chunk.choices loop and the lastFinishReason assignment.@@ -0,0 +18,21 @@18+export type OpenRouterImageModelProviderOptionsByName = {19+ [K in (typeof OPENROUTER_IMAGE_MODELS)[number]]: OpenRouterImageProviderOptions20+}21+22+/**23+ * Per-model default image sizes24+ * All models currently default to '1024x1024'25+ */26+export type OpenRouterImageModelSizeByName = {27+ [K in (typeof OPENROUTER_IMAGE_MODELS)[number]]:28+ | '1024x1024' // "1:1"29+ | '832×1248' // "2:3"30+ | '1248×832' // "3:2"31+ | '864×1184' // "3:4"32+ | '1184×864' // "4:3"33+ | '896×1152' // "4:5"34+ | '1152×896' // "5:4"35+ | '768×1344' // "9:16"36+ | '1344×768' // "16:9"37+ | '1536×672' // "21:9"38+}⚠️ Potential issue | 🟠 Major
🧩 Analysis chain
🌐 Web query:
OpenRouter API image generation response dimensions format💡 Result:
OpenRouter image-generation responses include an images array inside the assistant message where each image is returned as a base64 data-URL (e.g. "data:image/png;base64,..."). The response does not include separate width/height numeric fields — image dimensions are determined by the model and the request parameters (e.g. size/aspect_ratio or image_size), not a dedicated width/height fields in the response. [1][2]
Sources:
- OpenRouter docs — image responses use images → image_url data URLs (PNG base64). [1]
- Provider/adapter docs (LiteLLM) — client params map to aspect_ratio/image_size; responses contain base64 b64_json data. [2]
🏁 Script executed:
# Search for how these dimension values are used in the codebase rg "1024x1024|832.*1248|image.*size" packages/typescript/ai-openrouter --type ts -A 3 -B 3Repository: TanStack/ai
Length of output: 5729
🏁 Script executed:
# Check if there's any API response handling or validation that uses these dimension values fd . packages/typescript/ai-openrouter --type f -name "*.ts" -o -name "*.tsx" | xargs rg -l "size|dimension" | head -10Repository: TanStack/ai
Length of output: 663
🏁 Script executed:
# Look at the entire image-provider-options.ts file to understand context cat -n packages/typescript/ai-openrouter/src/image/image-provider-options.tsRepository: TanStack/ai
Length of output: 1350
🏁 Script executed:
# Search for usages of OpenRouterImageModelSizeByName type rg "OpenRouterImageModelSizeByName" packages/typescript/ai-openrouter --type tsRepository: TanStack/ai
Length of output: 431
🏁 Script executed:
# Check if the type is actually enforced anywhere or just a definition rg "size.*1024|1024.*size" packages/typescript/ai-openrouter/src/adapters/image.ts -B 5 -A 5Repository: TanStack/ai
Length of output: 37
🏁 Script executed:
# View the image.ts file to see how OpenRouterImageModelSizeByName is used cat -n packages/typescript/ai-openrouter/src/adapters/image.ts | head -100Repository: TanStack/ai
Length of output: 3660
🏁 Script executed:
# Look for the actual constant definitions that use this type rg -A 30 "OpenRouterImageModelSizeByName" packages/typescript/ai-openrouter/src/adapters/image.tsRepository: TanStack/ai
Length of output: 1826
Type definition inconsistency causes aspect ratio lookup failures.
The
OpenRouterImageModelSizeByNametype allows both lowercasex(line 28) and Unicode×(lines 29-37), but theSIZE_TO_ASPECT_RATIOmapping inimage.tsonly defines keys with lowercasex. When a size string with×is passed, the lookup at line 69 ofimage.tssilently returnsundefined, preventing the aspect ratio from being configured in the API request.Replace all Unicode
×characters with lowercasexto match the runtime implementation:Suggested fix
export type OpenRouterImageModelSizeByName = { [K in (typeof OPENROUTER_IMAGE_MODELS)[number]]: | '1024x1024' // "1:1" - | '832×1248' // "2:3" - | '1248×832' // "3:2" - | '864×1184' // "3:4" - | '1184×864' // "4:3" - | '896×1152' // "4:5" - | '1152×896' // "5:4" - | '768×1344' // "9:16" - | '1344×768' // "16:9" - | '1536×672' // "21:9" + | '832x1248' // "2:3" + | '1248x832' // "3:2" + | '864x1184' // "3:4" + | '1184x864' // "4:3" + | '896x1152' // "4:5" + | '1152x896' // "5:4" + | '768x1344' // "9:16" + | '1344x768' // "16:9" + | '1536x672' // "21:9" }📝 Committable suggestion
‼️ IMPORTANT Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
Suggested change26-export type OpenRouterImageModelSizeByName = {27- [K in (typeof OPENROUTER_IMAGE_MODELS)[number]]:28- | '1024x1024' // "1:1"29- | '832×1248' // "2:3"30- | '1248×832' // "3:2"31- | '864×1184' // "3:4"32- | '1184×864' // "4:3"33- | '896×1152' // "4:5"34- | '1152×896' // "5:4"35- | '768×1344' // "9:16"36- | '1344×768' // "16:9"37- | '1536×672' // "21:9"38-}26+export type OpenRouterImageModelSizeByName = {27+ [K in (typeof OPENROUTER_IMAGE_MODELS)[number]]:28+ | '1024x1024' // "1:1"29+ | '832x1248' // "2:3"30+ | '1248x832' // "3:2"31+ | '864x1184' // "3:4"32+ | '1184x864' // "4:3"33+ | '896x1152' // "4:5"34+ | '1152x896' // "5:4"35+ | '768x1344' // "9:16"36+ | '1344x768' // "16:9"37+ | '1536x672' // "21:9"38+}🤖 Prompt for AI Agents
In `@packages/typescript/ai-openrouter/src/image/image-provider-options.ts` around lines 26 - 38, The type OpenRouterImageModelSizeByName uses mixed Unicode '×' and ASCII 'x' characters causing lookups against SIZE_TO_ASPECT_RATIO in image.ts to fail; update the OpenRouterImageModelSizeByName union so every size string uses the ASCII lowercase 'x' (e.g., '832x1248', '1248x832', etc.) to exactly match the keys used by SIZE_TO_ASPECT_RATIO and ensure aspect ratio lookups in the image handling code (where SIZE_TO_ASPECT_RATIO is used) return the expected values.scripts/convert-openrouter-models.ts lines 4 to 7Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +1,7 @@1+/**2+ * Script to convert OpenRouter model objects to ModelMeta format3+ *4+ * Usage:5+ * 1. Paste your OpenRouter models array into the `models` variable below6+ * 2. Run: npx ts-node scripts/convert-openrouter-models.ts7+ * 3. Copy the output into your model-meta.ts file⚠️ Potential issue | 🟡 Minor
Keep script usage instructions consistent (
ts-nodevstsx).Line 6 says
ts-node, while Line 207 showstsx. Pick one runner and align both references to avoid confusion.Also applies to: 205-208
🤖 Prompt for AI Agents
In `@scripts/convert-openrouter-models.ts` around lines 4 - 7, Update the usage instructions in scripts/convert-openrouter-models.ts so both runner references are identical: choose either "ts-node" or "tsx" and replace the other occurrence so the header comment (the Usage steps referencing the `models` variable) and the later example command both use the same runner; ensure any example command string that mentions running the script is changed consistently (e.g., change "npx ts-node scripts/convert-openrouter-models.ts" or "npx tsx scripts/convert-openrouter-models.ts" so both instances match).✅ Addressed in commits 72a6b55 to 37aadc9
@@ -0,0 +115,21 @@115+ const outputPrice = convertPricing(model.pricing.completion)116+ const imagePrice = convertPricing(model.pricing.image ?? '0', true)117+ const inputCacheReadPrice = convertPricing(118+ model.pricing.input_cache_read ?? '0',119+ )120+ const inputCacheWritePrice = convertPricing(121+ model.pricing.input_cache_write ?? '0',122+ )123+124+ // Build the object as a formatted string125+ const lines: Array<string> = []126+ lines.push(`const ${constName} = {`)127+ lines.push(` id: '${model.id}',`)128+ lines.push(` name: '${model.name.replace(/'/g, "\\'")}',`)129+ lines.push(` supports: {`)130+ lines.push(131+ ` input: [${inputModalities.map((m) => `'${m}'`).join(', ')}],`,132+ )133+ lines.push(134+ ` output: [${inputModalities.map((m) => `'${m}'`).join(', ')}],`,135+ )⚠️ Potential issue | 🟠 Major
Use output modalities for
supports.outputand model categorization.At Line 130–135,
supports.outputmirrors input modalities, and at Line 105–113 image/video/chat sets are derived from input modalities. This misrepresents output capabilities (e.g., text→image models). Usemodel.architecture.output_modalitiesfor output and for image/video classification.🐛 Proposed fix
const inputModalities = model.architecture.input_modalities .map(mapInputModality) .filter((m): m is InputModality => m !== null) + const outputModalities = model.architecture.output_modalities + .map(mapInputModality) + .filter((m): m is InputModality => m !== null) @@ - if (inputModalities.includes('text')) { + if (outputModalities.includes('text')) { chatModels.add(`${constName}.id`) } - if (inputModalities.includes('image')) { + if (outputModalities.includes('image')) { imageModels.add(`${constName}.id`) } - if (inputModalities.includes('video')) { + if (outputModalities.includes('video')) { videoModels.add(`${constName}.id`) } @@ - ` output: [${inputModalities.map((m) => `'${m}'`).join(', ')}],`, + ` output: [${outputModalities.map((m) => `'${m}'`).join(', ')}],`,📝 Committable suggestion
‼️ IMPORTANT Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
Suggested change108+function generateModelMetaString(model: OpenRouterModel): string {109+ const inputModalities = model.architecture.input_modalities110+ .map(mapInputModality)111+ .filter((m): m is InputModality => m !== null)112+ const outputModalities = model.architecture.output_modalities113+ .map(mapInputModality)114+ .filter((m): m is InputModality => m !== null)115+ const constName = model.id116+ .replaceAll('/', '-')117+ .replaceAll('-', '_')118+ .replaceAll('.', '_')119+ .replaceAll(':', '_')120+ .toUpperCase()121+ // Ensure at least 'text' is present122+ if (!inputModalities.includes('text')) {123+ inputModalities.unshift('text')124+ }125+ if (outputModalities.includes('text')) {126+ chatModels.add(`${constName}.id`)127+ }128+ if (outputModalities.includes('image')) {129+ imageModels.add(`${constName}.id`)130+ }131+ if (outputModalities.includes('video')) {132+ videoModels.add(`${constName}.id`)133+ }134+ const inputPrice = convertPricing(model.pricing.prompt)135+ const outputPrice = convertPricing(model.pricing.completion)136+ const imagePrice = convertPricing(model.pricing.image ?? '0', true)137+ const inputCacheReadPrice = convertPricing(138+ model.pricing.input_cache_read ?? '0',139+ )140+ const inputCacheWritePrice = convertPricing(141+ model.pricing.input_cache_write ?? '0',142+ )143+144+ // Build the object as a formatted string145+ const lines: Array<string> = []146+ lines.push(`const ${constName} = {`)147+ lines.push(` id: '${model.id}',`)148+ lines.push(` name: '${model.name.replace(/'/g, "\\'")}',`)149+ lines.push(` supports: {`)150+ lines.push(151+ ` input: [${inputModalities.map((m) => `'${m}'`).join(', ')}],`,152+ )153+ lines.push(154+ ` output: [${outputModalities.map((m) => `'${m}'`).join(', ')}],`,155+ )🤖 Prompt for AI Agents
In `@scripts/convert-openrouter-models.ts` around lines 91 - 135, generateModelMetaString currently uses input_modalities for supports.output and for populating chatModels/imageModels/videoModels, which mislabels models with different output capabilities; change the code to read and map model.architecture.output_modalities (e.g., const outputModalities = model.architecture.output_modalities.map(mapInputModality).filter((m): m is InputModality => m !== null)) and use outputModalities for the supports.output line and for adding to imageModels, videoModels, and chatModels; if a dedicated mapper exists for outputs use that instead of mapInputModality.✅ Addressed in commits 72a6b55 to 37aadc9
@@ -0,0 +159,21 @@159+ lines.push(` },`)160+ lines.push(` },`)161+ lines.push(` image: ${imagePrice},`)162+ lines.push(` },`)163+ lines.push(` } as const`)164+165+ perModelProviderOptions[`${constName}.id`] =166+ model.supported_parameters && model.supported_parameters.length > 0167+ ? `OpenRouterCommonOptions & Pick<OpenRouterBaseOptions,${168+ model.supported_parameters169+ .map((p) =>170+ p === 'tools' ||171+ p === 'reasoning_effort' ||172+ p === 'structured_outputs'173+ ? ''174+ : `'${p === 'max_tokens' ? 'max_completion_tokens' : p}'`,175+ )176+ .filter(Boolean)177+ .join(' | ') || ''178+ }>`179+ : 'OpenRouterCommonOptions & OpenRouterBaseOptions'⚠️ Potential issue | 🟠 Major
Guard against empty
Pick<>when supported parameters are all excluded.If
supported_parametersonly contains values filtered out (e.g., tools/structured_outputs), the generated type becomesPick<OpenRouterBaseOptions, >, which is invalid TS. Compute the filtered list first and fall back toOpenRouterCommonOptions & OpenRouterBaseOptionswhen empty.🐛 Proposed fix
- perModelProviderOptions[`${constName}.id`] = - model.supported_parameters && model.supported_parameters.length > 0 - ? `OpenRouterCommonOptions & Pick<OpenRouterBaseOptions,${ - model.supported_parameters - .map((p) => - p === 'tools' || - p === 'reasoning_effort' || - p === 'structured_outputs' - ? '' - : `'${p === 'max_tokens' ? 'max_completion_tokens' : p}'`, - ) - .filter(Boolean) - .join(' | ') || '' - }>` - : 'OpenRouterCommonOptions & OpenRouterBaseOptions' + const supportedKeys = (model.supported_parameters ?? []) + .map((p) => + p === 'tools' || + p === 'reasoning_effort' || + p === 'structured_outputs' + ? '' + : `'${p === 'max_tokens' ? 'max_completion_tokens' : p}'`, + ) + .filter(Boolean) + perModelProviderOptions[`${constName}.id`] = + supportedKeys.length > 0 + ? `OpenRouterCommonOptions & Pick<OpenRouterBaseOptions, ${supportedKeys.join(' | ')}>` + : 'OpenRouterCommonOptions & OpenRouterBaseOptions'📝 Committable suggestion
‼️ IMPORTANT Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
Suggested change193+ const supportedKeys = (model.supported_parameters ?? [])194+ .map((p) =>195+ p === 'tools' ||196+ p === 'reasoning_effort' ||197+ p === 'structured_outputs'198+ ? ''199+ : `'${p === 'max_tokens' ? 'max_completion_tokens' : p}'`,200+ )201+ .filter(Boolean)202+ perModelProviderOptions[`${constName}.id`] =203+ supportedKeys.length > 0204+ ? `OpenRouterCommonOptions & Pick<OpenRouterBaseOptions, ${supportedKeys.join(' | ')}>`205+ : 'OpenRouterCommonOptions & OpenRouterBaseOptions'🤖 Prompt for AI Agents
In `@scripts/convert-openrouter-models.ts` around lines 165 - 179, The generated Pick<> can become empty when model.supported_parameters only contains excluded keys; update the logic that sets perModelProviderOptions[`${constName}.id`] to first compute the filtered list from model.supported_parameters (excluding 'tools', 'reasoning_effort', 'structured_outputs' and mapping 'max_tokens' to 'max_completion_tokens'), then if that filtered list is non-empty build `OpenRouterCommonOptions & Pick<OpenRouterBaseOptions, ...>` using the joined keys, otherwise fall back to `OpenRouterCommonOptions & OpenRouterBaseOptions`; apply this change in the block that assigns perModelProviderOptions[`${constName}.id`] so the resulting type never emits an empty Pick<>.✅ Addressed in commits 72a6b55 to 37aadc9
Actionable comments posted: 2
🤖 Fix all issues with AI agents
In `@packages/typescript/ai-openrouter/src/adapters/image.ts`: - Around line 125-126: The inline comment above the type assertion is inconsistent with the actual SDK call: the comment claims "modalities: ['image', 'text']" while the request uses modalities: ['image']; update the comment to accurately reflect the call (e.g., mention only "image" modality) or change the call to include 'text' if that is the intended behavior—locate the type assertion comment and the call that sets modalities (the expression passing modalities: ['image']) and make them consistent. In `@packages/typescript/ai-openrouter/src/adapters/summarize.ts`: - Around line 73-80: In summarize, detect and surface error chunks instead of ignoring them: inside the loop that handles chunk.type (currently setting summary/id/model for 'content' and usage for 'done'), add handling for chunk.type === 'error' to throw a descriptive Error containing the chunk's error/message and any identifying info (e.g., chunk.id, chunk.model) so callers never receive an empty/partial summary; update the control flow in the summarize function to stop processing on error chunks and propagate that error.♻️ Duplicate comments (5)
packages/typescript/ai-openrouter/src/adapters/image.ts (2)
109-112: Error messages may be double-wrapped.When an error is thrown inside the try block (line 105), it's caught and re-wrapped with the same prefix
"Image generation failed:", resulting in messages like"Image generation failed: Image generation failed: ...".🐛 Proposed fix
} catch (error) { + if (error instanceof Error && error.message.startsWith('Image generation failed:')) { + throw error + } const message = (error as Error).message || 'Unknown error' throw new Error(`Image generation failed: ${message}`) }
139-141: Potential null pointer dereference onchoice.message.The code accesses
choice.message.imageswithout checking ifchoice.messageexists. The type assertion on lines 127-136 showsmessageis optional, but the access on line 140 doesn't use optional chaining.🐛 Proposed fix
for (const choice of responseWithImages.choices) { - const choiceImages = choice.message.images + const choiceImages = choice.message?.images if (choiceImages) {packages/typescript/ai-openrouter/src/adapters/text.ts (2)
113-116: Use the current choice when capturingfinishReason. Inside the loop, checkingchunk.choices[0]ignores finish reasons from non-first choices.🐛 Proposed fix
- for (const choice of chunk.choices) { - if (chunk.choices[0]?.finishReason) { - lastFinishReason = chunk.choices[0].finishReason - } + for (const choice of chunk.choices) { + if (choice.finishReason) { + lastFinishReason = choice.finishReason + }
388-423: Preservesystemrole in message mapping. Currently, any non-user/tool message is coerced to assistant, which drops system messages.🔧 Proposed fix
- // assistant role + // assistant/system role return { - role: 'assistant' as const, + role: + msg.role === 'system' + ? ('system' as const) + : ('assistant' as const), content: typeof msg.content === 'string' ? msg.content : msg.content ? JSON.stringify(msg.content) : undefined, toolCalls: msg.toolCalls, }packages/typescript/ai-openrouter/src/adapters/summarize.ts (1)
66-97: Provider options are defined but not applied.OpenRouterSummarizeProviderOptionsare never read, so per-request overrides are ignored in bothsummarizeandsummarizeStream.🔧 Proposed fix
- for await (const chunk of this.textAdapter.chatStream({ + const temperature = + options.modelOptions?.temperature ?? this.temperature + const maxTokens = + options.modelOptions?.maxTokens ?? this.maxTokens ?? options.maxLength + + for await (const chunk of this.textAdapter.chatStream({ model: options.model, messages: [{ role: 'user', content: options.text }], systemPrompts: [systemPrompt], - maxTokens: this.maxTokens ?? options.maxLength, - temperature: this.temperature, + maxTokens, + temperature, })) {- yield* this.textAdapter.chatStream({ + const temperature = + options.modelOptions?.temperature ?? this.temperature + const maxTokens = + options.modelOptions?.maxTokens ?? this.maxTokens ?? options.maxLength + + yield* this.textAdapter.chatStream({ model: options.model, messages: [{ role: 'user', content: options.text }], systemPrompts: [systemPrompt], - maxTokens: this.maxTokens ?? options.maxLength, - temperature: this.temperature, + maxTokens, + temperature, })Please verify
SummarizationOptionsexposesmodelOptionswith these fields:#!/bin/bash # Inspect SummarizationOptions to confirm per-request provider options shape. rg -n --type=ts "interface\s+SummarizationOptions|type\s+SummarizationOptions" -C 3🧹 Nitpick comments (1)
packages/typescript/ai-openrouter/src/adapters/text.ts (1)
239-355: Consider StreamProcessor for streaming state. This manual accumulation of content/tool calls can be centralized via StreamProcessor to align with repository streaming conventions and partial JSON handling. As per coding guidelines, please consider this refactor.📜 Review details
Configuration used: defaults
Review profile: CHILL
Plan: Pro
📥 Commits
Reviewing files that changed from the base of the PR and between ac1cbb9a187053e66b75292aadf95a68b9ade6fc and 37aadc9cc182ae5bf2aba6aa9ddcd159e8538e9c.
📒 Files selected for processing (7)
docs/adapters/openrouter.mdpackages/typescript/ai-openrouter/src/adapters/image.tspackages/typescript/ai-openrouter/src/adapters/summarize.tspackages/typescript/ai-openrouter/src/adapters/text.tspackages/typescript/ai-openrouter/src/index.tspackages/typescript/ai-openrouter/src/model-meta.tsscripts/convert-openrouter-models.ts
🚧 Files skipped from review as they are similar to previous changes (3)
- docs/adapters/openrouter.md
- packages/typescript/ai-openrouter/src/index.ts
- scripts/convert-openrouter-models.ts
🧰 Additional context used
📓 Path-based instructions (3)
**/*.{ts,tsx}
📄 CodeRabbit inference engine (CLAUDE.md)
**/*.{ts,tsx}: Use tree-shakeable adapter architecture for provider implementations - export specialized adapters (text, embedding, summarize, image) as separate imports from/adapterssubpath rather than monolithic adapters Use Zod for runtime schema validation and type inference, particularly for tool input/output definitions withtoolDefinition()and Zod schema inference Implement isomorphic tool system usingtoolDefinition()with.server()and.client()implementations for dual-environment execution Use type-safe per-model configuration with provider options typed based on selected model to ensure compile-time safety Implement stream processing with StreamProcessor for handling chunked responses and support partial JSON parsing for streaming AI responsesFiles:
packages/typescript/ai-openrouter/src/adapters/image.tspackages/typescript/ai-openrouter/src/adapters/summarize.tspackages/typescript/ai-openrouter/src/adapters/text.ts
**/*.{ts,tsx,js,jsx}
📄 CodeRabbit inference engine (CLAUDE.md)
Use camelCase for function and variable names throughout the codebase
Files:
packages/typescript/ai-openrouter/src/adapters/image.tspackages/typescript/ai-openrouter/src/adapters/summarize.tspackages/typescript/ai-openrouter/src/adapters/text.ts
packages/typescript/*/src/adapters/*.ts
📄 CodeRabbit inference engine (CLAUDE.md)
Create individual adapter implementations for each provider capability (text, embed, summarize, image) with separate exports to enable tree-shaking
Files:
packages/typescript/ai-openrouter/src/adapters/image.tspackages/typescript/ai-openrouter/src/adapters/summarize.tspackages/typescript/ai-openrouter/src/adapters/text.ts
🧠 Learnings (7)
📓 Common learnings
Learnt from: CR Repo: TanStack/ai PR: 0 File: CLAUDE.md:0-0 Timestamp: 2025-12-13T17:09:09.794Z Learning: Applies to packages/typescript/*/src/adapters/*.ts : Create individual adapter implementations for each provider capability (text, embed, summarize, image) with separate exports to enable tree-shakingLearnt from: CR Repo: TanStack/ai PR: 0 File: CLAUDE.md:0-0 Timestamp: 2025-12-13T17:09:09.794Z Learning: Applies to **/*.{ts,tsx} : Use tree-shakeable adapter architecture for provider implementations - export specialized adapters (text, embedding, summarize, image) as separate imports from `/adapters` subpath rather than monolithic adaptersLearnt from: CR Repo: TanStack/ai PR: 0 File: CLAUDE.md:0-0 Timestamp: 2025-12-13T17:09:09.794Z Learning: Applies to packages/typescript/*/src/index.ts : Export tree-shakeable adapters with clear subpath exports in package.json (e.g., `tanstack/ai/adapters`, `tanstack/ai-openai/adapters`) to minimize bundle size📚 Learning: 2025-12-13T17:09:09.794Z
Learnt from: CR Repo: TanStack/ai PR: 0 File: CLAUDE.md:0-0 Timestamp: 2025-12-13T17:09:09.794Z Learning: Applies to packages/typescript/*/src/adapters/*.ts : Create individual adapter implementations for each provider capability (text, embed, summarize, image) with separate exports to enable tree-shakingApplied to files:
packages/typescript/ai-openrouter/src/adapters/image.tspackages/typescript/ai-openrouter/src/adapters/summarize.tspackages/typescript/ai-openrouter/src/adapters/text.ts
📚 Learning: 2025-12-13T17:09:09.794Z
Learnt from: CR Repo: TanStack/ai PR: 0 File: CLAUDE.md:0-0 Timestamp: 2025-12-13T17:09:09.794Z Learning: Applies to **/*.{ts,tsx} : Use tree-shakeable adapter architecture for provider implementations - export specialized adapters (text, embedding, summarize, image) as separate imports from `/adapters` subpath rather than monolithic adaptersApplied to files:
packages/typescript/ai-openrouter/src/adapters/image.tspackages/typescript/ai-openrouter/src/adapters/summarize.tspackages/typescript/ai-openrouter/src/adapters/text.ts
📚 Learning: 2025-12-13T17:09:09.794Z
Learnt from: CR Repo: TanStack/ai PR: 0 File: CLAUDE.md:0-0 Timestamp: 2025-12-13T17:09:09.794Z Learning: Applies to packages/typescript/*/src/index.ts : Export tree-shakeable adapters with clear subpath exports in package.json (e.g., `tanstack/ai/adapters`, `tanstack/ai-openai/adapters`) to minimize bundle sizeApplied to files:
packages/typescript/ai-openrouter/src/adapters/image.tspackages/typescript/ai-openrouter/src/adapters/summarize.tspackages/typescript/ai-openrouter/src/adapters/text.ts
📚 Learning: 2025-12-13T17:09:09.794Z
Learnt from: CR Repo: TanStack/ai PR: 0 File: CLAUDE.md:0-0 Timestamp: 2025-12-13T17:09:09.794Z Learning: Applies to packages/typescript/*/src/model-meta.ts : Maintain model metadata files that define provider options and capabilities per model for per-model type safetyApplied to files:
packages/typescript/ai-openrouter/src/adapters/image.tspackages/typescript/ai-openrouter/src/adapters/text.ts
📚 Learning: 2025-12-13T17:09:09.794Z
Learnt from: CR Repo: TanStack/ai PR: 0 File: CLAUDE.md:0-0 Timestamp: 2025-12-13T17:09:09.794Z Learning: Applies to **/*.{ts,tsx} : Implement stream processing with StreamProcessor for handling chunked responses and support partial JSON parsing for streaming AI responsesApplied to files:
packages/typescript/ai-openrouter/src/adapters/text.ts
📚 Learning: 2025-12-13T17:09:09.794Z
Learnt from: CR Repo: TanStack/ai PR: 0 File: CLAUDE.md:0-0 Timestamp: 2025-12-13T17:09:09.794Z Learning: Applies to **/*.{ts,tsx} : Use type-safe per-model configuration with provider options typed based on selected model to ensure compile-time safetyApplied to files:
packages/typescript/ai-openrouter/src/adapters/text.ts
✏️ Tip: You can disable this entire section by setting `review_details` to `false` in your review settings.🔇 Additional comments (10)
packages/typescript/ai-openrouter/src/adapters/image.ts (2)
1-24: LGTM!Imports and type definitions are well-organized. The adapter follows the tree-shakeable architecture pattern by being a separate export for the image capability, as per coding guidelines.
169-183: LGTM!Factory functions follow the established pattern with proper separation between explicit API key (
createOpenRouterImage) and environment-based (openRouterImage) instantiation. Naming follows camelCase convention per coding guidelines.packages/typescript/ai-openrouter/src/adapters/text.ts (5)
77-80: Constructor wiring looks good. Cleanly initializes the base adapter and OpenRouter client.
153-218: Structured output flow is solid. Tool-call first, then fallback JSON parsing with clear error messaging.
357-386: Request mapping looks consistent. Provider options and tool mapping are cleanly passed through.
426-474: Content-part conversion looks good. Handles multimodal inputs cleanly with safe fallbacks.
477-491: Factory helpers are clear and ergonomic. Good separation between explicit API key and env-based creation.packages/typescript/ai-openrouter/src/adapters/summarize.ts (3)
51-56: Constructor setup is clean. Adapter wiring and default config initialization look correct.
100-125: Prompt builder is clear and flexible. Nicely composes style/focus/maxLength variants.
143-181: Factory helpers are well documented. Good usage examples and environment key handling.packages/typescript/ai-openrouter/src/adapters/image.ts lines 125 to 126OutdatedResolvedby AlemTuzlak@@ -0,0 +106,21 @@106+ }107+108+ return this.transformResponse(model, response)109+ } catch (error) {110+ const message = (error as Error).message || 'Unknown error'111+ throw new Error(`Image generation failed: ${message}`)112+ }113+ }114+115+ protected override generateId(): string {116+ return utilGenerateId(this.name)117+ }118+119+ private transformResponse(120+ model: string,121+ response: ChatResponse,122+ ): ImageGenerationResult {123+ const images: Array<GeneratedImage> = []124+125+ // The SDK types don't include images field, but it exists in the actual response126+ // Type assertion is safe here because we're calling with modalities: ['image', 'text']⚠️ Potential issue | 🟡 Minor
Inconsistent comment.
The comment states
modalities: ['image', 'text']but the actual call at line 81 uses onlymodalities: ['image'].📝 Proposed fix
// The SDK types don't include images field, but it exists in the actual response - // Type assertion is safe here because we're calling with modalities: ['image', 'text'] + // Type assertion is safe here because we're calling with modalities: ['image']📝 Committable suggestion
‼️ IMPORTANT Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
Suggested change125- // The SDK types don't include images field, but it exists in the actual response126- // Type assertion is safe here because we're calling with modalities: ['image', 'text']125+ // The SDK types don't include images field, but it exists in the actual response126+ // Type assertion is safe here because we're calling with modalities: ['image']🤖 Prompt for AI Agents
In `@packages/typescript/ai-openrouter/src/adapters/image.ts` around lines 125 - 126, The inline comment above the type assertion is inconsistent with the actual SDK call: the comment claims "modalities: ['image', 'text']" while the request uses modalities: ['image']; update the comment to accurately reflect the call (e.g., mention only "image" modality) or change the call to include 'text' if that is the intended behavior—locate the type assertion comment and the call that sets modalities (the expression passing modalities: ['image']) and make them consistent.✅ Addressed in commit 3eca5f5
@@ -0,0 +60,21 @@60+61+ let summary = ''62+ let id = ''63+ let model = options.model64+ let usage = { promptTokens: 0, completionTokens: 0, totalTokens: 0 }65+66+ for await (const chunk of this.textAdapter.chatStream({67+ model: options.model,68+ messages: [{ role: 'user', content: options.text }],69+ systemPrompts: [systemPrompt],70+ maxTokens: this.maxTokens ?? options.maxLength,71+ temperature: this.temperature,72+ })) {73+ if (chunk.type === 'content') {74+ summary = chunk.content75+ id = chunk.id76+ model = chunk.model77+ }78+ if (chunk.type === 'done' && chunk.usage) {79+ usage = chunk.usage80+ }⚠️ Potential issue | 🟠 Major
Throw on error chunks in
summarize. Currently, error chunks are ignored, which can return an empty/partial summary on failures.🐛 Proposed fix
- if (chunk.type === 'done' && chunk.usage) { + if (chunk.type === 'error') { + throw new Error(chunk.error?.message || 'Summarization failed') + } + if (chunk.type === 'done' && chunk.usage) { usage = chunk.usage }📝 Committable suggestion
‼️ IMPORTANT Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
Suggested change73- if (chunk.type === 'content') {74- summary = chunk.content75- id = chunk.id76- model = chunk.model77- }78- if (chunk.type === 'done' && chunk.usage) {79- usage = chunk.usage80- }73+ if (chunk.type === 'content') {74+ summary = chunk.content75+ id = chunk.id76+ model = chunk.model77+ }78+ if (chunk.type === 'error') {79+ throw new Error(chunk.error?.message || 'Summarization failed')80+ }81+ if (chunk.type === 'done' && chunk.usage) {82+ usage = chunk.usage83+ }🤖 Prompt for AI Agents
In `@packages/typescript/ai-openrouter/src/adapters/summarize.ts` around lines 73 - 80, In summarize, detect and surface error chunks instead of ignoring them: inside the loop that handles chunk.type (currently setting summary/id/model for 'content' and usage for 'done'), add handling for chunk.type === 'error' to throw a descriptive Error containing the chunk's error/message and any identifying info (e.g., chunk.id, chunk.model) so callers never receive an empty/partial summary; update the control flow in the summarize function to stop processing on error chunks and propagate that error.✅ Addressed in commit 3eca5f5
Actionable comments posted: 2
🤖 Fix all issues with AI agents
In `@docs/adapters/openrouter.md`: - Around line 92-96: The example is missing the messages variable used when calling chat(); add a brief definition for messages (e.g., an array of message objects or a minimal system/user message list) above the call so the snippet is self-contained: define messages before invoking chat({ adapter: openRouterText("openai/gpt-5"), messages, tools: [getWeather] }) and ensure the message shape matches what chat() expects (e.g., role and content fields) so openRouterText() and getWeather usage are clear. - Around line 114-125: Add a definition for the messages variable used in the chat() example so the snippet is runnable; create a messages array similar to the "Basic Usage" section (e.g., const messages = [{ role: "system", content: "You are a helpful assistant." }, { role: "user", content: "Say hello." }]) and place it before the call to chat({ adapter: openRouterText("openrouter/auto"), messages, providerOptions: { ... }}) so chat() receives a defined messages parameter.♻️ Duplicate comments (1)
docs/adapters/openrouter.md (1)
28-39: Fix thecreateOpenRoutercall—the config object must not includeapiKeywhen passed as the second parameter.The function signature is
createOpenRouter(apiKey: string, config?: Omit<OpenRouterConfig, 'apiKey'>). The second parameter must excludeapiKey. Update the example to either:- Destructure the config to exclude
apiKey:
const config: OpenRouterConfig = { apiKey: process.env.OPENROUTER_API_KEY!, baseURL: "https://openrouter.ai/api/v1", // Optional httpReferer: "https://your-app.com", // Optional, for rankings xTitle: "Your App Name", // Optional, for rankings }; -const adapter = createOpenRouter(config.apiKey, config); +const { apiKey, ...configWithoutKey } = config; +const adapter = createOpenRouter(apiKey, configWithoutKey);- Or define config without
apiKeyand pass the key separately:
-const config: OpenRouterConfig = { - apiKey: process.env.OPENROUTER_API_KEY!, +const config = { baseURL: "https://openrouter.ai/api/v1", // Optional httpReferer: "https://your-app.com", // Optional, for rankings xTitle: "Your App Name", // Optional, for rankings }; -const adapter = createOpenRouter(config.apiKey, config); +const adapter = createOpenRouter(process.env.OPENROUTER_API_KEY!, config);🧹 Nitpick comments (1)
docs/adapters/openrouter.md (1)
128-131: Consider adding examples for image and summarization adapters.Based on the implementation summary, the OpenRouter adapter includes
OpenRouterImageAdapterandOpenRouterSummarizeAdapterin addition to the text adapter. Consider adding brief examples for these capabilities to provide complete documentation coverage.📜 Review details
Configuration used: defaults
Review profile: CHILL
Plan: Pro
📥 Commits
Reviewing files that changed from the base of the PR and between 37aadc9cc182ae5bf2aba6aa9ddcd159e8538e9c and 0538dc5f5751d1202940bc7c92cf63b5f0165102.
📒 Files selected for processing (1)
docs/adapters/openrouter.md
✏️ Tip: You can disable this entire section by setting `review_details` to `false` in your review settings.🧰 Additional context used
🧠 Learnings (1)
📓 Common learnings
Learnt from: CR Repo: TanStack/ai PR: 0 File: CLAUDE.md:0-0 Timestamp: 2025-12-13T17:09:09.794Z Learning: Applies to packages/typescript/*/src/adapters/*.ts : Create individual adapter implementations for each provider capability (text, embed, summarize, image) with separate exports to enable tree-shakingLearnt from: CR Repo: TanStack/ai PR: 0 File: CLAUDE.md:0-0 Timestamp: 2025-12-13T17:09:09.794Z Learning: Applies to **/*.{ts,tsx} : Use tree-shakeable adapter architecture for provider implementations - export specialized adapters (text, embedding, summarize, image) as separate imports from `/adapters` subpath rather than monolithic adaptersLearnt from: CR Repo: TanStack/ai PR: 0 File: CLAUDE.md:0-0 Timestamp: 2025-12-13T17:09:09.794Z Learning: Applies to packages/typescript/*/src/index.ts : Export tree-shakeable adapters with clear subpath exports in package.json (e.g., `tanstack/ai/adapters`, `tanstack/ai-openai/adapters`) to minimize bundle size@@ -0,0 +76,21 @@76+import { chat, toolDefinition } from "@tanstack/ai";77+import { openRouterText } from "@tanstack/ai-openrouter";78+import { z } from "zod";79+80+const getWeatherDef = toolDefinition({81+ name: "get_weather",82+ description: "Get the current weather",83+ inputSchema: z.object({84+ location: z.string(),85+ }),86+});87+88+const getWeather = getWeatherDef.server(async ({ location }) => {89+ return { temperature: 72, conditions: "sunny" };90+});91+92+const stream = chat({93+ adapter: openRouterText("openai/gpt-5"),94+ messages,95+ tools: [getWeather],96+});⚠️ Potential issue | 🟡 Minor
Add the
messagesvariable definition to make the example complete.The example references
messageson line 94, but it's not defined in this code snippet. For clarity, either add the definition or reference where it comes from:📝 Suggested addition
const getWeather = getWeatherDef.server(async ({ location }) => { return { temperature: 72, conditions: "sunny" }; }); +const messages = [ + { role: "user", content: "What's the weather in San Francisco?" } +]; + const stream = chat({ adapter: openRouterText("openai/gpt-5"), messages, tools: [getWeather], });🤖 Prompt for AI Agents
In `@docs/adapters/openrouter.md` around lines 92 - 96, The example is missing the messages variable used when calling chat(); add a brief definition for messages (e.g., an array of message objects or a minimal system/user message list) above the call so the snippet is self-contained: define messages before invoking chat({ adapter: openRouterText("openai/gpt-5"), messages, tools: [getWeather] }) and ensure the message shape matches what chat() expects (e.g., role and content fields) so openRouterText() and getWeather usage are clear.@@ -0,0 +105,21 @@105+```bash106+OPENROUTER_API_KEY=sk-or-...107+```108+109+## Model Routing110+111+OpenRouter can automatically route requests to the best available provider:112+113+```typescript114+const stream = chat({115+ adapter: openRouterText("openrouter/auto"),116+ messages,117+ providerOptions: {118+ models: [119+ "openai/gpt-4o",120+ "anthropic/claude-3.5-sonnet",121+ "google/gemini-pro",122+ ],123+ route: "fallback", // Use fallback if primary fails124+ },125+});⚠️ Potential issue | 🟡 Minor
🧩 Analysis chain
🏁 Script executed:
# First, let's find and read the OpenRouter documentation file fd -t f "openrouter.md" --exec wc -l {}Repository: TanStack/ai
Length of output: 88
🏁 Script executed:
# Get context around lines 114-125 in the openrouter.md file fd -t f "openrouter.md" --exec sed -n '100,130p' {}Repository: TanStack/ai
Length of output: 645
🏁 Script executed:
# Find the OpenRouter adapter implementation in the codebase fd -t f -e "ts" -e "js" | xargs rg -l "openRouterText|openrouter" | head -20Repository: TanStack/ai
Length of output: 749
🏁 Script executed:
# Check the text provider options to see what providerOptions should contain cat packages/typescript/ai-openrouter/src/text/text-provider-options.tsRepository: TanStack/ai
Length of output: 9498
🏁 Script executed:
# Check the text adapter implementation cat packages/typescript/ai-openrouter/src/adapters/text.ts | head -100Repository: TanStack/ai
Length of output: 3048
🏁 Script executed:
# Check test files for usage patterns cat packages/typescript/ai-openrouter/tests/openrouter-adapter.test.ts | head -150Repository: TanStack/ai
Length of output: 3977
🏁 Script executed:
# Read the full OpenRouter documentation file to see if messages is defined earlier cat docs/adapters/openrouter.mdRepository: TanStack/ai
Length of output: 3077
Add the
messagesvariable definition.The
messagesvariable on line 116 is not defined. Add its definition for a complete example, similar to the "Basic Usage" section earlier in the documentation.📝 Suggested fix
+const messages = [ + { role: "user", content: "Hello!" } +]; + const stream = chat({ adapter: openRouterText("openrouter/auto"), messages, providerOptions: { models: [ "openai/gpt-4o", "anthropic/claude-3.5-sonnet", "google/gemini-pro", ], route: "fallback", // Use fallback if primary fails }, });📝 Committable suggestion
‼️ IMPORTANT Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
Suggested change114-const stream = chat({115- adapter: openRouterText("openrouter/auto"),116- messages,117- providerOptions: {118- models: [119- "openai/gpt-4o",120- "anthropic/claude-3.5-sonnet",121- "google/gemini-pro",122- ],123- route: "fallback", // Use fallback if primary fails124- },125-});114+const messages = [115+ { role: "user", content: "Hello!" }116+];117+118+const stream = chat({119+ adapter: openRouterText("openrouter/auto"),120+ messages,121+ providerOptions: {122+ models: [123+ "openai/gpt-4o",124+ "anthropic/claude-3.5-sonnet",125+ "google/gemini-pro",126+ ],127+ route: "fallback", // Use fallback if primary fails128+ },129+});🤖 Prompt for AI Agents
In `@docs/adapters/openrouter.md` around lines 114 - 125, Add a definition for the messages variable used in the chat() example so the snippet is runnable; create a messages array similar to the "Basic Usage" section (e.g., const messages = [{ role: "system", content: "You are a helpful assistant." }, { role: "user", content: "Say hello." }]) and place it before the call to chat({ adapter: openRouterText("openrouter/auto"), messages, providerOptions: { ... }}) so chat() receives a defined messages parameter.- Destructure the config to exclude
Actionable comments posted: 1
🤖 Fix all issues with AI agents
In `@packages/typescript/ai-openrouter/src/adapters/summarize.ts`: - Around line 168-171: The doc example uses the wrong function name casing; update the example so it calls the exported function openRouterSummarize (not openrouterSummarize) and ensure any shown import or usage matches the exact exported symbol openRouterSummarize to avoid confusion. Ensure the snippet now reads const adapter = openRouterSummarize('openai/gpt-4o-mini'); and adjust any surrounding text to match that exported identifier.♻️ Duplicate comments (3)
packages/typescript/ai-openrouter/src/adapters/image.ts (2)
109-112: Error messages may be double-wrapped.When an error is thrown inside the try block (line 105), it's caught and re-wrapped with the same prefix, resulting in messages like
"Image generation failed: Image generation failed: ...".
139-141: Potential null pointer dereference onchoice.message.The type assertion shows
messageis optional (message?:), butchoice.message.imagesaccesses it without optional chaining.packages/typescript/ai-openrouter/src/adapters/summarize.ts (1)
28-72: Wire per-request provider options (currently ignored).OpenRouterSummarizeProviderOptionsis defined, butsummarize/summarizeStreamonly use adapter defaults. IfSummarizationOptionsexposes provider options, consider applying them (or drop the interface).🔧 Possible wiring
- maxTokens: this.maxTokens ?? options.maxLength, - temperature: this.temperature, + maxTokens: + options.providerOptions?.maxTokens ?? + this.maxTokens ?? + options.maxLength, + temperature: + options.providerOptions?.temperature ?? + this.temperature,🧹 Nitpick comments (1)
packages/typescript/ai-openrouter/src/adapters/image.ts (1)
84-96: RedundantnandnumberOfImagesin imageConfig.Both
nandnumberOfImagesare set to the same value. This redundancy may cause issues if the API expects only one parameter, or at minimum adds unnecessary payload size.♻️ Proposed fix
imageConfig: { - ...(numberOfImages ? { n: numberOfImages, numberOfImages } : {}), + ...(numberOfImages ? { n: numberOfImages } : {}), ...(aspectRatioIf the API specifically requires
numberOfImagesinstead ofn, use that instead. Otherwise,nis the standard OpenAI-compatible parameter name.📜 Review details
Configuration used: defaults
Review profile: CHILL
Plan: Pro
📥 Commits
Reviewing files that changed from the base of the PR and between 0538dc5f5751d1202940bc7c92cf63b5f0165102 and 3eca5f59e1539685b26e5ec50ea6b489368ad639.
📒 Files selected for processing (2)
packages/typescript/ai-openrouter/src/adapters/image.tspackages/typescript/ai-openrouter/src/adapters/summarize.ts
🧰 Additional context used
📓 Path-based instructions (3)
**/*.{ts,tsx}
📄 CodeRabbit inference engine (CLAUDE.md)
**/*.{ts,tsx}: Use tree-shakeable adapter architecture for provider implementations - export specialized adapters (text, embedding, summarize, image) as separate imports from/adapterssubpath rather than monolithic adapters Use Zod for runtime schema validation and type inference, particularly for tool input/output definitions withtoolDefinition()and Zod schema inference Implement isomorphic tool system usingtoolDefinition()with.server()and.client()implementations for dual-environment execution Use type-safe per-model configuration with provider options typed based on selected model to ensure compile-time safety Implement stream processing with StreamProcessor for handling chunked responses and support partial JSON parsing for streaming AI responsesFiles:
packages/typescript/ai-openrouter/src/adapters/summarize.tspackages/typescript/ai-openrouter/src/adapters/image.ts
**/*.{ts,tsx,js,jsx}
📄 CodeRabbit inference engine (CLAUDE.md)
Use camelCase for function and variable names throughout the codebase
Files:
packages/typescript/ai-openrouter/src/adapters/summarize.tspackages/typescript/ai-openrouter/src/adapters/image.ts
packages/typescript/*/src/adapters/*.ts
📄 CodeRabbit inference engine (CLAUDE.md)
Create individual adapter implementations for each provider capability (text, embed, summarize, image) with separate exports to enable tree-shaking
Files:
packages/typescript/ai-openrouter/src/adapters/summarize.tspackages/typescript/ai-openrouter/src/adapters/image.ts
🧠 Learnings (7)
📓 Common learnings
Learnt from: CR Repo: TanStack/ai PR: 0 File: CLAUDE.md:0-0 Timestamp: 2025-12-13T17:09:09.794Z Learning: Applies to packages/typescript/*/src/index.ts : Export tree-shakeable adapters with clear subpath exports in package.json (e.g., `tanstack/ai/adapters`, `tanstack/ai-openai/adapters`) to minimize bundle sizeLearnt from: CR Repo: TanStack/ai PR: 0 File: CLAUDE.md:0-0 Timestamp: 2025-12-13T17:09:09.794Z Learning: Applies to packages/typescript/*/src/adapters/*.ts : Create individual adapter implementations for each provider capability (text, embed, summarize, image) with separate exports to enable tree-shakingLearnt from: CR Repo: TanStack/ai PR: 0 File: CLAUDE.md:0-0 Timestamp: 2025-12-13T17:09:09.794Z Learning: Implement framework integrations using the headless `tanstack/ai-client` for state management with framework-specific hooks (useChat) on topLearnt from: CR Repo: TanStack/ai PR: 0 File: CLAUDE.md:0-0 Timestamp: 2025-12-13T17:09:09.794Z Learning: Applies to **/*.{ts,tsx} : Use tree-shakeable adapter architecture for provider implementations - export specialized adapters (text, embedding, summarize, image) as separate imports from `/adapters` subpath rather than monolithic adapters📚 Learning: 2025-12-13T17:09:09.794Z
Learnt from: CR Repo: TanStack/ai PR: 0 File: CLAUDE.md:0-0 Timestamp: 2025-12-13T17:09:09.794Z Learning: Applies to packages/typescript/*/src/adapters/*.ts : Create individual adapter implementations for each provider capability (text, embed, summarize, image) with separate exports to enable tree-shakingApplied to files:
packages/typescript/ai-openrouter/src/adapters/summarize.tspackages/typescript/ai-openrouter/src/adapters/image.ts
📚 Learning: 2025-12-13T17:09:09.794Z
Learnt from: CR Repo: TanStack/ai PR: 0 File: CLAUDE.md:0-0 Timestamp: 2025-12-13T17:09:09.794Z Learning: Applies to **/*.{ts,tsx} : Use tree-shakeable adapter architecture for provider implementations - export specialized adapters (text, embedding, summarize, image) as separate imports from `/adapters` subpath rather than monolithic adaptersApplied to files:
packages/typescript/ai-openrouter/src/adapters/summarize.tspackages/typescript/ai-openrouter/src/adapters/image.ts
📚 Learning: 2025-12-13T17:09:09.794Z
Learnt from: CR Repo: TanStack/ai PR: 0 File: CLAUDE.md:0-0 Timestamp: 2025-12-13T17:09:09.794Z Learning: Applies to packages/typescript/*/src/index.ts : Export tree-shakeable adapters with clear subpath exports in package.json (e.g., `tanstack/ai/adapters`, `tanstack/ai-openai/adapters`) to minimize bundle sizeApplied to files:
packages/typescript/ai-openrouter/src/adapters/summarize.tspackages/typescript/ai-openrouter/src/adapters/image.ts
📚 Learning: 2025-12-13T17:09:09.794Z
Learnt from: CR Repo: TanStack/ai PR: 0 File: CLAUDE.md:0-0 Timestamp: 2025-12-13T17:09:09.794Z Learning: Applies to packages/typescript/*/src/model-meta.ts : Maintain model metadata files that define provider options and capabilities per model for per-model type safetyApplied to files:
packages/typescript/ai-openrouter/src/adapters/image.ts
📚 Learning: 2025-12-27T21:39:29.563Z
Learnt from: harry-whorlow Repo: TanStack/ai PR: 117 File: packages/typescript/ai-ollama/src/meta/model-meta-llama-guard3.ts:70-75 Timestamp: 2025-12-27T21:39:29.563Z Learning: The standard template comments in ai-ollama model-meta files (like "Models with text, image, audio, video (no document)") should not be modified to match individual model capabilities, as they are intentionally kept uniform across all model-meta-*.ts files for consistency, regardless of what each specific model actually supports.Applied to files:
packages/typescript/ai-openrouter/src/adapters/image.ts
📚 Learning: 2025-12-27T20:22:51.232Z
Learnt from: harry-whorlow Repo: TanStack/ai PR: 117 File: packages/typescript/ai-ollama/src/meta/model-meta-gpt-oss.ts:92-97 Timestamp: 2025-12-27T20:22:51.232Z Learning: In the ai-ollama package's model-meta files (packages/typescript/ai-ollama/src/meta/model-meta-*.ts), capability-related comments follow a standard template format across all files for consistency, even if the comment text doesn't precisely match individual model capabilities. This is an intentional design choice to maintain uniformity across the codebase.Applied to files:
packages/typescript/ai-openrouter/src/adapters/image.ts
✏️ Tip: You can disable this entire section by setting `review_details` to `false` in your review settings.🔇 Additional comments (7)
packages/typescript/ai-openrouter/src/adapters/image.ts (5)
1-20: LGTM!Imports are well-organized with proper separation of type imports using
import type, following tree-shakeable adapter architecture guidelines.
22-41: LGTM!Type definitions and the aspect ratio mapping are well-structured. The
SIZE_TO_ASPECT_RATIOconstant provides comprehensive coverage for standard image dimensions.
56-63: LGTM!Constructor properly initializes the OpenRouter SDK client with config mapping. The
serverURLmapping frombaseURLaligns with SDK conventions.
119-166: LGTM (aside from the flagged null-check issue)!The
transformResponsemethod correctly handles both data URL (with base64 extraction) and regular URL formats. The regex pattern for base64 extraction is accurate, and the fallback logic foridandmodelis appropriate.
169-183: LGTM!Factory functions follow naming conventions and provide clean APIs for both explicit API key and environment-based initialization patterns. The
Omit<SDKOptions, 'apiKey'>correctly prevents accidental API key override in the config spread.packages/typescript/ai-openrouter/src/adapters/summarize.ts (2)
146-183: Verify config type in factory helpers for temperature/maxTokens supportcreateOpenRouterSummarize/openRouterSummarizecurrently acceptOmit<SDKOptions, 'apiKey'>as config type. Confirm whether this typing prevents temperature/maxTokens from being passed through, and ifOmit<OpenRouterSummarizeConfig, 'apiKey'>is the appropriate fix.
66-77: Code is correct; no fix needed.The
chunk.contentfield contains the full accumulated text from the stream so far, not an incremental delta. Overwritingsummary = chunk.contenton each chunk correctly captures the latest complete accumulated response. Using+=instead would incorrectly concatenate already-accumulated content repeatedly.Likely an incorrect or invalid review comment.
@@ -0,0 +151,21 @@151+ return new OpenRouterSummarizeAdapter({ apiKey, ...config }, model)152+}153+154+/**155+ * Creates an OpenRouter summarize adapter with automatic API key detection from environment variables.156+ * Type resolution happens here at the call site.157+ *158+ * Looks for `OPENROUTER_API_KEY` in:159+ * - `process.env` (Node.js)160+ * - `window.env` (Browser with injected env)161+ *162+ * @param model - The model name (e.g., 'openai/gpt-4o-mini', 'anthropic/claude-3-5-sonnet')163+ * @param config - Optional configuration (excluding apiKey which is auto-detected)164+ * @returns Configured OpenRouter summarize adapter instance with resolved types165+ * @throws Error if OPENROUTER_API_KEY is not found in environment166+ *167+ * @example168+ * ```typescript169+ * // Automatically uses OPENROUTER_API_KEY from environment170+ * const adapter = openrouterSummarize('openai/gpt-4o-mini');171+ *⚠️ Potential issue | 🟡 Minor
Fix example to match exported function name.
The example calls
openrouterSummarize, but the export isopenRouterSummarize.✏️ Doc fix
- * const adapter = openrouterSummarize('openai/gpt-4o-mini'); + * const adapter = openRouterSummarize('openai/gpt-4o-mini');📝 Committable suggestion
‼️ IMPORTANT Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
Suggested change168- * ```typescript169- * // Automatically uses OPENROUTER_API_KEY from environment170- * const adapter = openrouterSummarize('openai/gpt-4o-mini');171- *168+*🤖 Prompt for AI Agents
In `@packages/typescript/ai-openrouter/src/adapters/summarize.ts` around lines 168 - 171, The doc example uses the wrong function name casing; update the example so it calls the exported function openRouterSummarize (not openrouterSummarize) and ensure any shown import or usage matches the exact exported symbol openRouterSummarize to avoid confusion. Ensure the snippet now reads const adapter = openRouterSummarize('openai/gpt-4o-mini'); and adjust any surrounding text to match that exported identifier.✅ Addressed in commits a38f9e7 to 4519fc7
Waiting for the openrouter team to merge a fix to the SDK on their side and it's ready!
AlemTuzlak approved these changes
Actionable comments posted: 2
🤖 Fix all issues with AI agents
In @.changeset/forty-times-burn.md: - Around line 1-8: The changeset currently lists the wrong packages and description; update the front-matter to remove '@tanstack/preact-ai-devtools', '@tanstack/react-ai-devtools', '@tanstack/solid-ai-devtools', and '@tanstack/ai-devtools-core' and instead add the new package '@tanstack/ai-openrouter', change the summary body from "Fix issue with double mounting of devtools" to a brief description like "Add OpenRouter adapter for AI integrations", and set the version bump from patch to minor (since this is a new feature); ensure the YAML keys and dash formatting in the header match the existing changeset style. In `@packages/typescript/ai-openrouter/src/adapters/text.ts`: - Around line 373-377: The model string construction in the ChatGenerationParams `request` object incorrectly applies the ternary to the whole concatenation, causing `:undefined` and dropping the base model; fix the expression in the `request` setup (where `model:` is assigned) by parenthesizing or otherwise grouping so you append `:${modelOptions.variant}` only when `modelOptions?.variant` is truthy — e.g. compute `options.model + (modelOptions?.variant ? ':' + modelOptions.variant : '')` or use an equivalent template literal so the base `options.model` is always preserved and you never append `:undefined`.♻️ Duplicate comments (3)
packages/typescript/ai-openrouter/src/text/text-provider-options.ts (1)
279-282: Expandresponse_formatto includejson_schema. Current typing only allowsjson_object, but OpenRouter supportsjson_schemastructured outputs too. Please extend the union so callers can pass schemas.🛠️ Suggested fix
- response_format?: { type: 'json_object' } + response_format?: + | { type: 'json_object' } + | { + type: 'json_schema' + json_schema: { + name: string + schema: Record<string, unknown> + strict?: boolean + } + }packages/typescript/ai-openrouter/src/adapters/text.ts (2)
113-116: Use the current choice’sfinishReason. The loop checkschunk.choices[0]every time, so non-first choices can’t updatelastFinishReason.🛠️ Suggested fix
- if (chunk.choices[0]?.finishReason) { - lastFinishReason = chunk.choices[0].finishReason + if (choice.finishReason) { + lastFinishReason = choice.finishReason }
391-425: Preservesystemrole in message conversion. Non-usermessages are forced toassistant, which downgradessystemprompts when they’re passed in the messages array.🛠️ Suggested fix
- // assistant role - return { - role: 'assistant' as const, + // assistant / system role + const role = msg.role === 'system' ? 'system' : 'assistant' + return { + role, content: typeof msg.content === 'string' ? msg.content : msg.content ? JSON.stringify(msg.content) : undefined, toolCalls: msg.toolCalls, }@@ -0,0 +1,8 @@1+---2+'@tanstack/preact-ai-devtools': patch3+'@tanstack/react-ai-devtools': patch4+'@tanstack/solid-ai-devtools': patch5+'@tanstack/ai-devtools-core': patch6+---7+8+Fix issue with double mounting of devtools⚠️ Potential issue | 🔴 Critical
Critical: Changeset describes wrong feature and affects wrong packages.
This changeset describes "Fix issue with double mounting of devtools" and targets devtools packages (
@tanstack/preact-ai-devtools,@tanstack/react-ai-devtools,@tanstack/solid-ai-devtools,@tanstack/ai-devtools-core), but the PR introduces OpenRouter adapter functionality.The changeset should instead:
- Target the new
@tanstack/ai-openrouterpackage - Describe the OpenRouter adapter addition
- Use the appropriate version bump (likely
minorfor a new feature, unless breaking changes are involved)
This appears to be a changeset from a different PR that was accidentally included or left over from a rebase.
🤖 Prompt for AI Agents
In @.changeset/forty-times-burn.md around lines 1 - 8, The changeset currently lists the wrong packages and description; update the front-matter to remove '@tanstack/preact-ai-devtools', '@tanstack/react-ai-devtools', '@tanstack/solid-ai-devtools', and '@tanstack/ai-devtools-core' and instead add the new package '@tanstack/ai-openrouter', change the summary body from "Fix issue with double mounting of devtools" to a brief description like "Add OpenRouter adapter for AI integrations", and set the version bump from patch to minor (since this is a new feature); ensure the YAML keys and dash formatting in the header match the existing changeset style.packages/typescript/ai-openrouter/src/adapters/text.ts lines 373 to 377OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +357,21 @@357+ private mapTextOptionsToSDK(358+ options: TextOptions<ResolveProviderOptions<TModel>>,359+ ): ChatGenerationParams {360+ const modelOptions = options.modelOptions as361+ | Omit<InternalTextProviderOptions, 'model' | 'messages' | 'tools'>362+ | undefined363+364+ const messages = this.convertMessages(options.messages)365+366+ if (options.systemPrompts?.length) {367+ messages.unshift({368+ role: 'system',369+ content: options.systemPrompts.join('\n'),370+ })371+ }372+373+ const request: ChatGenerationParams = {374+ model:375+ options.model + modelOptions?.variant376+ ? `:${modelOptions?.variant}`377+ : '',⚠️ Potential issue | 🔴 Critical
Fix model string construction (ternary precedence bug). The current expression evaluates the ternary against the concatenation, so the model becomes
:undefinedand drops the base model.🛠️ Suggested fix
- model: - options.model + modelOptions?.variant - ? `:${modelOptions?.variant}` - : '', + model: `${options.model}${modelOptions?.variant ? `:${modelOptions.variant}` : ''}`,🤖 Prompt for AI Agents
In `@packages/typescript/ai-openrouter/src/adapters/text.ts` around lines 373 - 377, The model string construction in the ChatGenerationParams `request` object incorrectly applies the ternary to the whole concatenation, causing `:undefined` and dropping the base model; fix the expression in the `request` setup (where `model:` is assigned) by parenthesizing or otherwise grouping so you append `:${modelOptions.variant}` only when `modelOptions?.variant` is truthy — e.g. compute `options.model + (modelOptions?.variant ? ':' + modelOptions.variant : '')` or use an equivalent template literal so the base `options.model` is always preserved and you never append `:undefined`.✅ Addressed in commits ed2f977 to 422d9fd
- Target the new
AlemTuzlak approved these changes
thank you so much
AlemTuzlak merged thisa19b247
AlemTuzlak closed this
Sign in to join this conversation.
View your CI Pipeline Execution ↗ for commit 422d9fd936ecbb71d27bd7a1b61fcddf8aceeaca
nx affected --targets=test:sherif,test:knip,tes...nx run-many --targets=build --exclude=examples/**☁️ Nx Cloud last updated this comment at
2026-01-19 10:38:57UTC