Skip to content

feat: smart auto-routing (per-turn simple-vs-strong model selection) - #1734

Merged
kevincodex1 merged 17 commits into
Twigpine:mainfrom
beardthelion:feat/smart-auto-routing
Jul 7, 2026
Merged

kevincodex1 merged 17 commits into
Twigpine:mainfrom
beardthelion:feat/smart-auto-routing

Conversation

@beardthelion

@beardthelion beardthelion commented Jun 20, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Adds opt-in smart auto-routing: each user turn is classified simple or strong and routed to a cheaper or stronger model within the current provider. This wires the already-present-but-unconnected src/services/api/smartModelRouting.ts into the agent loop.
  • Off by default and labeled experimental. Configure via the new /smartroute command, a smartRouting settings block, or OPENCLAUDE_SMART_ROUTING* env vars.
  • Why: lets multi-provider users stop paying strong-model prices for trivial turns ("ok", "rename this"). The heuristic classifier already existed in the tree; the gap was the wiring plus the safety rails the agent loop needs (fallback, allowlist, cache/thinking correctness).

Impact

  • user-facing impact: new /smartroute command and smartRouting setting. When enabled, simple turns go to the cheaper model; /cost gains a routing summary (simple/strong split, simple->strong escalations, pricing-gated savings estimate). When disabled, the loop is byte-for-byte unchanged.
  • developer/maintainer impact: the per-turn routing decision is pinned in a query-loop local (classified once per user turn on transition === undefined); the routed-error fallback reuses the existing attemptWithFallback retry loop rather than adding a new one; the org model allowlist is enforced by calling isModelAllowed directly; thinking-block stripping on a model change goes through the existing provider gate (preserve-reasoning providers like DeepSeek/GLM are left untouched). A mid-turn provider-fallback swap drops the pin so a stale model id is never sent to the new endpoint. resolveModelOnlyModel and stripThinkingBlocksIfProviderAllows are newly exported (internal use).

Testing

  • bun run build
  • bun run smoke
  • bun run check — passes except 5 pre-existing full-suite failures (getAgentModel alias + applyConfigEnvironmentVariables) that also fail on main and are unrelated to this change; the routing tests are green
  • focused tests: src/services/api/smartRouting/*, src/commands/smartroute/*, conversationRecovery provider-gate, agentRouting, cost-tracker — all green

Notes

  • provider/model path tested: model-only routing within the active provider; cross-provider roles are detected and skipped (deferred). The provider-gated thinking strip is verified for preserve-reasoning providers so they don't 400 on a stripped block.
  • screenshots attached (if UI changed): n/a — output is terminal text (/smartroute status, /cost summary).
  • follow-up work or known limitations:
    • Cross-provider routing, an LLM-judge classifier, and provider benchmarking are intentionally out of scope.
    • query.ts is large; the inline routing/fallback blocks could be extracted into helpers. Deferred here rather than refactor the delicate generator inside this PR.
    • Loop-level integration tests for the fallback + provider-swap interaction are a follow-up; the decision logic and the provider-swap predicate are unit-tested.

Summary by CodeRabbit

Release Notes

  • New Features
    • Added opt-in Smart Auto-Routing (experimental, default off) to classify each turn as simple vs strong and route accordingly.
    • Added the /smartroute command to check status, enable/disable routing, and select role model keys.
  • Documentation
    • Added the Smart Auto-Routing guide plus startup environment variables and frontend settings.
  • Bug Fixes
    • Improved smart-routing reliability with per-turn routing pinning, provider-swap invalidation, and a one-time escalation retry to the strong model when appropriate.
    • Enhanced /cost to include a smart-routing usage summary; switching accounts now clears routing tallies too.

@coderabbitai

coderabbitai Bot commented Jun 20, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Adds an opt-in smart-routing feature that normalizes configuration, classifies turns, pins per-turn routing decisions, retries some routed failures on the strong model, and exposes routing state through /smartroute, /cost, and documentation.

Changes

Smart Auto-Routing End-to-End

Layer / File(s) Summary
Settings schema and normalization
src/utils/settings/types.ts, src/services/api/smartRouting/settings.ts, src/services/api/smartRouting/settings.test.ts
Adds the smartRouting settings shape, normalizes it from settings or env, and covers the normalization behavior with tests.
Config resolution and agentRouting export
src/services/api/agentRouting.ts, src/services/api/smartRouting/resolveConfig.ts, src/services/api/smartRouting/resolveConfig.test.ts
Exports model-only routing resolution, adds smart-routing config resolution, and tests cross-provider handling, fallback behavior, and threshold propagation.
Core routing service
src/services/api/smartRouting/index.ts, src/services/api/smartRouting/index.test.ts, src/services/api/smartModelRouting.ts
Implements turn routing decisions, session disable tracking, retryability checks, routing tallies, cost-summary formatting, turn-text extraction, and non-text-content routing, with tests for each path.
Thinking-block replay helper
src/utils/conversationRecovery.ts, src/utils/conversationRecovery.test.ts
Adds provider-gated thinking-block stripping and updates resume-time message recovery to call the shared helper.
Query loop pinning and fallback
src/query.ts
Adds per-turn routing pin state, applies pinned models on the first loop pass, drops pins on provider swap, and retries once on the strong model for retryable routed failures.
Cost tracker routing summary
src/cost-tracker.ts, src/commands/login/login.tsx
Resets routing tallies with cost state, appends routing summary output to the total-cost display, and routes account-switch cleanup through the shared cost-tracker wrapper.
/smartroute command and registration
src/commands/smartroute/index.ts, src/commands/smartroute/index.test.ts, src/commands.ts, src/services/api/openaiShim.ts, web/src/data/commands.ts, web/src/data/configuration.ts
Adds the local /smartroute command, registers it in command lists, exposes it in the web data and env docs, and covers the command behavior with tests.
Documentation
docs/smart-routing.md, README.md
Adds the smart-routing guide and links it from the README setup guides list.

Estimated code review effort: 5 (Critical) | ~120 minutes

Possibly related PRs

  • Gitlawb/openclaude#1228: Both PRs change thinking-block preservation and stripping in src/utils/conversationRecovery.ts, which affects replay behavior across providers.
  • Gitlawb/openclaude#1617: Smart routing reuses model-only agent routing resolution, including the exported resolveModelOnlyModel path.

Suggested labels: enhancement

Suggested reviewers: jatmn, kevincodex1

🚥 Pre-merge checks | ✅ 6 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 66.67% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (6 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Risk Surface Disclosed ✅ Passed Provider-routing/startup risks are explicitly called out as experimental, same-provider only, allowlisted, and out of scope; no blocker is introduced.
No Hidden Policy Change ✅ Passed No hidden policy change: routing defaults, allowlist, fallback, and cost/telemetry behavior are isolated in dedicated smart-routing files and documented, not buried in cleanup.
Title check ✅ Passed The title is concise and accurately describes the main change: opt-in smart auto-routing with simple-vs-strong model selection.
Description check ✅ Passed The description follows the required template and covers summary, impact, testing, and notes with the needed detail.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/commands/smartroute/index.test.ts (1)

1-109: ⚠️ Potential issue | 🔴 Critical | ⚡ Quick win

Fix type narrowing to resolve typecheck failures.

The pipeline shows 11 typecheck errors because the tests access res.value without first narrowing the LocalCommandResult type. Since LocalCommandResult is a discriminated union, you must check res.type === 'text' before accessing .value:

 test('status with no config shows disabled and available keys', async () => {
   const ctx = makeContext()
   const res = await call('', ctx)
+  expect(res.type).toBe('text')
+  if (res.type !== 'text') throw new Error('Expected text result')
   expect(res.value).toContain('status: disabled')
   expect(res.value).toContain('mini, main')
 })

Apply this pattern to all test cases that access res.value.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/commands/smartroute/index.test.ts` around lines 1 - 109, The tests access
res.value without type narrowing the LocalCommandResult discriminated union,
causing typecheck failures. Before accessing res.value in each test case where
the call function is invoked (in tests like 'status with no config shows
disabled and available keys', 'on without both roles set is rejected',
'simple/strong with no value argument is rejected', 'setting a role to an
unknown key is rejected with available keys', 'enabling with simple cheaper than
strong gives no warning', 'warns when the simple model is not cheaper than the
strong model', and 'off disables'), add a type guard check to verify res.type
=== 'text' before accessing the .value property.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/services/api/smartRouting/index.test.ts`:
- Around line 114-139: The three test cases 'short non-first turn routes
simple', 'first turn routes strong (routeModel turnNumber===1 guard)', and
'strong-signal prompt routes strong' are failing because decideTurnModel calls
isModelAllowed(model) to enforce org allowlist restrictions, but these tests do
not mock that function. Since the mock is not present, the real isModelAllowed
implementation runs and rejects the test models (gpt-5-mini and gpt-5), causing
routing to be disabled and returning routed: false instead of the expected
routed: true. Add a mock for isModelAllowed before each of these three test
cases to allow the test model names to pass the allowlist check. You can either
add the mock individually before each test or create a beforeEach block that
mocks isModelAllowed for the scope of these tests only.

In `@src/utils/conversationRecovery.test.ts`:
- Around line 409-444: The test cases stripThinkingBlocksIfProviderAllows
preserves thinking for preserve-reasoning 3P and
stripThinkingBlocksIfProviderAllows strips thinking for generic OpenAI 3P both
use as any type assertions to bypass TypeScript type checking when constructing
test message objects. Replace these as any casts with properly-typed test
fixtures that match the NormalizedMessage shape expected by
stripThinkingBlocksIfProviderAllows. Create a typed helper function or factory
that constructs the assistant message objects with correct types, ensuring the
function parameter and the content array elements conform to the actual expected
types without requiring type assertions.

In `@src/utils/conversationRecovery.ts`:
- Around line 228-256: The provider-detection logic for stripping thinking
blocks is duplicated between the new stripThinkingBlocksIfProviderAllows
function and the deserializeMessagesWithInterruptDetection function. Replace the
duplicated provider-gate logic in deserializeMessagesWithInterruptDetection (the
section that mirrors the implementation in stripThinkingBlocksIfProviderAllows)
with a direct call to stripThinkingBlocksIfProviderAllows to eliminate code
duplication and maintain a single source of truth for this logic.

---

Outside diff comments:
In `@src/commands/smartroute/index.test.ts`:
- Around line 1-109: The tests access res.value without type narrowing the
LocalCommandResult discriminated union, causing typecheck failures. Before
accessing res.value in each test case where the call function is invoked (in
tests like 'status with no config shows disabled and available keys', 'on
without both roles set is rejected', 'simple/strong with no value argument is
rejected', 'setting a role to an unknown key is rejected with available keys',
'enabling with simple cheaper than strong gives no warning', 'warns when the
simple model is not cheaper than the strong model', and 'off disables'), add a
type guard check to verify res.type === 'text' before accessing the .value
property.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: 39570f9c-171f-4330-b1a9-5196b79794e4

📥 Commits

Reviewing files that changed from the base of the PR and between b581bd9 and 58139eb.

📒 Files selected for processing (21)
  • README.md
  • docs/smart-routing.md
  • src/commands.ts
  • src/commands/login/login.tsx
  • src/commands/smartroute/index.test.ts
  • src/commands/smartroute/index.ts
  • src/cost-tracker.ts
  • src/query.ts
  • src/services/api/agentRouting.ts
  • src/services/api/openaiShim.ts
  • src/services/api/smartRouting/index.test.ts
  • src/services/api/smartRouting/index.ts
  • src/services/api/smartRouting/resolveConfig.test.ts
  • src/services/api/smartRouting/resolveConfig.ts
  • src/services/api/smartRouting/settings.test.ts
  • src/services/api/smartRouting/settings.ts
  • src/utils/conversationRecovery.test.ts
  • src/utils/conversationRecovery.ts
  • src/utils/settings/types.ts
  • web/src/data/commands.ts
  • web/src/data/configuration.ts
📜 Review details
🧰 Additional context used
📓 Path-based instructions (18)
src/**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

Use TypeScript with strict mode and ESM imports

Files:

  • src/services/api/smartRouting/resolveConfig.test.ts
  • src/services/api/smartRouting/settings.ts
  • src/commands.ts
  • src/commands/smartroute/index.test.ts
  • src/services/api/openaiShim.ts
  • src/utils/settings/types.ts
  • src/services/api/smartRouting/settings.test.ts
  • src/utils/conversationRecovery.ts
  • src/services/api/smartRouting/index.test.ts
  • src/services/api/smartRouting/resolveConfig.ts
  • src/utils/conversationRecovery.test.ts
  • src/commands/login/login.tsx
  • src/commands/smartroute/index.ts
  • src/cost-tracker.ts
  • src/services/api/agentRouting.ts
  • src/services/api/smartRouting/index.ts
  • src/query.ts
{src/commands/**/*.ts,src/services/**/*.ts,src/entrypoints/**/*.ts}

