cc-switchboard 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,14 @@
1
+ {
2
+ "name": "switchboard",
3
+ "owner": {
4
+ "name": "Siamak Rostami"
5
+ },
6
+ "plugins": [
7
+ {
8
+ "name": "switchboard",
9
+ "source": "./",
10
+ "description": "Automatic model routing for Claude Code with saved setups."
11
+ }
12
+ ],
13
+ "description": "Switchboard: automatic model routing for Claude Code with saved setups."
14
+ }
@@ -0,0 +1,20 @@
1
+ {
2
+ "name": "switchboard",
3
+ "description": "Automatic model routing: Fable plans and reviews, Opus does hard code and UI, Sonnet does regular code and writing, Haiku does chores. Setups are saved and switchable with the switchboard CLI.",
4
+ "version": "0.1.0",
5
+ "author": {
6
+ "name": "Siamak Rostami"
7
+ },
8
+ "repository": "https://github.com/siamakrostami/ClaudeModelRouter",
9
+ "license": "MIT",
10
+ "keywords": [
11
+ "model",
12
+ "routing",
13
+ "subagents",
14
+ "fable",
15
+ "opus",
16
+ "sonnet",
17
+ "haiku"
18
+ ],
19
+ "homepage": "https://github.com/siamakrostami/ClaudeModelRouter"
20
+ }
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Siamak Rostami
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,85 @@
1
- # Temporary Holding Version
1
+ # Switchboard
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ [![npm](https://img.shields.io/npm/v/cc-switchboard.svg)](https://www.npmjs.com/package/cc-switchboard)
4
+ [![node](https://img.shields.io/node/v/cc-switchboard.svg)](https://nodejs.org)
5
+ [![license](https://img.shields.io/npm/l/cc-switchboard.svg)](LICENSE)
6
+
7
+ Automatic model routing for Claude Code. You type your request as usual, and Switchboard
8
+ hands each kind of work to a helper running on the model that suits it:
9
+
10
+ | Role | Handles | Default |
11
+ |---|---|---|
12
+ | plan | planning, architecture, big decisions (main chat) | Fable · xhigh |
13
+ | review | code review | Fable · high |
14
+ | hard | hard code, UI, debugging | Opus · high |
15
+ | code | regular code, tests, refactors | Sonnet · medium |
16
+ | write | PR descriptions, Slack, docs, tickets | Sonnet · medium |
17
+ | chores | git, renames, formatting, lookups, commit messages | Haiku · low |
18
+
19
+ ## How it works
20
+
21
+ - **SessionStart hook** adds one standing rule: routing notes are the user's instruction.
22
+ - **UserPromptSubmit hook** matches the prompt against keyword rules and adds a one-line
23
+ note naming the helper to use, e.g. `switchboard:router-code`.
24
+ - **PreToolUse hook** forces every `router-*` helper onto the model and effort of your
25
+ active setup, whatever model the main chat asked for.
26
+ - **Status line segment** shows the active setup and what is running:
27
+ `⇢ default · code→sonnet`.
28
+
29
+ ## Install
30
+
31
+ ```bash
32
+ npm install -g cc-switchboard
33
+ claude plugin marketplace add "$(npm root -g)/cc-switchboard"
34
+ claude plugin install switchboard@switchboard
35
+ ```
36
+
37
+ From a clone instead: `npm install && npm link`, then `claude plugin marketplace add "$PWD"`
38
+ and the same `claude plugin install` line.
39
+
40
+ Set the main chat to Fable (`"model": "fable"` in `~/.claude/settings.json`). To show the
41
+ segment in your status line, add this to your status line script:
42
+
43
+ ```bash
44
+ seg=$(switchboard status-segment "$session_id")
45
+ ```
46
+
47
+ ## Use
48
+
49
+ You don't need any command for daily use. These overrides are optional, and each one
50
+ applies only to the prompt it appears in:
51
+
52
+ - `#plan` `#review` `#hard` `#code` `#write` `#chores`: force a role
53
+ - `@fable` `@opus` `@sonnet` `@haiku`: force a model
54
+ - `#self`: no routing; the main chat does the work
55
+
56
+ Setups:
57
+
58
+ ```bash
59
+ switchboard # interactive picker
60
+ switchboard show | list
61
+ switchboard set code opus high
62
+ switchboard save fast # save the current setup under a name
63
+ switchboard use default
64
+ switchboard off | on # add --session <id> for one session only
65
+ ```
66
+
67
+ Inside Claude Code: `/router`, `/router use fast`, `/router off`.
68
+
69
+ Data lives in `~/.claude/switchboard/`: `setups.json` and `rules.json` (keyword regexes,
70
+ which you can edit) and `sessions/` (per-session state). Errors go to `error.log`.
71
+
72
+ ## Switching models yourself
73
+
74
+ If you change the main chat's model with `/model`, Switchboard steps aside for that
75
+ session: no routing notes, and helpers are left alone. The status line shows
76
+ `⇢ manual (opus)`. Switch back to Fable (the configured main model) and routing resumes
77
+ on your next prompt. To turn routing off or on explicitly, use `/router off` or
78
+ `switchboard off` (and `on`). If your main model is not Fable, set `main_model` in
79
+ `setups.json` (or `SWITCHBOARD_MAIN_MODEL`).
80
+
81
+ ## Test
82
+
83
+ ```bash
84
+ npm test
85
+ ```
@@ -0,0 +1,6 @@
1
+ ---
2
+ name: router-chores
3
+ description: Switchboard assistant for mechanical work. Use for git operations, renames, formatting, lint fixes, moving files, version bumps, quick lookups and commit messages.
4
+ model: haiku
5
+ ---
6
+ You do mechanical tasks quickly and exactly. Do only what was asked, verify the result (run the formatter, linter or git status), and report in one or two lines. Never push, delete branches or rewrite history unless the request says so explicitly.
@@ -0,0 +1,6 @@
1
+ ---
2
+ name: router-code
3
+ description: Switchboard engineer. Use for regular coding: implementing features, endpoints, tests, refactors and ordinary bug fixes.
4
+ model: sonnet
5
+ ---
6
+ You write everyday production code. Follow the project's existing patterns, keep the change focused, write or update tests, and run them. Report what changed and what you verified.
@@ -0,0 +1,6 @@
1
+ ---
2
+ name: router-hard
3
+ description: Switchboard senior engineer. Use for hard code, UI work (SwiftUI, Compose, web UI, layout, animation) and debugging crashes, flaky tests, races and regressions.
4
+ model: opus
5
+ ---
6
+ You handle the hard engineering. For bugs: reproduce, find the root cause, then fix it; never patch symptoms. For UI: match the platform's conventions and the existing design system. Run the build and tests that prove the change, and report what you verified and what you could not.
@@ -0,0 +1,7 @@
1
+ ---
2
+ name: router-plan
3
+ description: Switchboard planner. Use for planning, architecture, design docs, trade-off analysis and big decisions when Switchboard routes "plan" work to a helper.
4
+ model: fable
5
+ tools: Read, Grep, Glob, Bash, WebSearch, WebFetch
6
+ ---
7
+ You plan. Read what exists before proposing anything. Give one recommended approach, the alternatives you rejected and why, the risks, and concrete next steps in order. Do not edit files; return the plan as text.
@@ -0,0 +1,7 @@
1
+ ---
2
+ name: router-review
3
+ description: Switchboard reviewer. Use for code review: diffs, pull requests, branches or files that need a careful second read.
4
+ model: fable
5
+ tools: Read, Grep, Glob, Bash, WebSearch, WebFetch
6
+ ---
7
+ You review code. Hunt for real bugs first (logic, edge cases, concurrency, error handling, security), then risky design choices. For each finding give file:line, what goes wrong and when, and a fix. Skip style nits unless asked. Do not edit files.
@@ -0,0 +1,6 @@
1
+ ---
2
+ name: router-write
3
+ description: Switchboard writer. Use for prose other people will read: PR descriptions, Slack messages, emails, Jira tickets, Confluence pages, READMEs and docs.
4
+ model: sonnet
5
+ ---
6
+ You write text people will read. If the matt3r-writing skill is available, follow it. Be short, plain and specific; lead with what matters; no filler or hype. Return the draft; never send or post anything yourself.
@@ -0,0 +1,4 @@
1
+ #!/usr/bin/env node
2
+ import { main } from '../src/cli.js';
3
+
4
+ process.exitCode = await main(process.argv.slice(2));
@@ -0,0 +1,8 @@
1
+ ---
2
+ description: Show or change Switchboard model routing (setups, on/off)
3
+ argument-hint: "[show|list|use <setup>|set <role> <model> [effort]|save <name>|on|off]"
4
+ allowed-tools: Bash(node:*)
5
+ ---
6
+ !`node "${CLAUDE_PLUGIN_ROOT}/bin/switchboard.js" $ARGUMENTS --session "${CLAUDE_SESSION_ID}"`
7
+
8
+ Show the output above to the user as is, in a code block. Do not add commentary unless it shows an error.
@@ -0,0 +1,50 @@
1
+ {
2
+ "hooks": {
3
+ "SessionStart": [
4
+ {
5
+ "hooks": [
6
+ {
7
+ "type": "command",
8
+ "command": "node \"${CLAUDE_PLUGIN_ROOT}/hooks/on-session-start.js\"",
9
+ "timeout": 5
10
+ }
11
+ ]
12
+ }
13
+ ],
14
+ "UserPromptSubmit": [
15
+ {
16
+ "hooks": [
17
+ {
18
+ "type": "command",
19
+ "command": "node \"${CLAUDE_PLUGIN_ROOT}/hooks/on-prompt.js\"",
20
+ "timeout": 5
21
+ }
22
+ ]
23
+ }
24
+ ],
25
+ "PreToolUse": [
26
+ {
27
+ "matcher": "Agent|Task",
28
+ "hooks": [
29
+ {
30
+ "type": "command",
31
+ "command": "node \"${CLAUDE_PLUGIN_ROOT}/hooks/on-agent-pre.js\"",
32
+ "timeout": 5
33
+ }
34
+ ]
35
+ }
36
+ ],
37
+ "PostToolUse": [
38
+ {
39
+ "matcher": "Agent|Task",
40
+ "hooks": [
41
+ {
42
+ "type": "command",
43
+ "command": "node \"${CLAUDE_PLUGIN_ROOT}/hooks/on-agent-post.js\"",
44
+ "timeout": 5
45
+ }
46
+ ]
47
+ }
48
+ ]
49
+ }
50
+ }
@@ -0,0 +1,3 @@
1
+ #!/usr/bin/env node
2
+ import { runHook, handleAgentPost } from '../src/core/hooks.js';
3
+ runHook(handleAgentPost);
@@ -0,0 +1,3 @@
1
+ #!/usr/bin/env node
2
+ import { runHook, handleAgentPre } from '../src/core/hooks.js';
3
+ runHook(handleAgentPre);
@@ -0,0 +1,3 @@
1
+ #!/usr/bin/env node
2
+ import { runHook, handlePrompt } from '../src/core/hooks.js';
3
+ runHook(handlePrompt);
@@ -0,0 +1,3 @@
1
+ #!/usr/bin/env node
2
+ import { runHook, handleSessionStart } from '../src/core/hooks.js';
3
+ runHook(handleSessionStart);
package/package.json CHANGED
@@ -1,6 +1,49 @@
1
1
  {
2
2
  "name": "cc-switchboard",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Automatic model routing for Claude Code: Fable plans and reviews, Opus does hard code, Sonnet does regular code and writing, Haiku does chores.",
5
+ "keywords": [
6
+ "claude-code",
7
+ "claude",
8
+ "model-routing",
9
+ "plugin",
10
+ "fable",
11
+ "opus",
12
+ "sonnet",
13
+ "haiku"
14
+ ],
15
+ "homepage": "https://github.com/siamakrostami/ClaudeModelRouter#readme",
16
+ "bugs": {
17
+ "url": "https://github.com/siamakrostami/ClaudeModelRouter/issues"
18
+ },
19
+ "repository": {
20
+ "type": "git",
21
+ "url": "git+https://github.com/siamakrostami/ClaudeModelRouter.git"
22
+ },
23
+ "license": "MIT",
24
+ "author": "Siamak Rostami",
25
+ "type": "module",
26
+ "bin": {
27
+ "switchboard": "bin/switchboard.js"
28
+ },
29
+ "files": [
30
+ "bin",
31
+ "src",
32
+ "hooks",
33
+ "agents",
34
+ "commands",
35
+ ".claude-plugin",
36
+ "README.md",
37
+ "LICENSE"
38
+ ],
39
+ "engines": {
40
+ "node": ">=20"
41
+ },
42
+ "scripts": {
43
+ "test": "node --test test/"
44
+ },
45
+ "dependencies": {
46
+ "ink": "^5.2.1",
47
+ "react": "^18.3.1"
48
+ }
49
+ }
package/src/cli.js ADDED
@@ -0,0 +1,110 @@
1
+ import { ROLES, ROLE_INFO } from './core/defaults.js';
2
+ import * as store from './core/store.js';
3
+ import { statusSegment } from './core/status.js';
4
+
5
+ const USAGE = `Usage: switchboard [command]
6
+
7
+ (no command) open the interactive picker (terminal only)
8
+ show show the active setup
9
+ list list saved setups (* = active)
10
+ use <setup> switch to a saved setup
11
+ set <role> <model> [effort] change one role in the active setup
12
+ save <name> save the active setup under a new name and switch to it
13
+ delete <setup> delete a saved setup
14
+ on | off turn routing on/off (add --session <id> for one session only)
15
+ status-segment [session] print the status line segment
16
+
17
+ Roles: ${ROLES.join(', ')}
18
+ Models: fable, opus, sonnet, haiku Efforts: low, medium, high, xhigh, max
19
+ `;
20
+
21
+ function takeSession(argv) {
22
+ const args = [...argv];
23
+ let session = null;
24
+ const i = args.indexOf('--session');
25
+ if (i !== -1) {
26
+ const v = args[i + 1];
27
+ session = v && !v.startsWith('-') ? v : null;
28
+ args.splice(i, v !== undefined && !v.startsWith('-') ? 2 : 1);
29
+ }
30
+ return { args: args.filter(a => a !== ''), session, sessionFlag: i !== -1 };
31
+ }
32
+
33
+ function showText(session) {
34
+ const s = store.activeSetup();
35
+ const on = session ? store.sessionEnabled(session) : store.loadSetups().enabled;
36
+ const lines = [`Setup: ${store.activeName()}${on ? '' : ' (routing OFF' + (session ? ' for this session' : '') + ')'}`, ''];
37
+ for (const r of ROLES) {
38
+ lines.push(`${r.padEnd(8)} ${s[r].model.padEnd(8)} ${s[r].effort.padEnd(7)} ${ROLE_INFO[r]}`);
39
+ }
40
+ if (process.env.CLAUDE_CODE_SUBAGENT_MODEL) {
41
+ lines.push('', `Warning: CLAUDE_CODE_SUBAGENT_MODEL=${process.env.CLAUDE_CODE_SUBAGENT_MODEL} is set and overrides every helper's model.`);
42
+ }
43
+ return lines.join('\n') + '\n';
44
+ }
45
+
46
+ /** Run the CLI. io = {stdout, stderr, isTTY}. Returns the exit code. */
47
+ export async function main(argv, io = { stdout: process.stdout, stderr: process.stderr, isTTY: process.stdout.isTTY && process.stdin.isTTY }) {
48
+ const { args, session, sessionFlag } = takeSession(argv);
49
+ const [cmd, ...rest] = args;
50
+ const out = s => io.stdout.write(s);
51
+ try {
52
+ switch (cmd) {
53
+ case undefined:
54
+ if (io.isTTY) {
55
+ const { runPicker } = await import('./picker/app.js');
56
+ await runPicker();
57
+ return 0;
58
+ }
59
+ out(showText(session));
60
+ return 0;
61
+ case 'show':
62
+ out(showText(session));
63
+ return 0;
64
+ case 'list': {
65
+ const { active, names } = store.listSetups();
66
+ out(names.map(n => `${n === active ? '*' : ' '} ${n}`).join('\n') + '\n');
67
+ return 0;
68
+ }
69
+ case 'use':
70
+ store.use(rest[0]);
71
+ out(showText(session));
72
+ return 0;
73
+ case 'set':
74
+ store.setRole(rest[0], rest[1], rest[2]);
75
+ out(showText(session));
76
+ return 0;
77
+ case 'save':
78
+ store.saveAs(rest[0]);
79
+ out(`Saved and switched to "${rest[0]}".\n`);
80
+ return 0;
81
+ case 'delete':
82
+ store.remove(rest[0]);
83
+ out(`Deleted "${rest[0]}".\n`);
84
+ return 0;
85
+ case 'on':
86
+ case 'off':
87
+ if (sessionFlag && !session) {
88
+ io.stderr.write('No session id was passed, so nothing changed. Use `switchboard on|off` in a terminal for a global switch.\n');
89
+ return 2;
90
+ }
91
+ store.setEnabled(cmd === 'on', session || undefined);
92
+ out(`Routing ${cmd.toUpperCase()}${session ? ' for this session' : ''}.\n`);
93
+ return 0;
94
+ case 'status-segment':
95
+ out(statusSegment(rest[0] || session || null));
96
+ return 0;
97
+ case 'help':
98
+ case '--help':
99
+ case '-h':
100
+ out(USAGE);
101
+ return 0;
102
+ default:
103
+ io.stderr.write(`Unknown command "${cmd}".\n\n${USAGE}`);
104
+ return 2;
105
+ }
106
+ } catch (e) {
107
+ io.stderr.write(`${e.message}\n`);
108
+ return 2;
109
+ }
110
+ }
@@ -0,0 +1,68 @@
1
+ import { ROLES, DEFAULT_SETUP, agentName } from './defaults.js';
2
+
3
+ const MAX_SCAN = 4000; // only the start of a prompt is scanned, keeps huge pastes fast
4
+
5
+ // Plain-language versions of #self and @model.
6
+ const SELF_RE = /\b(do it yourself|do this yourself|don'?t delegate|no helpers?|without (a )?helpers?)\b/i;
7
+ const PLAIN_MODEL_RE = /\b(?:use|using|with|on|switch to|via)\s+(?:the\s+)?(fable|opus|sonnet|haiku)\b/i;
8
+
9
+ const compiled = new WeakMap();
10
+ function compile(rules) {
11
+ let c = compiled.get(rules);
12
+ if (c) return c;
13
+ c = {};
14
+ for (const role of ROLES) {
15
+ c[role] = [];
16
+ for (const src of rules[role] || []) {
17
+ try { c[role].push(new RegExp(src, 'i')); } catch { /* bad user regex: skip */ }
18
+ }
19
+ }
20
+ compiled.set(rules, c);
21
+ return c;
22
+ }
23
+
24
+ function route(role, setup, forced, modelOverride) {
25
+ const s = setup[role] || DEFAULT_SETUP[role];
26
+ return { role, model: modelOverride || s.model, effort: s.effort, agent: agentName(role), forced };
27
+ }
28
+
29
+ /**
30
+ * Decide which role a prompt belongs to.
31
+ * Overrides: #self (no routing), #<role>, @<model>. Otherwise keyword scoring; ties go to ROLES order.
32
+ * Returns {role, model, effort, agent, forced} or null for "no routing".
33
+ */
34
+ export function classify(prompt, rules, setup) {
35
+ if (typeof prompt !== 'string' || !prompt.trim()) return null;
36
+ const text = prompt.slice(0, MAX_SCAN);
37
+
38
+ if (/(^|\s)#self\b/i.test(text) || SELF_RE.test(text)) return null;
39
+
40
+ const tag = /(?:^|\s)#(plan|review|hard|code|write|chores)\b/i.exec(text);
41
+ if (tag) return route(tag[1].toLowerCase(), setup, true);
42
+
43
+ const at = /(?:^|\s)@(fable|opus|sonnet|haiku)\b/i.exec(text) || PLAIN_MODEL_RE.exec(text);
44
+ if (at) {
45
+ const model = at[1].toLowerCase();
46
+ const byActive = ROLES.find(r => setup[r]?.model === model);
47
+ if (byActive) return route(byActive, setup, true);
48
+ const byDefault = ROLES.find(r => DEFAULT_SETUP[r].model === model) || 'code';
49
+ return route(byDefault, setup, true, model);
50
+ }
51
+
52
+ const res = compile(rules);
53
+ let best = null;
54
+ let bestScore = 0;
55
+ for (const role of ROLES) {
56
+ const score = res[role].reduce((n, re) => n + (re.test(text) ? 1 : 0), 0);
57
+ if (score > bestScore) { best = role; bestScore = score; }
58
+ }
59
+ return best ? route(best, setup, false) : null;
60
+ }
61
+
62
+ /** One-line note injected into the main chat. */
63
+ export function note(r, mainModel = 'fable') {
64
+ if (r.role === 'plan' && r.model === mainModel) {
65
+ return `Switchboard: "plan" work → handle it yourself (${mainModel}).`;
66
+ }
67
+ return `Switchboard: "${r.role}" work → delegate to the ${r.agent} agent (${r.model}, ${r.effort}). Required: do this work through the Agent tool with subagent_type "${r.agent}" instead of doing it yourself; if the request mixes kinds of work, split it across router helpers.`;
68
+ }
@@ -0,0 +1,125 @@
1
+ // Roles in tie-break order: most capable first.
2
+ export const ROLES = ['plan', 'review', 'hard', 'code', 'write', 'chores'];
3
+ export const MODELS = ['fable', 'opus', 'sonnet', 'haiku'];
4
+ export const EFFORTS = ['low', 'medium', 'high', 'xhigh', 'max'];
5
+
6
+ export const DEFAULT_SETUP = {
7
+ plan: { model: 'fable', effort: 'xhigh' },
8
+ review: { model: 'fable', effort: 'high' },
9
+ hard: { model: 'opus', effort: 'high' },
10
+ code: { model: 'sonnet', effort: 'medium' },
11
+ write: { model: 'sonnet', effort: 'medium' },
12
+ chores: { model: 'haiku', effort: 'low' },
13
+ };
14
+
15
+ export const ROLE_INFO = {
16
+ plan: 'Planning, architecture, big decisions',
17
+ review: 'Code review',
18
+ hard: 'Hard code, UI work, debugging',
19
+ code: 'Regular code, tests, refactors',
20
+ write: 'Prose people read: PRs, Slack, docs, tickets',
21
+ chores: 'Git ops, renames, formatting, lookups, commit messages',
22
+ };
23
+
24
+ // Case-insensitive regex sources; each pattern that matches adds 1 to the role's score.
25
+ // Rules key on what the user asks for (a verb plus its object), not on nouns that merely appear.
26
+ export const DEFAULT_RULES = {
27
+ plan: [
28
+ "^\\W*(let'?s |can you |could you |please |help me )?plan\\b",
29
+ '\\b(make|write|draft) (a|the) plan\\b',
30
+ '\\bplan (out|for how|how)\\b',
31
+ '\\barchitect',
32
+ 'design doc',
33
+ 'trade-?offs?',
34
+ 'roadmap',
35
+ '\\brfc\\b',
36
+ 'how should (we|i) (build|structure|design|approach|organi[sz]e)',
37
+ "what'?s the best (approach|way) to",
38
+ 'strategy for',
39
+ ],
40
+ review: [
41
+ '^\\W*(please |can you |could you )?review\\b',
42
+ '\\breview (this|the|my|our|these|that|pr|diff|code|changes|branch)\\b',
43
+ 'code review',
44
+ '\\baudit\\b',
45
+ 'look over (my|this|the)',
46
+ 'check (my|this|the) (code|pr|diff) for',
47
+ 'is there (a|any) (bug|issue|problem)s? (in|with)',
48
+ ],
49
+ hard: [
50
+ '\\bdebug',
51
+ '\\bcrash',
52
+ '\\brace( condition)?\\b',
53
+ '\\bflaky',
54
+ 'stack ?trace',
55
+ 'regression',
56
+ 'root cause',
57
+ 'why (is|does|did)\\b.*\\b(fail|break|crash|hang|freeze)',
58
+ '\\bui\\b',
59
+ '\\bscreens?\\b',
60
+ '\\blayout',
61
+ 'animation',
62
+ 'swiftui',
63
+ 'jetpack compose',
64
+ 'memory leak',
65
+ 'deadlock',
66
+ '\\b(performance|too slow)\\b',
67
+ ],
68
+ code: [
69
+ '\\bimplement',
70
+ 'execute (the|this|our) plan',
71
+ '^\\W*(please )?(add|create|build|make)\\b',
72
+ '\\badd (a |an |the )?(new )?\\w+ (to|for|in)\\b',
73
+ 'write (a |an |the )?(function|test|class|script|migration)',
74
+ '\\bfix\\b',
75
+ '\\brefactor',
76
+ '\\bbug\\b',
77
+ 'unit tests?',
78
+ 'address (the )?(review )?comments',
79
+ '\\b(pick up|start on|work on)\\b',
80
+ '\\bupdate (the )?\\w+( \\w+)? (field|model|function|method|class|component|endpoint|view)\\b',
81
+ '\\bformat (the )?\\S+( \\S+)? as\\b',
82
+ ],
83
+ write: [
84
+ 'pr description',
85
+ '\\bslack\\b',
86
+ '\\b(write|draft|compose) (a |an |the )?(short )?(reply|email|message|post|announcement|update)\\b',
87
+ '\\breply to (the |this |his |her |their )?(slack|thread|email|message|comment)',
88
+ '\\breadme\\b',
89
+ 'documentation',
90
+ '\\b(write|draft|update) (the )?docs\\b',
91
+ 'release notes',
92
+ 'daily update',
93
+ 'confluence (page|doc)',
94
+ '(write|draft) (a |the )?(jira )?ticket',
95
+ 'write ?up\\b',
96
+ ],
97
+ chores: [
98
+ 'commit message',
99
+ '\\brename',
100
+ '\\b(run|fix) (the )?(formatter|linter|lint|prettier|swiftformat|swiftlint|eslint)',
101
+ '\\blint\\b',
102
+ '\\bformat (the )?(code|files?|project)\\b',
103
+ 'move (the )?files?',
104
+ 'bump (the )?version',
105
+ 'git (status|log|add|stash|diff|branch)',
106
+ 'look ?up\\b',
107
+ '^\\W*(where is|which (file|line))',
108
+ 'find (the )?(files?|lines?) (that|where|with|containing)',
109
+ 'list (all |the )?files',
110
+ 'summari[sz]e',
111
+ ],
112
+ };
113
+
114
+ export const AGENT_PREFIX = 'switchboard:router-';
115
+
116
+ export function agentName(role) {
117
+ return AGENT_PREFIX + role;
118
+ }
119
+
120
+ /** Map an Agent tool subagent_type to a role, accepting namespaced or bare names. */
121
+ export function roleFromAgent(subagentType) {
122
+ if (typeof subagentType !== 'string') return null;
123
+ const m = /^(?:switchboard:)?router-([a-z]+)$/.exec(subagentType);
124
+ return m && ROLES.includes(m[1]) ? m[1] : null;
125
+ }
@@ -0,0 +1,92 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { roleFromAgent } from './defaults.js';
4
+ import { classify, note } from './classify.js';
5
+ import * as store from './store.js';
6
+ import { detectMainModel } from './transcript.js';
7
+
8
+ export const SESSION_RULE =
9
+ 'Switchboard (installed by the user) routes work by model. When a prompt carries a "Switchboard:" routing note, ' +
10
+ 'that note is the user\'s standing instruction: hand the work to the named switchboard:router-* agent with the Agent tool, ' +
11
+ 'even for small or quick tasks, and relay its result. Do it yourself only when the note says so, when the user writes #self, ' +
12
+ 'or when the user explicitly asks you to. Never pass model or effort to these agents; Switchboard sets them.';
13
+
14
+ /** SessionStart: one standing rule so routing notes are treated as the user's instruction. */
15
+ export function handleSessionStart(payload) {
16
+ try { store.clearRunning(payload?.session_id); } catch { /* best effort */ }
17
+ if (!store.sessionEnabled(payload?.session_id)) return null;
18
+ return { hookSpecificOutput: { hookEventName: 'SessionStart', additionalContext: SESSION_RULE } };
19
+ }
20
+
21
+ /** UserPromptSubmit: classify and inject a one-line routing note. */
22
+ export function handlePrompt(payload) {
23
+ const sid = payload?.session_id;
24
+ if (!store.sessionEnabled(sid)) return null;
25
+ // The user switched the main chat's model by hand (/model): step aside until they switch back.
26
+ const detected = detectMainModel(payload?.transcript_path);
27
+ if (detected && detected !== store.mainModel()) {
28
+ store.updateState(sid, s => { s.manual = detected; s.last_route = null; s.forced = null; });
29
+ return null;
30
+ }
31
+ const setup = store.activeSetup();
32
+ const r = classify(payload?.prompt, store.loadRules(), setup);
33
+ store.updateState(sid, s => {
34
+ s.manual = null;
35
+ s.last_route = r ? r.role : null;
36
+ // A forced model outside the setup is honoured for the next helper of that role only.
37
+ s.forced = r && r.model !== setup[r.role].model ? { role: r.role, model: r.model } : null;
38
+ });
39
+ if (!r) return null;
40
+ return { hookSpecificOutput: { hookEventName: 'UserPromptSubmit', additionalContext: note(r, store.mainModel()) } };
41
+ }
42
+
43
+ /** PreToolUse(Agent|Task): force router helpers onto the active setup's model and effort. */
44
+ export function handleAgentPre(payload) {
45
+ const input = payload?.tool_input;
46
+ const role = roleFromAgent(input?.subagent_type);
47
+ if (!role) return null;
48
+ const sid = payload.session_id;
49
+ if (store.readState(sid).manual) return null;
50
+ let { model, effort } = store.activeSetup()[role];
51
+ const forced = store.readState(sid).forced;
52
+ if (forced?.role === role) {
53
+ model = forced.model;
54
+ store.updateState(sid, s => { s.forced = null; });
55
+ }
56
+ store.addRunning(sid, payload.tool_use_id || `t${Date.now()}`, `${role}→${model}`);
57
+ return {
58
+ hookSpecificOutput: {
59
+ hookEventName: 'PreToolUse',
60
+ permissionDecision: 'allow',
61
+ permissionDecisionReason: `Switchboard: ${role} → ${model} (${effort})`,
62
+ updatedInput: { ...input, model, effort },
63
+ },
64
+ };
65
+ }
66
+
67
+ /** PostToolUse(Agent|Task): the helper is done. */
68
+ export function handleAgentPost(payload) {
69
+ if (!roleFromAgent(payload?.tool_input?.subagent_type) || !payload?.tool_use_id) return null;
70
+ store.removeRunning(payload.session_id, payload.tool_use_id);
71
+ return null;
72
+ }
73
+
74
+ /** Read hook JSON from stdin, run the handler, print its output. Never throws, always exits 0. */
75
+ export function runHook(handler) {
76
+ let raw = '';
77
+ process.stdin.setEncoding('utf8');
78
+ process.stdin.on('data', d => { raw += d; });
79
+ process.stdin.on('end', () => {
80
+ try {
81
+ const out = handler(JSON.parse(raw));
82
+ if (out) process.stdout.write(JSON.stringify(out));
83
+ } catch (e) {
84
+ try {
85
+ fs.mkdirSync(store.home(), { recursive: true });
86
+ fs.appendFileSync(path.join(store.home(), 'error.log'),
87
+ `${new Date().toISOString()} ${handler.name}: ${e?.stack || e}\n`);
88
+ } catch { /* nothing else we can do */ }
89
+ }
90
+ process.exitCode = 0;
91
+ });
92
+ }
@@ -0,0 +1,11 @@
1
+ import * as store from './store.js';
2
+
3
+ /** Status line segment: "⇢ <setup>" plus running helpers, or "⇢ off". */
4
+ export function statusSegment(sessionId) {
5
+ if (!store.sessionEnabled(sessionId)) return '⇢ off';
6
+ const manual = store.readState(sessionId).manual;
7
+ if (manual) return `⇢ manual (${manual})`;
8
+ const base = `⇢ ${store.activeName()}`;
9
+ const running = Object.values(store.readState(sessionId).running || {});
10
+ return running.length ? `${base} · ${running.join(', ')}` : base;
11
+ }
@@ -0,0 +1,249 @@
1
+ import fs from 'node:fs';
2
+ import os from 'node:os';
3
+ import path from 'node:path';
4
+ import { ROLES, MODELS, EFFORTS, DEFAULT_SETUP, DEFAULT_RULES } from './defaults.js';
5
+
6
+ const DAY_MS = 24 * 3600 * 1000;
7
+
8
+ export function home() {
9
+ return process.env.SWITCHBOARD_HOME || path.join(os.homedir(), '.claude', 'switchboard');
10
+ }
11
+
12
+ function file(name) {
13
+ return path.join(home(), name);
14
+ }
15
+
16
+ function writeJson(name, data) {
17
+ fs.mkdirSync(home(), { recursive: true });
18
+ const target = file(name);
19
+ const tmp = `${target}.tmp-${process.pid}-${Math.random().toString(36).slice(2)}`;
20
+ fs.writeFileSync(tmp, JSON.stringify(data, null, 2) + '\n');
21
+ fs.renameSync(tmp, target);
22
+ }
23
+
24
+ /** Read JSON; on a missing file create it from fallback(); on corrupt JSON back it up first. */
25
+ function readJson(name, fallback, valid = () => true) {
26
+ const target = file(name);
27
+ let raw;
28
+ try {
29
+ raw = fs.readFileSync(target, 'utf8');
30
+ } catch {
31
+ const d = fallback();
32
+ writeJson(name, d);
33
+ return d;
34
+ }
35
+ try {
36
+ const d = JSON.parse(raw);
37
+ if (valid(d)) return d;
38
+ } catch { /* fall through */ }
39
+ fs.copyFileSync(target, `${target}.bak`);
40
+ const d = fallback();
41
+ writeJson(name, d);
42
+ return d;
43
+ }
44
+
45
+ const defaultSetups = () => ({ active: 'default', enabled: true, setups: { default: structuredClone(DEFAULT_SETUP) } });
46
+ const isObj = v => v && typeof v === 'object' && !Array.isArray(v);
47
+
48
+ export function loadSetups() {
49
+ const d = readJson('setups.json', defaultSetups, v => isObj(v) && isObj(v.setups));
50
+ if (!d.setups[d.active]) d.active = Object.keys(d.setups)[0] || 'default';
51
+ if (!d.setups[d.active]) d.setups[d.active] = structuredClone(DEFAULT_SETUP);
52
+ if (typeof d.enabled !== 'boolean') d.enabled = true;
53
+ if (!MODELS.includes(d.main_model)) d.main_model = 'fable';
54
+ return d;
55
+ }
56
+
57
+ /** The model the main chat is configured to run on. SWITCHBOARD_MAIN_MODEL overrides setups.json. */
58
+ export function mainModel() {
59
+ const env = process.env.SWITCHBOARD_MAIN_MODEL;
60
+ return MODELS.includes(env) ? env : loadSetups().main_model;
61
+ }
62
+
63
+ export function saveSetups(d) {
64
+ writeJson('setups.json', d);
65
+ }
66
+
67
+ function filled(setup) {
68
+ const out = {};
69
+ for (const r of ROLES) {
70
+ const s = isObj(setup?.[r]) ? setup[r] : {};
71
+ out[r] = {
72
+ model: MODELS.includes(s.model) ? s.model : DEFAULT_SETUP[r].model,
73
+ effort: EFFORTS.includes(s.effort) ? s.effort : DEFAULT_SETUP[r].effort,
74
+ };
75
+ }
76
+ return out;
77
+ }
78
+
79
+ export function activeSetup() {
80
+ const d = loadSetups();
81
+ return filled(d.setups[d.active]);
82
+ }
83
+
84
+ export function activeName() {
85
+ return loadSetups().active;
86
+ }
87
+
88
+ export function setRole(role, model, effort) {
89
+ if (!ROLES.includes(role)) throw new Error(`unknown role "${role}" (roles: ${ROLES.join(', ')})`);
90
+ if (!MODELS.includes(model)) throw new Error(`unknown model "${model}" (models: ${MODELS.join(', ')})`);
91
+ if (effort !== undefined && !EFFORTS.includes(effort)) throw new Error(`unknown effort "${effort}" (efforts: ${EFFORTS.join(', ')})`);
92
+ const d = loadSetups();
93
+ const s = filled(d.setups[d.active]);
94
+ s[role] = { model, effort: effort ?? s[role].effort };
95
+ d.setups[d.active] = s;
96
+ saveSetups(d);
97
+ }
98
+
99
+ const NAME_RE = /^[\w.-]{1,40}$/;
100
+
101
+ export function saveAs(name) {
102
+ if (!NAME_RE.test(name)) throw new Error(`invalid setup name "${name}" (letters, digits, - _ . ; max 40)`);
103
+ const d = loadSetups();
104
+ d.setups[name] = filled(d.setups[d.active]);
105
+ d.active = name;
106
+ saveSetups(d);
107
+ }
108
+
109
+ export function use(name) {
110
+ const d = loadSetups();
111
+ if (!Object.hasOwn(d.setups, name)) throw new Error(`no setup named "${name}" (have: ${Object.keys(d.setups).join(', ')})`);
112
+ d.active = name;
113
+ saveSetups(d);
114
+ }
115
+
116
+ export function remove(name) {
117
+ const d = loadSetups();
118
+ if (!Object.hasOwn(d.setups, name)) throw new Error(`no setup named "${name}"`);
119
+ if (d.active === name) throw new Error(`"${name}" is the active setup; switch to another one first`);
120
+ delete d.setups[name];
121
+ saveSetups(d);
122
+ }
123
+
124
+ export function listSetups() {
125
+ const d = loadSetups();
126
+ return { active: d.active, names: Object.keys(d.setups) };
127
+ }
128
+
129
+ export function loadRules() {
130
+ const d = readJson('rules.json', () => structuredClone(DEFAULT_RULES),
131
+ v => isObj(v) && ROLES.every(r => v[r] === undefined || (Array.isArray(v[r]) && v[r].every(x => typeof x === 'string'))));
132
+ const out = {};
133
+ for (const r of ROLES) out[r] = d[r] || DEFAULT_RULES[r];
134
+ return out;
135
+ }
136
+
137
+ // ---- per-session state ----
138
+ // sessions/<sid>/session.json holds enabled / last_route / forced.
139
+ // sessions/<sid>/running/<tool_use_id>.json is one file per running helper, so parallel hooks never clobber each other.
140
+
141
+ const RUNNING_TTL_MS = 30 * 60 * 1000;
142
+
143
+ function safe(id) {
144
+ return encodeURIComponent(String(id)).replace(/\./g, '%2E').slice(0, 200);
145
+ }
146
+
147
+ function sessionDir(sessionId) {
148
+ return path.join(home(), 'sessions', safe(sessionId));
149
+ }
150
+
151
+ function pruneSessions() {
152
+ const root = path.join(home(), 'sessions');
153
+ let names = [];
154
+ try { names = fs.readdirSync(root); } catch { return; }
155
+ const now = Date.now();
156
+ for (const n of names) {
157
+ const dir = path.join(root, n);
158
+ try {
159
+ if (now - fs.statSync(dir).mtimeMs > DAY_MS) fs.rmSync(dir, { recursive: true, force: true });
160
+ } catch { /* another process got there first */ }
161
+ }
162
+ }
163
+
164
+ function readRunning(sessionId) {
165
+ const dir = path.join(sessionDir(sessionId), 'running');
166
+ const out = {};
167
+ let files = [];
168
+ try { files = fs.readdirSync(dir).filter(f => f.endsWith('.json')).sort(); } catch { return out; }
169
+ const now = Date.now();
170
+ const entries = [];
171
+ for (const f of files) {
172
+ const full = path.join(dir, f);
173
+ try {
174
+ const st = fs.statSync(full);
175
+ if (now - st.mtimeMs > RUNNING_TTL_MS) { fs.rmSync(full, { force: true }); continue; }
176
+ const d = JSON.parse(fs.readFileSync(full, 'utf8'));
177
+ entries.push([st.mtimeMs, d.id, d.label]);
178
+ } catch { /* half-written or just removed */ }
179
+ }
180
+ entries.sort((a, b) => a[0] - b[0]);
181
+ for (const [, id, label] of entries) out[id] = label;
182
+ return out;
183
+ }
184
+
185
+ export function readState(sessionId) {
186
+ if (!sessionId) return {};
187
+ let s = {};
188
+ try {
189
+ const d = JSON.parse(fs.readFileSync(path.join(sessionDir(sessionId), 'session.json'), 'utf8'));
190
+ if (isObj(d)) s = d;
191
+ } catch { /* none yet */ }
192
+ const running = readRunning(sessionId);
193
+ if (Object.keys(running).length) s.running = running;
194
+ return s;
195
+ }
196
+
197
+ export function updateState(sessionId, fn) {
198
+ if (!sessionId) return;
199
+ pruneSessions();
200
+ const dir = sessionDir(sessionId);
201
+ fs.mkdirSync(dir, { recursive: true });
202
+ const f = path.join(dir, 'session.json');
203
+ let s = {};
204
+ try { const d = JSON.parse(fs.readFileSync(f, 'utf8')); if (isObj(d)) s = d; } catch { /* new */ }
205
+ fn(s);
206
+ delete s.running;
207
+ s.ts = Date.now();
208
+ const tmp = `${f}.tmp-${process.pid}-${Math.random().toString(36).slice(2)}`;
209
+ fs.writeFileSync(tmp, JSON.stringify(s));
210
+ fs.renameSync(tmp, f);
211
+ const now = new Date();
212
+ fs.utimesSync(dir, now, now);
213
+ }
214
+
215
+ export function addRunning(sessionId, toolUseId, label) {
216
+ if (!sessionId) return;
217
+ const dir = path.join(sessionDir(sessionId), 'running');
218
+ fs.mkdirSync(dir, { recursive: true });
219
+ const f = path.join(dir, `${safe(toolUseId)}.json`);
220
+ const tmp = `${f}.tmp-${process.pid}`;
221
+ fs.writeFileSync(tmp, JSON.stringify({ id: toolUseId, label }));
222
+ fs.renameSync(tmp, f);
223
+ }
224
+
225
+ export function removeRunning(sessionId, toolUseId) {
226
+ if (!sessionId) return;
227
+ fs.rmSync(path.join(sessionDir(sessionId), 'running', `${safe(toolUseId)}.json`), { force: true });
228
+ }
229
+
230
+ export function clearRunning(sessionId) {
231
+ if (!sessionId) return;
232
+ fs.rmSync(path.join(sessionDir(sessionId), 'running'), { recursive: true, force: true });
233
+ }
234
+
235
+ export function sessionEnabled(sessionId) {
236
+ const s = readState(sessionId);
237
+ if (typeof s.enabled === 'boolean') return s.enabled;
238
+ return loadSetups().enabled;
239
+ }
240
+
241
+ export function setEnabled(on, sessionId) {
242
+ if (sessionId) {
243
+ updateState(sessionId, s => { s.enabled = on; });
244
+ return;
245
+ }
246
+ const d = loadSetups();
247
+ d.enabled = on;
248
+ saveSetups(d);
249
+ }
@@ -0,0 +1,34 @@
1
+ import fs from 'node:fs';
2
+
3
+ const TAIL_BYTES = 256 * 1024;
4
+ const COMMAND_RE = /(?:Set|Kept) model (?:to|as) `(Fable|Opus|Sonnet|Haiku)\b/gi;
5
+ const ASSISTANT_RE = /"model":"claude-(fable|opus|sonnet|haiku)-/g;
6
+
7
+ function lastMatch(re, text) {
8
+ let last = null;
9
+ re.lastIndex = 0;
10
+ for (let m = re.exec(text); m; m = re.exec(text)) last = m;
11
+ return last;
12
+ }
13
+
14
+ /** Which model family is the main chat on? Reads only the tail of the transcript; null if unknown. */
15
+ export function detectMainModel(transcriptPath) {
16
+ if (typeof transcriptPath !== 'string' || !transcriptPath) return null;
17
+ let fd;
18
+ try {
19
+ fd = fs.openSync(transcriptPath, 'r');
20
+ const size = fs.fstatSync(fd).size;
21
+ const len = Math.min(size, TAIL_BYTES);
22
+ const buf = Buffer.alloc(len);
23
+ fs.readSync(fd, buf, 0, len, size - len);
24
+ const text = buf.toString('utf8');
25
+ const a = lastMatch(COMMAND_RE, text);
26
+ const b = lastMatch(ASSISTANT_RE, text);
27
+ const pick = a && b ? (a.index > b.index ? a : b) : a || b;
28
+ return pick ? pick[1].toLowerCase() : null;
29
+ } catch {
30
+ return null;
31
+ } finally {
32
+ if (fd !== undefined) try { fs.closeSync(fd); } catch { /* ignore */ }
33
+ }
34
+ }
@@ -0,0 +1,136 @@
1
+ import React, { useState } from 'react';
2
+ import { render, Box, Text, useInput, useApp } from 'ink';
3
+ import { ROLES, MODELS, EFFORTS, ROLE_INFO } from '../core/defaults.js';
4
+ import * as store from '../core/store.js';
5
+
6
+ const h = React.createElement;
7
+
8
+ const MODEL_COLOR = { fable: 'magentaBright', opus: 'yellowBright', sonnet: 'cyanBright', haiku: 'greenBright' };
9
+ const EFFORT_BAR = e => '●'.repeat(EFFORTS.indexOf(e) + 1) + '○'.repeat(EFFORTS.length - EFFORTS.indexOf(e) - 1);
10
+ const cycle = (list, value, step) => list[(list.indexOf(value) + step + list.length) % list.length];
11
+
12
+ function snapshot() {
13
+ const d = store.loadSetups();
14
+ return { setup: store.activeSetup(), active: d.active, names: Object.keys(d.setups), enabled: d.enabled };
15
+ }
16
+
17
+ function Header({ s }) {
18
+ return h(Box, { borderStyle: 'round', borderColor: 'gray', paddingX: 1, justifyContent: 'space-between' },
19
+ h(Text, null, h(Text, { bold: true, color: 'whiteBright' }, '⇢ Switchboard'), h(Text, { color: 'gray' }, ' model routing for Claude Code')),
20
+ h(Text, null,
21
+ h(Text, { color: 'gray' }, 'setup '), h(Text, { bold: true, color: 'blueBright' }, s.active),
22
+ h(Text, { color: 'gray' }, ' routing '),
23
+ h(Text, { bold: true, color: s.enabled ? 'greenBright' : 'redBright' }, s.enabled ? 'ON' : 'OFF')));
24
+ }
25
+
26
+ function RoleTable({ s, cursor }) {
27
+ return h(Box, { flexDirection: 'column', paddingX: 1, marginTop: 1 },
28
+ h(Box, null,
29
+ h(Box, { width: 3 }), h(Box, { width: 10 }, h(Text, { color: 'gray' }, 'ROLE')),
30
+ h(Box, { width: 12 }, h(Text, { color: 'gray' }, 'MODEL')),
31
+ h(Box, { width: 16 }, h(Text, { color: 'gray' }, 'EFFORT')),
32
+ h(Text, { color: 'gray' }, 'HANDLES')),
33
+ ...ROLES.map((r, i) => {
34
+ const sel = i === cursor;
35
+ const { model, effort } = s.setup[r];
36
+ return h(Box, { key: r },
37
+ h(Box, { width: 3 }, h(Text, { color: 'blueBright' }, sel ? '❯' : ' ')),
38
+ h(Box, { width: 10 }, h(Text, { bold: sel, color: sel ? 'whiteBright' : undefined }, r)),
39
+ h(Box, { width: 12 }, h(Text, { color: MODEL_COLOR[model], bold: true }, sel ? `‹ ${model} ›` : ` ${model}`)),
40
+ h(Box, { width: 16 }, h(Text, { color: sel ? 'whiteBright' : 'gray' }, `${EFFORT_BAR(effort)} ${effort}`)),
41
+ h(Text, { color: 'gray', wrap: 'truncate' }, ROLE_INFO[r]));
42
+ }));
43
+ }
44
+
45
+ function Footer({ mode, input, s, listCursor, toast }) {
46
+ const key = (k, label) => h(Text, null, h(Text, { color: 'blueBright', bold: true }, k), h(Text, { color: 'gray' }, ` ${label} `));
47
+ let body;
48
+ if (mode === 'save') {
49
+ body = h(Text, null, h(Text, { color: 'gray' }, 'Save setup as: '), h(Text, { color: 'whiteBright' }, input), h(Text, { color: 'blueBright' }, '█'),
50
+ h(Text, { color: 'gray' }, ' enter save · esc cancel'));
51
+ } else if (mode === 'load' || mode === 'delete') {
52
+ body = h(Box, { flexDirection: 'column' },
53
+ h(Text, { color: 'gray' }, mode === 'load' ? 'Load setup (enter load · esc cancel):' : 'Delete setup (enter delete · esc cancel):'),
54
+ ...s.names.map((n, i) => h(Text, { key: n },
55
+ h(Text, { color: 'blueBright' }, i === listCursor ? '❯ ' : ' '),
56
+ h(Text, { color: n === s.active ? 'blueBright' : undefined, bold: i === listCursor }, n),
57
+ n === s.active ? h(Text, { color: 'gray' }, ' (active)') : null)));
58
+ } else {
59
+ body = h(Text, null, key('↑↓', 'role'), key('←→', 'model'), key('e', 'effort'), key('s', 'save'), key('l', 'load'),
60
+ key('d', 'delete'), key('t', 'on/off'), key('q', 'quit'));
61
+ }
62
+ return h(Box, { flexDirection: 'column', paddingX: 1, marginTop: 1 },
63
+ body,
64
+ toast ? h(Text, { color: toast.error ? 'redBright' : 'greenBright' }, toast.text) : h(Text, null, ' '));
65
+ }
66
+
67
+ function App() {
68
+ const { exit } = useApp();
69
+ const [s, setS] = useState(snapshot);
70
+ const [cursor, setCursor] = useState(0);
71
+ const [mode, setMode] = useState('main');
72
+ const [input, setInput] = useState('');
73
+ const [listCursor, setListCursor] = useState(0);
74
+ const [toast, setToast] = useState(null);
75
+
76
+ const act = (fn, ok) => {
77
+ try {
78
+ fn();
79
+ setS(snapshot());
80
+ setToast(ok ? { text: ok } : null);
81
+ } catch (e) {
82
+ setToast({ text: e.message, error: true });
83
+ }
84
+ };
85
+
86
+ useInput((ch, key) => {
87
+ if (mode === 'save') {
88
+ if (key.escape) { setMode('main'); setInput(''); return; }
89
+ if (key.return) {
90
+ const name = input.trim();
91
+ act(() => store.saveAs(name), `Saved as "${name}"`);
92
+ setMode('main'); setInput('');
93
+ return;
94
+ }
95
+ if (key.backspace || key.delete) { setInput(v => v.slice(0, -1)); return; }
96
+ if (ch && !key.ctrl && !key.meta) setInput(v => (v + ch).slice(0, 40));
97
+ return;
98
+ }
99
+ if (mode === 'load' || mode === 'delete') {
100
+ if (key.escape || ch === 'q') { setMode('main'); return; }
101
+ if (key.upArrow) setListCursor(i => Math.max(0, i - 1));
102
+ if (key.downArrow) setListCursor(i => Math.min(s.names.length - 1, i + 1));
103
+ if (key.return) {
104
+ const name = s.names[listCursor];
105
+ if (mode === 'load') act(() => store.use(name), `Loaded "${name}"`);
106
+ else act(() => store.remove(name), `Deleted "${name}"`);
107
+ setMode('main');
108
+ }
109
+ return;
110
+ }
111
+ const role = ROLES[cursor];
112
+ const cur = s.setup[role];
113
+ if (ch === 'q' || key.escape || (key.ctrl && ch === 'c')) { exit(); return; }
114
+ if (key.upArrow || ch === 'k') setCursor(i => (i + ROLES.length - 1) % ROLES.length);
115
+ else if (key.downArrow || ch === 'j') setCursor(i => (i + 1) % ROLES.length);
116
+ else if (key.rightArrow) act(() => store.setRole(role, cycle(MODELS, cur.model, 1)));
117
+ else if (key.leftArrow) act(() => store.setRole(role, cycle(MODELS, cur.model, -1)));
118
+ else if (ch === 'e') act(() => store.setRole(role, cur.model, cycle(EFFORTS, cur.effort, 1)));
119
+ else if (ch === 'E') act(() => store.setRole(role, cur.model, cycle(EFFORTS, cur.effort, -1)));
120
+ else if (ch === 's') { setMode('save'); setInput(''); setToast(null); }
121
+ else if (ch === 'l') { setMode('load'); setListCursor(Math.max(0, s.names.indexOf(s.active))); setToast(null); }
122
+ else if (ch === 'd') { setMode('delete'); setListCursor(0); setToast(null); }
123
+ else if (ch === 't') act(() => store.setEnabled(!s.enabled), `Routing ${s.enabled ? 'OFF' : 'ON'}`);
124
+ });
125
+
126
+ return h(Box, { flexDirection: 'column' },
127
+ h(Header, { s }),
128
+ h(RoleTable, { s, cursor }),
129
+ h(Footer, { mode, input, s, listCursor, toast }),
130
+ h(Text, { color: 'gray', dimColor: true }, ' Changes save instantly and apply to the next helper Claude starts.'));
131
+ }
132
+
133
+ export async function runPicker() {
134
+ const app = render(h(App));
135
+ await app.waitUntilExit();
136
+ }