Skip to content

agent: auto-router + cheap-fallback onboarding (UltraCode-Shim shape) - #203

Merged
FMXExpress merged 2 commits into
mainfrom
claude/auto-router
Jun 9, 2026
Merged

FMXExpress merged 2 commits into
mainfrom
claude/auto-router

Conversation

@FMXExpress

Copy link
Copy Markdown
Owner

Heuristic task-difficulty classifier that routes "easy" turns to a cheap-tier fallback provider while keeping the primary for real work. Sits on top of the existing ResolveFallbacks machinery — turns it from "retry on error" into "route by complexity". Opt-in via two coupled onboarding prompts; default off.

How routing decides

PasClaw.Agent.AutoRouter.ClassifyTask looks at three cheap signals on every user message:

  1. Hard keyword markers — implement, refactor, debug, fix bug, write tests, optimize, migrate, architect, port to, review, pr feedback. Any match → hard outright, no further inspection. Real work doesn't care how concise the request is.

  2. Token-count threshold (auto_router.easy_max_tokens, default 500) — a long message is real work regardless of phrasing. Above the threshold → hard.

  3. Tool-mix gate — when the loop's allowlist contains write/run tools (shell_exec, execute_code, fs_write, fs_edit_hashline) and the message has no easy marker, ambiguous one-word turns (yes, continue, ok) abstain. They might mean "now go run the script you just proposed" — we don't know, so we stay on the primary.