📄 CodeRabbit inference engine (AGENTS.md)

Use chalk for terminal color in CLI code

Files:

  • src/services/api/smartRouting/resolveConfig.test.ts
  • src/services/api/smartRouting/settings.ts
  • src/commands/smartroute/index.test.ts
  • src/services/api/openaiShim.ts
  • src/services/api/smartRouting/settings.test.ts
  • src/services/api/smartRouting/index.test.ts
  • src/services/api/smartRouting/resolveConfig.ts
  • src/commands/smartroute/index.ts
  • src/services/api/agentRouting.ts
  • src/services/api/smartRouting/index.ts
{src/services/**/*.ts,src/utils/**/*.ts}

📄 CodeRabbit inference engine (AGENTS.md)

Use execa for child processes

Files:

  • src/services/api/smartRouting/resolveConfig.test.ts
  • src/services/api/smartRouting/settings.ts
  • src/services/api/openaiShim.ts
  • src/utils/settings/types.ts
  • src/services/api/smartRouting/settings.test.ts
  • src/utils/conversationRecovery.ts
  • src/services/api/smartRouting/index.test.ts
  • src/services/api/smartRouting/resolveConfig.ts
  • src/utils/conversationRecovery.test.ts
  • src/services/api/agentRouting.ts
  • src/services/api/smartRouting/index.ts
{src/integrations/**/*.ts,src/services/**/*.ts}

📄 CodeRabbit inference engine (AGENTS.md)

Test the exact provider/model path you changed when possible for provider modifications

Files:

  • src/services/api/smartRouting/resolveConfig.test.ts
  • src/services/api/smartRouting/settings.ts
  • src/services/api/openaiShim.ts
  • src/services/api/smartRouting/settings.test.ts
  • src/services/api/smartRouting/index.test.ts
  • src/services/api/smartRouting/resolveConfig.ts
  • src/services/api/agentRouting.ts
  • src/services/api/smartRouting/index.ts
**/*.{ts,tsx,js,jsx,py,json,md}

📄 CodeRabbit inference engine (CONTRIBUTING.md)

Follow the existing code style in the touched files

Files:

  • src/services/api/smartRouting/resolveConfig.test.ts
  • src/services/api/smartRouting/settings.ts
  • web/src/data/commands.ts
  • src/commands.ts
  • src/commands/smartroute/index.test.ts
  • README.md
  • src/services/api/openaiShim.ts
  • docs/smart-routing.md
  • src/utils/settings/types.ts
  • web/src/data/configuration.ts
  • src/services/api/smartRouting/settings.test.ts
  • src/utils/conversationRecovery.ts
  • src/services/api/smartRouting/index.test.ts
  • src/services/api/smartRouting/resolveConfig.ts
  • src/utils/conversationRecovery.test.ts
  • src/commands/login/login.tsx
  • src/commands/smartroute/index.ts
  • src/cost-tracker.ts
  • src/services/api/agentRouting.ts
  • src/services/api/smartRouting/index.ts
  • src/query.ts
**/*.test.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (CONTRIBUTING.md)

Add or update tests when the change affects behavior

Files:

  • src/services/api/smartRouting/resolveConfig.test.ts
  • src/commands/smartroute/index.test.ts
  • src/services/api/smartRouting/settings.test.ts
  • src/services/api/smartRouting/index.test.ts
  • src/utils/conversationRecovery.test.ts
**/*.test.{ts,tsx,js}

📄 CodeRabbit inference engine (CONTRIBUTING.md)

Test the exact provider/model path you changed when possible

Files:

  • src/services/api/smartRouting/resolveConfig.test.ts
  • src/commands/smartroute/index.test.ts
  • src/services/api/smartRouting/settings.test.ts
  • src/services/api/smartRouting/index.test.ts
  • src/utils/conversationRecovery.test.ts
**/*.{ts,tsx,js,jsx,py}

📄 CodeRabbit inference engine (CONTRIBUTING.md)

Keep comments useful and concise

Files:

  • src/services/api/smartRouting/resolveConfig.test.ts
  • src/services/api/smartRouting/settings.ts
  • web/src/data/commands.ts
  • src/commands.ts
  • src/commands/smartroute/index.test.ts
  • src/services/api/openaiShim.ts
  • src/utils/settings/types.ts
  • web/src/data/configuration.ts
  • src/services/api/smartRouting/settings.test.ts
  • src/utils/conversationRecovery.ts
  • src/services/api/smartRouting/index.test.ts
  • src/services/api/smartRouting/resolveConfig.ts
  • src/utils/conversationRecovery.test.ts
  • src/commands/login/login.tsx
  • src/commands/smartroute/index.ts
  • src/cost-tracker.ts
  • src/services/api/agentRouting.ts
  • src/services/api/smartRouting/index.ts
  • src/query.ts
**/*.{ts,tsx}

📄 CodeRabbit inference engine (CONTRIBUTING.md)

Follow TypeScript strict mode and type safety practices by running typecheck before submitting

Files:

  • src/services/api/smartRouting/resolveConfig.test.ts
  • src/services/api/smartRouting/settings.ts
  • web/src/data/commands.ts
  • src/commands.ts
  • src/commands/smartroute/index.test.ts
  • src/services/api/openaiShim.ts
  • src/utils/settings/types.ts
  • web/src/data/configuration.ts
  • src/services/api/smartRouting/settings.test.ts
  • src/utils/conversationRecovery.ts
  • src/services/api/smartRouting/index.test.ts
  • src/services/api/smartRouting/resolveConfig.ts
  • src/utils/conversationRecovery.test.ts
  • src/commands/login/login.tsx
  • src/commands/smartroute/index.ts
  • src/cost-tracker.ts
  • src/services/api/agentRouting.ts
  • src/services/api/smartRouting/index.ts
  • src/query.ts
**/*

⚙️ CodeRabbit configuration file

