cc-switchboard 0.0.0-stage → 0.2.10
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.
- package/.claude-plugin/marketplace.json +14 -0
- package/.claude-plugin/plugin.json +21 -0
- package/LICENSE +21 -0
- package/README.md +86 -2
- package/bin/switchboard.js +4 -0
- package/hooks/config.ts +79 -0
- package/hooks/hooks.json +1 -0
- package/hooks/switchboard.tsx +417 -0
- package/package.json +47 -4
- package/src/cli.js +105 -0
- package/src/core/classify.js +75 -0
- package/src/core/defaults.js +125 -0
- package/src/core/store.js +249 -0
- package/src/picker/app.js +136 -0
- package/types/index.d.ts +42 -0
package/package.json
CHANGED
|
@@ -1,6 +1,49 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "cc-switchboard",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.2.10",
|
|
4
|
+
"description": "Per-turn model routing for Claude Code: each prompt runs on the right model and effort, with a band above the prompt and a /router pane.",
|
|
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
|
+
"types",
|
|
34
|
+
".claude-plugin",
|
|
35
|
+
"README.md",
|
|
36
|
+
"LICENSE",
|
|
37
|
+
"!hooks/*.test.tsx"
|
|
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,105 @@
|
|
|
1
|
+
import { ROLES, ROLE_INFO } from './core/defaults.js';
|
|
2
|
+
import * as store from './core/store.js';
|
|
3
|
+
|
|
4
|
+
const USAGE = `Usage: switchboard [command]
|
|
5
|
+
|
|
6
|
+
(no command) open the interactive picker (terminal only)
|
|
7
|
+
show show the active setup
|
|
8
|
+
list list saved setups (* = active)
|
|
9
|
+
use <setup> switch to a saved setup
|
|
10
|
+
set <role> <model> [effort] change one role in the active setup
|
|
11
|
+
save <name> save the active setup under a new name and switch to it
|
|
12
|
+
delete <setup> delete a saved setup
|
|
13
|
+
on | off turn routing on/off everywhere (in a session: /router off)
|
|
14
|
+
|
|
15
|
+
Roles: ${ROLES.join(', ')}
|
|
16
|
+
Models: fable, opus, sonnet, haiku Efforts: low, medium, high, xhigh, max
|
|
17
|
+
`;
|
|
18
|
+
|
|
19
|
+
function takeSession(argv) {
|
|
20
|
+
const args = [...argv];
|
|
21
|
+
let session = null;
|
|
22
|
+
const i = args.indexOf('--session');
|
|
23
|
+
if (i !== -1) {
|
|
24
|
+
const v = args[i + 1];
|
|
25
|
+
session = v && !v.startsWith('-') ? v : null;
|
|
26
|
+
args.splice(i, v !== undefined && !v.startsWith('-') ? 2 : 1);
|
|
27
|
+
}
|
|
28
|
+
return { args: args.filter(a => a !== ''), session, sessionFlag: i !== -1 };
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function showText(session) {
|
|
32
|
+
const s = store.activeSetup();
|
|
33
|
+
const on = session ? store.sessionEnabled(session) : store.loadSetups().enabled;
|
|
34
|
+
const lines = [`Setup: ${store.activeName()}${on ? '' : ' (routing OFF' + (session ? ' for this session' : '') + ')'}`, ''];
|
|
35
|
+
for (const r of ROLES) {
|
|
36
|
+
lines.push(`${r.padEnd(8)} ${s[r].model.padEnd(8)} ${s[r].effort.padEnd(7)} ${ROLE_INFO[r]}`);
|
|
37
|
+
}
|
|
38
|
+
if (process.env.CLAUDE_CODE_SUBAGENT_MODEL) {
|
|
39
|
+
lines.push('', `Warning: CLAUDE_CODE_SUBAGENT_MODEL=${process.env.CLAUDE_CODE_SUBAGENT_MODEL} is set and overrides every helper's model.`);
|
|
40
|
+
}
|
|
41
|
+
return lines.join('\n') + '\n';
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** Run the CLI. io = {stdout, stderr, isTTY}. Returns the exit code. */
|
|
45
|
+
export async function main(argv, io = { stdout: process.stdout, stderr: process.stderr, isTTY: process.stdout.isTTY && process.stdin.isTTY }) {
|
|
46
|
+
const { args, session, sessionFlag } = takeSession(argv);
|
|
47
|
+
const [cmd, ...rest] = args;
|
|
48
|
+
const out = s => io.stdout.write(s);
|
|
49
|
+
try {
|
|
50
|
+
switch (cmd) {
|
|
51
|
+
case undefined:
|
|
52
|
+
if (io.isTTY) {
|
|
53
|
+
const { runPicker } = await import('./picker/app.js');
|
|
54
|
+
await runPicker();
|
|
55
|
+
return 0;
|
|
56
|
+
}
|
|
57
|
+
out(showText(session));
|
|
58
|
+
return 0;
|
|
59
|
+
case 'show':
|
|
60
|
+
out(showText(session));
|
|
61
|
+
return 0;
|
|
62
|
+
case 'list': {
|
|
63
|
+
const { active, names } = store.listSetups();
|
|
64
|
+
out(names.map(n => `${n === active ? '*' : ' '} ${n}`).join('\n') + '\n');
|
|
65
|
+
return 0;
|
|
66
|
+
}
|
|
67
|
+
case 'use':
|
|
68
|
+
store.use(rest[0]);
|
|
69
|
+
out(showText(session));
|
|
70
|
+
return 0;
|
|
71
|
+
case 'set':
|
|
72
|
+
store.setRole(rest[0], rest[1], rest[2]);
|
|
73
|
+
out(showText(session));
|
|
74
|
+
return 0;
|
|
75
|
+
case 'save':
|
|
76
|
+
store.saveAs(rest[0]);
|
|
77
|
+
out(`Saved and switched to "${rest[0]}".\n`);
|
|
78
|
+
return 0;
|
|
79
|
+
case 'delete':
|
|
80
|
+
store.remove(rest[0]);
|
|
81
|
+
out(`Deleted "${rest[0]}".\n`);
|
|
82
|
+
return 0;
|
|
83
|
+
case 'on':
|
|
84
|
+
case 'off':
|
|
85
|
+
if (sessionFlag && !session) {
|
|
86
|
+
io.stderr.write('No session id was passed, so nothing changed. Use `switchboard on|off` in a terminal for a global switch.\n');
|
|
87
|
+
return 2;
|
|
88
|
+
}
|
|
89
|
+
store.setEnabled(cmd === 'on', session || undefined);
|
|
90
|
+
out(`Routing ${cmd.toUpperCase()}${session ? ' for this session' : ''}.\n`);
|
|
91
|
+
return 0;
|
|
92
|
+
case 'help':
|
|
93
|
+
case '--help':
|
|
94
|
+
case '-h':
|
|
95
|
+
out(USAGE);
|
|
96
|
+
return 0;
|
|
97
|
+
default:
|
|
98
|
+
io.stderr.write(`Unknown command "${cmd}".\n\n${USAGE}`);
|
|
99
|
+
return 2;
|
|
100
|
+
}
|
|
101
|
+
} catch (e) {
|
|
102
|
+
io.stderr.write(`${e.message}\n`);
|
|
103
|
+
return 2;
|
|
104
|
+
}
|
|
105
|
+
}
|
|
@@ -0,0 +1,75 @@
|
|
|
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, why = '') {
|
|
25
|
+
const s = setup[role] || DEFAULT_SETUP[role];
|
|
26
|
+
return { role, model: modelOverride || s.model, effort: s.effort, agent: agentName(role), forced, why };
|
|
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, why} 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, undefined, tag[0].trim());
|
|
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
|
+
const why = at[0].trim();
|
|
48
|
+
if (byActive) return route(byActive, setup, true, undefined, why);
|
|
49
|
+
const byDefault = ROLES.find(r => DEFAULT_SETUP[r].model === model) || 'code';
|
|
50
|
+
return route(byDefault, setup, true, model, why);
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
const res = compile(rules);
|
|
54
|
+
let best = null;
|
|
55
|
+
let bestScore = 0;
|
|
56
|
+
let bestWhy = '';
|
|
57
|
+
for (const role of ROLES) {
|
|
58
|
+
let score = 0;
|
|
59
|
+
let why = '';
|
|
60
|
+
for (const re of res[role]) {
|
|
61
|
+
const m = re.exec(text);
|
|
62
|
+
if (m) { score += 1; if (!why) why = m[0].trim(); }
|
|
63
|
+
}
|
|
64
|
+
if (score > bestScore) { best = role; bestScore = score; bestWhy = why; }
|
|
65
|
+
}
|
|
66
|
+
return best ? route(best, setup, false, undefined, bestWhy) : null;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** One-line note injected into the main chat. */
|
|
70
|
+
export function note(r, mainModel = 'fable') {
|
|
71
|
+
if (r.role === 'plan' && r.model === mainModel) {
|
|
72
|
+
return `Switchboard: "plan" work → handle it yourself (${mainModel}).`;
|
|
73
|
+
}
|
|
74
|
+
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.`;
|
|
75
|
+
}
|
|
@@ -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,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
|
+
}
|