@alexeiled/claude-router 0.8.0 → 1.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.
- package/.claude-plugin/plugin.json +11 -7
- package/CHANGELOG.md +43 -0
- package/README.md +55 -98
- package/docs/architecture.md +55 -419
- package/docs/configuration.md +88 -182
- package/docs/evaluation.md +62 -81
- package/docs/native-router.md +80 -0
- package/docs/router-band.svg +119 -0
- package/docs/router-pane-now.svg +85 -0
- package/docs/router-pane-tiers.svg +62 -0
- package/docs/user-guide.md +127 -172
- package/hooks/hooks.json +1 -26
- package/hooks/native-router.mjs +701 -0
- package/lib/config.mjs +97 -63
- package/lib/{facts.mjs → facts-pure.mjs} +2 -23
- package/lib/{jev.mjs → jev-contract.mjs} +17 -38
- package/lib/native-band.mjs +206 -0
- package/lib/native-cost.mjs +88 -0
- package/lib/native-display.mjs +122 -0
- package/lib/native-jev.mjs +125 -0
- package/lib/native-panel.mjs +492 -0
- package/lib/native-router.mjs +221 -0
- package/lib/policy.mjs +17 -21
- package/package.json +10 -8
- package/scripts/migrate-config.mjs +57 -0
- package/types/index.d.ts +112 -0
- package/lib/cost.mjs +0 -93
- package/lib/gateway.mjs +0 -221
- package/lib/idle.mjs +0 -41
- package/lib/rewrite.mjs +0 -130
- package/lib/router.mjs +0 -276
- package/lib/runtime.mjs +0 -78
- package/lib/sse.mjs +0 -57
- package/lib/status.mjs +0 -152
- package/lib/store.mjs +0 -76
- package/scripts/ensure-gateway.mjs +0 -143
- package/scripts/gateway.mjs +0 -81
- package/scripts/git-hooks/pre-commit +0 -41
- package/scripts/git-hooks/pre-push +0 -34
- package/scripts/status.mjs +0 -20
- package/scripts/statusline.mjs +0 -45
- package/scripts/transcript-models.sh +0 -4
- package/skills/high/SKILL.md +0 -9
- package/skills/low/SKILL.md +0 -7
- package/skills/medium/SKILL.md +0 -8
- package/skills/micro/SKILL.md +0 -7
- package/skills/setup/SKILL.md +0 -31
- package/skills/status/SKILL.md +0 -12
package/lib/runtime.mjs
DELETED
|
@@ -1,78 +0,0 @@
|
|
|
1
|
-
// Process bootstrap shared by the daemon and the hooks: configuration and data directory from the environment.
|
|
2
|
-
// A project's `.claude/settings.json` can set process env for a plugin hook (ROUTER_CONFIG, HOME, ...). `home`
|
|
3
|
-
// comes from the OS user database (`os.userInfo().homedir`), never from `$HOME`, so a project cannot redirect it.
|
|
4
|
-
// A `ROUTER_CONFIG` env value is honored only when it resolves inside `<home>/.claude/`; anywhere else it is
|
|
5
|
-
// ignored (with a warning that names the variable, never the rejected path) and the default file is used instead.
|
|
6
|
-
import { execFileSync } from 'node:child_process';
|
|
7
|
-
import { tmpdir, userInfo } from 'node:os';
|
|
8
|
-
import { isAbsolute, join, relative, resolve } from 'node:path';
|
|
9
|
-
import { loadConfig, TIERS } from './config.mjs';
|
|
10
|
-
import { readJsonFile } from './store.mjs';
|
|
11
|
-
|
|
12
|
-
// null for a UID without a passwd entry (`docker run --user <uid>`, devcontainers), where userInfo() throws. There
|
|
13
|
-
// the only home is $HOME, which a project can set, so there is no trusted home at all.
|
|
14
|
-
export function userHome(info = userInfo) {
|
|
15
|
-
try {
|
|
16
|
-
return info().homedir;
|
|
17
|
-
} catch {
|
|
18
|
-
return null;
|
|
19
|
-
}
|
|
20
|
-
}
|
|
21
|
-
|
|
22
|
-
// Pure path resolution: no file access. `configPath` is an explicit `--config` value (unrestricted: it comes
|
|
23
|
-
// from a hook's own argv, which a project's settings cannot change) and wins over `env.ROUTER_CONFIG`.
|
|
24
|
-
// Without a trusted home the gateway runs on the defaults: starting beats an outage, and a project chooses nothing.
|
|
25
|
-
export function resolveConfigPath(env, { home = userHome(), configPath = null } = {}) {
|
|
26
|
-
if (configPath) return { path: resolve(configPath), warning: null };
|
|
27
|
-
if (!home) return { path: null, warning: 'no OS user account entry: router.json ignored, defaults used' };
|
|
28
|
-
const fallback = join(home, '.claude', 'router.json');
|
|
29
|
-
const requested = env.ROUTER_CONFIG;
|
|
30
|
-
if (!requested) return { path: fallback, warning: null };
|
|
31
|
-
const resolved = resolve(requested);
|
|
32
|
-
const rel = relative(join(home, '.claude'), resolved);
|
|
33
|
-
const inside = rel === '' || (!rel.startsWith('..') && !isAbsolute(rel));
|
|
34
|
-
if (inside) return { path: resolved, warning: null };
|
|
35
|
-
return { path: fallback, warning: 'ROUTER_CONFIG ignored: not under ~/.claude' };
|
|
36
|
-
}
|
|
37
|
-
|
|
38
|
-
// Whatever answers on the gateway port reports a pid; the hook signals it only if that pid runs this plugin's daemon.
|
|
39
|
-
// pid 0 or -1 would signal a process group or every process of the user, so neither reaches `ps` or `kill`.
|
|
40
|
-
export function isRouterGateway(pid, run = execFileSync) {
|
|
41
|
-
if (!Number.isInteger(pid) || pid <= 1) return false;
|
|
42
|
-
try {
|
|
43
|
-
return /scripts\/gateway\.mjs\b/.test(run('ps', ['-o', 'command=', '-p', String(pid)], { encoding: 'utf8' }));
|
|
44
|
-
} catch {
|
|
45
|
-
return false; // no such process, or no ps: do not signal
|
|
46
|
-
}
|
|
47
|
-
}
|
|
48
|
-
|
|
49
|
-
// `--flag value` from argv (e.g. `process.argv`). null when the flag is absent.
|
|
50
|
-
export function cliArg(argv, flag) {
|
|
51
|
-
const i = argv.indexOf(flag);
|
|
52
|
-
return i === -1 ? null : (argv[i + 1] ?? null);
|
|
53
|
-
}
|
|
54
|
-
|
|
55
|
-
// The --config for a gateway that a hook starts. spawn() turns null into "null", a path relative to the project the
|
|
56
|
-
// hook runs in, so no resolved path means no flag: the gateway then resolves the same way the hook did.
|
|
57
|
-
export function configArgs(configPath) {
|
|
58
|
-
return configPath ? ['--config', configPath] : [];
|
|
59
|
-
}
|
|
60
|
-
|
|
61
|
-
export function loadRuntime(env, { home = userHome(), configPath = null, forceTier = null } = {}) {
|
|
62
|
-
if (forceTier !== null && !TIERS.includes(forceTier))
|
|
63
|
-
throw new Error(`--force-tier must be one of ${TIERS.join(', ')}`);
|
|
64
|
-
const { path, warning } = resolveConfigPath(env, { home, configPath });
|
|
65
|
-
const userFile = path ? readJsonFile(path) : null; // its own errors name the file
|
|
66
|
-
let config;
|
|
67
|
-
try {
|
|
68
|
-
config = loadConfig({ env, userFile, forcedTier: forceTier });
|
|
69
|
-
} catch (error) {
|
|
70
|
-
throw new Error(`${path}: ${error.message}`);
|
|
71
|
-
}
|
|
72
|
-
return {
|
|
73
|
-
config,
|
|
74
|
-
dataDir: env.CLAUDE_PLUGIN_DATA || join(tmpdir(), 'router'),
|
|
75
|
-
configPath: path,
|
|
76
|
-
warning,
|
|
77
|
-
};
|
|
78
|
-
}
|
package/lib/sse.mjs
DELETED
|
@@ -1,57 +0,0 @@
|
|
|
1
|
-
// Incremental usage and stop-reason reader for a Messages response: streaming SSE or a plain JSON body.
|
|
2
|
-
export class UsageReader {
|
|
3
|
-
constructor() {
|
|
4
|
-
this.buffer = '';
|
|
5
|
-
this.usage = null;
|
|
6
|
-
this.model = null;
|
|
7
|
-
this.stopReason = null;
|
|
8
|
-
}
|
|
9
|
-
|
|
10
|
-
feed(chunk) {
|
|
11
|
-
this.buffer += chunk;
|
|
12
|
-
for (let at = this.buffer.indexOf('\n'); at >= 0; at = this.buffer.indexOf('\n')) {
|
|
13
|
-
const line = this.buffer.slice(0, at).trim();
|
|
14
|
-
this.buffer = this.buffer.slice(at + 1);
|
|
15
|
-
if (line.startsWith('data:')) this.take(line.slice(5).trim());
|
|
16
|
-
}
|
|
17
|
-
}
|
|
18
|
-
|
|
19
|
-
end() {
|
|
20
|
-
const rest = this.buffer.trim();
|
|
21
|
-
if (rest.startsWith('{')) this.take(rest);
|
|
22
|
-
this.buffer = '';
|
|
23
|
-
return this.result();
|
|
24
|
-
}
|
|
25
|
-
|
|
26
|
-
take(json) {
|
|
27
|
-
let event;
|
|
28
|
-
try {
|
|
29
|
-
event = JSON.parse(json);
|
|
30
|
-
} catch {
|
|
31
|
-
return;
|
|
32
|
-
}
|
|
33
|
-
const message = event.type === 'message_start' ? event.message : event.type === 'message' ? event : null;
|
|
34
|
-
if (message?.usage) {
|
|
35
|
-
this.model = message.model ?? this.model;
|
|
36
|
-
this.usage = { ...(this.usage ?? {}), ...message.usage };
|
|
37
|
-
}
|
|
38
|
-
if (message?.stop_reason) this.stopReason = message.stop_reason;
|
|
39
|
-
if (event.type === 'message_delta') {
|
|
40
|
-
if (event.usage) this.usage = { ...(this.usage ?? {}), ...event.usage };
|
|
41
|
-
if (event.delta?.stop_reason) this.stopReason = event.delta.stop_reason;
|
|
42
|
-
}
|
|
43
|
-
}
|
|
44
|
-
|
|
45
|
-
result() {
|
|
46
|
-
if (!this.usage) return null;
|
|
47
|
-
const u = this.usage;
|
|
48
|
-
const tokens = (u.input_tokens ?? 0) + (u.cache_read_input_tokens ?? 0) + (u.cache_creation_input_tokens ?? 0);
|
|
49
|
-
return {
|
|
50
|
-
model: this.model,
|
|
51
|
-
tokens,
|
|
52
|
-
cacheReadTokens: u.cache_read_input_tokens ?? 0,
|
|
53
|
-
outputTokens: u.output_tokens ?? 0,
|
|
54
|
-
ttl: (u.cache_creation?.ephemeral_1h_input_tokens ?? 0) > 0 ? '1h' : '5m',
|
|
55
|
-
};
|
|
56
|
-
}
|
|
57
|
-
}
|
package/lib/status.mjs
DELETED
|
@@ -1,152 +0,0 @@
|
|
|
1
|
-
// Router status: the snapshot the gateway serves at GET /router/status, and its text forms for the
|
|
2
|
-
// status line and /router:status. The snapshot never carries the API key, only whether one is set.
|
|
3
|
-
import { createRequire } from 'node:module';
|
|
4
|
-
import { TIERS } from './config.mjs';
|
|
5
|
-
import { clampEffort } from './rewrite.mjs';
|
|
6
|
-
|
|
7
|
-
const _require = createRequire(import.meta.url);
|
|
8
|
-
export const ROUTER_VERSION = _require('../package.json').version;
|
|
9
|
-
|
|
10
|
-
// True when `running` is older than `current`. Gateways before 0.3.0 report no version: they count as older.
|
|
11
|
-
export function isOlderVersion(running, current) {
|
|
12
|
-
const parse = (v) => (/^\d+\.\d+\.\d+/.test(v ?? '') ? v.split('.').map((n) => Number.parseInt(n, 10)) : [0, 0, 0]);
|
|
13
|
-
const [a, b] = [parse(running), parse(current)];
|
|
14
|
-
for (let i = 0; i < 3; i += 1) if (a[i] !== b[i]) return a[i] < b[i];
|
|
15
|
-
return false;
|
|
16
|
-
}
|
|
17
|
-
|
|
18
|
-
export const STATUS_PATH = '/router/status';
|
|
19
|
-
// The name of the alias in the /model picker and in discovery.
|
|
20
|
-
export const ROUTER_DISPLAY_NAME = 'Jev Router (auto)';
|
|
21
|
-
const FETCH_TIMEOUT_MS = 300;
|
|
22
|
-
|
|
23
|
-
export function statusSnapshot(config, memory) {
|
|
24
|
-
const { alias, port, baselineTier } = config.gateway;
|
|
25
|
-
return {
|
|
26
|
-
version: ROUTER_VERSION,
|
|
27
|
-
alias,
|
|
28
|
-
port,
|
|
29
|
-
keySet: Boolean(config.apiKey),
|
|
30
|
-
forcedTier: config.forcedTier ?? null,
|
|
31
|
-
baselineTier,
|
|
32
|
-
routes: TIERS.map((tier) => routeRow(config, tier)),
|
|
33
|
-
session: memory?.lastRoute
|
|
34
|
-
? {
|
|
35
|
-
tier: memory.lastRoute,
|
|
36
|
-
reason: memory.lastReason ?? null,
|
|
37
|
-
estimate: memory.lastEstimate ?? null,
|
|
38
|
-
effort: memory.lastEffort ?? null,
|
|
39
|
-
model: memory.lastRequest?.model ?? null,
|
|
40
|
-
tokens: memory.lastRequest?.tokens ?? null,
|
|
41
|
-
cacheReadTokens: memory.lastRequest?.cacheReadTokens ?? null,
|
|
42
|
-
at: memory.lastRequest?.at ?? null,
|
|
43
|
-
}
|
|
44
|
-
: null,
|
|
45
|
-
};
|
|
46
|
-
}
|
|
47
|
-
|
|
48
|
-
function routeRow(config, tier) {
|
|
49
|
-
const route = config.routes[tier];
|
|
50
|
-
const model = config.models[route.model];
|
|
51
|
-
const effort = model.efforts.length === 0 ? 'none' : (clampEffort(route.effort, model.efforts) ?? 'as sent');
|
|
52
|
-
return { tier, model: model.id, effort };
|
|
53
|
-
}
|
|
54
|
-
|
|
55
|
-
// Why the route of the last turn is what it is, for /router:status.
|
|
56
|
-
const REASONS = {
|
|
57
|
-
upgrade: 'Jev voted above the current tier often enough, with enough mass for the switching tax',
|
|
58
|
-
jump: 'Jev was confident enough to skip a tier and the vote delay',
|
|
59
|
-
downgrade: 'Jev voted for a lower tier often enough, with enough mass',
|
|
60
|
-
'upgrade-pending': 'Jev asked for a higher tier; the route stays until the votes and the mass are enough',
|
|
61
|
-
'downgrade-pending': 'Jev asked for a lower tier; the route stays until the votes and the mass are enough',
|
|
62
|
-
'same-tier': 'Jev agreed with the current tier',
|
|
63
|
-
continuation: 'the prompt continues the task, so the route stays',
|
|
64
|
-
uncertain: 'Jev abstained, so the route stays',
|
|
65
|
-
'no-advice': 'no Jev answer (no key, a failure or a pause), so the route stays',
|
|
66
|
-
escalation: 'the same error came back after an edit: one tier up',
|
|
67
|
-
hold: 'the tier stays up for a few turns after an escalation',
|
|
68
|
-
'cash-gate':
|
|
69
|
-
'cold-write guard: the first cache write on a credits model would cost more than policy.cashCapUsd, so the strongest plan tier served',
|
|
70
|
-
'context-fit': "the chosen model's window does not hold the context",
|
|
71
|
-
forced: 'the gateway was started with --force-tier',
|
|
72
|
-
pinned: 'you pinned this turn with /router:<tier>',
|
|
73
|
-
};
|
|
74
|
-
|
|
75
|
-
// One status-line segment, e.g. "router ▸ opus-5-5 · xhigh · upgrade".
|
|
76
|
-
export function statusSegment(status) {
|
|
77
|
-
if (!status) return 'router: gateway off, the next prompt starts it';
|
|
78
|
-
const last = status.session;
|
|
79
|
-
if (!last) return `${status.alias}: no turn yet`;
|
|
80
|
-
const model = shortModel(last.model ?? status.routes.find((r) => r.tier === last.tier)?.model);
|
|
81
|
-
return [`${status.alias} ▸ ${model}`, last.effort, last.reason].filter(Boolean).join(' · ');
|
|
82
|
-
}
|
|
83
|
-
|
|
84
|
-
// Markdown for /router:status.
|
|
85
|
-
export function statusReport(status) {
|
|
86
|
-
if (!status)
|
|
87
|
-
return 'The router gateway is not running. The next prompt starts it. If it does not start, read `gateway.log` in the plugin data directory.';
|
|
88
|
-
const lines = [
|
|
89
|
-
`Router v${status.version}, gateway: http://127.0.0.1:${status.port}, alias \`${status.alias}\`.`,
|
|
90
|
-
`Jev routing: ${jevState(status)}.`,
|
|
91
|
-
`Default tier: ${status.baselineTier}.${status.forcedTier ? ` Forced tier: ${status.forcedTier}.` : ''}`,
|
|
92
|
-
'',
|
|
93
|
-
'| Tier | Model | Effort |',
|
|
94
|
-
'| ---- | ----- | ------ |',
|
|
95
|
-
...status.routes.map((r) => `| ${r.tier} | ${r.model} | ${r.effort} |`),
|
|
96
|
-
'',
|
|
97
|
-
];
|
|
98
|
-
const last = status.session;
|
|
99
|
-
if (!last) lines.push('No routed turn in this session yet.');
|
|
100
|
-
else {
|
|
101
|
-
const model = last.model ?? status.routes.find((r) => r.tier === last.tier)?.model;
|
|
102
|
-
const effort = last.effort ? ` at ${last.effort}` : '';
|
|
103
|
-
const context = last.tokens ? `, context ${last.tokens} tokens, cache reads ${last.cacheReadTokens}` : '';
|
|
104
|
-
lines.push(`Last turn: ${last.tier} → ${model}${effort}, reason ${last.reason ?? 'unknown'}${context}.`);
|
|
105
|
-
if (REASONS[last.reason]) lines.push(`Why: ${REASONS[last.reason]}.`);
|
|
106
|
-
const estimate = describeEstimate(last.estimate);
|
|
107
|
-
if (estimate) lines.push(`Estimate: ${estimate}.`);
|
|
108
|
-
}
|
|
109
|
-
return lines.join('\n');
|
|
110
|
-
}
|
|
111
|
-
|
|
112
|
-
// Dollars are list prices: for `plan` models a list-price equivalent, not a charge. `unknown` cache: no response for
|
|
113
|
-
// that cache since the session started or its history broke.
|
|
114
|
-
function describeEstimate(e) {
|
|
115
|
-
if (!e) return null;
|
|
116
|
-
const usd = (n) => `$${n.toFixed(2)}`;
|
|
117
|
-
const parts = [];
|
|
118
|
-
if (e.upgradeMass !== undefined)
|
|
119
|
-
parts.push(
|
|
120
|
-
`upgrade mass ${e.upgradeMass.toFixed(2)} against a bar of ${e.threshold.toFixed(2)}`,
|
|
121
|
-
`switching tax ${usd(e.taxUsd)} at list prices`,
|
|
122
|
-
);
|
|
123
|
-
if (e.downgradeMass !== undefined) parts.push(`downgrade mass ${e.downgradeMass.toFixed(2)}`);
|
|
124
|
-
if (e.coldUsd !== undefined) parts.push(`cold write ${usd(e.coldUsd)} against the cap of ${usd(e.cap)}`);
|
|
125
|
-
if (e.streak !== undefined) parts.push(`${e.streak} vote(s) in a row`);
|
|
126
|
-
if (e.cache?.candidate) parts.push(`cache: candidate ${e.cache.candidate}, current ${e.cache.incumbent}`);
|
|
127
|
-
else if (typeof e.cache === 'string') parts.push(`cache ${e.cache}`);
|
|
128
|
-
return parts.join(', ');
|
|
129
|
-
}
|
|
130
|
-
|
|
131
|
-
// null when the gateway does not answer in time.
|
|
132
|
-
export async function fetchStatus(port, sessionId) {
|
|
133
|
-
const query = sessionId ? `?session=${encodeURIComponent(sessionId)}` : '';
|
|
134
|
-
try {
|
|
135
|
-
const res = await fetch(`http://127.0.0.1:${port}${STATUS_PATH}${query}`, {
|
|
136
|
-
signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
|
|
137
|
-
});
|
|
138
|
-
return res.ok ? await res.json() : null;
|
|
139
|
-
} catch {
|
|
140
|
-
return null;
|
|
141
|
-
}
|
|
142
|
-
}
|
|
143
|
-
|
|
144
|
-
function jevState(status) {
|
|
145
|
-
if (!status.keySet) return 'inactive, no key: every turn runs on the default tier';
|
|
146
|
-
if (status.jevPausedUntil) return `paused after repeated failures, next try at ${status.jevPausedUntil}`;
|
|
147
|
-
return 'active';
|
|
148
|
-
}
|
|
149
|
-
|
|
150
|
-
function shortModel(id) {
|
|
151
|
-
return id ? id.replace(/^claude-/, '') : 'unknown';
|
|
152
|
-
}
|
package/lib/store.mjs
DELETED
|
@@ -1,76 +0,0 @@
|
|
|
1
|
-
// Files: user config, per-session memory and the decision log. The only module that touches the filesystem.
|
|
2
|
-
import {
|
|
3
|
-
appendFileSync,
|
|
4
|
-
mkdirSync,
|
|
5
|
-
readdirSync,
|
|
6
|
-
readFileSync,
|
|
7
|
-
renameSync,
|
|
8
|
-
rmSync,
|
|
9
|
-
statSync,
|
|
10
|
-
writeFileSync,
|
|
11
|
-
} from 'node:fs';
|
|
12
|
-
import { join } from 'node:path';
|
|
13
|
-
|
|
14
|
-
export const LOG_LIMIT_BYTES = 20 * 1024 * 1024;
|
|
15
|
-
const SESSION_TTL_MS = 30 * 24 * 3_600_000;
|
|
16
|
-
|
|
17
|
-
// A JSON syntax error says only that: V8's message quotes the text around the bad token, and the hook prints it.
|
|
18
|
-
export function readJsonFile(path) {
|
|
19
|
-
try {
|
|
20
|
-
return JSON.parse(readFileSync(path, 'utf8'));
|
|
21
|
-
} catch (error) {
|
|
22
|
-
if (error.code === 'ENOENT') return null;
|
|
23
|
-
throw new Error(`cannot read ${path}: ${error instanceof SyntaxError ? 'not valid JSON' : error.message}`);
|
|
24
|
-
}
|
|
25
|
-
}
|
|
26
|
-
|
|
27
|
-
export function loadMemory(dir, sessionId, fallback) {
|
|
28
|
-
try {
|
|
29
|
-
return { ...fallback, ...JSON.parse(readFileSync(memoryPath(dir, sessionId), 'utf8')) };
|
|
30
|
-
} catch {
|
|
31
|
-
return fallback;
|
|
32
|
-
}
|
|
33
|
-
}
|
|
34
|
-
|
|
35
|
-
export function saveMemory(dir, sessionId, memory) {
|
|
36
|
-
mkdirSync(join(dir, 'sessions'), { recursive: true });
|
|
37
|
-
const path = memoryPath(dir, sessionId);
|
|
38
|
-
writeFileSync(`${path}.tmp`, JSON.stringify(memory));
|
|
39
|
-
renameSync(`${path}.tmp`, path);
|
|
40
|
-
}
|
|
41
|
-
|
|
42
|
-
export function appendLog(dir, entry) {
|
|
43
|
-
mkdirSync(dir, { recursive: true });
|
|
44
|
-
appendFileSync(join(dir, 'decisions.jsonl'), `${JSON.stringify(entry)}\n`);
|
|
45
|
-
}
|
|
46
|
-
|
|
47
|
-
// Keeps one previous generation: `<file>.1`. Only for files written by path, not held open.
|
|
48
|
-
export function rotate(path, limitBytes = LOG_LIMIT_BYTES) {
|
|
49
|
-
try {
|
|
50
|
-
if (statSync(path).size > limitBytes) renameSync(path, `${path}.1`);
|
|
51
|
-
} catch (error) {
|
|
52
|
-
if (error.code !== 'ENOENT') throw error;
|
|
53
|
-
}
|
|
54
|
-
}
|
|
55
|
-
|
|
56
|
-
// Bounds the data directory of a long-running gateway: the decision log and a month of session memory.
|
|
57
|
-
// gateway.log is the daemon's open stderr, so the hook that starts the daemon rotates it instead.
|
|
58
|
-
export function housekeeping(dir, now = Date.now()) {
|
|
59
|
-
rotate(join(dir, 'decisions.jsonl'));
|
|
60
|
-
const sessions = join(dir, 'sessions');
|
|
61
|
-
let names;
|
|
62
|
-
try {
|
|
63
|
-
names = readdirSync(sessions);
|
|
64
|
-
} catch (error) {
|
|
65
|
-
if (error.code === 'ENOENT') return;
|
|
66
|
-
throw error;
|
|
67
|
-
}
|
|
68
|
-
for (const name of names) {
|
|
69
|
-
const path = join(sessions, name);
|
|
70
|
-
if (now - statSync(path).mtimeMs > SESSION_TTL_MS) rmSync(path, { force: true });
|
|
71
|
-
}
|
|
72
|
-
}
|
|
73
|
-
|
|
74
|
-
function memoryPath(dir, sessionId) {
|
|
75
|
-
return join(dir, 'sessions', `${String(sessionId).replace(/[^\w.-]/g, '_')}.json`);
|
|
76
|
-
}
|
|
@@ -1,143 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
// Hook entry (SessionStart, UserPromptSubmit): make sure a gateway of this plugin version or newer answers on the port.
|
|
3
|
-
// Starts one on a free port and replaces an older one; leaves a newer one alone, so a session that still runs an older
|
|
4
|
-
// plugin never downgrades it. Detached, so the gateway outlives the session. After a crash, the next prompt restarts it.
|
|
5
|
-
// `--quiet` prints nothing: UserPromptSubmit output goes into the model's context.
|
|
6
|
-
import { spawn } from 'node:child_process';
|
|
7
|
-
import { mkdirSync, openSync } from 'node:fs';
|
|
8
|
-
import { connect } from 'node:net';
|
|
9
|
-
import { dirname, join } from 'node:path';
|
|
10
|
-
import { fileURLToPath } from 'node:url';
|
|
11
|
-
import { cliArg, configArgs, isRouterGateway, loadRuntime } from '../lib/runtime.mjs';
|
|
12
|
-
import { isOlderVersion, ROUTER_VERSION, STATUS_PATH } from '../lib/status.mjs';
|
|
13
|
-
import { rotate } from '../lib/store.mjs';
|
|
14
|
-
|
|
15
|
-
const WAIT_STEP_MS = 100;
|
|
16
|
-
const WAIT_STEPS = 20;
|
|
17
|
-
const STATUS_TIMEOUT_MS = 500;
|
|
18
|
-
|
|
19
|
-
const env = process.env;
|
|
20
|
-
const quiet = process.argv.includes('--quiet');
|
|
21
|
-
|
|
22
|
-
function say(message) {
|
|
23
|
-
if (!quiet) process.stdout.write(`router: ${message}\n`);
|
|
24
|
-
}
|
|
25
|
-
|
|
26
|
-
let config;
|
|
27
|
-
let dataDir;
|
|
28
|
-
let configPath;
|
|
29
|
-
let configWarning;
|
|
30
|
-
try {
|
|
31
|
-
({
|
|
32
|
-
config,
|
|
33
|
-
dataDir,
|
|
34
|
-
configPath,
|
|
35
|
-
warning: configWarning,
|
|
36
|
-
} = loadRuntime(env, {
|
|
37
|
-
configPath: cliArg(process.argv, '--config'),
|
|
38
|
-
}));
|
|
39
|
-
} catch (error) {
|
|
40
|
-
say(`invalid configuration (${error.message}); the next prompt tries again`);
|
|
41
|
-
process.exit(0);
|
|
42
|
-
}
|
|
43
|
-
if (configWarning) say(configWarning);
|
|
44
|
-
const port = config.gateway.port;
|
|
45
|
-
|
|
46
|
-
function probe() {
|
|
47
|
-
return new Promise((resolve) => {
|
|
48
|
-
const socket = connect({ host: '127.0.0.1', port });
|
|
49
|
-
socket.once('connect', () => {
|
|
50
|
-
socket.destroy();
|
|
51
|
-
resolve(true);
|
|
52
|
-
});
|
|
53
|
-
socket.once('error', () => resolve(false));
|
|
54
|
-
});
|
|
55
|
-
}
|
|
56
|
-
|
|
57
|
-
// Waits until the port answers (`true`) or is free (`false`).
|
|
58
|
-
async function waitFor(answering) {
|
|
59
|
-
for (let i = 0; i < WAIT_STEPS; i += 1) {
|
|
60
|
-
if ((await probe()) === answering) return true;
|
|
61
|
-
await new Promise((resolve) => setTimeout(resolve, WAIT_STEP_MS));
|
|
62
|
-
}
|
|
63
|
-
return false;
|
|
64
|
-
}
|
|
65
|
-
|
|
66
|
-
async function runningGateway() {
|
|
67
|
-
try {
|
|
68
|
-
const res = await fetch(`http://127.0.0.1:${port}${STATUS_PATH}`, {
|
|
69
|
-
signal: AbortSignal.timeout(STATUS_TIMEOUT_MS),
|
|
70
|
-
});
|
|
71
|
-
return res.ok ? await res.json() : null;
|
|
72
|
-
} catch {
|
|
73
|
-
return null;
|
|
74
|
-
}
|
|
75
|
-
}
|
|
76
|
-
|
|
77
|
-
// SIGTERM: the old gateway releases the port at once and finishes its open streams. Gateways from 0.4.0 on report
|
|
78
|
-
// their pid; older ones cannot be retired from here.
|
|
79
|
-
async function retire(running) {
|
|
80
|
-
const from = running.version ?? 'before 0.3.0';
|
|
81
|
-
if (!running.pid) {
|
|
82
|
-
say(
|
|
83
|
-
`gateway ${from} runs on port ${port}. Stop it once with \`pkill -f scripts/gateway.mjs\`; the next prompt starts ${ROUTER_VERSION}.`,
|
|
84
|
-
);
|
|
85
|
-
return false;
|
|
86
|
-
}
|
|
87
|
-
if (!isRouterGateway(running.pid)) {
|
|
88
|
-
say(`port ${port} answers as gateway ${from}, but pid ${running.pid} is not a router gateway: left alone`);
|
|
89
|
-
return false;
|
|
90
|
-
}
|
|
91
|
-
try {
|
|
92
|
-
process.kill(running.pid, 'SIGTERM');
|
|
93
|
-
} catch (error) {
|
|
94
|
-
say(`cannot stop gateway ${from} (pid ${running.pid}): ${error.message}`);
|
|
95
|
-
return false;
|
|
96
|
-
}
|
|
97
|
-
if (await waitFor(false)) return true;
|
|
98
|
-
say(`gateway ${from} (pid ${running.pid}) did not release port ${port}`);
|
|
99
|
-
return false;
|
|
100
|
-
}
|
|
101
|
-
|
|
102
|
-
async function start() {
|
|
103
|
-
mkdirSync(dataDir, { recursive: true });
|
|
104
|
-
const logPath = join(dataDir, 'gateway.log');
|
|
105
|
-
try {
|
|
106
|
-
rotate(logPath);
|
|
107
|
-
} catch {
|
|
108
|
-
// Rotation is housekeeping; a gateway that starts matters more.
|
|
109
|
-
}
|
|
110
|
-
const log = openSync(logPath, 'a');
|
|
111
|
-
// Claude Code exports the plugin option as CLAUDE_PLUGIN_OPTION_<KEY>; the gateway reads one name only.
|
|
112
|
-
const childEnv = {
|
|
113
|
-
...env,
|
|
114
|
-
TYPESAFE_API_KEY: env.TYPESAFE_API_KEY || env.CLAUDE_PLUGIN_OPTION_TYPESAFE_API_KEY || '',
|
|
115
|
-
};
|
|
116
|
-
const child = spawn(
|
|
117
|
-
process.execPath,
|
|
118
|
-
[join(dirname(fileURLToPath(import.meta.url)), 'gateway.mjs'), ...configArgs(configPath)],
|
|
119
|
-
{
|
|
120
|
-
detached: true,
|
|
121
|
-
stdio: ['ignore', log, log],
|
|
122
|
-
env: childEnv,
|
|
123
|
-
},
|
|
124
|
-
);
|
|
125
|
-
child.unref();
|
|
126
|
-
// Wait for the listener so the session's first request finds it.
|
|
127
|
-
return { pid: child.pid, up: await waitFor(true) };
|
|
128
|
-
}
|
|
129
|
-
|
|
130
|
-
if (!(env.ANTHROPIC_BASE_URL ?? '').includes(`127.0.0.1:${port}`))
|
|
131
|
-
say('Claude Code does not use the gateway yet. Run /router:setup, then restart Claude Code.');
|
|
132
|
-
|
|
133
|
-
const running = await runningGateway();
|
|
134
|
-
if (running && !isOlderVersion(running.version, ROUTER_VERSION)) process.exit(0);
|
|
135
|
-
if (running && !(await retire(running))) process.exit(0);
|
|
136
|
-
if (!running && (await probe())) {
|
|
137
|
-
say(`port ${port} answers, but not as the router gateway`);
|
|
138
|
-
process.exit(0);
|
|
139
|
-
}
|
|
140
|
-
const { pid, up } = await start();
|
|
141
|
-
const verb = running ? `replaced ${running.version ?? 'an older gateway'} on` : 'started on';
|
|
142
|
-
say(`gateway ${ROUTER_VERSION} ${up ? verb : 'not answering yet on'} 127.0.0.1:${port} (pid ${pid})`);
|
|
143
|
-
process.exit(0);
|
package/scripts/gateway.mjs
DELETED
|
@@ -1,81 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
// Daemon entry: local gateway on 127.0.0.1:<gateway.port>. Started by the plugin hooks or by hand.
|
|
3
|
-
import { createGateway } from '../lib/gateway.mjs';
|
|
4
|
-
import { IdleTracker } from '../lib/idle.mjs';
|
|
5
|
-
import { Router } from '../lib/router.mjs';
|
|
6
|
-
import { cliArg, loadRuntime } from '../lib/runtime.mjs';
|
|
7
|
-
import { ROUTER_VERSION } from '../lib/status.mjs';
|
|
8
|
-
import { housekeeping } from '../lib/store.mjs';
|
|
9
|
-
|
|
10
|
-
// On stop the port is released at once; open streams get this long to finish (Claude Code's request timeout).
|
|
11
|
-
const DRAIN_MS = 600_000;
|
|
12
|
-
const HOUSEKEEPING_MS = 3_600_000;
|
|
13
|
-
const IDLE_CHECK_MS = 60_000;
|
|
14
|
-
|
|
15
|
-
process.stderr.on('error', () => {}); // a full disk must not turn a log line into a crash
|
|
16
|
-
const log = (message) => process.stderr.write(`${new Date().toISOString()} router: ${message}\n`);
|
|
17
|
-
const onError = (error) => log(error.message);
|
|
18
|
-
|
|
19
|
-
// Every Claude Code session on the machine goes through this process, so a stray exception is logged, not fatal.
|
|
20
|
-
// Request state is per request and per session; the worst case after such an error is one misrouted turn.
|
|
21
|
-
process.on('uncaughtException', (error) => log(`uncaught exception: ${error.stack ?? error.message}`));
|
|
22
|
-
process.on('unhandledRejection', (reason) => log(`unhandled rejection: ${reason?.stack ?? reason}`));
|
|
23
|
-
|
|
24
|
-
let config;
|
|
25
|
-
let dataDir;
|
|
26
|
-
try {
|
|
27
|
-
({ config, dataDir } = loadRuntime(process.env, {
|
|
28
|
-
configPath: cliArg(process.argv, '--config'),
|
|
29
|
-
forceTier: cliArg(process.argv, '--force-tier'),
|
|
30
|
-
}));
|
|
31
|
-
} catch (error) {
|
|
32
|
-
log(`invalid configuration: ${error.message}`);
|
|
33
|
-
process.exit(1);
|
|
34
|
-
}
|
|
35
|
-
const { port, alias, idleShutdownMs } = config.gateway;
|
|
36
|
-
const router = new Router({ config, fetchFn: globalThis.fetch, dataDir, onError });
|
|
37
|
-
const activity = new IdleTracker();
|
|
38
|
-
const server = createGateway({ router, onError, activity });
|
|
39
|
-
|
|
40
|
-
server.on('error', (error) => {
|
|
41
|
-
if (error.code === 'EADDRINUSE') {
|
|
42
|
-
log(`port ${port} is in use, another gateway serves it: exiting`);
|
|
43
|
-
process.exit(0);
|
|
44
|
-
}
|
|
45
|
-
log(`server error: ${error.message}`);
|
|
46
|
-
process.exit(1);
|
|
47
|
-
});
|
|
48
|
-
|
|
49
|
-
let stopping = false;
|
|
50
|
-
function stop(reason) {
|
|
51
|
-
if (stopping) return;
|
|
52
|
-
stopping = true;
|
|
53
|
-
log(`${reason}: no new connections, finishing open streams`);
|
|
54
|
-
server.close(() => process.exit(0));
|
|
55
|
-
server.closeIdleConnections();
|
|
56
|
-
setTimeout(() => process.exit(0), DRAIN_MS).unref();
|
|
57
|
-
}
|
|
58
|
-
process.once('SIGTERM', () => stop('SIGTERM'));
|
|
59
|
-
process.once('SIGINT', () => stop('SIGINT'));
|
|
60
|
-
|
|
61
|
-
if (idleShutdownMs > 0) {
|
|
62
|
-
const minutes = Math.round(idleShutdownMs / 60_000);
|
|
63
|
-
const check = () => {
|
|
64
|
-
if (activity.idle(idleShutdownMs)) stop(`idle for ${minutes} min, no turn waits for a tool`);
|
|
65
|
-
};
|
|
66
|
-
setInterval(check, Math.min(idleShutdownMs, IDLE_CHECK_MS)).unref();
|
|
67
|
-
}
|
|
68
|
-
|
|
69
|
-
function tidy() {
|
|
70
|
-
try {
|
|
71
|
-
housekeeping(dataDir);
|
|
72
|
-
} catch (error) {
|
|
73
|
-
onError(error);
|
|
74
|
-
}
|
|
75
|
-
}
|
|
76
|
-
tidy();
|
|
77
|
-
setInterval(tidy, HOUSEKEEPING_MS).unref();
|
|
78
|
-
|
|
79
|
-
server.listen(port, '127.0.0.1', () =>
|
|
80
|
-
log(`${ROUTER_VERSION} listening on http://127.0.0.1:${port} as ${alias} (pid ${process.pid})`),
|
|
81
|
-
);
|
|
@@ -1,41 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env bash
|
|
2
|
-
# Staged-only checks: Biome on staged .mjs/.json, ShellCheck on staged shell
|
|
3
|
-
# scripts, Gitleaks on the staged diff. Full check/test/pack runs in pre-push.
|
|
4
|
-
set -euo pipefail
|
|
5
|
-
|
|
6
|
-
cd "$(git rev-parse --show-toplevel)"
|
|
7
|
-
|
|
8
|
-
biome=node_modules/.bin/biome
|
|
9
|
-
[ -x "$biome" ] || {
|
|
10
|
-
echo "pre-commit: $biome missing; run 'npm ci'" >&2
|
|
11
|
-
exit 1
|
|
12
|
-
}
|
|
13
|
-
command -v gitleaks >/dev/null || {
|
|
14
|
-
echo "pre-commit: gitleaks missing; run 'brew install gitleaks'" >&2
|
|
15
|
-
exit 1
|
|
16
|
-
}
|
|
17
|
-
|
|
18
|
-
files=()
|
|
19
|
-
shell_files=()
|
|
20
|
-
while IFS= read -r -d '' f; do
|
|
21
|
-
case "$f" in
|
|
22
|
-
*.mjs | *.json) files+=("$f") ;;
|
|
23
|
-
*.sh | scripts/git-hooks/*) shell_files+=("$f") ;;
|
|
24
|
-
esac
|
|
25
|
-
done < <(git diff --cached --name-only -z --diff-filter=ACMR)
|
|
26
|
-
|
|
27
|
-
if [ "${#files[@]}" -gt 0 ]; then
|
|
28
|
-
"$biome" check --no-errors-on-unmatched -- "${files[@]}"
|
|
29
|
-
fi
|
|
30
|
-
|
|
31
|
-
# Checked only when shell files are staged, so contributors who never touch
|
|
32
|
-
# them don't need shellcheck installed.
|
|
33
|
-
if [ "${#shell_files[@]}" -gt 0 ]; then
|
|
34
|
-
command -v shellcheck >/dev/null || {
|
|
35
|
-
echo "pre-commit: shellcheck missing; run 'brew install shellcheck'" >&2
|
|
36
|
-
exit 1
|
|
37
|
-
}
|
|
38
|
-
shellcheck -- "${shell_files[@]}"
|
|
39
|
-
fi
|
|
40
|
-
|
|
41
|
-
gitleaks git --pre-commit --staged --redact --verbose --no-banner
|
|
@@ -1,34 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env bash
|
|
2
|
-
# CI-equivalent validation before code leaves the machine (mirrors .github/workflows/ci.yml).
|
|
3
|
-
set -euo pipefail
|
|
4
|
-
|
|
5
|
-
cd "$(git rev-parse --show-toplevel)"
|
|
6
|
-
zero=0000000000000000000000000000000000000000
|
|
7
|
-
|
|
8
|
-
[ -x node_modules/.bin/biome ] || {
|
|
9
|
-
echo "pre-push: node_modules/.bin/biome missing; run 'npm ci'" >&2
|
|
10
|
-
exit 1
|
|
11
|
-
}
|
|
12
|
-
command -v gitleaks >/dev/null || {
|
|
13
|
-
echo "pre-push: gitleaks missing; run 'brew install gitleaks'" >&2
|
|
14
|
-
exit 1
|
|
15
|
-
}
|
|
16
|
-
|
|
17
|
-
ranges=()
|
|
18
|
-
while read -r _local_ref local_sha _remote_ref remote_sha; do
|
|
19
|
-
[ "$local_sha" = "$zero" ] && continue
|
|
20
|
-
if [ "$remote_sha" = "$zero" ]; then
|
|
21
|
-
ranges+=("$local_sha") # new remote branch: scan all reachable history
|
|
22
|
-
else
|
|
23
|
-
ranges+=("$remote_sha..$local_sha")
|
|
24
|
-
fi
|
|
25
|
-
done
|
|
26
|
-
|
|
27
|
-
[ "${#ranges[@]}" -eq 0 ] && exit 0 # deletion-only push
|
|
28
|
-
|
|
29
|
-
npm run check
|
|
30
|
-
npm test
|
|
31
|
-
npm run pack:dry
|
|
32
|
-
for range in "${ranges[@]}"; do
|
|
33
|
-
gitleaks git --redact --no-banner --log-opts="$range"
|
|
34
|
-
done
|