**/*: Apply the OpenClaude maintainer review rubric from AGENTS.md. Review the current diff, not stale discussion context. Separate real blockers from suggestions. Do not request changes for vague style churn. Treat approval as merge-ready from CodeRabbit's side, pending required human review and GitHub Checks. If checks are failing or unavailable, say so clearly instead of implying the PR is fully ready.

Files:

  • src/services/api/smartRouting/resolveConfig.test.ts
  • src/services/api/smartRouting/settings.ts
  • web/src/data/commands.ts
  • src/commands.ts
  • src/commands/smartroute/index.test.ts
  • README.md
  • src/services/api/openaiShim.ts
  • docs/smart-routing.md
  • src/utils/settings/types.ts
  • web/src/data/configuration.ts
  • src/services/api/smartRouting/settings.test.ts
  • src/utils/conversationRecovery.ts
  • src/services/api/smartRouting/index.test.ts
  • src/services/api/smartRouting/resolveConfig.ts
  • src/utils/conversationRecovery.test.ts
  • src/commands/login/login.tsx
  • src/commands/smartroute/index.ts
  • src/cost-tracker.ts
  • src/services/api/agentRouting.ts
  • src/services/api/smartRouting/index.ts
  • src/query.ts
{src/services/api/**,src/integrations/**,src/utils/model/**,src/utils/provider*.ts,src/commands/provider/**}

⚙️ CodeRabbit configuration file

{src/services/api/**,src/integrations/**,src/utils/model/**,src/utils/provider*.ts,src/commands/provider/**}: Review provider routing, model selection, env precedence, auth/token handling, OpenAI-compatible shims, retries, proxy behavior, and outbound HTTP behavior with high scrutiny. Block on silent default changes, hidden fallback expansion, credential reuse mistakes, hardcoded provider assumptions, or new network reach that is not intentional and documented.

Files:

  • src/services/api/smartRouting/resolveConfig.test.ts
  • src/services/api/smartRouting/settings.ts
  • src/services/api/openaiShim.ts
  • src/services/api/smartRouting/settings.test.ts
  • src/services/api/smartRouting/index.test.ts
  • src/services/api/smartRouting/resolveConfig.ts
  • src/services/api/agentRouting.ts
  • src/services/api/smartRouting/index.ts
{src/**/*.test.ts,src/**/*.test.tsx,tests/**,scripts/**/*.test.ts,vscode-extension/**/*.test.js}

⚙️ CodeRabbit configuration file

{src/**/*.test.ts,src/**/*.test.tsx,tests/**,scripts/**/*.test.ts,vscode-extension/**/*.test.js}: Review tests for meaningful coverage of the changed behavior, isolation of global/env/config state, async cleanup, fake timers, provider profile leaks, and Windows-compatible assumptions. Block when risky runtime changes lack focused regression coverage or tests assert implementation details while missing the user-visible behavior.

Files:

  • src/services/api/smartRouting/resolveConfig.test.ts
  • src/commands/smartroute/index.test.ts
  • src/services/api/smartRouting/settings.test.ts
  • src/services/api/smartRouting/index.test.ts
  • src/utils/conversationRecovery.test.ts
**

⚙️ CodeRabbit configuration file

**: # AGENTS.md - AI Agent Coding Guide

This guide is for AI coding agents working in the OpenClaude repository. Read it before changing code, and also follow CONTRIBUTING.md for contributor policy, PR expectations, review follow-up, and project scope.

Project Snapshot

OpenClaude is a coding-agent CLI for cloud and local model providers. It supports OpenAI-compatible APIs, Anthropic, Gemini, DeepSeek, Ollama, MCP, local backends, slash commands, tools, agents, and a React/Ink terminal UI.

The installed CLI runs on Node.js >=22.0.0. Bun is used for source builds, scripts, dependency management, and tests.

Work Style

  • Keep changes focused on one problem.
  • Prefer existing patterns in the file or nearby module.
  • Avoid unrelated formatting, renames, dependency changes, or broad rewrites.
  • Add or update tests when behavior changes.
  • Update docs when setup, commands, provider behavior, or user-facing behavior changes.
  • For new features, larger refactors, dependencies, or runtime changes, follow the issue-first guidance in CONTRIBUTING.md.

Stack And Conventions

  • TypeScript with strict mode and ESM imports.
  • React + Ink for terminal UI.
  • Bun lockfile and Bun scripts for development workflows.
  • Node runtime for the built CLI.
  • Python exists for legacy/local-provider helper code. Do not add new Python code or expand Python-based features unless a maintainer explicitly approves that direction.

Common libraries and patterns:

  • chalk for terminal color.
  • commander for CLI argument parsing.
  • execa for child processes.
  • Existing service, provider, settings, permission, and UI patterns over new abstractions.

