Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
17 commits
Select commit Hold shift + click to select a range
227e7fe
feat(smart-routing): add smartRouting settings schema and reader
beardthelion Jun 20, 2026
acc3779
feat(smart-routing): resolve role keys to a SmartRoutingConfig
beardthelion Jun 20, 2026
2cb6fa6
feat(smart-routing): wire per-user-turn routing into the query loop
beardthelion Jun 20, 2026
8d80d63
feat(smart-routing): add routed-error fallback to the strong model
beardthelion Jun 20, 2026
6a99d65
feat(smart-routing): add /smartroute command and env defaults
beardthelion Jun 20, 2026
3479bff
feat(smart-routing): show routing summary in /cost
beardthelion Jun 20, 2026
ff6b4a5
fix(smart-routing): re-pin to strong after a routed-error fallback
beardthelion Jun 20, 2026
c64dcda
fix(review): provider-swap guard, tally reset, notice-storm, env docs
beardthelion Jun 20, 2026
3eefe54
docs(smart-routing): document /smartroute, settings, and env vars
beardthelion Jun 20, 2026
e812a46
fix(review): clear tally on /login, extract+test swap predicate, cap …
beardthelion Jun 20, 2026
934d840
test(smart-routing): make allowlist tests robust to cross-file module…
beardthelion Jun 20, 2026
86d0741
fix(smart-routing): address CodeRabbit review and green CI
beardthelion Jun 20, 2026
afff773
fix(smart-routing): scope cost claims to first-party reference pricing
beardthelion Jun 21, 2026
3b8fb27
fix(smart-routing): clarify simple role wording
jatmn Jul 7, 2026
2be79eb
Fix smart routing review findings
jatmn Jul 7, 2026
d264c0b
fix(smart-routing): honor env roles and non-text turns
jatmn Jul 7, 2026
56377bf
test(smart-routing): cover non-text skip path
jatmn Jul 7, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -216,6 +216,7 @@ Beginner-friendly guides:
Advanced and source-build guides:

- [Advanced Setup](docs/advanced-setup.md)
- [Smart Auto-Routing](docs/smart-routing.md)
- [Android Install](ANDROID_INSTALL.md)

## Supported Providers
Expand Down
57 changes: 57 additions & 0 deletions docs/smart-routing.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
# Smart auto-routing

Smart routing is an opt-in mode that classifies each user turn as **simple** or **strong** and sends it to your configured **simple** or **strong** model accordingly, so trivial turns ("ok", "rename this", "what does this do?") can go to a cheaper model while the strong model handles everything non-trivial. Whether the simple role is actually cheaper depends on how your provider bills it. OpenClaude routes to the role you set and does not verify your provider's pricing.

It is **off by default** and **experimental** — the classifier is a fast heuristic (prompt length, code blocks, reasoning/planning keywords, first turn of a session), not a perfect judge. When in doubt it routes to the strong model, so the failure mode is "no savings on a turn that could have been cheap," never a silently degraded answer on a turn you cared about.

Smart routing is provider-agnostic: it swaps the model within your current provider. It works against any backend where you have both a cheaper and a stronger model configured. It does not read your provider's, gateway's, or account's pricing, so any savings or cost estimates it shows are based on a first-party reference table and may not match what you are actually billed.

## Setup

Both roles point at `agentModels` keys (or bare model ids). For example, in `~/.openclaude.json`:

```json
{
"agentModels": {
"mini": { "model": "gpt-5-mini" },
"main": { "model": "gpt-5" }
},
"smartRouting": {
"enabled": true,
"simpleModel": "mini",
"strongModel": "main"
}
}
```

Optional tuning fields: `simpleMaxChars` and `simpleMaxWords` raise or lower the size threshold for "simple".

## The `/smartroute` command

| Command | Effect |
| --- | --- |
| `/smartroute` | Show status (enabled/disabled, the two roles, available `agentModels` keys). |
| `/smartroute on` | Enable (requires both roles set). |
| `/smartroute off` | Disable. |
| `/smartroute simple <key>` | Set the simple-turn model to an `agentModels` key. |
| `/smartroute strong <key>` | Set the strong-turn model. |

When you set roles, the command warns if the simple model is not actually priced below the strong model (for models with known first-party pricing).

## Environment variables

These set a startup default. An explicit `smartRouting` block in settings always overrides them.

| Variable | Meaning |
| --- | --- |
| `OPENCLAUDE_SMART_ROUTING` | `1` or `true` enables routing at startup. |
| `OPENCLAUDE_SMART_ROUTING_SIMPLE` | `agentModels` key or model id for simple turns. |
| `OPENCLAUDE_SMART_ROUTING_STRONG` | `agentModels` key or model id for strong turns. |

## Behavior notes

