Repository navigation
agent: auto-router + cheap-fallback onboarding (UltraCode-Shim shape) - #203
Conversation
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".
There was a problem hiding this comment.
💡 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".
| RoutedThisTurn := False; | ||
| if (not Offline) and (PrimaryProvider <> nil) then | ||
| if RouteProvider(Cfg, Line, | ||
| Reg.Names, |
There was a problem hiding this comment.
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 👍 / 👎.
| if RoutedModelOverride <> '' then | ||
| LoopCfg.Model := RoutedModelOverride; |
There was a problem hiding this comment.
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 👍 / 👎.
| if Spec.Auth.Kind <> asNone then | ||
| Key := Trim(ReadLineEcho(' ' + Spec.DisplayName + | ||
| ' API key (leave blank to keep existing): ')); |
There was a problem hiding this comment.
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.)
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
ResolveFallbacksmachinery — 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.ClassifyTasklooks at three cheap signals on every user message: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.Token-count threshold (
auto_router.easy_max_tokens, default 500) — a long message is real work regardless of phrasing. Above the threshold → hard.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.enabledis True ANDauto_router.easy_providerresolves againstCfg.ProvidersdoesRouteProviderreturn 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.RunInteractiveper-turn:LoopCfg.Providerto the easy one.LoopCfg.Fallbacksso a fumbled easy turn falls back to the provider the operator would have used anyway — zero manual recovery on a misclassification.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):
Cfg.ProvidersAND toCfg.Fallbacks. Useful in isolation: even without the router, the operator now has a retry-on-error chain instead of a single point of failure.auto_router.enabled = trueandauto_router.easy_provider. Skipping leaves the fallback intact but routing off.Was a real gap before this PR:
Cfg.Fallbackscould only be set by editingconfig.jsonor running the obscurepasclaw 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 thresholdTestEasyKeywordsRouteEasy—summarize/what is/list/translate/explainroute easy with read-only toolsTestWriteRunToolsBlockEasyOnAmbiguousIntent—yes/continue/okabstain whenshell_exec/execute_codeare in the registryTestWriteToolsAllowEasyWithEasyMarker— easy marker beats the tool-mix gate (summarize what shell_exec returned)TestRouteProviderRespectsDisabledFlag— flag off → FalseTestRouteProviderRefusesUnconfiguredEasyProvider— typo / catalog drift → False (no crash mid-turn)TestRouteProviderHappyPath—Provider+EasyModelthreaded throughTestRouteProviderEmptyModelOverride— emptyEasyModelreturns empty Model so the caller falls through to the catalog defaultAll 17 test programs pass on clean FPC 3.2.2 build.
.dprojupdated 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