Repository Map

  • src/commands/ - slash and CLI command implementations.
  • src/components/ - React/Ink UI components.
  • src/services/ - API, MCP, OAuth, wiki, voice, and other service integrations.
  • src/tools/ - tool implementations.
  • src/utils/ - shared utilities.
  • `src/integration...

Files:

  • src/services/api/smartRouting/resolveConfig.test.ts
  • src/services/api/smartRouting/settings.ts
  • web/src/data/commands.ts
  • src/commands.ts
  • src/commands/smartroute/index.test.ts
  • README.md
  • src/services/api/openaiShim.ts
  • docs/smart-routing.md
  • src/utils/settings/types.ts
  • web/src/data/configuration.ts
  • src/services/api/smartRouting/settings.test.ts
  • src/utils/conversationRecovery.ts
  • src/services/api/smartRouting/index.test.ts
  • src/services/api/smartRouting/resolveConfig.ts
  • src/utils/conversationRecovery.test.ts
  • src/commands/login/login.tsx
  • src/commands/smartroute/index.ts
  • src/cost-tracker.ts
  • src/services/api/agentRouting.ts
  • src/services/api/smartRouting/index.ts
  • src/query.ts
web/**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (CONTRIBUTING.md)

Web changes must pass web typecheck and build via 'bun run web:typecheck' and 'bun run web:build'

Files:

  • web/src/data/commands.ts
  • web/src/data/configuration.ts
web/**

⚙️ CodeRabbit configuration file

web/**: Review browser extension changes for content-script isolation, message validation, cross-origin assumptions, permission surfaces, and failures that could leak prompts or credentials.

Files:

  • web/src/data/commands.ts
  • web/src/data/configuration.ts
{src/commands/**/*.ts,src/entrypoints/**/*.ts}

📄 CodeRabbit inference engine (AGENTS.md)

Use commander for CLI argument parsing

Files:

  • src/commands/smartroute/index.test.ts
  • src/commands/smartroute/index.ts
{README.md,CONTRIBUTING.md,docs/**,.github/pull_request_template.md}

⚙️ CodeRabbit configuration file

{README.md,CONTRIBUTING.md,docs/**,.github/pull_request_template.md}: Review docs for accuracy against current code behavior. Flag security or provider claims that overpromise, stale install commands, missing setup caveats, and instructions that could push users toward unsafe credential handling. Keep purely wording-level suggestions non-blocking.

Files:

  • README.md
  • docs/smart-routing.md
docs/**/*.md

📄 CodeRabbit inference engine (CONTRIBUTING.md)

Update docs when setup, commands, or user-facing behavior changes

Files:

  • docs/smart-routing.md
🪛 GitHub Actions: PR Checks / 1_smoke-and-tests.txt
src/services/api/smartRouting/index.test.ts

[error] 115-120: Test failed (Jest): expect(received).toMatchObject(expected) in decideTurnModel > disabled settings → routed:false. Expected { routed: true, complexity: 'simple', model: 'gpt-5-mini', strongModel: 'gpt-5' } but received { routed: false } at index.test.ts:120:15.

🪛 GitHub Actions: PR Checks / 2_typecheck.txt
src/commands/smartroute/index.test.ts

[error] 41-41: tsc (TypeScript) error TS2339: Property 'value' does not exist on type 'LocalCommandResult'. Property 'value' does not exist on type '{ type: "compact"; compactionResult: CompactionResult; displayText?: string | undefined; nextInput?: string | undefined; submitNextInput?: boolean | undefined; }'.


[error] 42-42: tsc (TypeScript) error TS2339: Property 'value' does not exist on type 'LocalCommandResult'. Property 'value' does not exist on type '{ type: "compact"; compactionResult: CompactionResult; displayText?: string | undefined; nextInput?: string | undefined; submitNextInput?: boolean | undefined; }'.


[error] 48-48: tsc (TypeScript) error TS2339: Property 'value' does not exist on type 'LocalCommandResult'. Property 'value' does not exist on type '{ type: "compact"; compactionResult: CompactionResult; displayText?: string | undefined; nextInput?: string | undefined; submitNextInput?: boolean | undefined; }'.


[error] 70-70: tsc (TypeScript) error TS2339: Property 'value' does not exist on type 'LocalCommandResult'. Property 'value' does not exist on type '{ type: "compact"; compactionResult: CompactionResult; displayText?: string | undefined; nextInput?: string | undefined; submitNextInput?: boolean | undefined; }'.


[error] 77-77: tsc (TypeScript) error TS2339: Property 'value' does not exist on type 'LocalCommandResult'. Property 'value' does not exist on type '{ type: "compact"; compactionResult: CompactionResult; displayText?: string | undefined; nextInput?: string | undefined; submitNextInput?: boolean | undefined; }'.


[error] 78-78: tsc (TypeScript) error TS2339: Property 'value' does not exist on type 'LocalCommandResult'. Property 'value' does not exist on type '{ type: "compact"; compactionResult: CompactionResult; displayText?: string | undefined; nextInput?: string | undefined; submitNextInput?: boolean | undefined; }'.


[error] 85-85: tsc (TypeScript) error TS2339: Property 'value' does not exist on type 'LocalCommandResult'. Property 'value' does not exist on type '{ type: "compact"; compactionResult: CompactionResult; displayText?: string | undefined; nextInput?: string | undefined; submitNextInput?: boolean | undefined; }'.


[error] 86-86: tsc (TypeScript) error TS2339: Property 'value' does not exist on type 'LocalCommandResult'. Property 'value' does not exist on type '{ type: "compact"; compactionResult: CompactionResult; displayText?: string | undefined; nextInput?: string | undefined; submitNextInput?: boolean | undefined; }'.


[error] 96-96: tsc (TypeScript) error TS2339: Property 'value' does not exist on type 'LocalCommandResult'. Property 'value' does not exist on type '{ type: "compact"; compactionResult: CompactionResult; displayText?: string | undefined; nextInput?: string | undefined; submitNextInput?: boolean | undefined; }'.


[error] 97-97: tsc (TypeScript) error TS2339: Property 'value' does not exist on type 'LocalCommandResult'. Property 'value' does not exist on type '{ type: "compact"; compactionResult: CompactionResult; displayText?: string | undefined; nextInput?: string | undefined; submitNextInput?: boolean | undefined; }'.


[error] 103-103: tsc (TypeScript) error TS2339: Property 'value' does not exist on type 'LocalCommandResult'. Property 'value' does not exist on type '{ type: "compact"; compactionResult: CompactionResult; displayText?: string | undefined; nextInput?: string | undefined; submitNextInput?: boolean | undefined; }'.

🪛 GitHub Actions: PR Checks / smoke-and-tests
src/services/api/smartRouting/index.test.ts

[error] 115-120: Test failed in decideTurnModel. expect(received).toMatchObject(expected) mismatched: expected { routed: true, complexity: 'simple', model: 'gpt-5-mini', strongModel: 'gpt-5' } but received { routed: false }.

🪛 GitHub Actions: PR Checks / typecheck
src/commands/smartroute/index.test.ts

[error] 41-41: tsc --noEmit: TS2339 Property 'value' does not exist on type 'LocalCommandResult'. (Property 'value' does not exist on type '{ type: "compact"; compactionResult: CompactionResult; displayText?: string | undefined; nextInput?: string | undefined; submitNextInput?: boolean | undefined; }').


[error] 42-42: tsc --noEmit: TS2339 Property 'value' does not exist on type 'LocalCommandResult'. (Property 'value' does not exist on type '{ type: "compact"; compactionResult: CompactionResult; displayText?: string | undefined; nextInput?: string | undefined; submitNextInput?: boolean | undefined; }').


[error] 48-48: tsc --noEmit: TS2339 Property 'value' does not exist on type 'LocalCommandResult'.


[error] 70-70: tsc --noEmit: TS2339 Property 'value' does not exist on type 'LocalCommandResult'.


[error] 77-77: tsc --noEmit: TS2339 Property 'value' does not exist on type 'LocalCommandResult'.


[error] 78-78: tsc --noEmit: TS2339 Property 'value' does not exist on type 'LocalCommandResult'.


[error] 85-85: tsc --noEmit: TS2339 Property 'value' does not exist on type 'LocalCommandResult'.


[error] 86-86: tsc --noEmit: TS2339 Property 'value' does not exist on type 'LocalCommandResult'.


[error] 96-96: tsc --noEmit: TS2339 Property 'value' does not exist on type 'LocalCommandResult'.


[error] 97-97: tsc --noEmit: TS2339 Property 'value' does not exist on type 'LocalCommandResult'.


[error] 103-103: tsc --noEmit: TS2339 Property 'value' does not exist on type 'LocalCommandResult'.

🪛 GitHub Check: smoke-and-tests
src/services/api/smartRouting/index.test.ts

[failure] 138-138: error: expect(received).toMatchObject(expected)
{

  • "complexity": "strong",
  • "model": "gpt-5",
  • "routed": true,
  • "routed": false,
    }
  • Expected - 3
  • Received + 1

    at <anonymous> (/home/runner/work/openclaude/openclaude/src/services/api/smartRouting/index.test.ts:138:15)
    

[failure] 129-129: error: expect(received).toMatchObject(expected)
{

  • "complexity": "strong",
  • "model": "gpt-5",
  • "routed": true,
  • "routed": false,
    }
  • Expected - 3
  • Received + 1

    at <anonymous> (/home/runner/work/openclaude/openclaude/src/services/api/smartRouting/index.test.ts:129:15)
    

[failure] 120-120: error: expect(received).toMatchObject(expected)
{

  • "complexity": "simple",
  • "model": "gpt-5-mini",
  • "routed": true,
  • "strongModel": "gpt-5",
  • "routed": false,
    }
  • Expected - 4
  • Received + 1

    at <anonymous> (/home/runner/work/openclaude/openclaude/src/services/api/smartRouting/index.test.ts:120:15)
    
🔇 Additional comments (23)
README.md (1)

191-191: LGTM — Smart Auto-Routing doc link placement is correct.

The addition fits naturally under "Advanced and source-build guides" as an optional experimental feature. The link format is valid for relative navigation.

docs/smart-routing.md (1)

1-58: Documentation is accurate and complete.

Verified all major claims against the implemented /smartroute command handler, decideTurnModel logic, and query-loop integration:

  • Setup example and schema match configured defaults ✓
  • Command table (status/on/off/simple/strong) matches handler branches ✓
  • Env vars match expected naming (OPENCLAUDE_SMART_ROUTING*) ✓
  • Behavior: one-per-turn decision, fallback to strong on retryable errors, allowlist coercion with session disable, re-enable via /smartroute on — all documented correctly ✓
  • /cost summary telemetry mentioned as per PR scope ✓
  • Experimental label and off-by-default flags are clear ✓

Minor non-blocking note: The docs don't detail the classifier heuristic (prompt length, code blocks, reasoning keywords), but this is intentional—the conservative failure mode ("routes to strong when unsure") is the key guarantee, and implementation details aren't a user concern. Appropriate level of abstraction.

src/utils/settings/types.ts (1)

783-808: LGTM!

src/services/api/smartRouting/settings.ts (1)

1-84: LGTM!

src/services/api/smartRouting/settings.test.ts (1)

1-112: LGTM!

src/services/api/agentRouting.ts (1)

163-172: LGTM!

src/services/api/smartRouting/resolveConfig.ts (1)

1-84: LGTM!

src/services/api/smartRouting/resolveConfig.test.ts (1)

1-94: LGTM!

src/services/api/smartRouting/index.ts (1)

1-277: LGTM!

src/services/api/smartRouting/index.test.ts (1)

65-316: ⚡ Quick win

Test coverage is comprehensive once the allowlist mock issue is fixed.

The remaining tests (deriveUserTurnNumber, extractLatestUserText, allowlist enforcement, retryability, pin-drop logic, tally tracking, and summary formatting) are well-structured and cover the expected edge cases. The session-scoped disable tracking tests (lines 158-213) correctly verify isolation and clearing behavior. The retryability tests (lines 217-234) match the intentional 404/429-retryable design documented in index.ts line 132-137.

src/cost-tracker.ts (1)

12-13: LGTM!

Also applies to: 88-90, 294-299

src/commands/login/login.tsx (1)

4-6: LGTM!

src/commands/smartroute/index.ts (1)

1-120: LGTM!

src/commands.ts (1)

165-165: LGTM!

Also applies to: 276-276

web/src/data/commands.ts (1)

95-95: LGTM!

web/src/data/configuration.ts (1)

53-53: LGTM!

Also applies to: 77-79

src/services/api/openaiShim.ts (1)

22-26: LGTM!

src/query.ts (6)

106-106: LGTM!


126-138: LGTM!


370-379: LGTM!


774-828: LGTM!


946-952: LGTM!


1274-1331: LGTM!

Comment thread src/services/api/smartRouting/index.test.ts
Comment thread src/utils/conversationRecovery.test.ts
Comment thread src/utils/conversationRecovery.ts
coderabbitai[bot]
coderabbitai Bot previously approved these changes Jun 20, 2026

@jatmn jatmn left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I found an issue that needs to be addressed before this is ready.

Findings

  • [P2] Stop presenting smart routing as provider-aware cost savings
    src/services/api/smartRouting/index.ts:15
    The feature is documented and surfaced as routing simple turns to the cheaper model for the current provider, and /smartroute plus /cost claim to warn/estimate when the simple model is not actually cheaper. The implementation cannot know that today: getKnownInputCost() only canonicalizes the model name and looks it up in the static first-party MODEL_COSTS table, without passing the active provider/profile/base URL/gateway route/account pricing or comparing observed billed usage. For OpenAI-compatible gateways and hosted providers, the same model id or alias can have different pricing from OpenClaude's first-party table, and unknown/private models just lose the estimate entirely. That means the UI can tell a multi-provider user that routing is saving money, or fail to warn that it is not, even though the current provider's pricing says otherwise. Please either make the cheaper-model check provider/route-aware, or narrow the docs/UI to say it only routes to the user-configured "simple" role and only estimates savings for pricing sources the code can actually verify.

@beardthelion

Copy link
Copy Markdown
Contributor Author

@jatmn good catch, fixed in c114ff2.

You're right that getKnownInputCost only reads the static first-party MODEL_COSTS table and can't know the active provider/gateway/account pricing. I took the second option you offered: narrow the claims rather than assert savings the code can't verify. The /cost summary, the /smartroute cheaper-warning, and docs/smart-routing.md now label the numbers as first-party reference pricing and note your provider may bill differently; the docs also state plainly that routing targets the role you configure and does not read your provider's pricing. Tests assert the qualifier on every reworded branch so it can't silently regress.

I didn't make the check provider/route-aware (your first option). OpenClaude has no per-provider or per-gateway pricing data today, and comparing observed billed usage is a real feature rather than a fix for this PR, so honest framing is the right scope here. Happy to file a follow-up for provider-aware pricing if you'd like it tracked separately.

coderabbitai[bot]
coderabbitai Bot previously approved these changes Jun 21, 2026
@jatmn
jatmn marked this pull request as draft July 7, 2026 01:05
beardthelion and others added 14 commits July 6, 2026 18:06
Classify once per user turn (transition===undefined), pin the decision in a
loop-local, and apply the model-only route before the blocking-limit math.
Enforce the org allowlist by calling isModelAllowed directly (coerce disallowed
to strong; disable for the session if strong is also disallowed). Strip thinking
history on a model change only under the provider gate (preserve-reasoning
providers are left untouched). Export stripThinkingBlocksIfProviderAllows.
A simple-routed turn whose model call hits a retryable error retries once on
the strong model, reusing the existing attemptWithFallback retry loop. Aborts
and 4xx client errors propagate. Adds a session routing tally (simple/strong
counts and simple->strong escalations) for the observability surface.
/smartroute shows status and sets/toggles the simple and strong roles from
agentModels keys, warning when the simple model is not first-party-cheaper than
the strong one. OPENCLAUDE_SMART_ROUTING(_SIMPLE/_STRONG) provide startup
defaults; an explicit settings block overrides env.
Appends a session routing summary (turns simple/strong, simple->strong
escalations) to /cost, with an estimated-savings line gated on first-party
pricing and annotated unavailable for unknown third-party pricing. Per-turn
cost is already attributed to the routed model via the existing per-model
breakdown.
Without this, a turn's later continuation passes re-applied the pinned simple
model after a fallback, re-triggering the same failure each pass. Re-pinning to
strong keeps the rest of the turn on the recovered model.
- Add the KTD6 provider-swap guard: drop the per-turn routing pin when a
  mid-turn provider-fallback swap changes the active provider, so the old
  provider's model id is not replayed at the new endpoint (adversarial P1).
- Reset the routing tally in resetCostState() so /cost does not show stale
  cross-session counts.
- Don't emit the disabled-for-session notice on every turn when no sessionId
  is available (suppress instead of storm).
- Document OPENCLAUDE_SMART_ROUTING* in the openaiShim env-var header.
- Add tests: provider-swap-safe pin, undefined-session silence, /smartroute
  strong arm and no-value guard.
Register /smartroute in the web command catalog, add the smartRouting setting
and OPENCLAUDE_SMART_ROUTING* env vars to the configuration reference, add a
docs/smart-routing.md usage guide, and link it from the README.
…disabled set

- /login used the raw bootstrap resetCostState, leaking the routing tally
  across an account switch; switch it to the cost-tracker wrapper.
- Extract the provider-swap drop check as a pure, tested
  shouldDropPinForProviderSwap() and use it in the query loop.
- Cap the disabledSessions set so a long-lived host can't grow it unbounded.
- Document the 404/429 retry-by-design rationale; add tests for it.
- Clarify the routedFallbackUsed per-turn scope and the apply-after-guard
  comment; document cross-provider role rejection and the re-enable path.
… mocks

The decideTurnModel allowlist tests spied the global settings singleton, which
let another file's leaked mock.module of modelAllowlist (agent.test.ts) flip
isModelAllowed out from under them in the full suite. Spy isModelAllowed
directly and restore it in afterEach so the tests are deterministic regardless
of suite ordering.
- index.test.ts: pin the allowlist in the three happy-path decideTurnModel
  tests so they no longer inherit a leaked cross-file isModelAllowed mock
  (the CI test failure)
- smartroute/index.test.ts: narrow the LocalCommandResult union via an
  expectText helper instead of reading .value off the union (the CI
  typecheck failure)
- conversationRecovery.ts: route deserialize's thinking-strip gate through
  stripThinkingBlocksIfProviderAllows, removing the duplicated provider
  detection
- conversationRecovery.test.ts: replace the two as-any fixtures with a
  shared typed factory
Smart routing's savings estimate and "simple isn't cheaper" warning were
derived from the static first-party MODEL_COSTS table via getKnownInputCost,
with no knowledge of the active provider, gateway, or account pricing. For a
multi-provider user whose model ids happen to exist in that table but bill
differently, the /cost summary and /smartroute warning stated a savings figure
as if it reflected what they are actually charged.

Narrow the copy instead of inventing provider-aware pricing the code cannot
verify: the /cost line, the /smartroute warning, and docs/smart-routing.md now
label the numbers as first-party reference pricing and note the active provider
may bill differently. Tests assert the qualifier on every reworded branch so it
cannot silently regress. No routing logic changed.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/commands/smartroute/index.ts`:
- Around line 27-30: The model-key lookup logic is duplicated in roleModelString
and getRoutingSummaryForDisplay, so update the smartroute command to reuse a
single shared resolver instead of repeating settings?.agentModels?.[key]?.model
?? key. Move or extract the lookup into a common helper used by both
roleModelString and the smartRouting display logic so the behavior stays
consistent and cannot drift.
- Around line 52-58: The persist flow is ignoring write failures from
updateSettingsForSource, so the in-memory state changes even when the on-disk
save fails. Update persist in smartroute/index.ts to capture the returned {
error } and make callers handle that result before composing the success
response. In the Smart routing command handlers that call persist, append a
warning to the user-facing message when persistence fails, using the existing
SmartRoutingSettings and updateSettingsForSource symbols to locate the affected
code.
- Around line 61-74: The `/smartroute` status output is reading
`current.simpleModel` and `current.strongModel` even when
`readSmartRouting(settings)` has enabled routing from environment-backed values.
Update the status block in the `smartroute` command to use the normalized
smart-routing values returned by `readSmartRouting` for the `simple` and
`strong` lines, so env-only setups no longer show `enabled` with both roles as
`(unset)`. Keep the existing `isSmartRoutingDisabledForSession` messaging and
`HELP` output unchanged.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 99ff2fa7-70eb-4e04-9d7d-c9f760666467