- **One decision per turn.** The model is chosen once when your message arrives and held for the whole turn (including its tool calls), so it does not flap mid-turn.
- **Fallback.** If a simple-routed turn's model call errors (transport or server error), it retries once on the strong model. Aborts and auth/permission/bad-request errors are not retried.
- **Allowlist.** Any model smart routing selects is checked against your org model allowlist (`availableModels`). A disallowed model is coerced to strong; if strong is also disallowed, routing disables itself for the session and the default model is used. Running `/smartroute on` re-enables routing and clears that session disable.
- **Same-provider only.** Roles must be model-only `agentModels` entries (or bare model ids). If a role resolves to a cross-provider entry (one with `base_url`/`api_key`), routing silently disables — cross-provider routing is not supported yet.
- **Auditing.** `/cost` shows a routing summary: how many turns went simple vs strong, how many escalated to strong via fallback, and an estimated savings line when both models appear in the first-party reference pricing table. That estimate is reference pricing only and may not reflect what your provider/gateway/account actually bills.
2 changes: 2 additions & 0 deletions src/commands.ts
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,7 @@ import chrome from './commands/chrome/index.js'
import stickers from './commands/stickers/index.js'
import advisor from './commands/advisor.js'
import ads from './commands/ads.js'
import smartroute from './commands/smartroute/index.js'
import { logError } from './utils/log.js'
import { toError } from './utils/errors.js'
import { logForDebugging } from './utils/debug.js'
Expand Down Expand Up @@ -278,6 +279,7 @@ const COMMANDS = memoize((): Command[] => [
addDir,
advisor,
ads,
smartroute,
agents,
autoFix,
branch,
Expand Down
4 changes: 3 additions & 1 deletion src/commands/login/login.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import { feature } from 'bun:bundle'
import * as React from 'react'

import { resetCostState } from '../../bootstrap/state.js'
// Use the cost-tracker wrapper (not the raw bootstrap reset) so the routing
// tally is cleared alongside cost counters on an account switch.
import { resetCostState } from '../../cost-tracker.js'
import {
clearTrustedDeviceToken,
enrollTrustedDevice,
Expand Down
182 changes: 182 additions & 0 deletions src/commands/smartroute/index.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,182 @@
import { afterEach, beforeEach, describe, expect, spyOn, test } from 'bun:test'
import command from './index.js'
import * as settingsModule from '../../utils/settings/settings.js'
import type { SettingsJson } from '../../utils/settings/types.js'
import type { LocalCommandResult } from '../../types/command.js'

// The command always returns a `text` result; narrow the union so `.value` is
// accessible without an `as` cast (and assert that contract while we're here).
function expectText(res: LocalCommandResult): Extract<LocalCommandResult, { type: 'text' }> {
if (res.type !== 'text') throw new Error(`expected a text result, got ${res.type}`)
return res
}

// Two model-only agentModels keys with first-party-priced models so the
// cheaper-than warning can be exercised: haiku (cheap) vs opus (expensive).
const AGENT_MODELS = {
mini: { model: 'claude-haiku-4-5' },
main: { model: 'claude-opus-4-5' },
}
const SMART_ROUTING_ENV_KEYS = [
'OPENCLAUDE_SMART_ROUTING',
'OPENCLAUDE_SMART_ROUTING_SIMPLE',
'OPENCLAUDE_SMART_ROUTING_STRONG',
] as const

function makeContext(initial: Partial<SettingsJson> = {}) {
let state = {
settings: { agentModels: AGENT_MODELS, ...initial } as SettingsJson,
}
return {
getAppState: () => state as never,
setAppState: (updater: (s: typeof state) => typeof state) => {
state = updater(state)
},
_state: () => state,
} as unknown as Parameters<Awaited<ReturnType<typeof command.load>>['call']>[1] & {
_state: () => typeof state
}
}

describe('/smartroute command', () => {
let writeSpy: ReturnType<typeof spyOn>
let call: Awaited<ReturnType<typeof command.load>>['call']
let savedEnv: Record<(typeof SMART_ROUTING_ENV_KEYS)[number], string | undefined>

beforeEach(async () => {
savedEnv = Object.fromEntries(SMART_ROUTING_ENV_KEYS.map(key => [key, process.env[key]])) as typeof savedEnv
for (const key of SMART_ROUTING_ENV_KEYS) delete process.env[key]
writeSpy = spyOn(settingsModule, 'updateSettingsForSource').mockImplementation(() => ({ error: null }))
call = (await command.load()).call
})
afterEach(() => {
writeSpy.mockRestore()
for (const key of SMART_ROUTING_ENV_KEYS) {
const value = savedEnv[key]
if (value == null) delete process.env[key]
else process.env[key] = value
}
})

test('status with no config shows disabled and available keys', async () => {
const ctx = makeContext()
const res = expectText(await call('', ctx))
expect(res.value).toContain('status: disabled')
expect(res.value).toContain('mini, main')
})

test('status shows env-backed role values when settings have no smartRouting block', async () => {
process.env.OPENCLAUDE_SMART_ROUTING = '1'
process.env.OPENCLAUDE_SMART_ROUTING_SIMPLE = 'mini'
process.env.OPENCLAUDE_SMART_ROUTING_STRONG = 'main'
const ctx = makeContext()
const res = expectText(await call('', ctx))
expect(res.value).toContain('status: enabled')
expect(res.value).toContain('simple: mini')
expect(res.value).toContain('strong: main')
})

test('on without both roles set is rejected', async () => {
const ctx = makeContext({ smartRouting: { enabled: false, simpleModel: 'mini' } })
const res = expectText(await call('on', ctx))
expect(res.value).toContain('Set both roles first')
expect(writeSpy).not.toHaveBeenCalled()
})

test('on accepts env-backed roles and persists the normalized settings block', async () => {
process.env.OPENCLAUDE_SMART_ROUTING = '1'
process.env.OPENCLAUDE_SMART_ROUTING_SIMPLE = 'mini'
process.env.OPENCLAUDE_SMART_ROUTING_STRONG = 'main'
const ctx = makeContext()
const res = expectText(await call('on', ctx))
expect(res.value).toContain('Smart routing enabled')
expect(writeSpy).toHaveBeenCalledWith('userSettings', {
smartRouting: { enabled: true, simpleModel: 'mini', strongModel: 'main' },
})
expect(ctx._state().settings.smartRouting).toEqual({
enabled: true,
simpleModel: 'mini',
strongModel: 'main',
})
})

test('setting simple/strong to a valid key persists', async () => {
const ctx = makeContext()
await call('simple mini', ctx)
expect(writeSpy).toHaveBeenCalledWith('userSettings', { smartRouting: { simpleModel: 'mini' } })
expect((ctx as never as { _state: () => { settings: SettingsJson } })._state().settings.smartRouting).toEqual({
simpleModel: 'mini',
})
})

test('setting a role reports persistence errors without mutating app state', async () => {
writeSpy.mockImplementation(() => ({ error: new Error('settings are read-only') }))
const ctx = makeContext()
const res = expectText(await call('simple mini', ctx))
expect(res.value).toContain('Failed to update smart routing settings: settings are read-only')
expect(ctx._state().settings.smartRouting).toBeUndefined()
})

test('setting the strong role to a valid key persists', async () => {
const ctx = makeContext()
await call('strong main', ctx)
expect(writeSpy).toHaveBeenCalledWith('userSettings', { smartRouting: { strongModel: 'main' } })
})

test('setting one role preserves env-backed defaults instead of shadowing them with a partial block', async () => {
process.env.OPENCLAUDE_SMART_ROUTING = '1'
process.env.OPENCLAUDE_SMART_ROUTING_SIMPLE = 'mini'
process.env.OPENCLAUDE_SMART_ROUTING_STRONG = 'main'
const ctx = makeContext()
await call('simple main', ctx)
expect(writeSpy).toHaveBeenCalledWith('userSettings', {
smartRouting: { enabled: true, simpleModel: 'main', strongModel: 'main' },
})
})

test('simple/strong with no value argument is rejected', async () => {
const ctx = makeContext()
const res = expectText(await call('simple', ctx))
expect(res.value).toContain('Specify an agentModels key')
expect(writeSpy).not.toHaveBeenCalled()
})

test('setting a role to an unknown key is rejected with available keys', async () => {
const ctx = makeContext()
const res = expectText(await call('simple nope', ctx))
expect(res.value).toContain('not a configured agentModels key')
expect(res.value).toContain('mini, main')
expect(writeSpy).not.toHaveBeenCalled()
})

test('enabling with simple cheaper than strong gives no warning', async () => {
const ctx = makeContext({ smartRouting: { enabled: false, simpleModel: 'mini', strongModel: 'main' } })
const res = expectText(await call('on', ctx))
expect(res.value).toContain('Smart routing enabled')
expect(res.value).not.toContain('Heads up')
expect(writeSpy).toHaveBeenCalledWith('userSettings', {
smartRouting: { enabled: true, simpleModel: 'mini', strongModel: 'main' },
})
})

test('warns when the simple model is not cheaper than the strong model', async () => {
// Swap roles: simple=opus (expensive), strong=haiku (cheap).
const ctx = makeContext({ smartRouting: { enabled: false, simpleModel: 'main', strongModel: 'mini' } })
const res = expectText(await call('on', ctx))
expect(res.value).toContain('Heads up')
expect(res.value).toContain('not cheaper')
// The warning must be hedged as first-party reference pricing, since the
// active provider may bill these models differently (jatmn P2).
expect(res.value).toContain('first-party reference pricing')
expect(res.value).toContain('provider may bill differently')
})

test('off disables', async () => {
const ctx = makeContext({ smartRouting: { enabled: true, simpleModel: 'mini', strongModel: 'main' } })
const res = expectText(await call('off', ctx))
expect(res.value).toContain('disabled')
expect(writeSpy).toHaveBeenCalledWith('userSettings', {
smartRouting: { enabled: false, simpleModel: 'mini', strongModel: 'main' },
})
})
})
Loading