SLOPSHOPPER

Mixture of Models

Routes each prompt to the cheapest capable model. Simple and coding work runs in a headless child Claude Code on an Anthropic-compatible gateway (GLM 5.3, Kimi…

panebandspinnerrowscommandprompt
★ 1v0.9.0MITupdated 2026-10-11alinaqi/mixture-of-models-claude-mod
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · mixture-of-models
› fix the failing auth test and add an audit log call ⏺ Read(src/auth.ts) ⎿ Read 6 lines ⏺ Update(src/auth.ts) ⎿ Added 2 lines, removed 1 line ⏺ Bash(bun test) ⎿ 3 pass, 1 fail ● Done. refresh now rejects expired claims and logs an audit event. ✻ Worked for 42s · done 4:20 PM route: claude-opus-5-5 · critical 10/10 code via default · 97.4k in / 1.5k out · cache 93% · main session · today: claude-opus-5-5 ×1 › /route ⎿ mixture-of-models: mixture-of-models observe-only (no gateway key for the child) · mode auto · current route: claude-opus-5-5 · c mixture-of-models · observe-only: no gateway key for the child 1: auto 2: glm 3: kimi 4: claude 5: off ⟨Claude Code's own drawing⟩ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Band
mixture-of-models · observe-only: no gateway key for the child 1: auto 2: glm 3: kimi 4: claud ⟨Claude Code's own drawing⟩
README

mixture-of-models-claude-mod

ci License: MIT Changelog

Keep your Claude subscription for the turns that need it. Hand the rest to a cheaper model. A Claude Code mod (an in-process plugin, new in Claude Code 2.1.287) that scores every prompt for blast radius and answers the low-score turns with a separate headless Claude Code on an Anthropic-compatible gateway (GLM, Kimi, DeepSeek, whatever yours serves). Your main session is never renamed, re-pointed or touched. Ported from Maggy's routing.

To be precise about what it is: turn-level delegation, not per-request model mixing. A routed turn runs in a child process with a short brief of your recent context; the child's answer lands in your transcript, tagged. Critical turns stay on Claude exactly as before.

Install

Mods need Claude Code 2.1.287 or later. The stable Homebrew cask is still 2.1.286, so check first:

claude --version
# too old? one of:
brew uninstall --cask claude-code && brew install --cask claude-code@latest   # Homebrew
npm install -g @anthropic-ai/claude-code@latest                               # npm
claude update                                                                 # native installer

Then:

claude plugin marketplace add alinaqi/mixture-of-models-claude-mod
claude plugin install mixture-of-models@mixture-of-models-claude-mod

or, inside a session, /plugin install mixture-of-models --marketplace alinaqi/mixture-of-models-claude-mod.

Give the child a gateway (any Anthropic-compatible endpoint that serves your model ids; tested with palgu, and z.ai or Moonshot's Anthropic endpoints work the same way), see Setup. Start claude, run /route. Until a gateway is configured the mod is observe-only and changes nothing.

Design rule: the main session is never touched. It stays on your claude.ai subscription with no ANTHROPIC_BASE_URL. When a prompt is routed to GLM or Kimi, the mod answers that turn itself by running a separate, headless claude -p child whose environment alone points at the gateway (palgu). The child's output becomes the turn's answer in your transcript. Nothing about the main process, its model, its auth or its requests changes.

Per prompt the mod:

  1. Scores it on two axes with one classifier call: a 1-10 blast radius and a task kind (code | research | review | docs | data | multimodal). The score decides whether Claude is mandatory; the kind picks which cheaper model gets the rest. A local Ollama model does it for free, claude-haiku-4-5 on your plan is the fallback, then the last verdict seen. See How it decides.
  2. Applies Maggy's pre-routing rules first: use claude or execute the plan force critical; follow-ups after a child-answered turn return to the main session; go ahead, yes, or a prompt of six words or fewer while the main session is mid-task keeps it there; coding-level work stays on a mid-task main session.
  3. Delegates a routed turn to the child: claude -p --model glm-5.3 on the gateway, fed a brief over stdin with the last few exchanges of your session plus the task.
  4. Falls back to the main model for that turn if the child fails, prints nothing, or its answer fails vetting (see What a child may not do), and says so in the transcript.
  5. Shows you what ran where, on every turn. See What you see.

critical turns never start a child. They run in the main session, on the subscription, exactly as if the mod were not there.

How it decides

The classifier is asked one question: how much damage does a wrong answer do? It answers with a number, and the rubric is explicit:

| Score | Means | Tier (default thresholds) | | :- | :- | :- | | 1-2 | lookups, grep, shell one-liners, syntax questions, reading logs, git status or diff | simple | | 3-4 | single-file edits, tests, docs, config changes, small bug fixes, scaffolding | 3 simple, 4 coding | | 5-6 | multi-file features, wiring services or tools together, integrations, deployments that follow a known pattern | coding | | 7-8 | debugging across services, data migrations, performance work, changes that are awkward to undo | 7 coding, 8 critical | | 9-10 | security or auth design, architecture decisions, production incidents, anything irreversible | critical |

The prompt tells the classifier that length, the number of services named, or pasted API keys do not raise the score by themselves, which is what used to push ordinary integration work onto the main session. It also says that deep reasoning (algorithms with proofs, concurrency, performance tuning, cryptography) scores at least 7 whatever the blast radius, so hard-but-safe work stays on Claude. Move the cut-offs with router.thresholds; for example { "simple": 3, "coding": 8 } keeps everything but 9-10 off Claude.

The kind picks the model. Below critical, routes.kinds maps the task kind to a model: by default research and review go to Kimi for its long context, multimodal stays on Claude, and everything else takes the tier's model (GLM). Add "docs": "deepseek-v4-pro" or "data": "..." to the matrix as your gateway allows.

Borderline scores get a second opinion. A score on the coding cut-off or one above it is sampled a second time and the higher wins, so a 7-or-8 debugging task doesn't flip tiers on classifier noise.

It remembers failures. Every two child failures for a kind lower that kind's coding cut-off by one (never below simple + 1), so work the cheap model keeps failing at drifts back to Claude. /route reset clears the memory.

It protects the thread of work. A child has no memory beyond its brief, so the mod never lets a follow-up land on one. After a child-answered turn, continue, yes or any prompt of six words or fewer goes back to the main session, which holds the whole transcript. And while the main session is mid-task (its last answer used tools), coding-level work stays with it (via mid-task guard on the route line); only lookups and new, self-contained tasks go out. Without these rules a session that had routed a task would restart it on every "continue".

Some turns never leave the main session, whatever the score or /route pin, because a child cannot see the conversation, teammates, background tasks or the session's tools (via notification, via session command, via security or verdict on the route line):

  • notifications: <teammate-message …>, idle_notification JSON, <task-notification>, [SYSTEM NOTIFICATION …];
  • short operator commands about session state or tools (12 words or fewer): approve git pull --ff-only, continue, resume, merge it, check the sub agents, what's the status, anything naming a PR, branch, CI, workflow or sub-agent;
  • security and verdict turns (security, vulnerability, CVE, verdict, …).

What a child may not do

Every brief opens with a preamble: the child has no access to the main session, must never invent statuses, IDs, PR numbers, run results or file changes, must never ask you to approve or run anything, and replies HANDBACK when the task needs the session's state or tools. The mod then vets the answer and discards it, letting the main model do the turn itself, when it:

| Answer | Example | | :- | :- | | starts with HANDBACK | HANDBACK / needs the PR list | | says it is blocked or asks you to act | "blocked by the permission system", "you must approve it in the UI", "run gh pr create yourself" | | claims an action or session fact with no tool call (num_turns 1) | "I added X", "PR #812 is open", "14 commits behind", "no build runs exist" | | is mostly narration of intent | "I'll read the config. Then I will update the router." | | repeats an answer already given | the same verdict re-posted on every idle notification |

A discarded answer counts as a child failure for that kind and shows as child answer discarded (<reason>), main model answered on the route line. The main model is never asked to relay a child's text: the mod answers the turn with a vetted child answer, or leaves the turn to the main model.

Every route line and the band show the score and the kind, so when a decision looks wrong you can see the numbers behind it.

What you see

Claude and the gateway are both visible, all the time:

| Surface | Main-session turn | Routed turn | | :- | :- | :- | | Band above the prompt | mixture-of-models · auto · last: claude-opus-5 (critical via rule) 1: auto 2: glm 3: kimi 4: claude 5: off | … · running glm-5.3 in a child… while it runs | | Spinner | Thinking… | Thinking · via glm-5.3 (child)… | | Question dialog | Claude's own questions | Child on glm-5.3 wants to run: Bash(git pull --ff-only) with Allow and continue / Deny | | Reply in the transcript | unchanged (or tagged ⇢ claude-opus-5 · main session with ui.tags: "all") | a dim ⇢ glm-5.3 · child on gateway line above the reply, kept in scrollback | | Line under the answer | route: claude-opus-5 · critical 9/10 via claude-haiku-4-5 · 23.1k in / 0.9k out · cache 91% · main session · today: claude-opus-5 ×3, glm-5.3 ×5 | route: glm-5.3 · coding 6/10 via ollama · child 42s · today: … | | /route | mixture-of-models live · mode auto · current route: … · today: … | same | | /route stats | A pane, "Mixture of models", with four tabs on hotkeys 1-4: models (bars per model, share of turns, the headline "N of M turns off Claude"), kinds (each kind and which models took it), scores (a 1-10 histogram coloured by tier, cut-offs marked), recent (the last decisions with score, kind, model and child time). Esc closes it. | same |

The band's buttons have digit hotkeys: with an empty prompt, type 3 and pause to pin Kimi, 1 to go back to auto. Turn the band off with "ui": { "band": false }.

Requirements

  • Claude Code v2.1.287 or later (claude --version). Mods do not load on older builds; claude update.
  • A gateway the child can use: palgu's Anthropic endpoint and a key, or any Anthropic-compatible endpoint that serves the model ids in routes.
  • Optional: Ollama with a small model for free classification (ollama pull qwen2.5-coder:3b). Without it the classifier falls back to Haiku on your plan.

Setup

See GETTING_STARTED.md for the full walkthrough, or ./install.sh.

  1. Give the child its gateway. The plugin asks for two values, and the key is masked and kept in Claude Code's secure storage, never in a settings file:
   /plugin configure mixture-of-models@mixture-of-models-claude-mod

or from the shell at install time: claude plugin install mixture-of-models@mixture-of-models-claude-mod --config gateway_url=https://api.palgu.ai/anthropic --config gateway_key=srt_…, or afterwards: echo '{"gateway_url":"https://api.palgu.ai/anthropic","gateway_key":"srt_…"}' | claude plugin configure mixture-of-models@mixture-of-models-claude-mod --values-stdin

  1. Optionally tune routes, thresholds and the child in ~/.claude/model-config.json; config.example.json in the repo is a complete starting point (also shown below).
  1. Start claude and run /route.

Until a gateway URL and key are present the mod is observe-only: it classifies and /route shows what it would do, but no child starts.

What this plugin runs, reads, sends and stores

The directory's security scan compares this section with the code. Everything the mod does outside its own code is listed here. In one breath:

  • It fetches http://localhost:11434/api/chat with $.http.fetch, sending the prompt text and the scoring rubric to a local Ollama, to score the prompt. No credentials, nothing leaves the machine.
  • It calls $.model.classify, which sends the same prompt text and rubric to Anthropic through Claude Code's own API client on your own account, when Ollama does not answer.
  • It runs one program, claude (Claude Code itself, headless), with $.process.run, for routed turns only, with the environment variables ANTHROPIC_BASE_URL and ANTHROPIC_API_KEY set to the gateway values you configured. That child sends your prompt and a short brief of recent session text to that gateway.
  • It reads ~/.claude/model-config.json, HOME and MAGGY_ROUTER_CHILD, and stores the route pin, per-day counts, the last verdict, per-kind failure counts and a log of the last 200 decisions (day, model, kind, tier, score, classifier source, child time and exit code; never prompt text) in the plugin store.

Full detail follows; a privacy policy is at PRIVACY.md.

Hooks

The hooks module hooks/register.js registers nine hooks. What each one does with the events and calls it sees:

| Hook | What it does | | :- | :- | | session.start | Reads ~/.claude/model-config.json, takes the gateway URL and key from the plugin's options, remembers the session's model, loads the /route pin from the plugin store, and registers the /route command. Does nothing when MAGGY_ROUTER_CHILD is set, so the mod stays inactive inside its own child. | | prompt.submit | Passes every prompt through unchanged. On the side it decides the route: pre-rules first, then a 1-10 blast score from the classifier (see Network), then the thresholds. Never drops, rewrites or adds to a prompt. Fails open: if scoring throws, the prompt still goes through. | | turn.start | Clears the previous turn's child result. | | turn.step | For a routed turn, instead of letting the main session call its model, runs the child process described under Programs and yields the child's text as the turn's answer with stopReason: end_turn. If the child's permission system refused a command, the hook asks you with $.ui.ask (the dialog Claude uses for questions), naming the exact commands; on "Allow and continue" it resumes the same child with those commands allowed, up to relayRounds times; on "Deny", or when nobody can answer, the child's own explanation is the answer. For every other turn, and for subagents, it calls next(e) unchanged. If the child fails or prints nothing it calls next(e), so the main model answers. | | turn.complete | Appends a line under the answer with the route, score, cost and where it ran, and updates per-day counts in the plugin store. | | ui.render for AbovePrompt | Draws the band: the current mode and last decision, plus buttons that change the /route pin. Keeps whatever other mods draw there. | | ui.render for AssistantMessage | Puts a dim provenance line above a reply the child produced. Other replies are passed through. | | ui.render for Spinner | Adds via <model> (child)… after the spinner's word during a routed turn. | | ui.render for Pane | Draws the "Mixture of models" stats pane (id routing-stats) from the decision log when /route stats opened it. Other panes are passed through. | | command.run for /route | Shows the route state or sets the pin (auto, off, a tier, or a model). |

The mod never handles tool.call or tool.check, so it never approves, denies or changes a tool call, and it never changes permission prompts.

Network: the hosts this plugin contacts

The mod itself makes exactly one kind of network call, and the child process it starts makes another:

| Who | Call | Address | What is sent | Why | | :- | :- | :- | :- | :- | | The mod, in prompt.submit | $.http.fetch | http://localhost:11434/api/chat, fixed in the code | The scoring rubric and the prompt text, as an Ollama chat request, no credentials | Free local classification. Skipped when nothing answers there. | | The mod, in prompt.submit | $.model.classify | Anthropic's API through Claude Code's own client and your own plan | The scoring rubric and the prompt text | Classification when Ollama is unavailable. Model: the classifier alias, claude-haiku-4-5 by default. | | The child process (Claude Code itself), started in turn.step | Claude Code's normal API client | The gateway_url you set in the plugin's options (for example https://api.palgu.ai/anthropic), with gateway_key as its API key | Your prompt plus a brief of the last contextMessages exchanges of the session (text only, truncated), then whatever the child's own agent loop sends while it works | That is the point of the plugin: the turn runs on the gateway's model instead of the main session's. |

The mod contacts no other host. The gateway is whatever you configure; nothing is sent to a fixed third party.

Programs this plugin runs

Which programs: exactly one, claude, which is Claude Code itself in headless mode. The plugin runs no shell, no script bundled in the plugin folder, no package launcher, and no other executable.

Why: a mod can rename the model on a request but cannot change the endpoint or credentials of the session it runs in. The only way to run a turn on a different endpoint with Claude Code's own tools, while leaving the main session's endpoint and credentials untouched, is a second Claude Code process whose environment points at the gateway. The child exists for that reason alone, and only for turns the score routes away from the main session.

How: one $.process.run call, in turn.step. The program name is the fixed text claude at the call. Its arguments:

claude -p --model <routed model id> --output-format json --max-turns <child.maxTurns> --add-dir <session cwd> --bare --permission-mode acceptEdits

and, only after you approve a relayed command (see below), the same program again with --resume <that child's session id> --allowedTools <the approved patterns> appended, so the same child continues. --bare keeps your hooks, plugins and keychain out of the child. child.args replaces the last three flags if you set it. The child's environment adds ANTHROPIC_BASE_URL and ANTHROPIC_API_KEY (the gateway values) and MAGGY_ROUTER_CHILD=1. The brief is written to its stdin. It runs in the session's working directory with Claude Code's tools under that permission mode, so it can read and edit files there and run commands the mode allows; those commands are the child's own agent decisions, governed by Claude Code's permission system, not commands this plugin issues. It is killed at child.timeoutMs.

Files and environment it reads

  • ~/.claude/model-config.json, through $.fs.read, for routes, thresholds, the classifier alias and child settings. It holds no credentials. Missing or invalid, the defaults apply.
  • The environment variables HOME and MAGGY_ROUTER_CHILD, through $.env.get.
  • Nothing else. The gateway key is never read from a file or from the environment; it comes only from the plugin's gateway_key option, which Claude Code keeps in secure storage.

What it stores

In the plugin's own store ($.store, under ~/.claude/plugins/store/): the /route pin, per-day counts per model, the last verdict, per-kind failure counts, and a log of the last 200 decisions (day, model, kind, tier, score, classifier source, child duration and exit code). No prompt text, no answers, no credentials.

What it never does

It never writes to settings files or to model-config.json, never changes the main session's model, endpoint or credentials, never handles tool calls, and never sends data anywhere other than the two classifier destinations above and the gateway you configured.

Configuration

The mod reads Maggy's single source of truth, ~/.claude/model-config.json, and adds an optional router block. It never writes to that file.

{
  "primary": "glm",
  "router": {
    "routes":     { "simple": "glm-5.3", "coding": "glm-5.3", "critical": "claude",
                    "kinds": { "research": "kimi-k3", "review": "kimi-k3", "multimodal": "claude" } },
    "thresholds": { "simple": 3, "coding": 7 },
    "ollama":     { "model": "qwen2.5-coder:3b" },
    "classifier": "claude-haiku-4-5",
    "child": {
      "baseUrl":  "https://api.palgu.ai/anthropic",
      "args":     ["--bare", "--permission-mode", "acceptEdits"],
      "maxTurns": 25,
      "timeoutMs": 600000,
      "contextMessages": 12,
      "relayRounds": 2
    },
    "ui":      { "band": true, "tags": "routed" },
    "summary": true
  }
}
  • routes: tier → model id the gateway serves, plus routes.kinds: kind → model for the non-critical tiers. "claude" means the main session.
  • primary (Maggy's followed model, set with /model-config): glm, kimi or deepseek makes the coding tier follow it unless routes.coding is set. primary: claude changes nothing: critical is already on Claude, and coding stays cheap unless you set routes.coding to "claude".
  • thresholds: the blast-score cut-offs, { "simple": 3, "coding": 7 } by default.
  • classifier: the Claude model used when Ollama is unreachable. Undated aliases only (claude-haiku-4-5, claude-sonnet-5, claude-opus-5).
  • child.baseUrl: fallback for the gateway URL when the plugin's gateway_url option is unset. The key has no fallback; it comes only from the gateway_key option.
  • child.args: extra flags. The default is --bare (no inherited hooks or plugins, API-key auth only, so the child can never fall back to your subscription) plus acceptEdits so it can edit files without prompting. The mod always adds --add-dir <cwd>, which keeps the project's CLAUDE.md in reach under --bare. Add --dangerously-skip-permissions only if you want the child to run commands unattended; drop --bare if you want your hooks and plugins inside the child.
  • child.maxTurns, timeoutMs: the child's agentic budget. timeoutMs caps at ten minutes, the limit of $.process.run.
  • child.contextMessages: how many recent exchanges go into the brief.
  • child.relayRounds: how many times one routed turn may pause to ask you about commands the child was refused (default 2).
  • ui.band: draw the band above the prompt (default true). ui.tags: which replies get the provenance tag, routed (default), all or off.

Commands

| Command | Effect | | :- | :- | | /route | Live or observe-only, mode, current decision, today's counts | | /route auto | Classify every prompt (default) | | /route off | Never start a child | | /route simple\|coding\|critical | Pin a tier | | /route reset | Clear the per-kind failure memory | | /route stats | Open the stats pane: models, kinds, scores, recent | | /route glm, /route kimi, /route kimi-k3, /route claude | Pin a model (a prefix expands to the configured model) |

Pins persist across sessions in the plugin's store.

What the child can and cannot do

  • It has Claude Code's tools and runs in the session's working directory, so it can read, edit and run things. Its tool calls are not shown in the main transcript, only its final text.
  • When it needs a command its permission mode doesn't allow (git pull, npm install, a deploy), it cannot ask you itself. The mod relays the request: you get Claude Code's question dialog naming the exact command, and "Allow and continue" resumes the same child with only that command allowed. Read-only commands such as git status or git log already run without asking.
  • It does not share the main session's memory. The brief carries the last contextMessages exchanges (12 by default, each truncated to 1,200 characters) and the task. This is why follow-ups never go to a child: see How it decides.
  • It runs --bare by default, so your hooks and plugins stay out of
Source 9 files
hooks/register.js 207 lines
1// mixture-of-models: Maggy's routing as a Claude Code mod. Score each prompt; answer a routed
2// turn with a headless `claude -p` child on the gateway; the main session never leaves its model.
3import { parseConfig } from './lib/config.js'
4import { VERDICTS, classifierPrompt, labelFor, ollamaBody, ollamaReply, parseVerdict, preClassify, sessionTurn } from './lib/classify.js'
5import { adjustThresholds, bumpFailures, isBorderline, midTaskGuard, parseRouteArg, resolveModel, summaryLine } from './lib/routing.js'
6import { allowPatterns, buildBrief, childArgs, childEnv, childReady, gatewayFrom, parseChildOutput, relayText } from './lib/child.js'
7import { vetAnswer } from './lib/vet.js'
8import { appendLog, bumpStats, statsLine, summarize } from './lib/stats.js'
9import { paneTree } from './lib/stats-pane.js'
10import { bandTree, reportText, tagText, tagTree } from './lib/ui.js'
11
12let cfg = parseConfig(''), options = {}, disabled = false, ready = false, key = '', sessionModel = ''
13let pin = { mode: 'auto' }, decision = { label: 'critical', model: '', source: 'default' }, lastPrompt = '', tab = 'models', lastWasChild = false
14const answered = new Map()
15
16async function loadConfig($) {
17  const home = (await $.env.get('HOME')) || ''
18  cfg = parseConfig(await $.fs.read(home + '/.claude/model-config.json').catch(() => ''))
19  ;({ baseUrl: cfg.child.baseUrl, key } = gatewayFrom(options, cfg.child))
20  ready = childReady(cfg.child, key)
21  sessionModel = await $.session.model()
22  pin = (await $.store.get('pin')) || { mode: 'auto' }
23}
24
25// The only network call the mod makes itself: a local Ollama, fixed address, no credentials.
26function askOllama($, text) {
27  return $.http.fetch('http://localhost:11434/api/chat', { method: 'POST', headers: { 'content-type': 'application/json' }, body: ollamaBody(cfg.ollama.model, classifierPrompt(text)) })
28    .then((r) => (r.ok ? parseVerdict(ollamaReply(r.text)) : undefined)).catch(() => undefined)
29}
30
31function askClaude($, text) {
32  return $.model.classify(classifierPrompt(text), VERDICTS, { model: cfg.classifier }).then(parseVerdict).catch(() => undefined)
33}
34
35async function sample($, text) {
36  const local = await askOllama($, text)
37  if (local) return { ...local, source: 'ollama' }
38  const remote = await askClaude($, text)
39  return remote ? { ...remote, source: cfg.classifier } : undefined
40}
41
42// One sample, a second on the coding/critical edge (the higher wins), else the last verdict seen.
43async function classify($, text) {
44  const first = await sample($, text)
45  const cached = first ? null : await $.store.get('last-verdict')
46  if (!first) return cached ? { ...cached, source: 'cache' } : { score: 10, kind: 'code', source: 'default' }
47  if (!isBorderline(first.score, cfg.thresholds)) return first
48  const second = await sample($, text)
49  return second && second.score > first.score ? second : first
50}
51
52function setDecision(label, source, verdict) {
53  decision = { label, source, ...(verdict || {}) }
54  decision.model = resolveModel(decision, cfg.routes, sessionModel)
55}
56
57function applyPin() {
58  if (pin.mode === 'label') setDecision(pin.label, 'pin')
59  if (pin.mode === 'model') decision = { label: 'pinned', source: 'pin', model: pin.model === 'claude' ? sessionModel : pin.model }
60}
61
62// Notifications, operator commands and security turns stay on the main session, pinned or not.
63async function decide($, text) {
64  const stay = sessionTurn(text)
65  if (stay) return setDecision('main', stay)
66  if (pin.mode === 'model' || pin.mode === 'label') return applyPin()
67  const last = (await $.session.messages()).filter((m) => m.role === 'assistant').pop()
68  const ctx = { lastHadTools: Boolean(last && last.toolUses.length), lastWasChild }
69  const pre = preClassify(text, ctx)
70  if (pre.kind === 'label') return setDecision(pre.label, 'rule')
71  if (pre.kind === 'main') return setDecision('main', pre.reason)
72  if (pre.kind !== 'classify') return
73  const verdict = await classify($, text)
74  await $.store.set('last-verdict', { score: verdict.score, kind: verdict.kind })
75  const thresholds = adjustThresholds(cfg.thresholds, await $.store.get('failures'), verdict.kind)
76  const label = labelFor(verdict.score, thresholds)
77  setDecision(label, midTaskGuard(label, ctx) ? 'mid-task guard' : verdict.source, { score: verdict.score, kind: verdict.kind })
78  if (midTaskGuard(label, ctx)) decision.model = sessionModel
79}
80
81function shouldDelegate(e) {
82  if (disabled || !ready || pin.mode === 'off' || e.agentId || e.index > 0) return false
83  return Boolean(decision.model) && decision.model !== sessionModel
84}
85
86// The only program this mod runs: Claude Code itself, headless, on the routed model.
87async function spawnChild($, extra, stdin) {
88  const argv = ['claude', ...childArgs(cfg.child, decision.model, await $.session.cwd()), ...extra]
89  const r = await $.process.run(argv, { env: childEnv(cfg.child, key), stdin, timeoutMs: cfg.child.timeoutMs }).catch(() => ({ exitCode: 1, stdout: '' }))
90  return parseChildOutput(r.stdout, r.exitCode)
91}
92
93// A command the child was refused becomes a real question here; nobody to ask counts as no.
94function askAllow($, patterns) {
95  return $.ui.ask('Child on ' + decision.model + ' wants to run: ' + patterns.join(' · '), ['Allow and continue', 'Deny'])
96    .then((a) => a === 'Allow and continue').catch(() => false)
97}
98
99async function runChild($) {
100  const started = Date.now()
101  let out = await spawnChild($, [], buildBrief(await $.session.messages(), lastPrompt, cfg.child.contextMessages))
102  for (let round = 0; out.ok && out.denials.length && round < cfg.child.relayRounds; round += 1) {
103    const patterns = allowPatterns(out.denials)
104    if (!(await askAllow($, patterns))) break
105    out = await spawnChild($, ['--resume', out.sessionId, '--allowedTools', ...patterns], relayText(patterns))
106  }
107  // A handback, a request that the user act, an unverified claim, narration or a repeat is discarded.
108  const vet = out.ok ? vetAnswer(out, answered) : { ok: false, reason: '' }
109  decision = { ...decision, child: { ms: Date.now() - started, exitCode: vet.ok ? 0 : 1, rejected: vet.reason } }
110  if (!vet.ok) await $.store.set('failures', bumpFailures(await $.store.get('failures'), decision.kind))
111  return vet.ok ? out.answer : ''
112}
113
114async function pinFrom($, arg) {
115  pin = parseRouteArg(arg, cfg.routes)
116  await $.store.set('pin', pin)
117  applyPin()
118  $.ui.invalidate('ui.render')
119  return 'routing set to ' + pin.mode + (pin.model ? ' ' + pin.model : pin.label ? ' ' + pin.label : '')
120}
121
122function bandView(e, theirs) {
123  return { disabled, ready, sessionModel, pin, decision, routes: cfg.routes, isWorking: e.props.isWorking, theirs }
124}
125
126export function register(on, opts) {
127  options = opts || {}
128  on('session.start', async ($, e, next) => {
129    disabled = Boolean(await $.env.get('MAGGY_ROUTER_CHILD'))
130    if (disabled) return next(e)
131    await loadConfig($)
132    applyPin()
133    await $.command.register({ name: 'route', description: 'Show or pin the model route, or open the stats pane: /route [stats|auto|off|reset|simple|coding|critical|<model>]', argumentHint: '[stats|auto|off|reset|label|model]', immediate: true })
134      .catch(() => $.ui.log('/route is taken by another plugin'))
135    return next(e)
136  })
137
138  on('prompt.submit', async ($, e, next) => {
139    if (disabled) return next(e)
140    lastPrompt = e.text
141    await decide($, e.text)
142    return next(e)
143  }).catch(async ($, e, next) => next(e))
144
145  on('turn.start', async ($, e, next) => {
146    decision = { ...decision, child: undefined }
147    return next(e)
148  })
149
150  on('turn.step', async function* ($, e, next) {
151    if (!e.agentId) lastWasChild = false
152    if (!shouldDelegate(e)) return yield* next(e)
153    const answer = await runChild($)
154    if (!answer) {
155      $.ui.log('child on ' + decision.model + (decision.child.rejected ? ' answer discarded (' + decision.child.rejected + ')' : ' failed') + ', main model takes this turn')
156      return yield* next(e)
157    }
158    lastWasChild = true
159    answered.set(answer, decision.model)
160    if (answered.size > 50) answered.delete(answered.keys().next().value)
161    yield { kind: 'text', index: 0, text: answer }
162    return { turnId: e.turnId, index: e.index, answer, toolUses: [], stopReason: 'end_turn', usage: null }
163  })
164
165  on('turn.complete', async ($, e, next) => {
166    const result = await next(e)
167    if (disabled || e.agentId || !cfg.summary || !decision.model) return result
168    const day = new Date().toISOString().slice(0, 10)
169    const stats = bumpStats((await $.store.get('stats')) || {}, day, decision.model)
170    await $.store.set('stats', stats)
171    await $.store.set('log', appendLog(await $.store.get('log'), { day, model: decision.model, kind: decision.kind, label: decision.label, score: decision.score, source: decision.source, child: decision.child || null }, 200))
172    return { ...result, text: summaryLine(decision, e.usage) + ' · ' + statsLine(stats, day) }
173  })
174
175  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
176    if (!cfg.ui.band || e.props.hasSurvey) return next(e)
177    const theirs = await next(e)
178    return bandTree($.ui.resolve(e), bandView(e, theirs), (arg) => pinFrom($, arg))
179  })
180
181  on('ui.render', { component: 'AssistantMessage' }, async ($, e, next) => {
182    const tagged = cfg.ui.tags !== 'off' && e.props.isFirstOfReply
183    const model = tagged ? answered.get(e.props.text.trim()) || (cfg.ui.tags === 'all' ? sessionModel : undefined) : undefined
184    if (!model) return next(e)
185    return tagTree($.ui.resolve(e), tagText(model, sessionModel), await next(e))
186  })
187
188  on('ui.render', { component: 'Pane' }, async ($, e, next) => {
189    if (e.requestId !== 'routing-stats') return next(e)
190    const view = { summary: summarize((await $.store.get('log')) || [], sessionModel), sessionModel, thresholds: cfg.thresholds, columns: e.props.bodyColumns, tab }
191    return paneTree($.ui.resolve(e), view, (t) => { tab = t; $.ui.invalidate('ui.render') })
192  })
193
194  on('ui.render', { component: 'Spinner' }, async ($, e, next) => {
195    if (!shouldDelegate({ index: 0 })) return next(e)
196    return next({ ...e, props: { ...e.props, suffix: ' · via ' + decision.model + ' (child)…' } })
197  })
198
199  on('command.run', { command: 'route' }, async ($, e) => {
200    const parsed = parseRouteArg(e.args, cfg.routes)
201    if (parsed.mode === 'show') return { text: reportText(bandView({ props: {} })) + ' · ' + statsLine((await $.store.get('stats')) || {}, new Date().toISOString().slice(0, 10)) }
202    if (parsed.mode === 'reset') return { text: 'failure memory cleared', ...(await $.store.set('failures', {}) || {}) }
203    if (parsed.mode === 'stats') return { ...(await $.ui.open({ id: 'routing-stats', title: 'Mixture of models', focus: true, closeOnEscape: true }) && {}) }
204    return { text: await pinFrom($, e.args) }
205  })
206}
207
hooks/lib/config.js 76 lines
1// Routing configuration: defaults and the ~/.claude/model-config.json overlay.
2// Pure: no mods API here, so every function is unit-testable.
3
4export const LABELS = ['simple', 'coding', 'critical']
5
6// Tier → model, and kind → model for the non-critical tiers. 'claude' means "keep the session's own model".
7export const DEFAULT_ROUTES = {
8  simple: 'glm-5.3',
9  coding: 'glm-5.3',
10  critical: 'claude',
11  kinds: { research: 'kimi-k3', review: 'kimi-k3', multimodal: 'claude' },
12}
13
14// Maggy's "followed" primary, as model-config.json names it, to the model id a gateway resolves.
15// `claude` is deliberately absent: following Claude keeps critical work there, not coding work.
16export const PRIMARY_MODELS = {
17  glm: 'glm-5.3',
18  kimi: 'kimi-k3',
19  deepseek: 'deepseek-v4-pro',
20}
21
22export const DEFAULTS = {
23  routes: DEFAULT_ROUTES,
24  subagents: { Explore: 'simple' },
25  // Blast score 1-10 → tier: ≤ simple is simple, ≤ coding is coding, above is critical.
26  thresholds: { simple: 3, coding: 7 },
27  ollama: { model: 'qwen2.5-coder:3b' },
28  // Fallback classifier when Ollama is down. Undated alias: Claude Code resolves it to the current snapshot.
29  classifier: 'claude-haiku-4-5',
30  // The delegate: a headless claude on the gateway, in its own process and environment.
31  child: {
32    baseUrl: '',
33    // --bare: no inherited hooks or plugins, strictly API-key auth, so the child never touches the subscription.
34    args: ['--bare', '--permission-mode', 'acceptEdits'],
35    maxTurns: 25,
36    timeoutMs: 600000,
37    contextMessages: 12,
38    // How many times a routed turn may pause to ask the user about commands the child was refused.
39    relayRounds: 2,
40  },
41  // The band above the prompt, and which replies get a provenance tag: 'routed', 'all' or 'off'.
42  ui: { band: true, tags: 'routed' },
43  summary: true,
44}
45
46function parseJson(text) {
47  try {
48    return JSON.parse(text || '{}')
49  } catch {
50    return {}
51  }
52}
53
54function codingRoute(primary, routes) {
55  const model = PRIMARY_MODELS[primary]
56  if (!model) return routes.coding
57  return model
58}
59
60export function parseConfig(text) {
61  const raw = parseJson(text)
62  const router = raw.router || {}
63  const routes = { ...DEFAULT_ROUTES, ...(router.routes || {}), kinds: { ...DEFAULT_ROUTES.kinds, ...((router.routes || {}).kinds || {}) } }
64  if (raw.primary && !(router.routes || {}).coding) routes.coding = codingRoute(raw.primary, routes)
65  return {
66    routes,
67    subagents: { ...DEFAULTS.subagents, ...(router.subagents || {}) },
68    thresholds: { ...DEFAULTS.thresholds, ...(router.thresholds || {}) },
69    ollama: { ...DEFAULTS.ollama, ...(router.ollama || {}) },
70    classifier: router.classifier || DEFAULTS.classifier,
71    child: { ...DEFAULTS.child, ...(router.child || {}) },
72    ui: { ...DEFAULTS.ui, ...(router.ui || {}) },
73    summary: router.summary === undefined ? DEFAULTS.summary : router.summary,
74  }
75}
76
hooks/lib/classify.js 101 lines
1// Prompt classification: the rules Maggy's route-task-hook applies before
2// asking a model, the blast-score-and-kind prompt, and the Ollama wire format. Pure.
3
4const CONTINUATIONS = new Set([
5  'go ahead', 'go', 'go on', 'continue', 'proceed', 'keep going', 'carry on', 'do it', 'run it', 'run',
6  'ok', 'okay', 'k', 'yes', 'yep', 'yeah', 'yes please', 'sure', 'next', 'next step', 'start', 'begin', 'execute',
7])
8const EXECUTION_INTENT = /validate[- ]plan|execute the plan|run the plan|implement the plan|start executing|begin implementation/
9const SHORT_WORDS = 6
10
11// Turns only the main session can serve: a child sees none of the conversation, teammates,
12// background tasks, PRs or the session's tools, so it would narrate or invent an answer.
13const NOTIFICATION = /<teammate-message\b|<task-notification>|\[SYSTEM NOTIFICATION|"type"\s*:\s*"idle_notification"/i
14const SESSION_VERB = /^(approve[ds]?|merge|push|pull|continue|resume|proceed|retry|rerun|check|status|land|ship|revert|rebase|cancel|stop|kill)\b/
15const SESSION_REF = /\b(status|sub[- ]?agents?|teammates?|workflows?|background (tasks?|jobs?)|pr\s*#?\d+|prs?|pull requests?|branch(es)?|ci|merged?|run ids?)\b/
16const SECURITY = /\b(security|vulnerab\w*|cve|exploit\w*|threat model|pen ?test|leaked (keys?|secrets?|tokens?)|verdict)\b/
17const COMMAND_WORDS = 12
18
19// The classifier answers "<score> <kind>". Score: blast radius. Kind: what sort of work it is.
20export const SCORES = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']
21export const KINDS = ['code', 'research', 'review', 'docs', 'data', 'multimodal']
22export const VERDICTS = KINDS.flatMap((k) => SCORES.map((s) => s + ' ' + k))
23
24function normalize(text) {
25  return text.toLowerCase().trim().replace(/[.!?]+$/, '')
26}
27
28// Why a prompt must stay on the main session, or '' when it may be classified.
29export function sessionTurn(text) {
30  if (NOTIFICATION.test(text)) return 'notification'
31  const lower = normalize(text)
32  const words = lower.split(/\s+/).filter(Boolean).length
33  if (words <= COMMAND_WORDS && (SESSION_VERB.test(lower) || SESSION_REF.test(lower))) return 'session command'
34  return SECURITY.test(lower) ? 'security or verdict' : ''
35}
36
37// What to do with a prompt before any model is asked. `ctx.lastHadTools`: the main
38// session's last answer used tools (it is mid-task). `ctx.lastWasChild`: the last answer
39// came from a child, which keeps no memory, so follow-ups belong to the main session.
40export function preClassify(text, ctx) {
41  const lower = normalize(text)
42  const words = lower.split(/\s+/).filter(Boolean).length
43  if (lower.startsWith('/')) return { kind: 'skip' }
44  const stay = sessionTurn(text)
45  if (stay) return { kind: 'main', reason: stay }
46  if (/\buse claude\b/.test(lower) || EXECUTION_INTENT.test(lower)) return { kind: 'label', label: 'critical' }
47  if (ctx.lastWasChild && CONTINUATIONS.has(lower)) return { kind: 'main', reason: 'continuation after a child turn' }
48  if (ctx.lastWasChild && words <= SHORT_WORDS) return { kind: 'main', reason: 'follow-up after a child turn' }
49  if (CONTINUATIONS.has(lower)) return { kind: 'sticky' }
50  if (words <= SHORT_WORDS && ctx.lastHadTools) return { kind: 'sticky' }
51  return { kind: 'classify' }
52}
53
54// Maggy's blast score: how much damage a wrong answer does, not how long the task is.
55export function classifierPrompt(text) {
56  return [
57    'Rate this coding-assistant task. Reply with two words: the blast radius from 1-10, a space, and the kind. Example: 6 code',
58    'Blast radius:',
59    '1-2: lookups, grep, shell one-liners, syntax questions, reading logs, git status or diff.',
60    '3-4: single-file edits, tests, docs, config changes, small bug fixes, scaffolding.',
61    '5-6: multi-file features, wiring services or tools together, integrations, deployments that follow a known pattern.',
62    '7-8: debugging across services, data migrations, performance work, changes that are awkward to undo.',
63    '9-10: security or auth design, architecture decisions, production incidents, anything irreversible.',
64    'Deep reasoning (algorithms with proofs, concurrency, performance tuning, cryptography) scores at least 7 whatever the blast radius.',
65    'Length, the number of services named, or pasted API keys do not raise the score by themselves.',
66    'Kind: code (write or change code, tests, config) · research (find out, compare, look things up) · review (review a diff or PR, explain existing code, summarise) · docs (prose: README, changelog, commit message, ADR) · data (SQL, logs, transforms, bulk extraction) · multimodal (images, screenshots, audio, video).',
67    '',
68    'Task: ' + text,
69  ].join('\n')
70}
71
72// "6 code", "Score: 7, kind: review", or a bare number (kind defaults to code).
73export function parseVerdict(raw) {
74  const score = (raw || '').match(/\b([1-9]|10)\b/)
75  if (!score) return undefined
76  const kind = KINDS.find((k) => new RegExp('\\b' + k + '\\b', 'i').test(raw)) || 'code'
77  return { score: Number(score[1]), kind }
78}
79
80export function labelFor(score, thresholds) {
81  if (score <= thresholds.simple) return 'simple'
82  return score <= thresholds.coding ? 'coding' : 'critical'
83}
84
85export function ollamaBody(model, prompt) {
86  return JSON.stringify({
87    model,
88    stream: false,
89    messages: [{ role: 'user', content: prompt }],
90    options: { temperature: 0.1, num_predict: 8 },
91  })
92}
93
94export function ollamaReply(text) {
95  try {
96    return JSON.parse(text).message.content || ''
97  } catch {
98    return ''
99  }
100}
101
hooks/lib/routing.js 86 lines
1// Route resolution, the /route argument grammar, and the summary line. Pure.
2import { LABELS } from './config.js'
3
4// The tier says whether Claude is mandatory; below that, the kind picks the cheaper model.
5export function resolveModel(decision, routes, sessionModel) {
6  const byTier = routes[decision.label]
7  if (!byTier || byTier === 'claude') return sessionModel
8  const model = (routes.kinds || {})[decision.kind] || byTier
9  return model === 'claude' ? sessionModel : model
10}
11
12// While the main session is mid-task (its last answer used tools), coding-level work stays
13// with it: a child would start over without the transcript. Lookups may still go out.
14export function midTaskGuard(label, ctx) {
15  return label === 'coding' && Boolean(ctx.lastHadTools)
16}
17
18// On the coding/critical edge one sample is noisy: these scores earn a second one.
19export function isBorderline(score, thresholds) {
20  return score === thresholds.coding || score === thresholds.coding + 1
21}
22
23export function bumpFailures(failures, kind) {
24  const k = kind || 'code'
25  return { ...(failures || {}), [k]: ((failures || {})[k] || 0) + 1 }
26}
27
28// Outcome memory: every two child failures of a kind lower that kind's coding cut-off by one.
29export function adjustThresholds(thresholds, failures, kind) {
30  const drop = Math.floor(((failures || {})[kind] || 0) / 2)
31  return { ...thresholds, coding: Math.max(thresholds.simple + 1, thresholds.coding - drop) }
32}
33
34export function routeModels(routes) {
35  return [...Object.values(routes).filter((m) => typeof m === 'string'), ...Object.values(routes.kinds || {})]
36}
37
38function modelByPrefix(arg, routes) {
39  return routeModels(routes).find((m) => m.startsWith(arg))
40}
41
42export function parseRouteArg(arg, routes) {
43  const word = (arg || '').trim().toLowerCase()
44  if (word === '') return { mode: 'show' }
45  if (['auto', 'off', 'reset', 'stats'].includes(word)) return { mode: word }
46  if (LABELS.includes(word)) return { mode: 'label', label: word }
47  return { mode: 'model', model: modelByPrefix(word, routes) || word }
48}
49
50function fmtTokens(n) {
51  return (n / 1000).toFixed(1) + 'k'
52}
53
54// The API's input_tokens excludes cached tokens, so the context size is the three summed.
55function contextTokens(usage) {
56  return usage.input_tokens + usage.cache_read_input_tokens + usage.cache_creation_input_tokens
57}
58
59function cachePercent(usage) {
60  const total = contextTokens(usage)
61  return total ? Math.round((usage.cache_read_input_tokens / total) * 100) : 0
62}
63
64function childNote(child) {
65  if (child.rejected) return ' · child answer discarded (' + child.rejected + '), main model answered'
66  if (child.exitCode !== 0) return ' · child failed, main model answered'
67  return ' · child ' + Math.round(child.ms / 1000) + 's'
68}
69
70function usageNote(usage) {
71  if (!usage) return ''
72  return ' · ' + fmtTokens(contextTokens(usage)) + ' in / ' + fmtTokens(usage.output_tokens) + ' out · cache ' + cachePercent(usage) + '%'
73}
74
75// Every turn gets a line: where it ran (child or main session) and what it cost.
76export function tierText(decision) {
77  const score = decision.score ? ' ' + decision.score + '/10' + (decision.kind ? ' ' + decision.kind : '') : ''
78  return decision.label + score + ' via ' + decision.source
79}
80
81export function summaryLine(decision, usage) {
82  const head = 'route: ' + decision.model + ' · ' + tierText(decision)
83  if (decision.child) return head + childNote(decision.child)
84  return head + usageNote(usage) + ' · main session'
85}
86
hooks/lib/child.js 84 lines
1// The delegate: a headless `claude -p` child on the gateway. Argument vector,
2// scoped environment, readiness, env-file parsing and the context brief. Pure.
3
4const MESSAGE_CHARS = 1200
5
6// Read first by every child: what it cannot see, what it must not invent, how to hand back.
7export const CHILD_PREAMBLE = [
8  'You are a delegate in a separate headless process. You have no access to the main session: not its full conversation, teammates, background tasks, PRs, branches or tools.',
9  'Never invent statuses, IDs, PR numbers, run results, commit counts or file changes. Report only what your own tool calls in this run showed or did.',
10  'Never ask the user to approve or run anything, and do not narrate what you would do: do it with your tools, or hand back.',
11  'If the task needs the main session\'s state or tools, reply with HANDBACK on the first line and one line saying why.',
12].join('\n')
13
14export function childReady(child, key) {
15  return Boolean(child.baseUrl && key)
16}
17
18export function childEnv(child, key) {
19  const env = { MAGGY_ROUTER_CHILD: '1' }
20  if (child.baseUrl) Object.assign(env, { ANTHROPIC_BASE_URL: child.baseUrl, ANTHROPIC_API_KEY: key })
21  return env
22}
23
24// The flags after the program name (`claude`, written as fixed text at the $.process.run call).
25// --add-dir keeps the project's CLAUDE.md in reach even when --bare skips auto-discovery.
26export function childArgs(child, model, cwd) {
27  return ['-p', '--model', model, '--output-format', 'json', '--max-turns', String(child.maxTurns), '--add-dir', cwd, ...child.args]
28}
29
30function describe(m) {
31  const text = m.text.length > MESSAGE_CHARS ? m.text.slice(0, MESSAGE_CHARS) + '…' : m.text
32  const tools = (m.toolUses || []).map((t) => t.name)
33  return m.role + ': ' + text + (tools.length ? ' [tools: ' + tools.join(', ') + ']' : '')
34}
35
36// What the child reads on stdin: the last few exchanges of the main session, then the task.
37export function buildBrief(messages, prompt, limit) {
38  let history = messages.filter((m) => m.text)
39  const last = history[history.length - 1]
40  if (last && last.role === 'user' && last.text === prompt) history = history.slice(0, -1)
41  history = history.slice(-limit)
42  const context = history.length ? '\n\nContext from the main session:\n' + history.map(describe).join('\n') : ''
43  return CHILD_PREAMBLE + context + '\n\nTask:\n' + prompt
44}
45
46// Where the child's gateway comes from: the URL from the plugin's options or model-config,
47// the key from the plugin's options only (masked, secure storage). Nothing is read from disk for it.
48export function gatewayFrom(options, child) {
49  const o = options || {}
50  return { baseUrl: o.gateway_url || child.baseUrl || '', key: o.gateway_key || '' }
51}
52
53function resultOf(raw) {
54  try {
55    const d = JSON.parse(raw)
56    const items = Array.isArray(d) ? d : [d]
57    return items.find((x) => x && x.type === 'result') || items[items.length - 1] || {}
58  } catch {
59    return {}
60  }
61}
62
63// The headless child's JSON: its answer, its session id (for --resume), every command the
64// permission system refused (so the user can be asked for real), and its turn count
65// (1 means it called no tools, which vet.js uses to spot unverified claims).
66export function parseChildOutput(raw, exitCode) {
67  const r = resultOf(raw)
68  const answer = String(r.result || '').trim()
69  const ok = exitCode === 0 && !r.is_error && answer !== ''
70  const seen = new Set()
71  const denials = (r.permission_denials || []).map((d) => ({ tool: d.tool_name, command: d.tool_name === 'Bash' ? d.tool_input.command || '' : '' }))
72    .filter((d) => !seen.has(d.tool + d.command) && seen.add(d.tool + d.command))
73  const turns = typeof r.num_turns === 'number' ? r.num_turns : undefined
74  return { ok, answer: ok ? answer : '', sessionId: ok ? String(r.session_id || '') : '', denials: ok ? denials : [], turns }
75}
76
77export function allowPatterns(denials) {
78  return denials.map((d) => (d.tool === 'Bash' ? 'Bash(' + d.command + ')' : d.tool))
79}
80
81export function relayText(patterns) {
82  return 'The user approved these, and they are now allowed: ' + patterns.join(', ') + '. Continue the task from where you stopped and run them.'
83}
84
hooks/lib/vet.js 33 lines
1// Delegate output validation. A child answer is only relayed when it is a real answer:
2// not a handback, not a request that the user act, not a claim it never checked, not
3// narration of intent, and not a repeat. Anything else goes back to the main model. Pure.
4
5const HANDBACK = /^\s*HANDBACK\b/
6const ASKS_USER = /\b(blocked by (the )?permission|permission (system|prompt|denied)|(need|needs|require|requires) (your )?approval|approve (it|this|them) in the ui|you (must|need to|will need to|'ll need to) (approve|run|execute|allow|grant|merge|push)|please (approve|run|execute|allow)|yourself|sandboxed)\b/i
7const CLAIM = /\b(I('ve| have)? (added|created|updated|fixed|changed|wrote|written|modified|implemented|committed|pushed|merged|opened|ran|deleted|removed|refactored|installed)|pr\s*#\d+|\d+ commits? (behind|ahead)|no [\w-]+ (runs?|prs?|builds?) exists?)\b/i
8const INTENT = /^(I'll|I will|let me|I'm going to|I am going to|next,? I|then,? I|first,? I|now,? I'll)\b/i
9
10function sentences(text) {
11  return text.split(/(?<=[.!?])\s+|\n+/).map((s) => s.trim()).filter(Boolean)
12}
13
14function isNarration(text) {
15  const all = sentences(text)
16  return all.length > 0 && all.filter((s) => INTENT.test(s)).length * 2 >= all.length
17}
18
19// `out.turns === 1` means the child answered without a single tool call.
20function reasonFor(out, previous) {
21  const text = out.answer
22  if (HANDBACK.test(text)) return 'handback'
23  if (ASKS_USER.test(text)) return 'asks the user to act'
24  if (out.turns === 1 && CLAIM.test(text)) return 'unverified claim'
25  if (isNarration(text)) return 'narration'
26  return previous.has(text) ? 'repeat of an earlier answer' : ''
27}
28
29export function vetAnswer(out, previous) {
30  const reason = reasonFor(out, previous)
31  return { ok: reason === '', reason }
32}
33
hooks/lib/stats.js 58 lines
1// Per-day counts for the route line, the bounded decision log, and the
2// summaries the stats pane draws. Pure.
3
4export function bumpStats(stats, day, model) {
5  const today = { ...(stats[day] || {}) }
6  today[model] = (today[model] || 0) + 1
7  return { ...stats, [day]: today }
8}
9
10export function statsLine(stats, day) {
11  const today = stats[day]
12  if (!today) return 'today: no routed turns yet'
13  return 'today: ' + Object.entries(today).map(([m, n]) => m + ' ×' + n).join(', ')
14}
15
16export function appendLog(log, entry, cap) {
17  return [...(log || []), entry].slice(-cap)
18}
19
20export function bar(n, max, width) {
21  const filled = max > 0 ? Math.round((n / max) * width) : 0
22  return '█'.repeat(filled) + '░'.repeat(width - filled)
23}
24
25function countBy(log, key) {
26  const counts = new Map()
27  for (const e of log) counts.set(e[key], (counts.get(e[key]) || 0) + 1)
28  return [...counts.entries()].sort((a, b) => b[1] - a[1])
29}
30
31function kindRows(log) {
32  return countBy(log, 'kind').map(([kind, n]) => {
33    const models = {}
34    for (const e of log.filter((x) => x.kind === kind)) models[e.model] = (models[e.model] || 0) + 1
35    return { kind, n, models }
36  })
37}
38
39function childStats(log) {
40  const runs = log.filter((e) => e.child)
41  const ms = runs.reduce((sum, e) => sum + e.child.ms, 0)
42  return { runs: runs.length, failed: runs.filter((e) => e.child.exitCode !== 0).length, avgMs: runs.length ? Math.round(ms / runs.length) : 0 }
43}
44
45export function summarize(log, sessionModel) {
46  const byScore = Array(10).fill(0)
47  for (const e of log) if (e.score >= 1 && e.score <= 10) byScore[e.score - 1] += 1
48  return {
49    total: log.length,
50    offClaude: log.filter((e) => e.model !== sessionModel).length,
51    byModel: countBy(log, 'model').map(([model, n]) => ({ model, n })),
52    byKind: kindRows(log),
53    byScore,
54    recent: [...log].reverse().slice(0, 8),
55    child: childStats(log),
56  }
57}
58
hooks/lib/stats-pane.js 57 lines
1// The "Mixture of models" pane: four tabs that chart the decision log. Pure:
2// elements come in, a tree goes out.
3import { bar } from './stats.js'
4
5const TABS = ['models', 'kinds', 'scores', 'recent']
6const COLORS = ['cyan', 'magenta', 'yellow', 'green', 'blue', 'red']
7
8function pct(n, total) {
9  return total ? Math.round((n / total) * 100) + '%' : '0%'
10}
11
12function row(el, label, text, color) {
13  return el.Box({ flexDirection: 'row', columnGap: 1, children: [el.Text({ color, children: [label.padEnd(18)] }), el.Text({ children: [text] })] })
14}
15
16function modelsTab(el, v) {
17  const { summary: s } = v
18  const width = Math.max(10, Math.min(30, v.columns - 36))
19  const max = s.byModel.length ? s.byModel[0].n : 0
20  return [
21    el.Text({ bold: true, children: [s.offClaude + ' of ' + s.total + ' turns off Claude (' + pct(s.offClaude, s.total) + ')'] }),
22    el.Text({ dimColor: true, children: ['child runs ' + s.child.runs + ' · failed ' + s.child.failed + ' · avg ' + Math.round(s.child.avgMs / 1000) + 's'] }),
23    ...s.byModel.map((m, i) => row(el, m.model, bar(m.n, max, width) + ' ' + m.n + ' · ' + pct(m.n, s.total), COLORS[i % COLORS.length])),
24  ]
25}
26
27function kindsTab(el, v) {
28  return v.summary.byKind.map((k, i) =>
29    row(el, k.kind, String(k.n).padStart(3) + '  ' + Object.entries(k.models).map(([m, n]) => m + ' ' + n).join(' · '), COLORS[i % COLORS.length]),
30  )
31}
32
33function scoresTab(el, v) {
34  const max = Math.max(...v.summary.byScore, 0)
35  const t = v.thresholds
36  const tone = (score) => (score <= t.simple ? 'green' : score <= t.coding ? 'yellow' : 'red')
37  return [
38    ...v.summary.byScore.map((n, i) => row(el, String(i + 1).padStart(2), bar(n, max, 20) + ' ' + n, tone(i + 1))),
39    el.Text({ dimColor: true, children: ['simple ≤ ' + t.simple + ' · coding ≤ ' + t.coding + ' · critical above'] }),
40  ]
41}
42
43function recentTab(el, v) {
44  return v.summary.recent.map((e) => {
45    const where = e.child ? (e.child.exitCode === 0 ? 'child ' + Math.round(e.child.ms / 1000) + 's' : 'child failed') : 'main'
46    return row(el, e.score + '/10 ' + e.kind, e.model + ' · ' + where + ' · via ' + e.source, e.model === v.sessionModel ? 'magenta' : 'cyan')
47  })
48}
49
50const BODIES = { models: modelsTab, kinds: kindsTab, scores: scoresTab, recent: recentTab }
51
52export function paneTree(el, v, onTab) {
53  const tabs = TABS.map((t, i) => el.Button({ key: 'tab-' + t, label: t, hotkey: String(i + 1), plain: true, dimColor: v.tab !== t, onPress: () => onTab(t) }))
54  const body = v.summary.total ? BODIES[v.tab](el, v) : [el.Text({ dimColor: true, children: ['No turns recorded yet. Send a prompt and come back.'] })]
55  return el.Box({ flexDirection: 'column', children: [el.Box({ flexDirection: 'row', columnGap: 3, children: tabs }), el.Text({ children: [' '] }), ...body] })
56}
57
hooks/lib/ui.js 67 lines
1// What the mod draws: the band above the prompt and the provenance tag on a
2// reply. Pure: elements come in as a parameter, trees go out as data.
3
4import { routeModels, summaryLine, tierText } from './routing.js'
5
6const NAME = 'mixture-of-models'
7
8function provider(model) {
9  return model.split('-')[0]
10}
11
12// One button per provider in the routes, framed by auto, claude and off.
13export function bandButtons(routes) {
14  const providers = [...new Set(routeModels(routes).filter((m) => m !== 'claude').map(provider))]
15  const args = ['auto', ...providers, 'claude', 'off']
16  return args.map((arg, i) => ({ key: 'pin-' + arg, label: arg, hotkey: String(i + 1), arg }))
17}
18
19function activeArg(pin) {
20  if (pin.mode === 'model') return pin.model === 'claude' ? 'claude' : provider(pin.model)
21  return pin.mode === 'label' ? '' : pin.mode
22}
23
24function lastDecision(d) {
25  if (!d.model) return 'no prompt yet'
26  return 'last: ' + d.model + ' (' + tierText(d) + ')'
27}
28
29export function bandText(v) {
30  if (v.disabled) return NAME + ' · inactive inside a child session'
31  if (!v.ready) return NAME + ' · observe-only: no gateway key for the child'
32  if (v.pin.mode === 'off') return NAME + ' · off · everything on ' + v.sessionModel
33  const routed = v.decision.model && v.decision.model !== v.sessionModel
34  if (v.isWorking) return NAME + ' · running ' + (routed ? v.decision.model + ' in a child…' : v.sessionModel + ' in the main session…')
35  if (v.pin.mode === 'model') return NAME + ' · pinned ' + v.decision.model
36  if (v.pin.mode === 'label') return NAME + ' · pinned ' + v.pin.label + ' → ' + v.decision.model
37  return NAME + ' · auto · ' + lastDecision(v.decision)
38}
39
40export function bandTree(el, v, onPin) {
41  const active = activeArg(v.pin)
42  const buttons = bandButtons(v.routes).map((b) =>
43    el.Button({ key: b.key, label: b.label, hotkey: b.hotkey, plain: true, dimColor: b.arg !== active, onPress: () => onPin(b.arg) }),
44  )
45  const row = el.Box({ flexDirection: 'row', columnGap: 2, children: [el.Text({ dimColor: true, children: [bandText(v) + '  '] }), ...buttons] })
46  return el.Box({ flexDirection: 'column', children: [row, v.theirs].filter(Boolean) })
47}
48
49export function tagText(model, sessionModel) {
50  return '⇢ ' + model + (model === sessionModel ? ' · main session' : ' · child on gateway')
51}
52
53export function tagTree(el, text, theirs) {
54  return el.Box({ flexDirection: 'column', children: [el.Text({ dimColor: true, children: [text] }), theirs] })
55}
56
57function pinWord(pin) {
58  if (pin.mode === 'auto') return 'auto'
59  return pin.mode + (pin.model ? ' ' + pin.model : pin.label ? ' ' + pin.label : '')
60}
61
62// The /route answer.
63export function reportText(v) {
64  const live = v.disabled ? 'disabled (child session)' : v.ready ? 'live' : 'observe-only (no gateway key for the child)'
65  return NAME + ' ' + live + ' · mode ' + pinWord(v.pin) + ' · current ' + summaryLine(v.decision, null)
66}
67