📥 Commits

Reviewing files that changed from the base of the PR and between c114ff2 and 3b8fb27.

📒 Files selected for processing (16)
  • README.md
  • docs/smart-routing.md
  • src/commands.ts
  • src/commands/login/login.tsx
  • src/commands/smartroute/index.test.ts
  • src/commands/smartroute/index.ts
  • src/cost-tracker.ts
  • src/query.ts
  • src/services/api/agentRouting.ts
  • src/services/api/openaiShim.ts
  • src/services/api/smartRouting/index.test.ts
  • src/services/api/smartRouting/index.ts
  • src/services/api/smartRouting/resolveConfig.test.ts
  • src/services/api/smartRouting/resolveConfig.ts
  • src/services/api/smartRouting/settings.test.ts
  • src/services/api/smartRouting/settings.ts
💤 Files with no reviewable changes (9)
  • src/services/api/smartRouting/resolveConfig.test.ts
  • src/services/api/smartRouting/settings.test.ts
  • src/services/api/openaiShim.ts
  • src/services/api/agentRouting.ts
  • src/services/api/smartRouting/settings.ts
  • src/services/api/smartRouting/resolveConfig.ts
  • src/services/api/smartRouting/index.test.ts
  • src/query.ts
  • src/services/api/smartRouting/index.ts
📜 Review details
⚠️ CI failures not shown inline (2)

GitHub Actions: PR Checks / smoke-and-tests: feat: smart auto-routing (per-turn simple-vs-strong model selection)

Conclusion: failure

View job details

ool uses reason-aware result for hard_max
 (pass) StreamingToolExecutor lifecycle tracking > already-aborted streaming tool uses reason-aware result for background [1.00ms]
 ##[endgroup]
 ##[group]src/services/tools/toolOrchestration.test.ts:
 (pass) Bash commands with shell parser limitations are serialized [3.00ms]
 ##[endgroup]
 ##[group]src/services/tools/toolExecution.test.ts:
 (pass) getSchemaValidationErrorOverride > returns actionable missing-skill error for SkillTool
 (pass) getSchemaValidationErrorOverride > does not override unrelated tool schema failures
 (pass) getSchemaValidationErrorOverride > does not override SkillTool when skill is present
 (pass) getSchemaValidationErrorOverride > uses the actionable override for structured toolUseResult too
 (pass) getReplayModifiedFiles > captures file-editing tool paths
 (pass) getReplayModifiedFiles > captures Bash simulated sed edit paths
 (pass) replay tool lifecycle records > records permission denied completions [1.00ms]
 (pass) replay tool lifecycle records > records success completions with modified files
 (pass) replay tool lifecycle records > records error completions
 (pass) replay tool lifecycle records > classifies abort-shaped tool failures as cancelled
 (pass) replay tool lifecycle records > captures the final executable input
 (pass) replay tool lifecycle records > normalizes denied file-tool replay inputs to match allowed retry inputs
 (pass) replay tool lifecycle records > records one error terminal status when post-call result processing fails [2.00ms]
 (pass) query lifecycle tool-use cleanup > successful tool execution leaves no active lifecycle tool use [1.00ms]
 (pass) query lifecycle tool-use cleanup > custom validation failure leaves no active lifecycle tool use
 (pass) query lifecycle tool-use cleanup > schema validation failure does not end a lifecycle entry that never started [1.00ms]
 (pass) query lifecycle tool-use cleanup > unknown tool does not end a lifecycle entry that never s...

GitHub Actions: PR Checks / 1_smoke-and-tests.txt: feat: smart auto-routing (per-turn simple-vs-strong model selection)

Conclusion: failure

View job details