Only when all three signals agree on easy AND auto_router.enabled is True AND auto_router.easy_provider resolves against Cfg.Providers does RouteProvider return True. Otherwise the caller keeps the primary. False-easy (cheap provider fumbles real work) costs more than false-hard (we paid the primary's price for a summarise call), so the bias is conservative.

Wiring in the agent loop

Cmd.Agent.RunInteractive per-turn:

  1. Classify the latest user message.
  2. On routed turns, lazy-build the easy provider (cached for the rest of the session).
  3. Swap LoopCfg.Provider to the easy one.
  4. Prepend the original primary to LoopCfg.Fallbacks so a fumbled easy turn falls back to the provider the operator would have used anyway — zero manual recovery on a misclassification.
  5. After RunToolLoop, the assistant header reads (routed -> <name>, auto-routed) so the operator can spot what just happened.

The original primary, the existing fallback chain, and the agent's session / prompt-cache machinery are otherwise untouched.

Config

{
  "auto_router": {
    "enabled":         true,
    "easy_provider":   "groq",
    "easy_model":      "llama-3.3-70b-versatile",   // optional; empty = use catalog default
    "easy_max_tokens": 500
  }
}

JSON round-trip emits the block only when at least one field departs from default, so fresh configs stay clean.

Onboarding

Two coupled prompts (the user's question on this: "should configuring the fallback be in onboarding?" — yes):

  1. "Set up a cheap fallback now [y/N]" — picks from the catalog (minus the primary), asks for a key if needed, adds to Cfg.Providers AND to Cfg.Fallbacks. Useful in isolation: even without the router, the operator now has a retry-on-error chain instead of a single point of failure.
  2. "Auto-route simple tasks (summarise / list / explain) to this fallback [y/N]" — sets auto_router.enabled = true and auto_router.easy_provider. Skipping leaves the fallback intact but routing off.

Was a real gap before this PR: Cfg.Fallbacks could only be set by editing config.json or running the obscure pasclaw auth fallback <a> <b> command. Most operators never discovered either.

Tests

auto_router_tests.pas (9 cases):

  • TestHardKeywordsBeatEverything — refactor and summarise → hard (order in the classifier matters)
  • TestTokenCountThreshold — 2500-char message → hard under default; abstain under raised threshold
  • TestEasyKeywordsRouteEasy — summarize / what is / list / translate / explain route easy with read-only tools
  • TestWriteRunToolsBlockEasyOnAmbiguousIntent — yes / continue / ok abstain when shell_exec / execute_code are in the registry
  • TestWriteToolsAllowEasyWithEasyMarker — easy marker beats the tool-mix gate (summarize what shell_exec returned)
  • TestRouteProviderRespectsDisabledFlag — flag off → False
  • TestRouteProviderRefusesUnconfiguredEasyProvider — typo / catalog drift → False (no crash mid-turn)
  • TestRouteProviderHappyPath — Provider + EasyModel threaded through
  • TestRouteProviderEmptyModelOverride — empty EasyModel returns empty Model so the caller falls through to the catalog default

All 17 test programs pass on clean FPC 3.2.2 build. .dproj updated for the Delphi build.

Inspired by UltraCode-Shim — same shape (cheap-tier router on top of a candidate pool) but the operator names the pool (existing Cfg.Fallbacks) instead of the router inferring pricing tiers from a catalog.


Generated by Claude Code

Heuristic task-difficulty classifier that routes "easy" turns to a
cheap-tier fallback provider while keeping the primary for real
work. Opt-in. Default off.

Pieces:

- PasClaw.Agent.AutoRouter: ClassifyTask + RouteProvider. Three
  signals, all cheap: hard-keyword markers (implement / refactor
  / debug / fix bug / write tests / optimize / migrate / ...) win
  outright; token-count threshold catches sneaky-long messages;
  tool-mix gate makes ambiguous one-word messages (yes / continue
  / ok) abstain when write/run tools are in the registry.
  Three-way result (tdEasy / tdAbstain / tdHard) -- only tdEasy
  triggers routing. False-easy is more expensive than false-hard,
  so the bias is to abstain on anything ambiguous.

- TAutoRouterConfig in PasClaw.Config: Enabled / EasyProvider /
  EasyModel / EasyMaxTokens. JSON round-trip emits only when at
  least one field departs from default, so fresh configs stay
  clean.

- Cmd.Agent.RunInteractive wires the router per-turn: classify
  the latest user message, swap LoopCfg.Provider to a lazy-built
  easy provider when routing fires, and PREPEND the original
  primary to LoopCfg.Fallbacks so a fumbled easy turn falls back
  to the provider the operator would have used anyway -- zero
  manual recovery on a misclassification. Routed turns print
  (routed -> <name>, auto-routed) so the operator can spot what
  happened.

- Onboarding (PromptAutoRouter): two-question flow. First asks
  whether to add a cheap fallback at all (writes Cfg.Fallbacks,
  useful even without routing for retry-on-error coverage).
  Second asks whether to auto-route easy turns to it (writes
  auto_router.enabled + easy_provider). Skipping either keeps
  the other half useful in isolation.

Tests (auto_router_tests, 9 cases):
- Hard keywords beat easy keywords (order matters in the
  classifier).
- Token-count threshold catches long messages even with no
  hard markers; raised threshold flips the decision.
- Easy markers route easy only when tool mix agrees -- write/
  run tools tip ambiguous messages to abstain.
- Easy marker beats tool-mix gate when present ("summarize
  what shell_exec returned" is still easy).
- RouteProvider returns False when the flag is off.
- RouteProvider returns False when EasyProvider doesn't
  resolve against Cfg.Providers (operator typo / catalog
  drift); never crashes mid-turn for a config mistake.
- Happy-path threading of EasyModel into the result.
- Empty EasyModel returns empty Model so the caller falls
  through to the catalog default.

Inspired by UltraCode-Shim. Sits on top of the existing
ResolveFallbacks machinery; turns it from "retry on error" into
"route by complexity".

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 5b3b2b9f82

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/cmd/PasClaw.Cmd.Agent.pas Outdated
RoutedThisTurn := False;
if (not Offline) and (PrimaryProvider <> nil) then
if RouteProvider(Cfg, Line,
Reg.Names,

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Guard Reg before calling Names

When interactive mode is started with --no-tools, Reg is intentionally left nil, but this new router call evaluates Reg.Names before RouteProvider can decide to return false. That makes every non-offline interactive turn crash with an access violation in the documented pasclaw agent --no-tools mode, even when auto_router.enabled is false; pass an empty tool-name array when Reg = nil instead.

Useful? React with 👍 / 👎.

Comment thread src/cmd/PasClaw.Cmd.Agent.pas Outdated
Comment on lines +736 to +737
if RoutedModelOverride <> '' then
LoopCfg.Model := RoutedModelOverride;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Use the easy provider's model when no override is set

If auto_router.easy_model is omitted as the config comment allows, this branch leaves LoopCfg.Model set to the primary provider's model from BuildLoopConfig; RunToolLoop passes Cfg.Model directly to Cfg.Provider.Chat, so a routed Groq/OpenAI-compatible call can be sent claude-* (or another primary-only model) and fail instead of using the easy provider's configured/catalog default. Set the model to the easy provider's default when the override is empty.

Useful? React with 👍 / 👎.

Comment thread src/cmd/PasClaw.Cmd.Onboard.pas Outdated
Comment on lines +506 to +508
if Spec.Auth.Kind <> asNone then
Key := Trim(ReadLineEcho(' ' + Spec.DisplayName +
' API key (leave blank to keep existing): '));

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Read fallback API keys without echoing

For fallback providers that require auth, this prompt uses ReadLineEcho, so the API key is printed into terminal scrollback/screen recordings while onboarding. The primary provider path in this same command uses ReadSecretLine for the identical credential prompt; the fallback prompt should do the same before saving the key into Cfg.Providers.

Useful? React with 👍 / 👎.

Three issues from Codex's review of PR #203, all legit.

1. AV in --no-tools mode (PR #203 review, P2).
   Reg can be intentionally nil ("pasclaw agent --no-tools"); the
   router call evaluated Reg.Names unconditionally and crashed every
   non-offline turn in that mode, even with auto_router.enabled=False.
   Fix: pass a nil tool array when Reg is nil. The classifier already
   tolerates an empty list -- write/run tool-mix gate just doesn't
   fire, which is correct for --no-tools (there ARE no tools).
   Test: TestNilToolsArraySafe.

2. Easy provider sent the primary's model (PR #203 review, P2).
   When auto_router.easy_model was omitted, the caller left
   LoopCfg.Model set to the primary's value from BuildLoopConfig,
   so a routed turn shipped e.g. claude-opus-4-8 to Groq and 4xx'd.
   Fix: RouteProvider now resolves the model itself in three steps
   (explicit override -> per-provider stored Model -> catalog
   DefaultModel) and refuses to route if all three are empty
   rather than handing the loop something it'll fail on. Caller
   no longer needs the empty-string branch -- LoopCfg.Model is
   always set on routed turns.
   Tests: TestRouteProviderFallsBackToProviderStoredModel (step 2),
   TestRouteProviderResolvesCatalogDefault (step 3),
   TestRouteProviderRefusesWithoutResolvableModel (refusal).

3. Fallback API key was echoed (PR #203 review, P2).
   PromptAutoRouter used ReadLineEcho for the API-key prompt, so
   the pasted credential landed in terminal scrollback and screen
   recordings. The primary provider path in the same command uses
   ReadSecretLine for the identical prompt; the fallback prompt
   now does the same. (Same exposure pattern Codex flagged on
   PR #126 for MCP tokens.)
@FMXExpress
FMXExpress merged commit 5e8bc7d into main Jun 9, 2026
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.

2 participants