hydra-nano 0.3.0 → 0.3.2

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "hydra-nano",
3
- "version": "0.3.0",
3
+ "version": "0.3.2",
4
4
  "description": "Small local models that take the noisy work off your coding agent: git history, test and build digests and OS inspection run on your machine, and only the lines that matter reach Claude Code, Codex, Cursor, OpenCode, Gemini CLI or Antigravity. Skill, MCP server and hooks.",
5
5
  "keywords": [
6
6
  "claude-code",
@@ -21,7 +21,7 @@ node scripts/hydra.mjs os [question...]
21
21
 
22
22
  - **Tests and builds:** `run --` executes the command and returns the failing tests, assertion diffs and source locations with the exit code, or a short pass summary. A run you already cut to a few lines yourself (`| tail -n 20`) gains nothing from Hydra.
23
23
  - **Git:** ask one full question per call and name the file, branch, commit or author when you know it; the model may only use a path, revision or name that appears in your question. A short check such as `git status --short` is cheaper to run yourself.
24
- - **Machine:** ports, processes, disk, memory, system info and environment variable names, with secrets withheld.
24
+ - **Machine:** ports, processes, disk, memory, system info and environment variables, with secret-looking names and values withheld.
25
25
 
26
26
  Read and search source files with your own tools: a measured trial found routing that work through Hydra cost 72% more tokens. Hydra also has `search`, `read`, `smell`, `refactor` and `design` commands (`node scripts/hydra.mjs` with no arguments lists them) for when the user asks for them.
27
27
 
@@ -29,7 +29,7 @@ Read and search source files with your own tools: a measured trial found routing
29
29
 
30
30
  - **test**: test and build output (`npm test`, `pytest`, `cargo test`, `go test`, `tsc` and others). On failure, the failing test name, assertion diff and the user's own file:line, with node_modules and framework frames dropped.
31
31
  - **git**: current branch and sync state, uncommitted and staged changes, commit history, what this branch adds over a base branch, one commit's patch, blame, branches, worktrees, remotes, stashes, tags.
32
- - **os**: listening ports, running processes and CPU consumers, disk space, memory, system info, environment variable names, never their values.
32
+ - **os**: listening ports, running processes and CPU consumers, disk space, memory, system info, and one environment variable's value unless its name or value looks like a credential.
33
33
 
34
34
  Changes to the repository, and questions that need reasoning about what code does, stay with you.
35
35
 
@@ -247,7 +247,8 @@ function improve(args) {
247
247
  for (const row of h.costMoreExamples) lines.push(` cost more: ${row.question.slice(0, 80)} (${row.raw} -> ${row.returned})`);
248
248
  }
249
249
  for (const [agent, a] of Object.entries(report.agents)) {
250
- lines.push(`agent ${agent}: ${a.calls} calls (${a.viaMcp} through MCP), ${a.denials} runs turned back, ${a.sessions} sessions started`);
250
+ const apps = Object.entries(a.fromApps ?? {}).map(([app, n]) => `, ${n} from ${app}`).join('');
251
+ lines.push(`agent ${agent}: ${a.calls} calls (${a.viaMcp} through MCP${apps}), ${a.denials} runs turned back, ${a.sessions} sessions started`);
251
252
  }
252
253
  const { denials, followedByHydra, trimmed, rawBypasses } = report.hooks;
253
254
  const { decisions, p50Ms, p90Ms } = report.hooks;
@@ -309,10 +310,7 @@ async function smellCommand(args) {
309
310
  let rawChars = 0;
310
311
 
311
312
  if (isDiff || isStaged) {
312
- const gitArgs = ['diff'];
313
- if (isStaged) gitArgs.push('--staged');
314
- const diffRes = await run('git', gitArgs, process.cwd());
315
- const diffOutput = diffRes.out || '';
313
+ const diffOutput = (await git.diffText(isStaged, process.cwd())) || '';
316
314
  rawChars = diffOutput.length;
317
315
  const diffReport = refactor.scanDiff(diffOutput);
318
316
  if (isJson) {
@@ -3,7 +3,7 @@
3
3
  // SessionStart: a short note tells the agent to ask Hydra about git history before reading it raw.
4
4
  // The installer registers them in the user's settings.json; `hydra hooks remove` takes them out again.
5
5
  // Only entries whose command points into skills/hydra/scripts/hooks/ are ever touched.
6
- import { copyFileSync, existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
6
+ import { chmodSync, copyFileSync, existsSync, mkdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs';
7
7
  import os from 'node:os';
8
8
  import path from 'node:path';
9
9
 
@@ -165,12 +165,22 @@ function withoutOurs(settings) {
165
165
  return settings;
166
166
  }
167
167
 
168
+ /** Replace a config file in one step, keeping its permission bits: a 0600 file can hold tokens.
169
+ * A file Hydra creates is owner-only. */
170
+ export function replaceFile(file, text) {
171
+ const mode = existsSync(file) ? statSync(file).mode & 0o777 : 0o600;
172
+ const temp = `${file}.hydra-tmp`;
173
+ rmSync(temp, { force: true });
174
+ writeFileSync(temp, text, { mode, flag: 'wx' });
175
+ chmodSync(temp, mode);
176
+ renameSync(temp, file);
177
+ }
178
+
168
179
  function save(file, settings) {
169
180
  mkdirSync(path.dirname(file), { recursive: true });
170
181
  // Keep the user's settings as they were before Hydra first touched them.
171
182
  if (existsSync(file) && !existsSync(`${file}.before-hydra`)) copyFileSync(file, `${file}.before-hydra`);
172
- writeFileSync(`${file}.hydra-tmp`, JSON.stringify(settings, null, 2) + '\n');
173
- renameSync(`${file}.hydra-tmp`, file);
183
+ replaceFile(file, JSON.stringify(settings, null, 2) + '\n');
174
184
  }
175
185
 
176
186
  /** Register both hooks for the Hydra scripts directory `scripts`; re-running replaces, never duplicates. */
@@ -2,6 +2,10 @@ import { execFile } from 'node:child_process';
2
2
  import { existsSync } from 'node:fs';
3
3
  import path from 'node:path';
4
4
 
5
+ // The 128+signal convention shells use for signal-terminated commands.
6
+ const SIGNALS = { SIGHUP: 1, SIGINT: 2, SIGQUIT: 3, SIGKILL: 9, SIGTERM: 15, SIGABRT: 6, SIGBUS: 7, SIGFPE: 8, SIGSEGV: 11, SIGPIPE: 13, SIGALRM: 14 };
7
+ const signalNumber = name => SIGNALS[name] ?? 15;
8
+
5
9
  // No shell: argv reaches the program as written, so nothing in it is interpreted.
6
10
  export function run(cmd, argv, cwd, env = {}) {
7
11
  // Windows batch shims cannot be launched by execFile. Use the package's
@@ -28,7 +32,18 @@ export function run(cmd, argv, cwd, env = {}) {
28
32
  (error, out, err) =>
29
33
  resolve({
30
34
  ok: !error,
31
- exitCode: error ? (typeof error.code === 'number' ? error.code : 1) : 0,
35
+ // A killed command is not a failing one: keep the real exit code when
36
+ // there is one, and use the 128+signal convention when a signal ended
37
+ // it, so a digest never presents a killed run as an ordinary exit-1
38
+ // test failure. A launch failure (ENOENT) stays exit 1.
39
+ exitCode: error
40
+ ? typeof error.code === 'number'
41
+ ? error.code
42
+ : error.signal
43
+ ? 128 + signalNumber(error.signal)
44
+ : 1
45
+ : 0,
46
+ signal: error?.signal ?? undefined,
32
47
  out: out ?? '',
33
48
  err: err || error?.message || '',
34
49
  }),
@@ -9,6 +9,12 @@ const FORMAT = ['--pretty=tformat:%h %ad %an: %s', '--date=short'];
9
9
  const PATCH = ['--no-ext-diff', '--no-textconv', '--stat', '-p'];
10
10
  const MAX_PROBES = 4;
11
11
 
12
+ /** The working-copy (or staged) patch, read with the same guards as every probe: no pager, fsmonitor,
13
+ * external diff or textconv driver from the repository's own config runs. */
14
+ export async function diffText(staged, cwd) {
15
+ return (await run('git', [...HARDEN, 'diff', '--no-ext-diff', '--no-textconv', ...(staged ? ['--staged'] : [])], cwd, ENV)).out;
16
+ }
17
+
12
18
  // A requested count belongs to the caller, not the model. Avoid treating line numbers or hashes as counts.
13
19
  const NUMBER_WORDS = {
14
20
  one: 1, two: 2, three: 3, four: 4, five: 5, six: 6, seven: 7, eight: 8, nine: 9,
@@ -16,10 +22,12 @@ const NUMBER_WORDS = {
16
22
  sixteen: 16, seventeen: 17, eighteen: 18, nineteen: 19, twenty: 20, thirty: 30, forty: 40, fifty: 50,
17
23
  };
18
24
  const COUNT = `(?:\\d+|(?:twenty|thirty|forty)[ -](?:one|two|three|four|five|six|seven|eight|nine)|${Object.keys(NUMBER_WORDS).join('|')})`;
19
- const COUNT_MODIFIERS = '(?:(?:last|latest|recent|newest|oldest|branch-only|file-specific|unique|matching|first|history|historical|past)\\s+){0,3}';
25
+ const COUNT_MODIFIERS = '(?:(?:last|latest|recent|most recent|newest|oldest|previous|prior|preceding|earlier|branch-only|file-specific|unique|matching|first|history|historical|past)\\s+){0,3}';
20
26
  const COUNT_ITEMS = '(?:commits?|revisions?|changesets?|records?)';
21
- const requestedCount = question => {
22
- const match = question.match(new RegExp(`\\b(?:last|latest|recent|top|first)\\s+(${COUNT})\\s+${COUNT_MODIFIERS}${COUNT_ITEMS}\\b`, 'i'))
27
+ // Caller-owned record counts are exported for testing; production callers pass
28
+ // them through gather, never through the model.
29
+ export const requestedCount = question => {
30
+ const match = question.match(new RegExp(`\\b(?:last|latest|recent|newest|oldest|top|first)\\s+(${COUNT})\\s+${COUNT_MODIFIERS}${COUNT_ITEMS}\\b`, 'i'))
23
31
  ?? question.match(new RegExp(`\\b(${COUNT})\\s+${COUNT_MODIFIERS}${COUNT_ITEMS}\\b`, 'i'));
24
32
  if (!match) return null;
25
33
  const text = match[1].toLowerCase();
@@ -44,6 +52,9 @@ const historyRequest = question => /\b(?:commits?|history|evolved|over time|git
44
52
  // "with timeout in their subjects", "messages mentioning cache"
45
53
  const subjectTerm = question => (question.match(/\bwith\s+["'`]?([\w.-]+)["'`]?\s+in\s+(?:their|the|its)\s+(?:subjects?|messages?|titles?)\b/i)
46
54
  ?? question.match(/\b(?:subjects?|messages?)\s+(?:containing|mentioning|that mention|with)\s+["'`]?([\w.-]+)/i))?.[1];
55
+ // "messages that mention main": the question searches message text for this word.
56
+ const searchesFor = (question, term) => subjectTerm(question)?.toLowerCase() === term.toLowerCase()
57
+ || new RegExp(`\\b(?:mention\\w*|contain\\w*|says?|saying)\\s+["'\`]?${term.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}(?![\\w.-])`, 'i').test(question);
47
58
  // The first word of the question that is a file inside the repository, e.g. src/app.ts or Makefile.
48
59
  function fileInQuestion(question, cwd) {
49
60
  for (const word of question.split(/\s+/)) {
@@ -108,7 +119,7 @@ export const PROBES = {
108
119
  blame: {
109
120
  about: 'line-by-line attribution of who wrote each specific line of a file (not for whole-file history); needs path',
110
121
  needs: 'path',
111
- argv: a => ['blame', '--date=short', '--', a.path],
122
+ argv: a => ['blame', '--no-textconv', '--date=short', '--', a.path],
112
123
  },
113
124
  branches: {
114
125
  about: 'local and remote branches with their latest commit',
@@ -208,6 +219,9 @@ async function clean(p, question, cwd) {
208
219
  // Preserve compound filtering only when the question also asks about messages.
209
220
  const asksMessage = /\b(?:messages?|subjects?|mention\w*)\b/i.test(question);
210
221
  if (safe(p.grep) && (asksMessage || (!a.path && !a.author))) a.grep = p.grep.trim();
222
+ // A branch or tag named in the question ("between v0.2.0 and main") is a range end, not message text.
223
+ if (a.grep && !searchesFor(question, a.grep)
224
+ && (await git(cwd, ['rev-parse', '--verify', '--quiet', `${a.grep}^{commit}`])).ok) delete a.grep;
211
225
  if (p.probe === 'log' && !a.grep && subjectTerm(question)) a.grep = subjectTerm(question);
212
226
  for (const key of ['rev', 'base']) {
213
227
  // HEAD as a base compares HEAD with itself and always shows nothing.
@@ -19,6 +19,7 @@
19
19
  import { copyFileSync, cpSync, existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
20
20
  import os from 'node:os';
21
21
  import path from 'node:path';
22
+ import { replaceFile } from './claude_hooks.mjs';
22
23
 
23
24
  const home = () => process.env.HYDRA_TOOLS_HOME || os.homedir();
24
25
  const OURS = /[\\/](?:\.hydra[\\/]scripts|skills[\\/]hydra[\\/]scripts)[\\/]/;
@@ -54,8 +55,7 @@ function backup(file) {
54
55
  function write(file, text) {
55
56
  mkdirSync(path.dirname(file), { recursive: true });
56
57
  backup(file);
57
- writeFileSync(`${file}.hydra-tmp`, text);
58
- renameSync(`${file}.hydra-tmp`, file);
58
+ replaceFile(file, text);
59
59
  }
60
60
 
61
61
  class Manual extends Error {
@@ -5,7 +5,7 @@
5
5
  // run through that its own pipeline already cuts to a few lines ('trimmed') or passed it ('pass', recorded
6
6
  // without the command). hookMs is the hook process's whole lifetime.
7
7
  // kind 'error': a command failed (model unavailable, crash).
8
- import { appendFileSync, mkdirSync, readFileSync } from 'node:fs';
8
+ import { appendFileSync, chmodSync, mkdirSync, readFileSync } from 'node:fs';
9
9
  import os from 'node:os';
10
10
  import path from 'node:path';
11
11
 
@@ -27,15 +27,31 @@ export function caller(session = process.env.CLAUDE_CODE_SESSION_ID) {
27
27
  const detail = process.env.HYDRA_AGENT || process.env.AI_AGENT || (process.env.CLAUDECODE ? undefined : app);
28
28
  const agent = process.env.HYDRA_AGENT ? detail.toLowerCase().replace(/[-_ ]?mcp[-_ ]?client$/, '')
29
29
  : process.env.AI_AGENT ? detail.split('_')[0] : process.env.CLAUDECODE ? 'claude-code' : app ? 'antigravity' : 'shell';
30
+ // An app that starts the agent for you (T3 Code runs Claude Code, Codex, ...) is kept apart from the agent itself.
31
+ const launcher = process.env.__CFBundleIdentifier === 'com.t3tools.t3code' || process.env.T3CODE_HOME ? 't3code' : undefined;
30
32
  return { agent, ...(detail ? { agentDetail: detail } : {}), ...(process.env.HYDRA_VIA ? { via: process.env.HYDRA_VIA } : {}),
31
- ...(session ? { session } : {}) };
33
+ ...(launcher ? { app: launcher } : {}), ...(session ? { session } : {}) };
32
34
  }
33
35
 
36
+ // Switches worth keeping readable in `hydra improve`; every other NAME=value is treated as a possible secret.
37
+ const PLAIN = /^(?:HYDRA_\w+|CI|NODE_ENV|DEBUG|FORCE_COLOR|NO_COLOR)$/;
38
+
39
+ /** A command with credential values masked: env assignments, URL passwords and secret-named flags. */
40
+ export const redact = text => String(text)
41
+ .replace(/([a-z][\w+.-]*:\/\/)[^\s/@]+@/gi, '$1***@')
42
+ .replace(/(^|[\s;&|(])([A-Za-z_]\w*)=("[^"]*"|'[^']*'|\S+)/g, (all, before, name) => (PLAIN.test(name) ? all : `${before}${name}=***`))
43
+ .replace(/(--?[\w-]*(?:token|password|passwd|secret|api[-_]?key|auth)[\w-]*)([ =])("[^"]*"|'[^']*'|\S+)/gi, '$1$2***');
44
+
34
45
  export function record(entry) {
35
46
  if (!enabled()) return;
36
47
  try {
37
- mkdirSync(home(), { recursive: true });
38
- appendFileSync(file(), `${JSON.stringify({ v: 2, kind: 'call', ...caller(), ...entry })}\n`);
48
+ // Commands and test questions can carry credentials, so the ledger is owner-only and masked.
49
+ const row = { v: 2, kind: 'call', ...caller(), ...entry };
50
+ for (const key of ['command', 'run']) if (typeof row[key] === 'string') row[key] = redact(row[key]);
51
+ if (row.head === 'test' && typeof row.question === 'string') row.question = redact(row.question);
52
+ mkdirSync(home(), { recursive: true, mode: 0o700 });
53
+ appendFileSync(file(), `${JSON.stringify(row)}\n`, { mode: 0o600 });
54
+ chmodSync(file(), 0o600);
39
55
  } catch {
40
56
  // Accounting must never fail the answer.
41
57
  }
@@ -82,7 +98,9 @@ export function stats(all = rows()) {
82
98
  const percentile = (values, p) => {
83
99
  if (!values.length) return 0;
84
100
  const sorted = [...values].sort((a, b) => a - b);
85
- return sorted[Math.min(sorted.length - 1, Math.floor(p * sorted.length))];
101
+ // Nearest-rank: the ceil(p*n)-th smallest value. floor(p*n) reported the
102
+ // maximum for p50 of two values and for p90 of ten, inflating latency.
103
+ return sorted[Math.min(sorted.length - 1, Math.max(0, Math.ceil(p * sorted.length) - 1))];
86
104
  };
87
105
 
88
106
  /**
@@ -118,8 +136,9 @@ export function findings(all = rows(), { since } = {}) {
118
136
  && call.head === 'test' && call.ts >= deny.ts && Date.parse(call.ts) - Date.parse(deny.ts) <= 5 * 60_000));
119
137
  const agents = {};
120
138
  for (const row of recent) {
121
- const agent = agents[row.agent ?? 'unknown'] ??= { calls: 0, viaMcp: 0, denials: 0, sessions: 0 };
139
+ const agent = agents[row.agent ?? 'unknown'] ??= { calls: 0, viaMcp: 0, denials: 0, sessions: 0, fromApps: {} };
122
140
  if (isCall(row)) { agent.calls += 1; if (row.via === 'mcp') agent.viaMcp += 1; }
141
+ if (isCall(row) && row.app) agent.fromApps[row.app] = (agent.fromApps[row.app] ?? 0) + 1;
123
142
  if (row.kind === 'hook' && row.decision === 'deny') agent.denials += 1;
124
143
  if (row.kind === 'session') agent.sessions += 1;
125
144
  }
@@ -26,10 +26,36 @@ async function healthy(url, model) {
26
26
  }
27
27
  catch { return false; }
28
28
  }
29
+ /** The path of the program a process runs, or undefined when it cannot be read. */
30
+ function executableOf(pid) {
31
+ try {
32
+ if (process.platform === 'win32') return execFileSync('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', `(Get-CimInstance Win32_Process -Filter 'ProcessId=${pid}').ExecutablePath`], { encoding: 'utf8', windowsHide: true }).trim() || undefined;
33
+ if (process.platform === 'linux') return readlinkSync(`/proc/${pid}/exe`);
34
+ return execFileSync('ps', ['-p', String(pid), '-o', 'comm='], { encoding: 'utf8' }).trim() || undefined;
35
+ } catch { return undefined; }
36
+ }
37
+ const sameFile = (a, b) => path.resolve(a).toLowerCase() === path.resolve(b).toLowerCase();
38
+
39
+ /** Any local user can bind 127.0.0.1:11435 first and answer as hydra-nano:git, so a listener counts as
40
+ * Hydra's only while server.pid names a live process of this user that runs config.server. */
41
+ export function ownServer(config) {
42
+ const file = path.join(home(), 'server.pid');
43
+ if (!existsSync(file)) return false;
44
+ const pid = Number(readFileSync(file, 'utf8'));
45
+ if (!Number.isSafeInteger(pid) || pid <= 0) return false;
46
+ try { process.kill(pid, 0); } catch { return false; } // gone, or another user's process (EPERM)
47
+ const executable = executableOf(pid);
48
+ return Boolean(executable) && sameFile(executable, config.server);
49
+ }
50
+
29
51
  async function startLocal(config) {
30
52
  const url = 'http://127.0.0.1:11435';
31
53
  if (config.url !== url) throw new Error('Managed Hydra server must use http://127.0.0.1:11435');
32
- if (await healthy(url, config.model)) return;
54
+ const notOurs = () => new Error('127.0.0.1:11435 answers, but not from the llama-server Hydra started (~/.hydra/server.pid); stop that process and retry');
55
+ if (await healthy(url, config.model)) {
56
+ if (ownServer(config)) return;
57
+ throw notOurs();
58
+ }
33
59
  if (!existsSync(config.server) || !existsSync(config.modelPath)) throw new Error('Hydra runtime or GGUF missing; rerun hydra-install');
34
60
  mkdirSync(home(), { recursive: true });
35
61
  const lock = path.join(home(), 'server.lock');
@@ -51,7 +77,10 @@ async function startLocal(config) {
51
77
  try {
52
78
  if (ownsLock) {
53
79
  const log = openSync(path.join(home(), 'server.log'), 'a');
54
- child = spawn(config.server, ['-m', config.modelPath, '--alias', config.model, '--host', '127.0.0.1', '--port', '11435', '-c', '8192', '-np', '1'], {
80
+ // No slot monitor (it can echo prompts), no web UI, and CORS only for localhost pages: Hydra's own
81
+ // client is Node and needs none of them, while any web page could otherwise call this port.
82
+ child = spawn(config.server, ['-m', config.modelPath, '--alias', config.model, '--host', '127.0.0.1', '--port', '11435', '-c', '8192', '-np', '1',
83
+ '--no-slots', '--no-webui', '--cors-origins', 'localhost'], {
55
84
  detached: true, windowsHide: true, stdio: ['ignore', log, log],
56
85
  });
57
86
  closeSync(log);
@@ -61,7 +90,10 @@ async function startLocal(config) {
61
90
  }
62
91
  const deadline = Date.now() + 120000;
63
92
  while (Date.now() < deadline) {
64
- if (await healthy(url, config.model)) return;
93
+ if (await healthy(url, config.model)) {
94
+ if (ownServer(config)) return;
95
+ throw notOurs();
96
+ }
65
97
  if (child && child.exitCode !== null) throw new Error('llama-server exited; inspect ~/.hydra/server.log');
66
98
  await new Promise(resolve => setTimeout(resolve, 500));
67
99
  }
@@ -77,14 +109,9 @@ export function stopLocal(config = localConfig()) {
77
109
  if (!config.managed || !existsSync(file)) return false;
78
110
  const pid = Number(readFileSync(file, 'utf8'));
79
111
  if (!Number.isSafeInteger(pid) || pid <= 0) throw new Error('Invalid managed server PID');
80
- let executable;
81
- try {
82
- if (process.platform === 'win32') executable = execFileSync('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', `(Get-CimInstance Win32_Process -Filter 'ProcessId=${pid}').ExecutablePath`], { encoding: 'utf8', windowsHide: true }).trim();
83
- else if (process.platform === 'linux') executable = readlinkSync(`/proc/${pid}/exe`);
84
- else executable = execFileSync('ps', ['-p', String(pid), '-o', 'comm='], { encoding: 'utf8' }).trim();
85
- } catch { return false; }
112
+ const executable = executableOf(pid);
86
113
  if (!executable) return false;
87
- if (path.resolve(executable).toLowerCase() !== path.resolve(config.server).toLowerCase()) throw new Error('Recorded PID belongs to another executable; refusing to stop it');
114
+ if (!sameFile(executable, config.server)) throw new Error('Recorded PID belongs to another executable; refusing to stop it');
88
115
  process.kill(pid);
89
116
  unlinkSync(file);
90
117
  starting = undefined;
@@ -6,7 +6,9 @@ const IS_MAC = process.platform === 'darwin';
6
6
  const IS_WINDOWS = process.platform === 'win32';
7
7
  const result = r => ({ ok: r.ok, out: r.out || r.err || (r.ok ? '(no output)' : '(probe failed)') });
8
8
  const powershell = script => run('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', script]);
9
- const SENSITIVE_PATTERN = /(?:SECRET|KEY|TOKEN|PASS|AUTH|CREDENTIAL|PRIVATE|CLOUDFLARE|API)/i;
9
+ const SENSITIVE_PATTERN = /(?:SECRET|KEY|TOKEN|PASS|AUTH|CREDENTIAL|PRIVATE|CLOUDFLARE|API|DSN|WEBHOOK|COOKIE|SESSION|CONN(?:ECTION)?_?STR|_PWD$|(?:^|_)PAT(?:_|$))/i;
10
+ // A value can carry a credential whatever its name: a URL with a password or user, or a connection-string key.
11
+ const SENSITIVE_VALUE = /:\/\/[^\s/@]+@|(?:AccountKey|SharedAccessKey|SharedAccessSignature|Password|Pwd)=/i;
10
12
 
11
13
  export const PROBES = {
12
14
  ports: {
@@ -101,6 +103,9 @@ export const PROBES = {
101
103
  return { ok: true, out: `[GUARDRAIL]: Variable "${v}" is flagged sensitive and cannot be inspected.` };
102
104
  }
103
105
  const val = process.env[v];
106
+ if (val !== undefined && SENSITIVE_VALUE.test(val)) {
107
+ return { ok: true, out: `[GUARDRAIL]: Variable "${v}" holds a credential-shaped value and cannot be inspected.` };
108
+ }
104
109
  return {
105
110
  ok: true,
106
111
  out: val !== undefined ? `${v}=${val}` : `Variable "${v}" is not set in environment.`,
@@ -159,9 +164,19 @@ function topic(text) {
159
164
  if (/\b(process(es)?|pids?|cpu)\b/.test(q)) return processes();
160
165
  if (/\b(ram|memory|swap)\b/.test(q)) return { probe: 'memory' };
161
166
  if (/\b(disk|space|filesystems?|storage|mount\w*)\b/.test(q)) return { probe: 'disk' };
162
- if (/\b(env|environment|path|variables?)\b/.test(q)) {
163
- const m = text.match(/\b([A-Z0-9_]{3,30})\b/);
164
- return { probe: 'env', var: m ? m[1] : 'PATH' };
167
+ if (/\b(env|environment|path|variables?|vars?)\b/.test(q)) {
168
+ // The variable the question names: an underscored ALL_CAPS name first, else
169
+ // a bare ALL_CAPS word such as HOME, TERM or USER that is not generic noise,
170
+ // else the identifier beside the singular word 'variable'/'var' (a lowercase
171
+ // shell variable such as home or pwd is just as valid). A plural 'variables'
172
+ // question names none and keeps the PATH default.
173
+ const bareCaps = (text.match(/\b[A-Z][A-Z0-9]{2,}\b/g) || []).filter(word => !NOISE_CAPS.has(word));
174
+ const named = text.match(/\b([A-Z][A-Z0-9]*(?:_[A-Z0-9]+)+)\b/)
175
+ ?? /\bvariable\s+([A-Za-z_][A-Za-z0-9_]{1,30})\b/i.exec(text)
176
+ ?? /\b([A-Za-z_][A-Za-z0-9_]{1,30})\s+variable\b/i.exec(text)
177
+ ?? /\bvar\s+([A-Za-z_][A-Za-z0-9_]{1,30})\b/i.exec(text)
178
+ ?? (bareCaps.length ? [undefined, bareCaps[0]] : null);
179
+ return { probe: 'env', var: named ? named[1] : 'PATH' };
165
180
  }
166
181
  // "running" alone is weak: "the RAM running low" is about memory, checked above.
167
182
  return /\brunning\b/.test(q) ? processes() : null;
@@ -176,6 +191,9 @@ function clauseTopics(question) {
176
191
  return found;
177
192
  }
178
193
 
194
+ // Short generic acronyms are not environment variable names; the bare-caps
195
+ // fallback below must not mistake them for one.
196
+ const NOISE_CAPS = new Set(['RAM', 'CPU', 'PID', 'OS', 'API', 'URL', 'ID', 'TODO', 'FIXME', 'GB', 'MB', 'KB']);
179
197
  const ENV_NAME = /^[A-Z][A-Z0-9]*(?:_[A-Z0-9]+)+$/;
180
198
  const MAX_LISTENERS = 40;
181
199
  // The one 2-5 digit number in a question that plans the ports probe is the port it asks about.
@@ -557,6 +557,29 @@ export function scanCode(content, filename = 'code.ts', options = {}) {
557
557
  let switchStartLine = -1;
558
558
  let nestingStart = -1;
559
559
  let maxDepthInBlock = 0;
560
+ // A file's indent width is the most common positive leading-space count on a
561
+ // nonblank code line (the mode, smallest on a tie), not the minimum: one
562
+ // stray ' x' line at the top of a file must not count every 4-space body line
563
+ // as four nesting levels. No real language indents by one space, so a
564
+ // 1-space line only defines the width when nothing wider is indented at all.
565
+ // 4-space Python still counts one level per 4 spaces.
566
+ const spaceCounts = new Map();
567
+ for (const line of lines) {
568
+ const trimmed = line.trim();
569
+ if (!trimmed || trimmed.startsWith('//') || trimmed.startsWith('#') || trimmed.startsWith('/*')) continue;
570
+ const spaces = /^ */.exec(line)[0].length;
571
+ if (spaces > 0) spaceCounts.set(spaces, (spaceCounts.get(spaces) ?? 0) + 1);
572
+ }
573
+ const unitCandidates = [...spaceCounts.keys()].filter(width => width >= 2).sort((a, b) => a - b);
574
+ const candidates = unitCandidates.length ? unitCandidates : [...spaceCounts.keys()].sort((a, b) => a - b);
575
+ let indentWidth = 0;
576
+ let mostLines = 0;
577
+ for (const width of candidates) {
578
+ if (spaceCounts.get(width) > mostLines) {
579
+ mostLines = spaceCounts.get(width);
580
+ indentWidth = width;
581
+ }
582
+ }
560
583
 
561
584
  for (let i = 0; i < lines.length; i++) {
562
585
  const line = lines[i];
@@ -590,7 +613,7 @@ export function scanCode(content, filename = 'code.ts', options = {}) {
590
613
  if (ch === '\t') tabCount++;
591
614
  else spaceCount++;
592
615
  }
593
- const depthFromSpaces = Math.floor(spaceCount / 2);
616
+ const depthFromSpaces = Math.floor(spaceCount / (indentWidth || 2));
594
617
  const depth = tabCount + depthFromSpaces;
595
618
 
596
619
  if (depth > maxNesting && !trimmed.startsWith('//') && !trimmed.startsWith('*')) {
@@ -645,7 +668,17 @@ export function scanCode(content, filename = 'code.ts', options = {}) {
645
668
  // Dead Code detection: single-line terminal statements not opening a multiline block
646
669
  if (/^\s*(?:return\b[^;{([,?:+\-=>]*;|throw\s+new\b[^;{([,?:+\-=>]*;|break;|continue;)\s*$/.test(trimmed)) {
647
670
  const nextLine = lines[i + 1]?.trim();
648
- if (nextLine && !/^[}\])]/.test(nextLine) && !/^(?:case\b|default\b|\/\/|\/\*)/.test(nextLine)) {
671
+ // An unbraced if/else makes the next line a sibling branch, not dead code:
672
+ // if (x)
673
+ // return 1;
674
+ // else <- reachable
675
+ // return 2;
676
+ // More generally, a next line less indented than the terminal statement
677
+ // left its block: it is new code, not unreachable code.
678
+ const nextIndent = lines[i + 1] ? (lines[i + 1].match(/^([ \t]*)/) ?? ['', ''])[1].length : 0;
679
+ const myIndent = line.match(/^([ \t]*)/)[1].length;
680
+ const siblingBranch = /^(?:else\b|elif\b|catch\b|finally\b)/.test(nextLine ?? '') || nextIndent < myIndent;
681
+ if (nextLine && !siblingBranch && !/^[}\])]/.test(nextLine) && !/^(?:case\b|default\b|\/\/|\/\*)/.test(nextLine)) {
649
682
  findings.push({
650
683
  smell: 'dead-code',
651
684
  name: SMELLS_CATALOG['dead-code'].name,
@@ -823,7 +856,7 @@ export function scanDiff(diffText) {
823
856
  const line = lines[i];
824
857
  if (line.startsWith('diff --git ')) {
825
858
  if (currentFile && addedLines.length) {
826
- fileDiffs.push({ file: currentFile, code: addedLines.map(l => l.text).join('\n') });
859
+ fileDiffs.push({ file: currentFile, code: addedLines.map(l => l.text).join('\n'), lineNumbers: addedLines.map(l => l.num) });
827
860
  }
828
861
  currentFile = line.split(' ')[2]?.replace(/^a\//, '') || 'unknown';
829
862
  addedLines = [];
@@ -839,12 +872,22 @@ export function scanDiff(diffText) {
839
872
  }
840
873
 
841
874
  if (currentFile && addedLines.length) {
842
- fileDiffs.push({ file: currentFile, code: addedLines.map(l => l.text).join('\n') });
875
+ fileDiffs.push({ file: currentFile, code: addedLines.map(l => l.text).join('\n'), lineNumbers: addedLines.map(l => l.num) });
843
876
  }
844
877
 
845
878
  const reports = [];
846
- for (const { file, code } of fileDiffs) {
879
+ for (const { file, code, lineNumbers } of fileDiffs) {
847
880
  const report = scanCode(code, file);
881
+ // scanCode numbers lines within the joined added-lines blob; map each
882
+ // finding back to the real new-file line it came from.
883
+ for (const finding of report.findings) {
884
+ const at = Math.min(Math.max(finding.line, 1), lineNumbers.length) - 1;
885
+ finding.line = lineNumbers[at];
886
+ if (finding.endLine !== undefined) {
887
+ const endAt = Math.min(Math.max(finding.endLine, 1), lineNumbers.length) - 1;
888
+ finding.endLine = lineNumbers[endAt];
889
+ }
890
+ }
848
891
  if (report.smellsFound > 0) {
849
892
  reports.push(report);
850
893
  }
@@ -1,4 +1,7 @@
1
1
  const FILES_FIRST = /^\s*(where|find|locate|which files?|how is|how does)\b/i;
2
+ // A build-failure question goes to the test head, whose digest carries the
3
+ // compiler/test errors; the failure word may come before or after "build".
4
+ const BUILD_FAILURE = /\bbuild\s+(?:is\s+)?(?:broken|broke|failing|failed|fails?|errors?)\b|\b(?:broken|broke|failing|failed|fails?|errors?)\b[^.?]*\bbuild\b|\bbuild\b[^.?]*\b(?:broken|broke|failing|failed|fails?|errors?)\b/i;
2
5
  const TEST = /\b(tests?|test failure|build failure|compile error|failing tests?)\b/i;
3
6
  const READ =
4
7
  /^\s*(read|slice|cat|outline|view code|inspect)\b|\b(outline of|slice lines?|lines \d+[:-]\d+)\b/i;
@@ -9,7 +12,7 @@ const GIT =
9
12
 
10
13
  // Routing is code, not a model: it must be the same every time and cost nothing.
11
14
  export function route(question, inRepo) {
12
- if (TEST.test(question)) return 'test';
15
+ if (TEST.test(question) || BUILD_FAILURE.test(question)) return 'test';
13
16
  if (!inRepo || FILES_FIRST.test(question)) return 'files';
14
17
  if (READ.test(question) || (FILE_AND_CODE.test(question) && /\b(show|read|slice|outline|implementation|defined in)\b/i.test(question))) {
15
18
  return 'read';
@@ -6,7 +6,7 @@
6
6
  // child process, so heads stay read-only, the model never writes a command, and every call lands in
7
7
  // the local ledger with the client's name as its agent.
8
8
  import { execFile } from 'node:child_process';
9
- import { existsSync, readFileSync, statSync } from 'node:fs';
9
+ import { existsSync, readFileSync, realpathSync, statSync } from 'node:fs';
10
10
  import path from 'node:path';
11
11
  import { fileURLToPath } from 'node:url';
12
12
  import { simpleCommands, testRun } from './lib/claude_hooks.mjs';
@@ -22,19 +22,22 @@ const INSTRUCTIONS = 'Hydra runs noisy read-only commands on a small local model
22
22
  + 'Keep using your own tools to read and search source files; Hydra does not save tokens there.';
23
23
 
24
24
  const cwdProperty = { type: 'string', description: 'Absolute path of the repository or project to work in. Defaults to the server\'s working directory.' };
25
- const TOOLS = [
25
+ // Clients use these hints to decide which calls need approval; hydra_run runs the project's own test scripts.
26
+ const READS = { readOnlyHint: true, openWorldHint: false };
27
+ export const TOOLS = [
26
28
  { name: 'hydra_git', description: 'Answer a read-only question about this git repository (history, diffs, blame, branches, stashes) and return only the matching lines.',
27
- inputSchema: { type: 'object', properties: { question: { type: 'string', description: 'The question, in plain words.' }, cwd: cwdProperty }, required: ['question'] } },
28
- { name: 'hydra_run', description: 'Run one test or build command (npm test, pytest, cargo test, go test, tsc, and similar) and return its digest. Shell operators are refused.',
29
- inputSchema: { type: 'object', properties: { command: { type: 'string', description: 'One test or build command, for example "npm test" or "pytest -q tests/test_api.py".' }, cwd: cwdProperty }, required: ['command'] } },
30
- { name: 'hydra_os', description: 'Answer a read-only question about this machine (ports, processes, disk, memory, system, environment variable names).',
31
- inputSchema: { type: 'object', properties: { question: { type: 'string', description: 'The question, in plain words.' } }, required: ['question'] } },
29
+ inputSchema: { type: 'object', properties: { question: { type: 'string', description: 'The question, in plain words.' }, cwd: cwdProperty }, required: ['question'] }, annotations: READS },
30
+ { name: 'hydra_run', description: 'Run one test or build command (npm test, pytest, cargo test, go test, tsc, and similar) in the project and return its digest. It runs the project\'s own test scripts. Shell operators, paths outside cwd and flags that load other code are refused.',
31
+ inputSchema: { type: 'object', properties: { command: { type: 'string', description: 'One test or build command, for example "npm test" or "pytest -q tests/test_api.py".' }, cwd: cwdProperty }, required: ['command'] },
32
+ annotations: { readOnlyHint: false, destructiveHint: true, openWorldHint: true } },
33
+ { name: 'hydra_os', description: 'Answer a read-only question about this machine (ports, processes, disk, memory, system, environment variables; credential-looking ones are withheld).',
34
+ inputSchema: { type: 'object', properties: { question: { type: 'string', description: 'The question, in plain words.' } }, required: ['question'] }, annotations: READS },
32
35
  { name: 'hydra_smell', description: 'Scan a file, directory or git diff for Refactoring.Guru code smells (Long Method, Large Class, Deep Nesting, Long Parameter List, etc.) with exact line numbers and refactoring recipes.',
33
- inputSchema: { type: 'object', properties: { target: { type: 'string', description: 'File or directory path to scan. Defaults to repository root.' }, diff: { type: 'boolean', description: 'If true, scans newly introduced smells in unstaged/staged git changes.' }, cwd: cwdProperty } } },
36
+ inputSchema: { type: 'object', properties: { target: { type: 'string', description: 'File or directory path to scan. Defaults to repository root.' }, diff: { type: 'boolean', description: 'If true, scans newly introduced smells in unstaged/staged git changes.' }, cwd: cwdProperty } }, annotations: READS },
34
37
  { name: 'hydra_refactor', description: 'Generate a step-by-step Refactoring.Guru recipe (Extract Method, Guard Clauses, Parameter Object) for a function or line range in a file.',
35
- inputSchema: { type: 'object', properties: { file: { type: 'string', description: 'Path to the file.' }, symbol: { type: 'string', description: 'Function, method or class name.' }, lines: { type: 'string', description: 'Line range like "40-90".' }, cwd: cwdProperty }, required: ['file'] } },
38
+ inputSchema: { type: 'object', properties: { file: { type: 'string', description: 'Path to the file.' }, symbol: { type: 'string', description: 'Function, method or class name.' }, lines: { type: 'string', description: 'Line range like "40-90".' }, cwd: cwdProperty }, required: ['file'] }, annotations: READS },
36
39
  { name: 'hydra_design', description: 'Query GoF design patterns from Refactoring.Guru (intent, problem, solution, applicability) or get pattern recommendations for an architectural problem.',
37
- inputSchema: { type: 'object', properties: { query: { type: 'string', description: 'Pattern name (e.g. strategy, builder, observer) or architectural problem description.' }, file: { type: 'string', description: 'Optional path to file to analyze for pattern recommendation.' }, cwd: cwdProperty }, required: ['query'] } },
40
+ inputSchema: { type: 'object', properties: { query: { type: 'string', description: 'Pattern name (e.g. strategy, builder, observer) or architectural problem description.' }, file: { type: 'string', description: 'Optional path to file to analyze for pattern recommendation.' }, cwd: cwdProperty }, required: ['query'] }, annotations: READS },
38
41
  ];
39
42
 
40
43
  let client = 'mcp-client';
@@ -81,6 +84,66 @@ function workdir(cwd) {
81
84
  return cwd;
82
85
  }
83
86
 
87
+ const inside = (root, file) => {
88
+ const rel = path.relative(root, file);
89
+ return rel !== '..' && !rel.startsWith(`..${path.sep}`) && !path.isAbsolute(rel);
90
+ };
91
+ // A word that names a file: a path separator, a leading dot or tilde. Test names, patterns and globs like ./... are checked too.
92
+ const pathLike = word => /[\\/]/.test(word) || /^[.~]/.test(word);
93
+
94
+ /** The file or directory a path word points to, if it stays inside cwd after ../ and symlinks are resolved. */
95
+ function confined(word, cwd) {
96
+ if (word.startsWith('~') || /^[A-Za-z][\w+.-]*:[^:]/.test(word) && /[\\/]/.test(word)) return null;
97
+ const file = path.resolve(cwd, word.split('::')[0]);
98
+ const root = realpathSync(cwd);
99
+ if (!inside(cwd, file) && !inside(root, file)) return null;
100
+ try { return inside(root, realpathSync(file)) ? file : null; } catch { return file; }
101
+ }
102
+
103
+ // Flags that make a runner load or run code named on the command line instead of the project's own tests.
104
+ const LOADS_CODE = [
105
+ /^--(?:import|require|loader|experimental-loader|eval|print|env-file(?:-if-exists)?|inspect(?:-brk|-port|-wait)?|experimental-config-file)(?:=|$)/,
106
+ /^-[erp]$/, // node -e/-r/-p; pytest -p is checked on its own below
107
+ /^--(?:script-shell|node-options|userconfig|globalconfig)(?:=|$)/, // npm, pnpm, yarn
108
+ /^--eval(?:=|$)/, // make
109
+ /^--config(?:=|$)/, /^-Z/, // cargo
110
+ /^--?(?:exec|toolexec|vettool|overlay)(?:=|$)/, // go
111
+ /^(?:--init-script(?:=|$)|-I)/, // gradle
112
+ ];
113
+
114
+ /** argv for one project test or build command in cwd, or a thrown reason the agent can read. */
115
+ export function runArgv(command, cwd) {
116
+ const argv = argvOf(command);
117
+ if (!argv || testRun(command.trim()) !== command.trim()) {
118
+ throw new Error('hydra_run takes one test or build command with no shell operators, redirection or env prefix, such as "npm test" or "pytest -q"');
119
+ }
120
+ const tool = path.basename(argv.find(word => !/^(?:uv|poetry|pipenv|run|-m|python3?(?:\.\d+)?|npx|pnpx|bunx)$/.test(path.basename(word))) ?? argv[0]);
121
+ for (let i = 0; i < argv.length; i++) {
122
+ const word = argv[i];
123
+ if (i > 0 && word === '--') break; // what follows goes to the test binary as its own arguments
124
+ const [flag, value] = word.startsWith('-') ? [word.split('=')[0], word.includes('=') ? word.slice(word.indexOf('=') + 1) : null] : [null, word];
125
+ if (flag && (tool === 'pytest' ? flag === '-p' && !String(value ?? argv[i + 1]).startsWith('no:') : LOADS_CODE.some(re => re.test(flag)))) {
126
+ throw new Error(`hydra_run refuses ${flag}: it loads code named on the command line`);
127
+ }
128
+ if (tool === 'make' && !flag && /^[A-Za-z_.][\w.]*=/.test(word)) throw new Error(`hydra_run refuses ${word}: a make variable can replace recipe commands`);
129
+ if (value !== null && pathLike(value) && !confined(value, cwd)) throw new Error(`hydra_run takes paths inside cwd only: ${value}`);
130
+ }
131
+ return argv;
132
+ }
133
+
134
+ const SOURCE = /\.(?:[cm]?js|jsx|tsx?|py|go|rs|java|cpp|c|h|cs)$/i;
135
+
136
+ /** A file or directory argument confined to cwd: no hidden path segment, a source extension for files. */
137
+ function projectPath(word, cwd, name) {
138
+ const refuse = () => { throw new Error(`${name} must be a source file or directory inside cwd`); };
139
+ if (typeof word !== 'string' || !word.trim() || word.startsWith('-')) refuse();
140
+ const file = confined(word, cwd);
141
+ if (!file || !existsSync(file)) refuse();
142
+ if (path.relative(realpathSync(cwd), realpathSync(file)).split(path.sep).some(part => part.startsWith('.'))) refuse();
143
+ if (!statSync(file).isDirectory() && !SOURCE.test(file)) refuse();
144
+ return realpathSync(file);
145
+ }
146
+
84
147
  function hydra(args, cwd) {
85
148
  return new Promise(resolve => {
86
149
  execFile(process.execPath, [CLI, ...args], {
@@ -103,30 +166,32 @@ export async function callTool(name, args = {}) {
103
166
  return hydra(['os', args.question], process.cwd());
104
167
  }
105
168
  if (name === 'hydra_run') {
106
- const argv = argvOf(args.command);
107
- if (!argv || testRun(args.command.trim()) !== args.command.trim()) {
108
- throw new Error('hydra_run takes one test or build command with no shell operators, redirection or env prefix, such as "npm test" or "pytest -q"');
109
- }
110
- return hydra(['run', '--', ...argv], workdir(args.cwd));
169
+ const cwd = workdir(args.cwd);
170
+ if (typeof args.command !== 'string') throw new Error('command is required');
171
+ return hydra(['run', '--', ...runArgv(args.command, cwd)], cwd);
111
172
  }
173
+ // The agent picks both cwd and the file, so a file must be project source under cwd, never a dotfile or a key.
112
174
  if (name === 'hydra_smell') {
175
+ const cwd = workdir(args.cwd);
113
176
  const cliArgs = ['smell'];
114
177
  if (args.diff) cliArgs.push('--diff');
115
- if (args.target) cliArgs.push(args.target);
116
- return hydra(cliArgs, workdir(args.cwd));
178
+ if (args.target !== undefined) cliArgs.push(projectPath(args.target, cwd, 'target'));
179
+ return hydra(cliArgs, cwd);
117
180
  }
118
181
  if (name === 'hydra_refactor') {
119
182
  if (typeof args.file !== 'string' || !args.file.trim()) throw new Error('file is required');
120
- const cliArgs = ['refactor', args.file];
121
- if (args.symbol) cliArgs.push(args.symbol);
122
- if (args.lines) cliArgs.push('--lines', args.lines);
123
- return hydra(cliArgs, workdir(args.cwd));
183
+ const cwd = workdir(args.cwd);
184
+ const cliArgs = ['refactor', projectPath(args.file, cwd, 'file')];
185
+ if (args.symbol) cliArgs.push(String(args.symbol));
186
+ if (args.lines) cliArgs.push('--lines', String(args.lines));
187
+ return hydra(cliArgs, cwd);
124
188
  }
125
189
  if (name === 'hydra_design') {
126
190
  if (typeof args.query !== 'string' || !args.query.trim()) throw new Error('query is required');
191
+ const cwd = workdir(args.cwd);
127
192
  const cliArgs = ['design', args.query];
128
- if (args.file) cliArgs.push('--file', args.file);
129
- return hydra(cliArgs, workdir(args.cwd));
193
+ if (args.file !== undefined) cliArgs.push('--file', projectPath(args.file, cwd, 'file'));
194
+ return hydra(cliArgs, cwd);
130
195
  }
131
196
  throw new Error(`Unknown tool: ${name}`);
132
197
  }