ncomplete streamed Bash commands when finish_reason is length [1.00ms]
 (pass) repairs truncated JSON objects even without command field [2.00ms]
 (pass) preserves raw input for unknown plain string tool arguments [1.00ms]
 (pass) preserves parsed string input for unknown JSON string tool arguments [1.00ms]
 (pass) sanitizes malformed MCP tool schemas before sending them to OpenAI [2.00ms]
 (pass) optional tool properties are not added to required[] — fixes Groq/Azure 400 tool_use_failed [1.00ms]
 (pass) coalesces consecutive user messages to avoid alternation errors (issue `#202`) [1.00ms]
 (pass) coalesces consecutive assistant messages preserving tool_calls (issue `#202`) [2.00ms]
 (pass) non-streaming: reasoning_content emitted as thinking block only when content is null [1.00ms]
 (pass) non-streaming: empty string content does not fall through to reasoning_content as text [1.00ms]
 (pass) non-streaming: real content takes precedence over reasoning_content [1.00ms]
 (pass) non-streaming: preserves response body when usage parsing fails [1.00ms]
 (pass) non-streaming: preserves response.url routing metadata after body read [1.00ms]
 (pass) non-streaming: strips <think> tag block from assistant content [1.00ms]
 (pass) streaming: thinking block closed before tool call [2.00ms]
 (pass) streaming: strips <think> tag block from assistant content deltas [1.00ms]
 (pass) streaming: strips <think> tag split across multiple content chunks [1.00ms]
 (pass) streaming: preserves prose without tags (no phrase-based false positive) [2.00ms]
 (pass) strips credentials and query params from URL in fetch network error message [1.00ms]
 (pass) classifies localhost transport failures with actionable category marker [2.00ms]
 (pass) transport failures are not labeled with HTTP status 503 [1.00ms]
 (pass) propagates AbortError without wrapping it as transport failure [1.00ms]
 (pass) classifies chat-completions endpoint 404 failures with endpoint_not_found marker [1.00ms]
 (pass) sel...
🧰 Additional context used
📓 Path-based instructions (5)
**

⚙️ CodeRabbit configuration file

**: # AGENTS.md - AI Agent Coding Guide

This guide is for AI coding agents working in the OpenClaude repository. Read it before changing code, and also follow CONTRIBUTING.md for contributor policy, PR expectations, review follow-up, and project scope.

Project Snapshot

OpenClaude is a coding-agent CLI for cloud and local model providers. It supports OpenAI-compatible APIs, Anthropic, Gemini, DeepSeek, Ollama, MCP, local backends, slash commands, tools, agents, and a React/Ink terminal UI.

The installed CLI runs on Node.js >=22.0.0. Bun is used for source builds, scripts, dependency management, and tests.

Work Style

  • Keep changes focused on one problem.
  • Prefer existing patterns in the file or nearby module.
  • Avoid unrelated formatting, renames, dependency changes, or broad rewrites.
  • Add or update tests when behavior changes.
  • Update docs when setup, commands, provider behavior, or user-facing behavior changes.
  • For new features, larger refactors, dependencies, or runtime changes, follow the issue-first guidance in CONTRIBUTING.md.

Stack And Conventions

  • TypeScript with strict mode and ESM imports.
  • React + Ink for terminal UI.
  • Bun lockfile and Bun scripts for development workflows.
  • Node runtime for the built CLI.

Common libraries and patterns:

  • chalk for terminal color.
  • commander for CLI argument parsing.
  • execa for child processes.
  • Existing service, provider, settings, permission, and UI patterns over new abstractions.

Repository Map

  • src/commands/ - slash and CLI command implementations.
  • src/components/ - React/Ink UI components.
  • src/services/ - API, MCP, OAuth, wiki, voice, and other service integrations.
  • src/tools/ - tool implementations.
  • src/utils/ - shared utilities.
  • src/integrations/ - provider and model integration metadata.
  • src/entrypoints/ - CLI, MCP, SDK, and generated public types.
  • src/tasks/ - local, remote, workflow, and monitor tas...

Files:

  • README.md
  • src/commands.ts
  • src/commands/login/login.tsx
  • docs/smart-routing.md
  • src/cost-tracker.ts
  • src/commands/smartroute/index.test.ts
  • src/commands/smartroute/index.ts
**/*

⚙️ CodeRabbit configuration file

**/*: Apply the OpenClaude maintainer review rubric from AGENTS.md. Review the current diff, not stale discussion context. Separate real blockers from suggestions. Do not request changes for vague style churn. Treat approval as merge-ready from CodeRabbit's side, pending required human review and GitHub Checks. If checks are failing or unavailable, say so clearly instead of implying the PR is fully ready.

