fix: anthropic tool call issues #275
🎯 Changes#
This fixes tool calls in the anthropic adapter.
✅ 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
- Added Claude Opus 4.6 model support with adaptive thinking capabilities.
Bug Fixes
- Fixed UI flicker caused by empty messages during streaming.
- Fixed consecutive user messages breaking role alternation in multi-turn conversations.
- Fixed duplicate tool results appearing in message history.
- Improved tool call handling to prevent empty assistant messages.
Documentation
- Added comprehensive chat stream architecture guide.
- 1
AlemTuzlak approved these changes
Actionable comments posted: 2
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
packages/typescript/ai-anthropic/src/text/text-provider-options.ts (1)
147-156: ⚠️ Potential issue | 🔴 CriticalFix type conflict:
{ type: 'adaptive' }is unassignable due to intersection withAnthropicThinkingOptions.ExternalTextProviderOptionsat line 152 intersectsAnthropicThinkingOptionswithPartial<AnthropicAdaptiveThinkingOptions>at line 155. Both define athinkingproperty with conflicting discriminated union types. TypeScript computes the intersection of these types — only discriminator variants present in BOTH unions are assignable. Since{ type: 'adaptive' }exists only inAnthropicAdaptiveThinkingOptions, it cannot satisfy the intersection, preventing users from passing adaptive thinking configuration despite it being declared in the interfaces.Replace
AnthropicThinkingOptionswithAnthropicAdaptiveThinkingOptions(which is a superset containing all variants including'adaptive') to preserve type safety for all thinking modes:Proposed fix
export type ExternalTextProviderOptions = AnthropicContainerOptions & AnthropicContextManagementOptions & AnthropicMCPOptions & AnthropicServiceTierOptions & AnthropicStopSequencesOptions & - AnthropicThinkingOptions & + AnthropicAdaptiveThinkingOptions & AnthropicToolChoiceOptions & AnthropicSamplingOptions & - Partial<AnthropicAdaptiveThinkingOptions> & Partial<AnthropicEffortOptions>🤖 Fix all issues with AI agents
In `@packages/typescript/ai-anthropic/src/adapters/text.ts`: - Around line 684-695: The code emits a TEXT_MESSAGE_END for any content_block_stop where currentBlockType !== 'tool_use', which can spuriously include non-text types like 'thinking'; modify the guard so the yield of { type: 'TEXT_MESSAGE_END', ... } only happens when the block that just ended was actually a text block (e.g., check currentBlockType === 'text' or explicitly match the set of text block types) in addition to hasEmittedTextMessageStart and accumulatedContent; update the conditional around the yield in the same block where hasEmittedTextMessageStart, accumulatedContent, and currentBlockType are referenced (symbols: currentBlockType, hasEmittedTextMessageStart, accumulatedContent, and the TEXT_MESSAGE_END yield) so TEXT_MESSAGE_END is not emitted for non-text/non-tool_use block types. In `@testing/panel/package.json`: - Around line 24-27: Remove the legacy package entry "@tanstack/start" from dependencies and update the TanStack package versions to be consistent with "@tanstack/react-start"; specifically, delete the "@tanstack/start": "^1.120.20" line and change "@tanstack/react-router": "^1.158.4" to "^1.159.0" so it matches "@tanstack/react-start": "^1.159.0" (leave "@tanstack/nitro-v2-vite-plugin" unchanged unless other TanStack version constraints require alignment).🧹 Nitpick comments (7)
scripts/fix-version-bump.ts (4)
78-78: UseArray<T>generic syntax per project lint rules.ESLint reports
@typescript-eslint/array-typeviolations on these two lines.🔧 Proposed fix
- const packagesToFix: PackageToFix[] = [] + const packagesToFix: Array<PackageToFix> = []- const errors: string[] = [] + const errors: Array<string> = []Also applies to: 108-108
146-150: Commit message guidance uses a hardcoded placeholder.Line 149 suggests committing with
"fix: correct version bump to X.Y.Z"but at this point the actual target version is known. Consider interpolating the resolved version for a more helpful message.🔧 Proposed fix
+ const resolvedVersion = cliVersion || packagesToFix[0].detectedVersion! console.log('\n✅ Done! Version bump fixed.') console.log('\nNext steps:') console.log(' 1. Review the changes: git diff') - console.log(' 2. Commit: git add -A && git commit -m "fix: correct version bump to X.Y.Z"') + console.log(` 2. Commit: git add -A && git commit -m "fix: correct version bump to ${resolvedVersion}"`)
14-23: CLI flag value joined with=is not handled.parseArgsonly supports--version X.Y.Z(space-separated), but common CLI convention also allows--version=X.Y.Z. Users passing the=form will silently getversion: nulland the script will fall back to auto-detection or error out.🔧 Proposed fix
function parseArgs(): { version: string | null } { const args = process.argv.slice(2) - const versionIndex = args.findIndex((arg) => arg === '--version' || arg === '-v') - - if (versionIndex !== -1 && args[versionIndex + 1]) { - return { version: args[versionIndex + 1] } + for (const arg of args) { + if (arg.startsWith('--version=') || arg.startsWith('-v=')) { + return { version: arg.split('=')[1] || null } + } + } + const versionIndex = args.findIndex((a) => a === '--version' || a === '-v') + if (versionIndex !== -1 && args[versionIndex + 1]) { + return { version: args[versionIndex + 1] } } - return { version: null } }
49-56: Regex-based JSON editing is fragile.fixPackageJsonuses a regex to replace the version string in raw JSON text. This works for typicalpackage.jsonfiles but could silently corrupt files with unusual formatting or multiple"version": "1.0.0"fields (e.g., in nested metadata). Since this is a one-off internal script rather than a library, the risk is low—just worth noting.packages/typescript/ai-anthropic/src/text/text-provider-options.ts (1)
207-217:validateThinkingdoesn't handletype: 'adaptive'.The validation function only handles
type: 'enabled'and would silently skiptype: 'adaptive'. If adaptive thinking has any constraints (e.g., it shouldn't coexist withbudget_tokens), they aren't enforced here. If no validation is needed for adaptive mode, a brief comment explaining that would help maintainability.packages/typescript/ai-anthropic/tests/anthropic-adapter.test.ts (1)
399-511: Thorough reproduction of the real-world multi-turn scenario.Minor note:
tools: [weatherTool](line 477) doesn't match the tool names used in the messages (getGuitars,recommendGuitar). This doesn't affect correctness since the test focuses on message formatting/deduplication, not tool dispatch — but aligning the tools would improve readability if this test is ever used as a reference for future debugging.packages/typescript/ai-anthropic/src/adapters/text.ts (1)
696-708:hasEmittedRunFinishednaming is slightly misleading for themax_tokenscase.When
stop_reasonismax_tokens, the code emitsRUN_ERROR(notRUN_FINISHED), but the flag namehasEmittedRunFinishedstill prevents a follow-upRUN_FINISHEDfrommessage_stop. The behavior is correct — we shouldn't emit both — but a name likehasEmittedTerminalEventwould better express intent. Minor nit, no functional issue.@@ -600,11 +684,12 @@600- type: 'TOOL_CALL_END',601- toolCallId: existing.id,602- toolName: existing.name,603- model,604- timestamp,605- input: parsedInput,684+ } else {685+ // Emit TEXT_MESSAGE_END only for text blocks (not tool_use blocks)686+ if (hasEmittedTextMessageStart && accumulatedContent) {687+ yield {688+ type: 'TEXT_MESSAGE_END',689+ messageId,690+ model,691+ timestamp,692+ }606693 }607694 }608-609- // Emit TEXT_MESSAGE_END if we had text content610- if (hasEmittedTextMessageStart && accumulatedContent) {695+ currentBlockType = null⚠️ Potential issue | 🟡 Minor
TEXT_MESSAGE_ENDmay emit spuriously for non-text, non-tool_use block types (e.g.,thinking).The
elsebranch fires for anycontent_block_stopwherecurrentBlockType !== 'tool_use', which includesthinkingblocks. If a text block preceded the thinking block, this would emit a spuriousTEXT_MESSAGE_ENDwhen the thinking block stops — becausehasEmittedTextMessageStartandaccumulatedContentare both still truthy.In practice Anthropic puts thinking blocks before text blocks, so this isn't currently triggered. But if the response ordering changes or new block types are added, it could surface.
Suggested guard
} else { - // Emit TEXT_MESSAGE_END only for text blocks (not tool_use blocks) - if (hasEmittedTextMessageStart && accumulatedContent) { + // Emit TEXT_MESSAGE_END only when a text block ends + if ( + currentBlockType === 'text' && + hasEmittedTextMessageStart && + accumulatedContent + ) { yield { type: 'TEXT_MESSAGE_END', messageId, model, timestamp, } } }🤖 Prompt for AI Agents
In `@packages/typescript/ai-anthropic/src/adapters/text.ts` around lines 684 - 695, The code emits a TEXT_MESSAGE_END for any content_block_stop where currentBlockType !== 'tool_use', which can spuriously include non-text types like 'thinking'; modify the guard so the yield of { type: 'TEXT_MESSAGE_END', ... } only happens when the block that just ended was actually a text block (e.g., check currentBlockType === 'text' or explicitly match the set of text block types) in addition to hasEmittedTextMessageStart and accumulatedContent; update the conditional around the yield in the same block where hasEmittedTextMessageStart, accumulatedContent, and currentBlockType are referenced (symbols: currentBlockType, hasEmittedTextMessageStart, accumulatedContent, and the TEXT_MESSAGE_END yield) so TEXT_MESSAGE_END is not emitted for non-text/non-tool_use block types.@@ -21,7 +21,7 @@2121 "@tanstack/ai-openrouter": "workspace:*",2222 "@tanstack/ai-react": "workspace:*",2323 "@tanstack/ai-react-ui": "workspace:*",24- "@tanstack/nitro-v2-vite-plugin": "^1.141.0",25- "@tanstack/react-router": "^1.141.1",26- "@tanstack/react-start": "^1.141.1",24+ "@tanstack/nitro-v2-vite-plugin": "^1.154.7",25+ "@tanstack/react-router": "^1.158.4",26+ "@tanstack/react-start": "^1.159.0",2727 "@tanstack/start": "^1.120.20",⚠️ Potential issue | 🟡 Minor
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash # Check if `@tanstack/start` is used elsewhere and what versions are pinned rg '"@tanstack/start"' --type json -nRepository: TanStack/ai
Length of output: 120
🌐 Web query:
@tanstack/start vs@tanstack/react-startversion alignment requirements💡 Result:
Don’t try to “align”
@tanstack/startwith@tanstack/react-start: they’re effectively different generations of TanStack Start. The current docs list React support as@tanstack/react-start(and Solid as@tanstack/solid-start) rather than using@tanstack/startdirectly. [2] A commonly referenced migration path is to remove@tanstack/startand install@tanstack/react-start. [3]@tanstack/react-startexpects same-version TanStack Router/Start internals: the package has hard-pinned dependencies (not ranges) on@tanstack/react-routerand multiple Start core packages (eg@tanstack/react-router: "1.158.1"when@tanstack/react-startis1.158.1). This means you should keep these TanStack packages on the exact same version (or let your package manager resolve them via@tanstack/react-start), otherwise you risk duplicate/mismatched installs. [1]Practical rule
- If you’re on modern Start: install/upgrade as a matched set:
@tanstack/react-start==@tanstack/react-router(and any other@tanstack/*start*packages you add). [1] - If you still have legacy
@tanstack/startin a project, treat it as a migration candidate, not something to version-match with@tanstack/react-start. [3]
- If you’re on modern Start: install/upgrade as a matched set:
Sources: [1]
@tanstack/react-startpackage.json (deps pinned to same version) https://app.unpkg.com/%40tanstack/react-start%401.158.1/files/package.json [2] TanStack Start docs – supported frameworks (React uses@tanstack/react-start) https://tanstack.com/start/v0/docs/framework [3] LogRocket migration article (remove@tanstack/start, install@tanstack/react-start) https://blog.logrocket.com/migrating-tanstack-start-vinxi-vite/
🏁 Script executed:
cat -n testing/panel/package.jsonRepository: TanStack/ai
Length of output: 1958
Remove legacy
@tanstack/startin favor of modern@tanstack/react-start.The repository includes both
@tanstack/start(^1.120.20) and@tanstack/react-start(^1.159.0). According to TanStack's migration guidance,@tanstack/startis a legacy package; modern React projects should use only@tanstack/react-start. Additionally,@tanstack/react-starthas hard-pinned dependencies on matching versions of related TanStack packages—ensure@tanstack/react-router(currently ^1.158.4) is kept at the same version as@tanstack/react-start(^1.159.0) to avoid duplicate or mismatched installs.🤖 Prompt for AI Agents
In `@testing/panel/package.json` around lines 24 - 27, Remove the legacy package entry "@tanstack/start" from dependencies and update the TanStack package versions to be consistent with "@tanstack/react-start"; specifically, delete the "@tanstack/start": "^1.120.20" line and change "@tanstack/react-router": "^1.158.4" to "^1.159.0" so it matches "@tanstack/react-start": "^1.159.0" (leave "@tanstack/nitro-v2-vite-plugin" unchanged unless other TanStack version constraints require alignment).View your CI Pipeline Execution ↗ for commit 28482da3aed63a7445a3aa29d24ccd49fba9ed11
Command Status Duration Result nx affected --targets=test:sherif,test:knip,tes...✅ Succeeded 3m 8s View ↗ nx run-many --targets=build --exclude=examples/**✅ Succeeded 1m 14s View ↗
☁️ Nx Cloud last updated this comment at
2026-02-10 00:38:56UTC@tanstack/ai
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai@275@tanstack/ai-anthropic
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-anthropic@275@tanstack/ai-client
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-client@275@tanstack/ai-devtools-core
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-devtools-core@275@tanstack/ai-gemini
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-gemini@275@tanstack/ai-grok
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-grok@275@tanstack/ai-ollama
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-ollama@275@tanstack/ai-openai
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-openai@275@tanstack/ai-openrouter
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-openrouter@275@tanstack/ai-preact
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-preact@275@tanstack/ai-react
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-react@275@tanstack/ai-react-ui
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-react-ui@275@tanstack/ai-solid
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-solid@275@tanstack/ai-solid-ui
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-solid-ui@275@tanstack/ai-svelte
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-svelte@275@tanstack/ai-vue
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-vue@275@tanstack/ai-vue-ui
npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-vue-ui@275@tanstack/preact-ai-devtools
npm i https://pkg.pr.new/TanStack/ai/@tanstack/preact-ai-devtools@275@tanstack/react-ai-devtools
npm i https://pkg.pr.new/TanStack/ai/@tanstack/react-ai-devtools@275@tanstack/solid-ai-devtools
npm i https://pkg.pr.new/TanStack/ai/@tanstack/solid-ai-devtools@275commit:
28482daActionable comments posted: 2
🤖 Fix all issues with AI agents
In `@packages/typescript/ai-openrouter/src/adapters/text.ts`: - Around line 114-138: Remove all local debug instrumentation in the chatStream flow: delete the fetch-based "agent log" blocks and their surrounding //#region...//#endregion comments inside the chatStream implementation, and remove the related chunkCountOuter and chunkCount tracking variables; ensure any references to these variables are also removed or replaced. Specifically, inside the chatStream method (and any helper logic that calls mapTextOptionsToSDK) remove the hardcoded fetch calls to 127.0.0.1:7244/ingest and the comment regions, then run the linter/tests to ensure no leftover references to chunkCountOuter, chunkCount, or the debug blocks remain. In `@testing/panel/src/routes/api.chat.ts`: - Around line 152-171: Remove all temporary debug "agent log" blocks that perform fire-and-forget fetches to http://127.0.0.1:7244/ingest/... within this file; specifically delete each // `#region` agent log ... // `#endregion` block (the POST handler entry block around the POST handler, and the similar blocks near lines referenced) so no hardcoded fetches or leaked internal data remain; search for the exact region marker string "// `#region` agent log" and the fetch URL to find every occurrence (e.g., the block inside the POST handler that logs '[DEBUG] POST /api/chat handler entered') and remove them, and if persistent telemetry is required replace them with calls to the app’s structured logging/observability API instead of direct fetches.🧹 Nitpick comments (4)
scripts/fix-version-bump.ts (2)
77-77: UseArray<T>generic syntax per project ESLint config.The project's
@typescript-eslint/array-typerule requires the generic form.♻️ Proposed fix
- const packagesToFix: PackageToFix[] = [] + const packagesToFix: Array<PackageToFix> = []- const errors: string[] = [] + const errors: Array<string> = []Also applies to: 110-110
14-25: Consider validating the CLI-provided version string.If a user passes a non-semver string (e.g.,
--version oops), it will be written verbatim intopackage.jsonandCHANGELOG.md. A simple regex check would guard against typos.🛡️ Suggested guard
function parseArgs(): { version: string | null } { const args = process.argv.slice(2) const versionIndex = args.findIndex( (arg) => arg === '--version' || arg === '-v', ) if (versionIndex !== -1 && args[versionIndex + 1]) { - return { version: args[versionIndex + 1] } + const version = args[versionIndex + 1] + if (!/^\d+\.\d+\.\d+/.test(version)) { + console.error(`❌ Invalid version format: ${version}`) + process.exit(1) + } + return { version } } return { version: null } }testing/panel/src/routes/api.chat.ts (1)
267-294: Wrappingchat()in try/catch is fine, but the catch only re-throws.Without the debug logging (which should be removed), the inner try/catch on lines 268–319 serves no purpose — it catches
chatErrorand immediately re-throws it, which the outercatchon line 345 already handles.If the intent is to add provider-specific error handling or transformation, implement that logic here; otherwise, remove the redundant try/catch to keep the code straightforward.
Proposed simplification (after removing debug logging)
- let stream: AsyncIterable<any> - try { - stream = chat({ + const stream = chat({ ...options, adapter, tools: [ getGuitars, recommendGuitarToolDef, addToCartToolServer, addToWishListToolDef, getPersonalGuitarPreferenceToolDef, ], systemPrompts: [SYSTEM_PROMPT], agentLoopStrategy: maxIterations(20), messages, modelOptions: {}, abortController, - }) - } catch (chatError: any) { - throw chatError - } + })packages/typescript/ai-openrouter/src/adapters/text.ts (1)
139-168: The inner try/catch aroundchat.sendis a good pattern — keep it, but clean it up.Wrapping the
await this.client.chat.send(...)call in its own try/catch (lines 140–168) is useful for distinguishing SDK initialization errors from stream-processing errors. After removing the debug logging, simplify to just re-throw or add meaningful error wrapping:Proposed cleanup
let stream: AsyncIterable<any> try { stream = await this.client.chat.send( { ...requestParams, stream: true }, { signal: options.request?.signal }, ) } catch (sendError: any) { - // `#region` agent log - fetch( - 'http://127.0.0.1:7244/ingest/830522ab-8098-40b9-a021-890f9c041588', - { ... }, - ).catch(() => {}) - // `#endregion` throw sendError }packages/typescript/ai-openrouter/src/adapters/text.ts lines 114 to 138OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -119,0 +118,21 @@118+ fetch(119+ 'http://127.0.0.1:7244/ingest/830522ab-8098-40b9-a021-890f9c041588',120+ {121+ method: 'POST',122+ headers: { 'Content-Type': 'application/json' },123+ body: JSON.stringify({124+ location: 'openrouter/text.ts:chatStream',125+ message: 'chatStream entry - request params',126+ data: {127+ model: requestParams.model,128+ messageCount: requestParams.messages?.length,129+ hasTools: !!requestParams.tools,130+ toolCount: requestParams.tools?.length,131+ keys: Object.keys(requestParams),132+ },133+ timestamp: Date.now(),134+ hypothesisId: 'C',135+ }),136+ },137+ ).catch(() => {})138+ // #endregion⚠️ Potential issue | 🔴 Critical
Critical: Remove all debug instrumentation from this published package.
This file is part of
@tanstack/ai-openrouter— a published npm package. The hardcodedfetchcalls tohttp://127.0.0.1:7244/ingest/...would execute for every consumer of this adapter. Even though they're fire-and-forget with.catch(() => {}), they:- Generate unnecessary network requests on every
chatStreamcall and on every streamed chunk (lines 176–202, 235–262) - Leak internal diagnostic data (error stacks, model params, content lengths) to a localhost endpoint
- Introduce latency and resource overhead in production
All
//#regionagent log … //#endregion`` blocks (lines 117–138, 146–166, 174–203, 233–263, 287–308, 310–330) and the supportingchunkCountOuter/chunkCounttracking variables (lines 114, 170, 172–173) that exist solely for this logging must be removed before merge.🤖 Prompt for AI Agents
In `@packages/typescript/ai-openrouter/src/adapters/text.ts` around lines 114 - 138, Remove all local debug instrumentation in the chatStream flow: delete the fetch-based "agent log" blocks and their surrounding //#region...//#endregion comments inside the chatStream implementation, and remove the related chunkCountOuter and chunkCount tracking variables; ensure any references to these variables are also removed or replaced. Specifically, inside the chatStream method (and any helper logic that calls mapTextOptionsToSDK) remove the hardcoded fetch calls to 127.0.0.1:7244/ingest and the comment regions, then run the linter/tests to ensure no leftover references to chunkCountOuter, chunkCount, or the debug blocks remain.✅ Addressed in commits 4ccfe30 to 28482da
testing/panel/src/routes/api.chat.ts lines 152 to 171OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -151 +151,21 @@151151 POST: async ({ request }) => {152+ // #region agent log153+ console.log(154+ '[DEBUG] POST /api/chat handler entered at',155+ new Date().toISOString(),156+ )157+ fetch(158+ 'http://127.0.0.1:7244/ingest/830522ab-8098-40b9-a021-890f9c041588',159+ {160+ method: 'POST',161+ headers: { 'Content-Type': 'application/json' },162+ body: JSON.stringify({163+ location: 'api.chat.ts:POST:ENTRY',164+ message: 'POST handler entered',165+ data: { url: request.url, method: request.method },166+ timestamp: Date.now(),167+ hypothesisId: 'ENTRY0',168+ }),169+ },170+ ).catch(() => {})171+ // #endregion⚠️ Potential issue | 🟠 Major
Remove debug instrumentation before merging to
main.These fire-and-forget
fetchcalls to a hardcodedhttp://127.0.0.1:7244/ingest/...endpoint are clearly temporary debugging artifacts. They appear in multiple regions throughout this file (lines 152–171, 226–249, 295–319, 321–342). Shipping them tomainadds dead code that will silently fail in any environment without that local service, clutters the handler, and leaks internal details (e.g.errorStack) to an uncontrolled endpoint.Please strip all
//#regionagent log … //#endregion`` blocks from this file before merge. If persistent telemetry is desired, consider a proper structured logging or observability solution.🤖 Prompt for AI Agents
In `@testing/panel/src/routes/api.chat.ts` around lines 152 - 171, Remove all temporary debug "agent log" blocks that perform fire-and-forget fetches to http://127.0.0.1:7244/ingest/... within this file; specifically delete each // `#region` agent log ... // `#endregion` block (the POST handler entry block around the POST handler, and the similar blocks near lines referenced) so no hardcoded fetches or leaked internal data remain; search for the exact region marker string "// `#region` agent log" and the fetch URL to find every occurrence (e.g., the block inside the POST handler that logs '[DEBUG] POST /api/chat handler entered') and remove them, and if persistent telemetry is required replace them with calls to the app’s structured logging/observability API instead of direct fetches.✅ Addressed in commits 4ccfe30 to 28482da
- Generate unnecessary network requests on every
Actionable comments posted: 1
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (3)
packages/typescript/ai/src/activities/chat/tools/tool-calls.ts (2)
298-306: ⚠️ Potential issue | 🟠 MajorDead branch and missing
"null"normalization.Two issues here:
argsStrcan never be falsy because of|| '{}'on line 298, soif (argsStr)on line 299 is always true—it's dead code.ToolCallManager.executeTools(line 134) normalizes the string"null"to"{}", but this function does not. If Anthropic sends"null"as tool arguments (a scenario this PR is meant to fix),JSON.parse("null")will yield JSnull, which will be passed to tool execute/validation as-is instead of{}.
Proposed fix
- const argsStr = toolCall.function.arguments.trim() || '{}' - if (argsStr) { - try { - input = JSON.parse(argsStr) - } catch (parseError) { - // If parsing fails, throw error to fail fast - throw new Error(`Failed to parse tool arguments as JSON: ${argsStr}`) - } + const argsStr = toolCall.function.arguments.trim() || '{}' + try { + input = JSON.parse(argsStr === 'null' ? '{}' : argsStr) + } catch (parseError) { + // If parsing fails, throw error to fail fast + throw new Error(`Failed to parse tool arguments as JSON: ${argsStr}`) }
418-426: ⚠️ Potential issue | 🟠 MajorJSON.parse(result)on string tool results can throw; falsy results coerced tonull.Two issues in the result handling (duplicated at lines 421–424 and 479–480):
If
tool.executereturns a non-JSON string (e.g."Success"),JSON.parse(result)throws aSyntaxError. The outercatchthen treats this as an execution error, even though the tool succeeded. By contrast,ToolCallManager.executeTools(line 179–180) keeps string results as-is.result || nullcoerces falsy values (0,"",false) tonull, silently discarding valid tool output.
Proposed fix (apply at both locations)
results.push({ toolCallId: toolCall.id, toolName, - result: - typeof result === 'string' - ? JSON.parse(result) - : result || null, + result: result ?? null, duration, })Also applies to: 476-482
packages/typescript/ai/src/activities/chat/stream/processor.ts (1)
1058-1067: ⚠️ Potential issue | 🟠 MajorClear
currentAssistantMessageIdwhen resetting stream state.If
StreamProcessor.process()is called multiple times on the same instance withoutprepareAssistantMessage(), new chunks will append to the previous assistant message because the ID persists. Clearing it inresetStreamState()prevents cross-run contamination.🛠️ Suggested fix
private resetStreamState(): void { this.totalTextContent = '' this.currentSegmentText = '' this.lastEmittedText = '' this.thinkingContent = '' this.toolCalls.clear() this.toolCallOrder = [] this.finishReason = null this.hasError = false + this.currentAssistantMessageId = null this.isDone = false this.chunkStrategy.reset?.() }🤖 Fix all issues with AI agents
In `@packages/typescript/ai/tests/tool-call-manager.test.ts`: - Around line 620-641: Add a test to verify that executeToolCalls normalizes the string "null" to an empty object like ToolCallManager.executeTools does: create a Tool (name 'simple_tool') with inputSchema z.object({}) and a mocked execute, call makeToolCall('call_1','simple_tool','null'), pass it into executeToolCalls(...), and assert result.results length is 1 and that tool.execute was called with {}; this will catch the inconsistency between executeToolCalls and ToolCallManager.executeTools.🧹 Nitpick comments (5)
packages/typescript/ai/docs/chat-architecture.md (1)
1-51: Excellent architectural overview, but add language specifiers to code blocks.The introduction and system overview effectively establish the document's purpose and architectural context. The ASCII diagram clearly illustrates the relationship between components.
However, the fenced code block at lines 29-51 (and many others throughout) lacks a language specifier, triggering markdownlint warnings. For ASCII diagrams, consider using
textorplaintextas the language identifier.📝 Suggested improvement for code block formatting
-``` +```text ┌──────────────────────────────────────────────────────────────┐ │ chat() function │Apply similar changes to all fenced code blocks throughout the document (lines 68, 120, 164, 187, 202, 240, 271, 287, 350, 358, 376, 400, 413).
packages/typescript/ai/tests/tool-call-manager.test.ts (2)
248-252: Avoidevaleven in tests.Using
eval(args.expression)is unnecessary here—the test controls the input. A static return (e.g.JSON.stringify({ result: 8 })) would be safer and avoids lint warnings.
380-641: Consider adding tests for the normal server-tool path (CASE 3) and the unknown-tool error path.The new suite covers client tools and server-with-approval well, but two paths in
executeToolCallslack dedicated tests:- Normal server tool without approval (CASE 3, lines 460–493 in the source) — the most common execution path.
- Unknown tool (lines 285–294) — when a tool call references a name not in the
toolsarray.
These are the happy-path and basic-error-path respectively, so coverage would be valuable.
packages/typescript/ai/tests/stream-processor.test.ts (2)
1-1: Use a top-level type-only import forMock.ESLint flags the inline
typespecifier. Split into a separate type import.Proposed fix
-import { type Mock, describe, expect, it, vi } from 'vitest' +import { describe, expect, it, vi } from 'vitest' +import type { Mock } from 'vitest'
19-71: Duplicated test helpers across test files.The
chunk()factory and theevshorthand object are nearly identical to those inchat.test.ts(lines 11-52). Consider extracting them into a shared test utility module (e.g.,tests/helpers/chunk-factory.ts) to keep the two suites in sync and reduce maintenance burden.#!/bin/bash # Check for other test files that might also duplicate these helpers rg -l 'function chunk<T extends StreamChunk' --type=ts@@ -375,0 +621,21 @@621+ it('should normalize empty arguments to empty object', async () => {622+ const tool: Tool = {623+ name: 'simple_tool',624+ description: 'A tool with no required args',625+ inputSchema: z.object({}),626+ execute: vi.fn(() => ({ done: true })),627+ }628+629+ const toolCalls = [makeToolCall('call_1', 'simple_tool', '')]630+631+ const result = await executeToolCalls(632+ toolCalls,633+ [tool],634+ new Map(),635+ new Map(),636+ )637+638+ expect(result.results).toHaveLength(1)639+ expect(tool.execute).toHaveBeenCalledWith({})640+ })641+ })⚠️ Potential issue | 🟡 Minor
Missing test for
"null"argument normalization.Given this PR fixes Anthropic tool-call issues where the provider can send
"null"as tool arguments, consider adding a test case that passes"null"asargstomakeToolCalland verifies the tool receives{}. This would also catch the inconsistency noted in the source file whereexecuteToolCallscurrently does not normalize"null"(unlikeToolCallManager.executeTools).Suggested test
it('should normalize "null" arguments to empty object', async () => { const tool: Tool = { name: 'simple_tool', description: 'A tool with no required args', inputSchema: z.object({}), execute: vi.fn(() => ({ done: true })), } const toolCalls = [makeToolCall('call_1', 'simple_tool', 'null')] const result = await executeToolCalls( toolCalls, [tool], new Map(), new Map(), ) expect(result.results).toHaveLength(1) expect(tool.execute).toHaveBeenCalledWith({}) })🤖 Prompt for AI Agents
In `@packages/typescript/ai/tests/tool-call-manager.test.ts` around lines 620 - 641, Add a test to verify that executeToolCalls normalizes the string "null" to an empty object like ToolCallManager.executeTools does: create a Tool (name 'simple_tool') with inputSchema z.object({}) and a mocked execute, call makeToolCall('call_1','simple_tool','null'), pass it into executeToolCalls(...), and assert result.results length is 1 and that tool.execute was called with {}; this will catch the inconsistency between executeToolCalls and ToolCallManager.executeTools.AlemTuzlak approved these changes
AlemTuzlak merged this5d98472
AlemTuzlak closed this
Sign in to join this conversation.
📝 Walkthrough
Walkthrough#
This PR fixes streaming message handling across AI adapters by implementing lazy assistant message creation, deduplicating tool result messages, merging consecutive same-role messages, and filtering empty messages. Updates include new APIs for querying lazy message state, comprehensive test coverage, comprehensive architectural documentation, and dependency version bumps across example and testing packages.
Changes#
packages/typescript/ai-anthropic/src/adapters/text.ts,packages/typescript/ai-anthropic/src/model-meta.ts,packages/typescript/ai-anthropic/src/text/text-provider-options.ts,packages/typescript/ai-anthropic/tests/anthropic-adapter.test.tspackages/typescript/ai-gemini/src/adapters/text.ts,packages/typescript/ai-gemini/tests/gemini-adapter.test.tspackages/typescript/ai/src/activities/chat/stream/processor.ts,packages/typescript/ai/src/activities/chat/messages.ts,packages/typescript/ai/src/activities/chat/index.ts,packages/typescript/ai/src/activities/chat/tools/tool-calls.ts,packages/typescript/ai/src/types.tspackages/typescript/ai-client/src/chat-client.tspackages/typescript/ai/tests/chat.test.ts,packages/typescript/ai/tests/stream-processor.test.ts,packages/typescript/ai/tests/message-converters.test.ts,packages/typescript/ai/tests/tool-call-manager.test.tspackages/typescript/ai/docs/chat-architecture.md,.changeset/fix-anthropic-multi-turn-tool-calls.md,.changeset/tighten-adapter-contract.mdexamples/ts-group-chat/package.json,examples/ts-react-chat/package.json,examples/ts-solid-chat/package.json,packages/typescript/smoke-tests/e2e/package.json,testing/panel/package.jsonexamples/ts-react-chat/src/routeTree.gen.ts,testing/panel/tests/tool-flow.spec.ts,testing/panel/src/lib/model-selection.tspackages/typescript/smoke-tests/adapters/src/tests/apr-approval-flow.ts,scripts/fix-version-bump.ts,.gitignoreEstimated Code Review Effort#
🎯 4 (Complex) | ⏱️ ~45 minutes
Possibly Related PRs#
Suggested Reviewers#
Poem#
🚥 Pre-merge checks | ✅ 2 | ❌ 1
❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✨ Finishing touches
🧪 Generate unit tests (beta)
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.
❤️ Share