Skip to content
Source
Sign inSign up
TanStack/ai

fix: anthropic tool call issues #275

Mergedjherrmerged 13 commits intomain fromrefs/pull/275/headmerged by AlemTuzlak View on GitHub

jherrcommented

🎯 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. coderabbitai[bot](GitHub profile, opens in a new tab)commented
      📝 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

      Cohort / File(s)Summary
      Anthropic Adapter
      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.ts
      Extended Anthropic options (effort, thinking, adaptive_thinking), added message role merging to fix consecutive user messages, deduplicates tool_result blocks, filters empty assistant messages, suppresses duplicate RUN_FINISHED events, and emits proper text/tool lifecycle signals. Adds comprehensive tests for multi-turn flows with tool results and empty message handling.
      Gemini Adapter
      packages/typescript/ai-gemini/src/adapters/text.ts, packages/typescript/ai-gemini/tests/gemini-adapter.test.ts
      Merges consecutive same-role messages, deduplicates functionResponse parts by name, filters empty model messages, and preserves message interleaving. Adds tests for multi-turn tool flows and deduplication scenarios.
      Stream Processor & Core Chat
      packages/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.ts
      Implements lazy assistant message creation via prepareAssistantMessage() and getCurrentAssistantMessageId(), rewrites message interleaving to preserve part order, adds TEXT_MESSAGE_START event handling, refactors text accumulation and tool-call lifecycle, adds tool result deduplication, and makes delta properties required in TextMessageContentEvent and StepFinishedEvent.
      Chat Client
      packages/typescript/ai-client/src/chat-client.ts
      Updates processStream to use lazy assistant message creation, prevents UI flicker from empty messages, and synchronizes pending client tool executions before stream finalization.
      Core Tests
      packages/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.ts
      Adds comprehensive test coverage for chat streaming, tool flows, message conversions, multi-iteration loops, approvals, structured output, error handling, and introduces public exports for convertMessagesToModelMessages, modelMessagesToUIMessages, normalizeToUIMessage, and executeToolCalls.
      Documentation & Configuration
      packages/typescript/ai/docs/chat-architecture.md, .changeset/fix-anthropic-multi-turn-tool-calls.md, .changeset/tighten-adapter-contract.md
      Adds extensive architectural reference for Chat Stream Architecture with event sequences, processor behaviors, and adapter contracts. Changesets document patch and minor version bumps with tightened adapter contract requirements.
      Dependency Updates
      examples/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.json
      Updates TanStack router, react-start, and nitro packages to newer minor versions (react-router ^1.141.1 → ^1.158.4, react-start ^1.141.1 → ^1.159.0, etc.).
      Routing & Test Updates
      examples/ts-react-chat/src/routeTree.gen.ts, testing/panel/tests/tool-flow.spec.ts, testing/panel/src/lib/model-selection.ts
      Normalizes route keys to use trailing slashes for guitars route, adds multi-turn follow-up test for tool-capable providers with extended retries, and updates Grok-4 label to indicate slow thinking.
      Smoke Tests & Scripts
      packages/typescript/smoke-tests/adapters/src/tests/apr-approval-flow.ts, scripts/fix-version-bump.ts, .gitignore
      Removes hasHammerInResponse check from APR test success condition, adds version-bump automation script for fixing 1.0.0 versions in packages, and reinstates test-results in gitignore while adding STATUS_*.md.

      Estimated Code Review Effort

      🎯 4 (Complex) | ⏱️ ~45 minutes

      • TanStack/ai#244 — Both PRs implement AG-UI event model changes and make matching updates across adapters, stream processor, types, and tool-call handling affecting the same files and APIs.
      • TanStack/ai#278 — Both PRs add Claude Opus 4.6 model support and extend Anthropic provider configuration (model-meta, text-provider-options).
      • TanStack/ai#263 — Both PRs modify message support and type/signature changes across client, processor, adapters, and tests (ContentPart, message conversion functions).

      Suggested Reviewers

      • AlemTuzlak

      Poem

      🐰 Messages now flow with rightful grace, No empty parts cluttering the space, Lazy creation sets them free, Tool results merged in harmony, Anthropic, Gemini both align— The streaming flows like perfect wine! ✨

      🚥 Pre-merge checks | ✅ 2 | ❌ 1
      ❌ Failed checks (1 warning)
      Check nameStatusExplanationResolution
      Docstring Coverage⚠️ WarningDocstring coverage is 64.00% which is insufficient. The required threshold is 80.00%.Write docstrings for the functions missing them to satisfy the coverage threshold.
      ✅ Passed checks (2 passed)
      Check nameStatusExplanation
      Title check✅ PassedThe PR title 'fix: anthropic tool call issues' directly addresses the main purpose of the changeset, which is to fix multiple tool-call related issues in the Anthropic adapter including message merging, deduplication, and streaming behavior.
      Description check✅ PassedThe PR description follows the provided template with all required sections completed, including the Changes section and fully completed Checklist and Release Impact sections indicating the contributor tested locally and generated a changeset.
      ✏️ Tip: You can configure your own custom pre-merge checks in the settings.
      ✨ Finishing touches
      • 📝 Generate docstrings
        🧪 Generate unit tests (beta)
      • Create PR with unit tests
      • Post copyable unit tests in a comment
      • Commit unit tests in branch `patch/anthropic-tool-calls`

      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
      Comment `@coderabbitai help` to get the list of available commands and usage tips.
    2. AlemTuzlak approved these changes

    3. 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 | 🔴 Critical

      Fix type conflict: { type: 'adaptive' } is unassignable due to intersection with AnthropicThinkingOptions.

      ExternalTextProviderOptions at line 152 intersects AnthropicThinkingOptions with Partial<AnthropicAdaptiveThinkingOptions> at line 155. Both define a thinking property 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 in AnthropicAdaptiveThinkingOptions, it cannot satisfy the intersection, preventing users from passing adaptive thinking configuration despite it being declared in the interfaces.

      Replace AnthropicThinkingOptions with AnthropicAdaptiveThinkingOptions (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: Use Array<T> generic syntax per project lint rules.

      ESLint reports @typescript-eslint/array-type violations 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.

      parseArgs only supports --version X.Y.Z (space-separated), but common CLI convention also allows --version=X.Y.Z. Users passing the = form will silently get version: null and 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.

      fixPackageJson uses a regex to replace the version string in raw JSON text. This works for typical package.json files 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: validateThinking doesn't handle type: 'adaptive'.

      The validation function only handles type: 'enabled' and would silently skip type: 'adaptive'. If adaptive thinking has any constraints (e.g., it shouldn't coexist with budget_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: hasEmittedRunFinished naming is slightly misleading for the max_tokens case.

      When stop_reason is max_tokens, the code emits RUN_ERROR (not RUN_FINISHED), but the flag name hasEmittedRunFinished still prevents a follow-up RUN_FINISHED from message_stop. The behavior is correct — we shouldn't emit both — but a name like hasEmittedTerminalEvent would 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 content
      610- if (hasEmittedTextMessageStart && accumulatedContent) {
      695+ currentBlockType = null
      coderabbitai[bot](GitHub profile, opens in a new tab)commented

      ⚠️ Potential issue | 🟡 Minor

      TEXT_MESSAGE_END may emit spuriously for non-text, non-tool_use block types (e.g., thinking).

      The else branch fires for any content_block_stop where currentBlockType !== 'tool_use', which includes thinking blocks. If a text block preceded the thinking block, this would emit a spurious TEXT_MESSAGE_END when the thinking block stops — because hasEmittedTextMessageStart and accumulatedContent are 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",
      coderabbitai[bot](GitHub profile, opens in a new tab)commented

      ⚠️ 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 -n

      Repository: TanStack/ai

      Length of output: 120


      🌐 Web query:

      @tanstack/start vs @tanstack/react-start version alignment requirements

      💡 Result:

      • Don’t try to “align” @tanstack/start with @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/start directly. [2] A commonly referenced migration path is to remove @tanstack/start and install @tanstack/react-start. [3]

      • @tanstack/react-start expects same-version TanStack Router/Start internals: the package has hard-pinned dependencies (not ranges) on @tanstack/react-router and multiple Start core packages (eg @tanstack/react-router: "1.158.1" when @tanstack/react-start is 1.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/start in a project, treat it as a migration candidate, not something to version-match with @tanstack/react-start. [3]

      Sources: [1] @tanstack/react-start package.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.json

      Repository: TanStack/ai

      Length of output: 1958


      Remove legacy @tanstack/start in 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/start is a legacy package; modern React projects should use only @tanstack/react-start. Additionally, @tanstack/react-start has 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).
    4. nx-cloud[bot](GitHub profile, opens in a new tab)commented

      View your CI Pipeline Execution ↗ for commit 28482da3aed63a7445a3aa29d24ccd49fba9ed11

      CommandStatusDurationResult
      nx affected --targets=test:sherif,test:knip,tes...✅ Succeeded3m 8sView ↗
      nx run-many --targets=build --exclude=examples/**✅ Succeeded1m 14sView ↗

      ☁️ Nx Cloud last updated this comment at 2026-02-10 00:38:56 UTC

    5. pkg-pr-new[bot](GitHub profile, opens in a new tab)commented

      Open in StackBlitz

      @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@275

      commit: 28482da

    6. Actionable 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: Use Array<T> generic syntax per project ESLint config.

      The project's @typescript-eslint/array-type rule 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 into package.json and CHANGELOG.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: Wrapping chat() 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 chatError and immediately re-throws it, which the outer catch on 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 around chat.send is 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
             }
    7. 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 | 🟠 Major

      Dead branch and missing "null" normalization.

      Two issues here:

      1. argsStr can never be falsy because of || '{}' on line 298, so if (argsStr) on line 299 is always true—it's dead code.

      2. 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 JS null, 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 | 🟠 Major

      JSON.parse(result) on string tool results can throw; falsy results coerced to null.

      Two issues in the result handling (duplicated at lines 421–424 and 479–480):

      1. If tool.execute returns a non-JSON string (e.g. "Success"), JSON.parse(result) throws a SyntaxError. The outer catch then treats this as an execution error, even though the tool succeeded. By contrast, ToolCallManager.executeTools (line 179–180) keeps string results as-is.

      2. result || null coerces falsy values (0, "", false) to null, 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 | 🟠 Major

      Clear currentAssistantMessageId when resetting stream state.

      If StreamProcessor.process() is called multiple times on the same instance without prepareAssistantMessage(), new chunks will append to the previous assistant message because the ID persists. Clearing it in resetStreamState() 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 text or plaintext as 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: Avoid eval even 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 executeToolCalls lack dedicated tests:

      1. Normal server tool without approval (CASE 3, lines 460–493 in the source) — the most common execution path.
      2. Unknown tool (lines 285–294) — when a tool call references a name not in the tools array.

      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 for Mock.

      ESLint flags the inline type specifier. 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 the ev shorthand object are nearly identical to those in chat.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+ })
      coderabbitai[bot](GitHub profile, opens in a new tab)commented

      ⚠️ 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" as args to makeToolCall and verifies the tool receives {}. This would also catch the inconsistency noted in the source file where executeToolCalls currently does not normalize "null" (unlike ToolCallManager.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.
    8. AlemTuzlak approved these changes

    9. AlemTuzlak merged this5d98472

    10. AlemTuzlak closed this

Sign in to join this conversation.