Files:

  • README.md
  • src/commands.ts
  • src/commands/login/login.tsx
  • docs/smart-routing.md
  • src/cost-tracker.ts
  • src/commands/smartroute/index.test.ts
  • src/commands/smartroute/index.ts
{README.md,CONTRIBUTING.md,docs/**,.github/pull_request_template.md}

⚙️ CodeRabbit configuration file

{README.md,CONTRIBUTING.md,docs/**,.github/pull_request_template.md}: Review docs for accuracy against current code behavior. Flag security or provider claims that overpromise, stale install commands, missing setup caveats, and instructions that could push users toward unsafe credential handling. Keep purely wording-level suggestions non-blocking.

Files:

  • README.md
  • docs/smart-routing.md
src/**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

src/**/*.{ts,tsx}: Use TypeScript with strict mode
Use ESM imports in TypeScript source files

Files:

  • src/commands.ts
  • src/commands/login/login.tsx
  • src/cost-tracker.ts
  • src/commands/smartroute/index.test.ts
  • src/commands/smartroute/index.ts
{src/**/*.test.ts,src/**/*.test.tsx,tests/**,scripts/**/*.test.ts,vscode-extension/**/*.test.js}

⚙️ CodeRabbit configuration file

{src/**/*.test.ts,src/**/*.test.tsx,tests/**,scripts/**/*.test.ts,vscode-extension/**/*.test.js}: Review tests for meaningful coverage of the changed behavior, isolation of global/env/config state, async cleanup, fake timers, provider profile leaks, and Windows-compatible assumptions. Block when risky runtime changes lack focused regression coverage or tests assert implementation details while missing the user-visible behavior.

Files:

  • src/commands/smartroute/index.test.ts
🔇 Additional comments (7)
src/cost-tracker.ts (1)

12-13: LGTM!

Also applies to: 88-90, 294-299

src/commands/login/login.tsx (1)

4-6: LGTM!

src/commands/smartroute/index.ts (1)

46-51: LGTM!

Also applies to: 79-82, 90-93, 95-102

src/commands/smartroute/index.test.ts (1)

1-121: LGTM!

src/commands.ts (1)

170-170: LGTM!

Also applies to: 282-282

docs/smart-routing.md (1)

1-58: LGTM!

README.md (1)

219-219: LGTM!

Comment thread src/commands/smartroute/index.ts Outdated
Comment thread src/commands/smartroute/index.ts Outdated
Comment thread src/commands/smartroute/index.ts

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
src/commands/smartroute/index.test.ts (1)

79-85: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Missing coverage: /smartroute on with env-only configured roles.

This test only covers the fully-unconfigured case. Given the status test at lines 68-77 proves readSmartRouting normalizes env-backed roles, add a case where OPENCLAUDE_SMART_ROUTING_SIMPLE/_STRONG are set via env (no smartRouting settings block) and assert /smartroute on succeeds — this would have caught the gate-check bug flagged in src/commands/smartroute/index.ts.

As per path instructions, "Review tests for meaningful coverage of the changed behavior... Block when risky runtime changes lack focused regression coverage."

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/commands/smartroute/index.test.ts` around lines 79 - 85, Add a regression
test in the smartroute command suite to cover /smartroute on when roles come
only from environment variables and there is no smartRouting settings block.
Reuse the existing test helpers in index.test.ts and the readSmartRouting
normalization behavior already verified by the status test to set
OPENCLAUDE_SMART_ROUTING_SIMPLE and OPENCLAUDE_SMART_ROUTING_STRONG, then assert
call('on', ctx) succeeds instead of returning the “Set both roles first”
rejection. This should exercise the gate in src/commands/smartroute/index.ts and
prove env-backed roles are accepted.

Source: Path instructions

src/commands/smartroute/index.ts (1)

47-90: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

/smartroute should use the normalized config, not raw settings.smartRouting
readSmartRouting() only falls back to OPENCLAUDE_SMART_ROUTING* when the settings block is absent, but this command still gates and persists from the raw block. That makes /smartroute on reject valid env-only configs, and /smartroute simple|strong can write a partial block that shadows the env defaults and disables routing. Use the normalized values here and persist the resolved role fields.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/commands/smartroute/index.ts` around lines 47 - 90, The /smartroute
command is using the raw settings.smartRouting block instead of the normalized
result from readSmartRouting(), which breaks env-only defaults and can shadow
them with partial writes. Update the logic in the SmartRouting command handler
to base validation and the enabled state on the normalized config returned by
readSmartRouting(settings), and make persist/updateSettingsForSource write the
resolved role fields rather than a partial smartRouting object. Ensure the
/smartroute on, simple, and strong paths all read from and persist the same
normalized SmartRoutingSettings shape.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Outside diff comments:
In `@src/commands/smartroute/index.test.ts`:
- Around line 79-85: Add a regression test in the smartroute command suite to
cover /smartroute on when roles come only from environment variables and there
is no smartRouting settings block. Reuse the existing test helpers in
index.test.ts and the readSmartRouting normalization behavior already verified
by the status test to set OPENCLAUDE_SMART_ROUTING_SIMPLE and
OPENCLAUDE_SMART_ROUTING_STRONG, then assert call('on', ctx) succeeds instead of
returning the “Set both roles first” rejection. This should exercise the gate in
src/commands/smartroute/index.ts and prove env-backed roles are accepted.

In `@src/commands/smartroute/index.ts`:
- Around line 47-90: The /smartroute command is using the raw
settings.smartRouting block instead of the normalized result from
readSmartRouting(), which breaks env-only defaults and can shadow them with
partial writes. Update the logic in the SmartRouting command handler to base
validation and the enabled state on the normalized config returned by
readSmartRouting(settings), and make persist/updateSettingsForSource write the
resolved role fields rather than a partial smartRouting object. Ensure the
/smartroute on, simple, and strong paths all read from and persist the same
normalized SmartRoutingSettings shape.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: dab1fdd4-f3a2-4473-b617-f4b275a44157

📥 Commits

Reviewing files that changed from the base of the PR and between 3b8fb27 and 2be79eb.

📒 Files selected for processing (4)
  • src/commands/smartroute/index.test.ts
  • src/commands/smartroute/index.ts
  • src/services/api/smartRouting/index.test.ts
  • src/services/api/smartRouting/index.ts
📜 Review details
⏰ Context from checks skipped due to timeout. (1)
  • GitHub Check: smoke-and-tests
🧰 Additional context used
📓 Path-based instructions (5)
src/**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

src/**/*.{ts,tsx}: Use TypeScript with strict mode
Use ESM imports in TypeScript source files

Files:

  • src/services/api/smartRouting/index.test.ts
  • src/commands/smartroute/index.ts
  • src/commands/smartroute/index.test.ts
  • src/services/api/smartRouting/index.ts
**

⚙️ CodeRabbit configuration file

**: # AGENTS.md - AI Agent Coding Guide

This guide is for AI coding agents working in the OpenClaude repository. Read it before changing code, and also follow CONTRIBUTING.md for contributor policy, PR expectations, review follow-up, and project scope.

Project Snapshot

OpenClaude is a coding-agent CLI for cloud and local model providers. It supports OpenAI-compatible APIs, Anthropic, Gemini, DeepSeek, Ollama, MCP, local backends, slash commands, tools, agents, and a React/Ink terminal UI.

The installed CLI runs on Node.js >=22.0.0. Bun is used for source builds, scripts, dependency management, and tests.

Work Style

  • Keep changes focused on one problem.
  • Prefer existing patterns in the file or nearby module.
  • Avoid unrelated formatting, renames, dependency changes, or broad rewrites.
  • Add or update tests when behavior changes.
  • Update docs when setup, commands, provider behavior, or user-facing behavior changes.
  • For new features, larger refactors, dependencies, or runtime changes, follow the issue-first guidance in CONTRIBUTING.md.

Stack And Conventions

  • TypeScript with strict mode and ESM imports.
  • React + Ink for terminal UI.
  • Bun lockfile and Bun scripts for development workflows.
  • Node runtime for the built CLI.

Common libraries and patterns:

  • chalk for terminal color.
  • commander for CLI argument parsing.
  • execa for child processes.
  • Existing service, provider, settings, permission, and UI patterns over new abstractions.

Repository Map

  • src/commands/ - slash and CLI command implementations.
  • src/components/ - React/Ink UI components.
  • src/services/ - API, MCP, OAuth, wiki, voice, and other service integrations.
  • src/tools/ - tool implementations.
  • src/utils/ - shared utilities.
  • src/integrations/ - provider and model integration metadata.
  • src/entrypoints/ - CLI, MCP, SDK, and generated public types.
  • src/tasks/ - local, remote, workflow, and monitor tas...

Files:

  • src/services/api/smartRouting/index.test.ts
  • src/commands/smartroute/index.ts
  • src/commands/smartroute/index.test.ts
  • src/services/api/smartRouting/index.ts
**/*

⚙️ CodeRabbit configuration file

**/*: Apply the OpenClaude maintainer review rubric from AGENTS.md. Review the current diff, not stale discussion context. Separate real blockers from suggestions. Do not request changes for vague style churn. Treat approval as merge-ready from CodeRabbit's side, pending required human review and GitHub Checks. If checks are failing or unavailable, say so clearly instead of implying the PR is fully ready.

Files:

  • src/services/api/smartRouting/index.test.ts
  • src/commands/smartroute/index.ts
  • src/commands/smartroute/index.test.ts
  • src/services/api/smartRouting/index.ts
{src/services/api/**,src/integrations/**,src/utils/model/**,src/utils/provider*.ts,src/commands/provider/**}

⚙️ CodeRabbit configuration file

{src/services/api/**,src/integrations/**,src/utils/model/**,src/utils/provider*.ts,src/commands/provider/**}: Review provider routing, model selection, env precedence, auth/token handling, OpenAI-compatible shims, retries, proxy behavior, and outbound HTTP behavior with high scrutiny. Block on silent default changes, hidden fallback expansion, credential reuse mistakes, hardcoded provider assumptions, or new network reach that is not intentional and documented.

Files:

  • src/services/api/smartRouting/index.test.ts
  • src/services/api/smartRouting/index.ts
{src/**/*.test.ts,src/**/*.test.tsx,tests/**,scripts/**/*.test.ts,vscode-extension/**/*.test.js}

⚙️ CodeRabbit configuration file

{src/**/*.test.ts,src/**/*.test.tsx,tests/**,scripts/**/*.test.ts,vscode-extension/**/*.test.js}: Review tests for meaningful coverage of the changed behavior, isolation of global/env/config state, async cleanup, fake timers, provider profile leaks, and Windows-compatible assumptions. Block when risky runtime changes lack focused regression coverage or tests assert implementation details while missing the user-visible behavior.

Files:

  • src/services/api/smartRouting/index.test.ts
  • src/commands/smartroute/index.test.ts
🔇 Additional comments (4)
src/services/api/smartRouting/index.ts (1)

7-7: LGTM!

Also applies to: 20-31, 217-225

src/services/api/smartRouting/index.test.ts (1)

8-8: LGTM!

Also applies to: 330-360

src/commands/smartroute/index.ts (1)

92-96: LGTM!

src/commands/smartroute/index.test.ts (1)

1-60: LGTM!

Also applies to: 86-154

coderabbitai[bot]
coderabbitai Bot previously approved these changes Jul 7, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 (1)
src/commands/smartroute/index.ts (1)

92-96: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Minor: persist + formatPersistError pattern repeated 3x.

on, off, and simple/strong each repeat const error = persist(next); if (error) return text(formatPersistError(error)). Not blocking, but a tiny helper would keep this from drifting if error handling changes later.

♻️ Optional consolidation
+  const persistOrError = (next: SmartRoutingSettings): { error: string } | { next: SmartRoutingSettings } => {
+    const error = persist(next)
+    return error ? { error: formatPersistError(error) } : { next }
+  }

Then in each branch: const r = persistOrError(next); if ('error' in r) return text(r.error).

Also applies to: 100-102, 115-117

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/commands/smartroute/index.ts` around lines 92 - 96, The
persist-and-format error handling is duplicated across the on, off, and
simple/strong branches in the smartroute command flow. Extract the repeated
`persist(next)` plus `formatPersistError` check into a small shared helper in
`index.ts` (for example, around the existing branch handlers) and have each
branch call that helper so future error handling changes stay consistent.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/services/api/smartRouting/index.test.ts`:
- Around line 119-122: The test for latestUserMessageHasNonTextContent is not
covering the meta/tool-result skip path because userMsg('plain') is the first
real match in the backward scan. Update the fixture in the smartRouting index
test so a non-text user message appears before the meta and tool-result carriers
in the array order, then assert true to verify the scan skips those carriers and
finds the earlier real message.

---

Outside diff comments:
In `@src/commands/smartroute/index.ts`:
- Around line 92-96: The persist-and-format error handling is duplicated across
the on, off, and simple/strong branches in the smartroute command flow. Extract
the repeated `persist(next)` plus `formatPersistError` check into a small shared
helper in `index.ts` (for example, around the existing branch handlers) and have
each branch call that helper so future error handling changes stay consistent.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 9a1701e3-70a6-4ab2-b7a6-025efe52fb95

📥 Commits

Reviewing files that changed from the base of the PR and between 2be79eb and d264c0b.

📒 Files selected for processing (6)
  • src/commands/smartroute/index.test.ts
  • src/commands/smartroute/index.ts
  • src/query.ts
  • src/services/api/smartModelRouting.ts
  • src/services/api/smartRouting/index.test.ts
  • src/services/api/smartRouting/index.ts
📜 Review details
⚠️ CI failures not shown inline (2)

GitHub Actions: PR Checks / smoke-and-tests: feat: smart auto-routing (per-turn simple-vs-strong model selection)

Conclusion: failure

View job details

st.ts:
 (pass) getSchemaValidationErrorOverride > returns actionable missing-skill error for SkillTool
 (pass) getSchemaValidationErrorOverride > does not override unrelated tool schema failures
 (pass) getSchemaValidationErrorOverride > does not override SkillTool when skill is present
 (pass) getSchemaValidationErrorOverride > uses the actionable override for structured toolUseResult too
 (pass) getReplayModifiedFiles > captures file-editing tool paths
 (pass) getReplayModifiedFiles > captures Bash simulated sed edit paths [1.00ms]
 (pass) replay tool lifecycle records > records permission denied completions
 (pass) replay tool lifecycle records > records success completions with modified files
 (pass) replay tool lifecycle records > records error completions
 (pass) replay tool lifecycle records > classifies abort-shaped tool failures as cancelled
 (pass) replay tool lifecycle records > captures the final executable input
 (pass) replay tool lifecycle records > normalizes denied file-tool replay inputs to match allowed retry inputs
 (pass) replay tool lifecycle records > records one error terminal status when post-call result processing fails [2.00ms]
 (pass) query lifecycle tool-use cleanup > successful tool execution leaves no active lifecycle tool use [1.00ms]
 (pass) query lifecycle tool-use cleanup > custom validation failure leaves no active lifecycle tool use
 (pass) query lifecycle tool-use cleanup > schema validation failure does not end a lifecycle entry that never started [1.00ms]
 (pass) query lifecycle tool-use cleanup > unknown tool does not end a lifecycle entry that never started [1.00ms]
 (pass) query lifecycle tool-use cleanup > permission denial leaves no active lifecycle tool use
 (pass) query lifecycle tool-use cleanup > already-aborted tool execution uses reason-aware result for query-timeout
 (pass) query lifecycle tool-use cleanup > already-aborted tool execution uses reason-aware result for hard_max
 (pass) query lifecycle tool-use cle...

GitHub Actions: PR Checks / 2_smoke-and-tests.txt: feat: smart auto-routing (per-turn simple-vs-strong model selection)

Conclusion: failure

View job details

oes not normalize incomplete streamed Bash commands when finish_reason is length [1.00ms]
 (pass) repairs truncated JSON objects even without command field [2.00ms]
 (pass) preserves raw input for unknown plain string tool arguments [1.00ms]
 (pass) preserves parsed string input for unknown JSON string tool arguments [1.00ms]
 (pass) sanitizes malformed MCP tool schemas before sending them to OpenAI [2.00ms]
 (pass) optional tool properties are not added to required[] — fixes Groq/Azure 400 tool_use_failed [1.00ms]
 (pass) coalesces consecutive user messages to avoid alternation errors (issue `#202`) [1.00ms]
 (pass) coalesces consecutive assistant messages preserving tool_calls (issue `#202`) [2.00ms]
 (pass) non-streaming: reasoning_content emitted as thinking block only when content is null [1.00ms]
 (pass) non-streaming: empty string content does not fall through to reasoning_content as text [1.00ms]
 (pass) non-streaming: real content takes precedence over reasoning_content [1.00ms]
 (pass) non-streaming: preserves response body when usage parsing fails [2.00ms]
 (pass) non-streaming: preserves response.url routing metadata after body read [1.00ms]
 (pass) non-streaming: strips <think> tag block from assistant content [1.00ms]
 (pass) streaming: thinking block closed before tool call [1.00ms]
 (pass) streaming: strips <think> tag block from assistant content deltas [2.00ms]
 (pass) streaming: strips <think> tag split across multiple content chunks [1.00ms]
 (pass) streaming: preserves prose without tags (no phrase-based false positive) [1.00ms]
 (pass) strips credentials and query params from URL in fetch network error message [2.00ms]
 (pass) classifies localhost transport failures with actionable category marker [2.00ms]
 (pass) transport failures are not labeled with HTTP status 503 [2.00ms]
 (pass) propagates AbortError without wrapping it as transport failure [1.00ms]
 (pass) classifies chat-completions endpoint 404 failures with endpoint_not_found marker [...
🧰 Additional context used
📓 Path-based instructions (5)
src/**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

src/**/*.{ts,tsx}: Use TypeScript with strict mode
Use ESM imports in TypeScript source files

Files:

  • src/services/api/smartModelRouting.ts
  • src/commands/smartroute/index.test.ts
  • src/services/api/smartRouting/index.test.ts
  • src/query.ts
  • src/commands/smartroute/index.ts
  • src/services/api/smartRouting/index.ts
**

⚙️ CodeRabbit configuration file

**: # AGENTS.md - AI Agent Coding Guide

This guide is for AI coding agents working in the OpenClaude repository. Read it before changing code, and also follow CONTRIBUTING.md for contributor policy, PR expectations, review follow-up, and project scope.

Project Snapshot

OpenClaude is a coding-agent CLI for cloud and local model providers. It supports OpenAI-compatible APIs, Anthropic, Gemini, DeepSeek, Ollama, MCP, local backends, slash commands, tools, agents, and a React/Ink terminal UI.

The installed CLI runs on Node.js >=22.0.0. Bun is used for source builds, scripts, dependency management, and tests.

Work Style

  • Keep changes focused on one problem.
  • Prefer existing patterns in the file or nearby module.
  • Avoid unrelated formatting, renames, dependency changes, or broad rewrites.
  • Add or update tests when behavior changes.
  • Update docs when setup, commands, provider behavior, or user-facing behavior changes.
  • For new features, larger refactors, dependencies, or runtime changes, follow the issue-first guidance in CONTRIBUTING.md.

Stack And Conventions

  • TypeScript with strict mode and ESM imports.
  • React + Ink for terminal UI.
  • Bun lockfile and Bun scripts for development workflows.
  • Node runtime for the built CLI.

Common libraries and patterns:

  • chalk for terminal color.
  • commander for CLI argument parsing.
  • execa for child processes.
  • Existing service, provider, settings, permission, and UI patterns over new abstractions.

Repository Map

  • src/commands/ - slash and CLI command implementations.
  • src/components/ - React/Ink UI components.
  • src/services/ - API, MCP, OAuth, wiki, voice, and other service integrations.
  • src/tools/ - tool implementations.
  • src/utils/ - shared utilities.
  • src/integrations/ - provider and model integration metadata.
  • src/entrypoints/ - CLI, MCP, SDK, and generated public types.
  • src/tasks/ - local, remote, workflow, and monitor tas...

Files:

  • src/services/api/smartModelRouting.ts
  • src/commands/smartroute/index.test.ts
  • src/services/api/smartRouting/index.test.ts
  • src/query.ts
  • src/commands/smartroute/index.ts
  • src/services/api/smartRouting/index.ts
**/*

⚙️ CodeRabbit configuration file

**/*: Apply the OpenClaude maintainer review rubric from AGENTS.md. Review the current diff, not stale discussion context. Separate real blockers from suggestions. Do not request changes for vague style churn. Treat approval as merge-ready from CodeRabbit's side, pending required human review and GitHub Checks. If checks are failing or unavailable, say so clearly instead of implying the PR is fully ready.

Files:

  • src/services/api/smartModelRouting.ts
  • src/commands/smartroute/index.test.ts
  • src/services/api/smartRouting/index.test.ts
  • src/query.ts
  • src/commands/smartroute/index.ts
  • src/services/api/smartRouting/index.ts
{src/services/api/**,src/integrations/**,src/utils/model/**,src/utils/provider*.ts,src/commands/provider/**}

⚙️ CodeRabbit configuration file

{src/services/api/**,src/integrations/**,src/utils/model/**,src/utils/provider*.ts,src/commands/provider/**}: Review provider routing, model selection, env precedence, auth/token handling, OpenAI-compatible shims, retries, proxy behavior, and outbound HTTP behavior with high scrutiny. Block on silent default changes, hidden fallback expansion, credential reuse mistakes, hardcoded provider assumptions, or new network reach that is not intentional and documented.

Files:

  • src/services/api/smartModelRouting.ts
  • src/services/api/smartRouting/index.test.ts
  • src/services/api/smartRouting/index.ts
{src/**/*.test.ts,src/**/*.test.tsx,tests/**,scripts/**/*.test.ts,vscode-extension/**/*.test.js}

⚙️ CodeRabbit configuration file

{src/**/*.test.ts,src/**/*.test.tsx,tests/**,scripts/**/*.test.ts,vscode-extension/**/*.test.js}: Review tests for meaningful coverage of the changed behavior, isolation of global/env/config state, async cleanup, fake timers, provider profile leaks, and Windows-compatible assumptions. Block when risky runtime changes lack focused regression coverage or tests assert implementation details while missing the user-visible behavior.

Files:

  • src/commands/smartroute/index.test.ts
  • src/services/api/smartRouting/index.test.ts
🔇 Additional comments (13)
src/services/api/smartRouting/index.ts (4)

104-136: LGTM!


275-286: LGTM!


65-87: 🩺 Stability & Availability

No eviction bug here. markSessionDisabled() clears the entire set once it reaches MAX_DISABLED_SESSIONS, so the map is capped and won't grow unbounded. The tradeoff is coarse rotation: all tracked session disables are dropped at once.

			> Likely an incorrect or invalid review comment.

138-153: 🩺 Stability & Availability

No change needed: unclassified routed errors are intentionally retryable. src/query.ts uses this only for the simple→strong smart-routing fallback, and the tests already cover 5xx, network, and undefined-status errors as retryable.

			> Likely an incorrect or invalid review comment.
src/services/api/smartRouting/index.test.ts (1)

108-118: LGTM!

Also applies to: 170-178

src/commands/smartroute/index.ts (1)

45-121: LGTM! Persist-then-check-error ordering and env-backed status/current resolution correctly address the prior review findings.

src/commands/smartroute/index.test.ts (1)

86-101: LGTM!

Also applies to: 126-135

src/query.ts (5)

138-151: LGTM!


1017-1017: 🎯 Functional Correctness

No type gap here. messagesForQuery is already compatible with readonly TurnCountMessage[], so this call is fine as-is.

			> Likely an incorrect or invalid review comment.

1568-1574: 🩺 Stability & Availability

No provider-id refresh needed here. pinnedRouteProviderId is the anchor for the provider the route was first pinned against; keeping it unchanged lets shouldDropPinForProviderSwap still drop the pin only if the active provider changes later.

			> Likely an incorrect or invalid review comment.

1598-1600: 📐 Maintainability & Code Quality

Need the inferred type here

Need the inferred type of messagesForQuery from getMessagesAfterCompactBoundary(...) before deciding whether this double cast is hiding a real mismatch or is just redundant.


1550-1606: 🩺 Stability & Availability

Drop this concern — isRetryableRoutedModelError already excludes 400/401/403, so the routed fallback won’t retry auth/permission/bad-request failures.

			> Likely an incorrect or invalid review comment.
src/services/api/smartModelRouting.ts (1)

38-56: LGTM!

Also applies to: 151-158

Comment thread src/services/api/smartRouting/index.test.ts
@jatmn
jatmn marked this pull request as ready for review July 7, 2026 02:26

@jatmn jatmn left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@kevincodex1 kevincodex1 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@kevincodex1
kevincodex1 merged commit e2bbb02 into Twigpine:main Jul 7, 2026
4 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants