@0perator/operator 0.1.313 → 0.1.321

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.
Files changed (71) hide show
  1. package/dist/autonomy/agent-cli.js +6 -2
  2. package/dist/autonomy/cron.js +1 -1
  3. package/dist/autonomy/delegate.js +29 -4
  4. package/dist/autonomy/index.js +22 -0
  5. package/dist/autonomy/profile.js +1 -1
  6. package/dist/browser/cdp.js +1 -1
  7. package/dist/cli.js +119 -43
  8. package/dist/config/persona.js +29 -12
  9. package/dist/config/settings.js +12 -7
  10. package/dist/engine/agent.js +4 -2
  11. package/dist/engine/aurora.js +8 -3
  12. package/dist/engine/batch-scheduler.js +3 -3
  13. package/dist/engine/cli.js +1171 -0
  14. package/dist/engine/compaction.js +1 -1
  15. package/dist/engine/loop-guard.js +1 -1
  16. package/dist/engine/router-adapter.js +1 -0
  17. package/dist/idle/activity.js +20 -0
  18. package/dist/idle/index.js +5 -0
  19. package/dist/idle/monitor.js +71 -0
  20. package/dist/idle/policy.js +66 -0
  21. package/dist/idle/proc.js +22 -0
  22. package/dist/idle/reaper.js +69 -0
  23. package/dist/idle/session-record.js +59 -0
  24. package/dist/index.js +1 -1
  25. package/dist/mcp/config.js +72 -14
  26. package/dist/mcp/index.js +9 -2
  27. package/dist/memory/index.js +1 -1
  28. package/dist/permissions/index.js +22 -7
  29. package/dist/permissions/tier.js +1 -1
  30. package/dist/remote/host.js +20 -2
  31. package/dist/remote/safe-commands.js +38 -0
  32. package/dist/router/models.js.bak +78 -0
  33. package/dist/router/models.js.bak-1791259923 +78 -0
  34. package/dist/router/models.js.bak-pre-gateway +78 -0
  35. package/dist/router/models.js.bak-pre-patch2 +78 -0
  36. package/dist/router/models.js.bak2 +78 -0
  37. package/dist/services/model-autodetect.js +240 -0
  38. package/dist/services/preflight.js +54 -2
  39. package/dist/services/store-sync.js +111 -0
  40. package/dist/session-teardown.js +10 -1
  41. package/dist/session.js +22 -0
  42. package/dist/skills/catalogue.js +1 -1
  43. package/dist/tools/chauffeur-native.js +155 -0
  44. package/dist/tools/chauffeur.js +14 -3
  45. package/dist/tools/download.js +229 -0
  46. package/dist/tools/executor.js +1 -1
  47. package/dist/tools/monitoring-tools.js +312 -0
  48. package/dist/tools/native-redirect.js +140 -0
  49. package/dist/tools/paths.js +154 -0
  50. package/dist/tools/power-tools.js +627 -0
  51. package/dist/tools/registry.js +309 -18
  52. package/dist/tools/registry.js.bak-1791259948 +1914 -0
  53. package/dist/tools/registry.js.bak-pre-plugins +1914 -0
  54. package/dist/tools/shell-jobs.js +5 -2
  55. package/dist/tools/shell-session.js +4 -2
  56. package/dist/tools/tool-output-spill.js +1 -1
  57. package/dist/ui/BusTray.js +70 -0
  58. package/dist/ui/Composer.js +5 -2
  59. package/dist/ui/QuestionPrompt.js +1 -1
  60. package/dist/ui/ToolStep.js +16 -1
  61. package/dist/ui/liveTools.js +1 -1
  62. package/dist/ui/resize.js +160 -0
  63. package/dist/util/mentions.js +1 -1
  64. package/dist/vault/store.js +1 -1
  65. package/mcp/README.md +88 -0
  66. package/mcp/ocr-macos.swift +45 -0
  67. package/mcp/powertools-media.mjs +464 -0
  68. package/mcp/powertools-toolbox.mjs +1114 -0
  69. package/mcp/powertools.md +210 -0
  70. package/mcp/powertools.mjs +861 -0
  71. package/package.json +2 -1
@@ -0,0 +1,1114 @@
1
+ // powertools-toolbox.mjs — §4 enterprise candidates (25 tools).
2
+ // Loaded by powertools.mjs. Same security contract: argv-only, env cleared, root sandbox,
3
+ // soft-miss bins, caps. Mutating / remote tools require explicit env allowlists.
4
+
5
+ import { spawn } from "node:child_process";
6
+ import { createHash } from "node:crypto";
7
+ import { readdir, stat, readFile, mkdir } from "node:fs/promises";
8
+ import { join, extname } from "node:path";
9
+
10
+ const MAX_TREE_FILES = 500;
11
+ const MAX_B64 = 48 * 1024;
12
+ const MAX_HAR_ENTRIES = 200;
13
+ const WATCH_MAX_N = 20;
14
+ const WATCH_MAX_INTERVAL_MS = 10_000;
15
+
16
+ function parseAllowlist(envVal) {
17
+ if (!envVal || typeof envVal !== "string") return new Set();
18
+ return new Set(
19
+ envVal
20
+ .split(/[,;\s]+/)
21
+ .map((s) => s.trim())
22
+ .filter(Boolean),
23
+ );
24
+ }
25
+
26
+ function hostAllowed(host) {
27
+ const allow = parseAllowlist(process.env.POWERTOOLS_SSH_HOSTS);
28
+ if (!allow.size) return { ok: false, error: "error: POWERTOOLS_SSH_HOSTS allowlist required (comma-separated hosts)" };
29
+ if (!allow.has(host)) return { ok: false, error: `error: host '${host}' not in POWERTOOLS_SSH_HOSTS` };
30
+ return { ok: true };
31
+ }
32
+
33
+ function cmdAllowed(cmd) {
34
+ const allow = parseAllowlist(process.env.POWERTOOLS_SSH_CMDS);
35
+ if (!allow.size) return { ok: false, error: "error: POWERTOOLS_SSH_CMDS allowlist required (exact remote argv[0] tokens)" };
36
+ if (!allow.has(cmd)) return { ok: false, error: `error: remote command '${cmd}' not in POWERTOOLS_SSH_CMDS` };
37
+ return { ok: true };
38
+ }
39
+
40
+ function mutateAllowed() {
41
+ return process.env.POWERTOOLS_ALLOW_MUTATE === "1" || process.env.POWERTOOLS_ALLOW_MUTATE === "true";
42
+ }
43
+
44
+ function unitAllowed(unit) {
45
+ const allow = parseAllowlist(process.env.POWERTOOLS_RESPAWN_UNITS);
46
+ if (!allow.size) return { ok: false, error: "error: POWERTOOLS_RESPAWN_UNITS allowlist required" };
47
+ if (!allow.has(unit)) return { ok: false, error: `error: unit '${unit}' not in POWERTOOLS_RESPAWN_UNITS` };
48
+ return { ok: true };
49
+ }
50
+
51
+ const HOST_RE = /^[A-Za-z0-9](?:[A-Za-z0-9.-]{0,251}[A-Za-z0-9])?$/;
52
+ const UNIT_RE = /^[A-Za-z0-9][A-Za-z0-9._@-]{0,127}$/;
53
+ const CONTAINER_RE = /^[A-Za-z0-9][A-Za-z0-9._/-]{0,127}$/;
54
+
55
+ /**
56
+ * @param {object} S shared helpers from powertools.mjs
57
+ * @returns {{ binCandidates: Record<string, string[]>, toolDefs: object[] }}
58
+ */
59
+ export function buildToolbox(S) {
60
+ const {
61
+ findBinary,
62
+ resolveUnderRoot,
63
+ runCapped,
64
+ okText,
65
+ errText,
66
+ clampInt,
67
+ PROJECT_ROOT,
68
+ UNTRUSTED,
69
+ realpath,
70
+ TIMEOUT_MS,
71
+ DEFAULT_MAX_RESULTS,
72
+ HARD_MAX_RESULTS,
73
+ } = S;
74
+
75
+ const binCandidates = {
76
+ file: ["/usr/bin/file", "/opt/homebrew/bin/file"],
77
+ strings: ["/usr/bin/strings", "/opt/homebrew/bin/strings"],
78
+ find: ["/usr/bin/find", "/bin/find"],
79
+ comm: ["/usr/bin/comm", "/bin/comm"],
80
+ join: ["/usr/bin/join", "/bin/join"],
81
+ tar: ["/usr/bin/tar", "/bin/tar"],
82
+ unzip: ["/usr/bin/unzip", "/opt/homebrew/bin/unzip"],
83
+ base64: ["/usr/bin/base64", "/bin/base64"],
84
+ curl: ["/usr/bin/curl", "/opt/homebrew/bin/curl"],
85
+ openssl: ["/usr/bin/openssl", "/opt/homebrew/bin/openssl"],
86
+ ssh: ["/usr/bin/ssh", "/opt/homebrew/bin/ssh"],
87
+ scp: ["/usr/bin/scp", "/opt/homebrew/bin/scp"],
88
+ launchctl: ["/bin/launchctl"],
89
+ systemctl: ["/usr/bin/systemctl", "/bin/systemctl"],
90
+ docker: ["/usr/bin/docker", "/usr/local/bin/docker", "/Users/jl2/.docker/bin/docker", "/opt/homebrew/bin/docker"],
91
+ podman: ["/usr/bin/podman", "/opt/homebrew/bin/podman"],
92
+ git: ["/usr/bin/git", "/opt/homebrew/bin/git", "/usr/local/bin/git"],
93
+ npm: ["/opt/homebrew/bin/npm", "/usr/local/bin/npm"],
94
+ npx: ["/opt/homebrew/bin/npx", "/usr/local/bin/npx"],
95
+ pytest: ["/opt/homebrew/bin/pytest", "/usr/local/bin/pytest"],
96
+ biome: ["/opt/homebrew/bin/biome", "/usr/local/bin/biome"],
97
+ ruff: ["/opt/homebrew/bin/ruff", "/usr/local/bin/ruff"],
98
+ eslint: ["/opt/homebrew/bin/eslint", "/usr/local/bin/eslint"],
99
+ };
100
+
101
+ // Resolve bins into a local map (caller also merges into main BIN)
102
+ const B = {};
103
+ for (const [name, cands] of Object.entries(binCandidates)) {
104
+ B[name] = findBinary(name, cands);
105
+ }
106
+
107
+ function need(name) {
108
+ if (!B[name]) return errText(`error: binary '${name}' not installed on this host (soft-miss)`);
109
+ return null;
110
+ }
111
+
112
+ async function walkHash(dir, depth, maxDepth, out, limit) {
113
+ if (out.length >= limit) return;
114
+ let entries;
115
+ try {
116
+ entries = await readdir(dir, { withFileTypes: true });
117
+ } catch {
118
+ return;
119
+ }
120
+ for (const e of entries) {
121
+ if (out.length >= limit) return;
122
+ if (e.name === ".git" || e.name === "node_modules" || e.name === ".venv") continue;
123
+ const p = join(dir, e.name);
124
+ if (e.isDirectory()) {
125
+ if (depth < maxDepth) await walkHash(p, depth + 1, maxDepth, out, limit);
126
+ } else if (e.isFile()) {
127
+ try {
128
+ const buf = await readFile(p);
129
+ const h = createHash("sha256").update(buf).digest("hex");
130
+ out.push(`${h} ${p}`);
131
+ } catch {
132
+ /* skip unreadable */
133
+ }
134
+ }
135
+ }
136
+ }
137
+
138
+ // ── Handlers ─────────────────────────────────────────────────────────────
139
+
140
+ async function handleFileInfo(args) {
141
+ const miss = need("file");
142
+ if (miss) return miss;
143
+ const r = await resolveUnderRoot(args?.path);
144
+ if (r.error) return errText(r.error);
145
+ const fileOut = await runCapped(B.file, ["--brief", "--", r.path]);
146
+ if (fileOut.isError) return fileOut;
147
+ let stLine = "";
148
+ try {
149
+ const st = await stat(r.path);
150
+ stLine = JSON.stringify({
151
+ size: st.size,
152
+ mode: (st.mode & 0o777).toString(8),
153
+ mtime: st.mtime.toISOString(),
154
+ isFile: st.isFile(),
155
+ isDirectory: st.isDirectory(),
156
+ isSymbolicLink: st.isSymbolicLink(),
157
+ });
158
+ } catch (e) {
159
+ stLine = `stat_error: ${e.message}`;
160
+ }
161
+ return okText(`file: ${fileOut.content[0].text.trim()}\nstat: ${stLine}`);
162
+ }
163
+
164
+ async function handleStringsScan(args) {
165
+ const miss = need("strings");
166
+ if (miss) return miss;
167
+ const r = await resolveUnderRoot(args?.path);
168
+ if (r.error) return errText(r.error);
169
+ const min = clampInt(args?.min_length, 4, 64);
170
+ return runCapped(B.strings, ["-n", String(min), "--", r.path]);
171
+ }
172
+
173
+ async function handleHashTree(args) {
174
+ const path = args?.path;
175
+ const searchRoot = path
176
+ ? await resolveUnderRoot(path)
177
+ : { path: await realpath(PROJECT_ROOT).catch(() => PROJECT_ROOT) };
178
+ if (searchRoot.error) return errText(searchRoot.error);
179
+ const depth = clampInt(args?.max_depth, 4, 16);
180
+ const limit = clampInt(args?.max_files, 100, MAX_TREE_FILES);
181
+ const out = [];
182
+ await walkHash(searchRoot.path, 0, depth, out, limit);
183
+ if (!out.length) return okText("(no files hashed)");
184
+ if (out.length >= limit) out.push(`[truncated: hashed ${limit} files]`);
185
+ return okText(out.join("\n"));
186
+ }
187
+
188
+ async function handleCommJoin(args) {
189
+ const mode = String(args?.mode || "comm12");
190
+ const a = await resolveUnderRoot(args?.path_a);
191
+ if (a.error) return errText(a.error);
192
+ const b = await resolveUnderRoot(args?.path_b);
193
+ if (b.error) return errText(b.error);
194
+ if (mode === "comm12" || mode === "comm23" || mode === "comm13") {
195
+ const miss = need("comm");
196
+ if (miss) return miss;
197
+ const flags =
198
+ mode === "comm12" ? ["-12"] : mode === "comm23" ? ["-23"] : ["-13"];
199
+ return runCapped(B.comm, [...flags, "--", a.path, b.path]);
200
+ }
201
+ if (mode === "join") {
202
+ const miss = need("join");
203
+ if (miss) return miss;
204
+ return runCapped(B.join, ["--", a.path, b.path]);
205
+ }
206
+ return errText("error: mode must be comm12|comm23|comm13|join");
207
+ }
208
+
209
+ async function handleArchiveList(args) {
210
+ const r = await resolveUnderRoot(args?.path);
211
+ if (r.error) return errText(r.error);
212
+ const ext = extname(r.path).toLowerCase();
213
+ if (ext === ".zip") {
214
+ const miss = need("unzip");
215
+ if (miss) return miss;
216
+ return runCapped(B.unzip, ["-l", "--", r.path]);
217
+ }
218
+ const miss = need("tar");
219
+ if (miss) return miss;
220
+ return runCapped(B.tar, ["-tf", "--", r.path]);
221
+ }
222
+
223
+ async function handleArchiveExtract(args) {
224
+ if (!mutateAllowed()) {
225
+ return errText("error: archive_extract requires POWERTOOLS_ALLOW_MUTATE=1");
226
+ }
227
+ const src = await resolveUnderRoot(args?.path);
228
+ if (src.error) return errText(src.error);
229
+ const destArg = args?.dest || ".";
230
+ const dest = await resolveUnderRoot(destArg);
231
+ // dest may not exist yet — resolve parent under root
232
+ let destPath = dest.path;
233
+ if (dest.error) {
234
+ const abs = destArg.startsWith("/")
235
+ ? destArg
236
+ : join(PROJECT_ROOT, destArg);
237
+ const parent = join(abs, "..");
238
+ const rp = await resolveUnderRoot(parent);
239
+ if (rp.error) return errText(dest.error);
240
+ destPath = abs;
241
+ await mkdir(destPath, { recursive: true }).catch(() => {});
242
+ const check = await resolveUnderRoot(destPath);
243
+ if (check.error) return errText(check.error);
244
+ destPath = check.path;
245
+ }
246
+ const ext = extname(src.path).toLowerCase();
247
+ if (ext === ".zip") {
248
+ const miss = need("unzip");
249
+ if (miss) return miss;
250
+ return runCapped(B.unzip, ["-o", "-d", destPath, "--", src.path]);
251
+ }
252
+ const miss = need("tar");
253
+ if (miss) return miss;
254
+ return runCapped(B.tar, ["-xf", src.path, "-C", destPath]);
255
+ }
256
+
257
+ async function handleBase64Codec(args) {
258
+ const miss = need("base64");
259
+ if (miss) return miss;
260
+ const op = String(args?.op || "encode");
261
+ if (op !== "encode" && op !== "decode") return errText("error: op must be encode|decode");
262
+ let input = args?.data;
263
+ if (args?.path) {
264
+ const r = await resolveUnderRoot(args.path);
265
+ if (r.error) return errText(r.error);
266
+ input = await readFile(r.path, "utf8");
267
+ }
268
+ if (typeof input !== "string") return errText("error: provide data or path");
269
+ if (input.length > MAX_B64) return errText(`error: input exceeds ${MAX_B64} bytes`);
270
+ if (op === "encode") {
271
+ return runCapped(B.base64, [], { stdin: input });
272
+ }
273
+ // decode: macOS base64 -D, linux -d
274
+ const argv = process.platform === "darwin" ? ["-D"] : ["-d"];
275
+ return runCapped(B.base64, argv, { stdin: input });
276
+ }
277
+
278
+ async function handleHttpProbe(args) {
279
+ const url = String(args?.url || "");
280
+ if (!/^https?:\/\//i.test(url) || url.length > 2048) {
281
+ return errText("error: url must be http(s) and ≤2048 chars");
282
+ }
283
+ const method = String(args?.method || "HEAD").toUpperCase();
284
+ if (method !== "GET" && method !== "HEAD") return errText("error: method must be GET|HEAD");
285
+ const timeoutMs = clampInt(args?.timeout_ms, 3000, 15000);
286
+ // Prefer curl if present (cleared env); else fetch
287
+ if (B.curl) {
288
+ const argv = ["-sS", "-D", "-", "-o", "/dev/null", "-X", method, "--max-time", String(Math.ceil(timeoutMs / 1000)), "--", url];
289
+ if (method === "GET") {
290
+ argv[4] = "-o"; // keep headers on stdout via -D - ; body discarded
291
+ // -D - -o /dev/null still works for GET
292
+ }
293
+ return runCapped(B.curl, argv, { okCodes: [0, 22] });
294
+ }
295
+ const ctrl = new AbortController();
296
+ const t = setTimeout(() => ctrl.abort(), timeoutMs);
297
+ const t0 = Date.now();
298
+ try {
299
+ const res = await fetch(url, { method, signal: ctrl.signal, redirect: "manual" });
300
+ const hdrs = [...res.headers.entries()].map(([k, v]) => `${k}: ${v}`).join("\n");
301
+ return okText(`status: ${res.status}\nlatency_ms: ${Date.now() - t0}\n${hdrs}`);
302
+ } catch (e) {
303
+ return errText(`error: ${e.message}`);
304
+ } finally {
305
+ clearTimeout(t);
306
+ }
307
+ }
308
+
309
+ async function handleTlsInspect(args) {
310
+ const miss = need("openssl");
311
+ if (miss) return miss;
312
+ const host = String(args?.host || "");
313
+ if (!HOST_RE.test(host)) return errText("error: invalid host");
314
+ const port = clampInt(args?.port, 443, 65535);
315
+ // -servername for SNI; quit after handshake via echo Q
316
+ return runCapped(
317
+ B.openssl,
318
+ ["s_client", "-connect", `${host}:${port}`, "-servername", host, "-brief"],
319
+ { stdin: "Q\n", okCodes: [0, 1] },
320
+ );
321
+ }
322
+
323
+ async function handleSshExec(args) {
324
+ const miss = need("ssh");
325
+ if (miss) return miss;
326
+ const host = String(args?.host || "");
327
+ if (!HOST_RE.test(host)) return errText("error: invalid host");
328
+ const ha = hostAllowed(host);
329
+ if (!ha.ok) return errText(ha.error);
330
+ const remoteCmd = String(args?.command || "");
331
+ if (!remoteCmd || remoteCmd.length > 256 || /[;&|`$<>]/.test(remoteCmd)) {
332
+ return errText("error: command must be a single allowlisted token (no shell metacharacters)");
333
+ }
334
+ const ca = cmdAllowed(remoteCmd.split(/\s+/)[0]);
335
+ if (!ca.ok) return errText(ca.error);
336
+ const remoteArgs = Array.isArray(args?.args)
337
+ ? args.args.map(String).slice(0, 8)
338
+ : [];
339
+ for (const a of remoteArgs) {
340
+ if (a.length > 256 || /[\0\n]/.test(a)) return errText("error: bad remote arg");
341
+ }
342
+ // BatchMode: no password prompt; no free shell — command as remote argv via --
343
+ return runCapped(B.ssh, ["-o", "BatchMode=yes", "-o", "ConnectTimeout=5", host, "--", remoteCmd, ...remoteArgs]);
344
+ }
345
+
346
+ async function handleScpGet(args) {
347
+ const miss = need("scp");
348
+ if (miss) return miss;
349
+ const host = String(args?.host || "");
350
+ if (!HOST_RE.test(host)) return errText("error: invalid host");
351
+ const ha = hostAllowed(host);
352
+ if (!ha.ok) return errText(ha.error);
353
+ const remote = String(args?.remote_path || "");
354
+ if (!remote || remote.includes("..") || remote.length > 512) return errText("error: bad remote_path");
355
+ const local = await resolveUnderRoot(args?.local_path);
356
+ if (local.error) return errText(local.error);
357
+ return runCapped(B.scp, ["-o", "BatchMode=yes", "-o", "ConnectTimeout=5", "--", `${host}:${remote}`, local.path]);
358
+ }
359
+
360
+ async function handleScpPut(args) {
361
+ if (!mutateAllowed()) return errText("error: scp_put requires POWERTOOLS_ALLOW_MUTATE=1");
362
+ const miss = need("scp");
363
+ if (miss) return miss;
364
+ const host = String(args?.host || "");
365
+ if (!HOST_RE.test(host)) return errText("error: invalid host");
366
+ const ha = hostAllowed(host);
367
+ if (!ha.ok) return errText(ha.error);
368
+ const remote = String(args?.remote_path || "");
369
+ if (!remote || remote.includes("..") || remote.length > 512) return errText("error: bad remote_path");
370
+ const local = await resolveUnderRoot(args?.local_path);
371
+ if (local.error) return errText(local.error);
372
+ return runCapped(B.scp, ["-o", "BatchMode=yes", "-o", "ConnectTimeout=5", "--", local.path, `${host}:${remote}`]);
373
+ }
374
+
375
+ async function handleSshTunnelLocal(args) {
376
+ if (!mutateAllowed()) return errText("error: ssh_tunnel_local requires POWERTOOLS_ALLOW_MUTATE=1");
377
+ const miss = need("ssh");
378
+ if (miss) return miss;
379
+ const host = String(args?.host || "");
380
+ if (!HOST_RE.test(host)) return errText("error: invalid host");
381
+ const ha = hostAllowed(host);
382
+ if (!ha.ok) return errText(ha.error);
383
+ const localPort = Number(args?.local_port);
384
+ const remotePort = Number(args?.remote_port);
385
+ if (!Number.isInteger(localPort) || localPort < 1024 || localPort > 65535) {
386
+ return errText("error: local_port must be 1024–65535");
387
+ }
388
+ if (!Number.isInteger(remotePort) || remotePort < 1 || remotePort > 65535) {
389
+ return errText("error: remote_port must be 1–65535");
390
+ }
391
+ const remoteHost = String(args?.remote_host || "127.0.0.1");
392
+ if (!HOST_RE.test(remoteHost) && remoteHost !== "127.0.0.1") {
393
+ return errText("error: invalid remote_host");
394
+ }
395
+ // One-shot check: open tunnel briefly then exit — full long-lived tunnels are owner/daemon territory.
396
+ // -f -N -o ExitOnForwardFailure=yes with a short sleep via BatchMode and -o ConnectTimeout
397
+ return runCapped(
398
+ B.ssh,
399
+ [
400
+ "-f",
401
+ "-N",
402
+ "-o",
403
+ "BatchMode=yes",
404
+ "-o",
405
+ "ExitOnForwardFailure=yes",
406
+ "-o",
407
+ "ConnectTimeout=5",
408
+ "-L",
409
+ `${localPort}:${remoteHost}:${remotePort}`,
410
+ host,
411
+ "true",
412
+ ],
413
+ { okCodes: [0] },
414
+ );
415
+ }
416
+
417
+ async function handlePortForwardStatus(args) {
418
+ // Reuse lsof from main BIN via S.BIN
419
+ const lsof = S.BIN?.lsof || B.lsof;
420
+ if (!lsof) return errText("error: binary 'lsof' not installed (soft-miss)");
421
+ const port = args?.port;
422
+ let argv = ["-nP", "-iTCP", "-sTCP:LISTEN"];
423
+ if (port != null) {
424
+ const p = Number(port);
425
+ if (!Number.isInteger(p) || p < 1 || p > 65535) return errText("error: bad port");
426
+ argv = ["-nP", `-iTCP:${p}`, "-sTCP:LISTEN"];
427
+ }
428
+ return runCapped(lsof, argv, { okCodes: [0, 1] });
429
+ }
430
+
431
+ async function handleTestRunner(args) {
432
+ if (!mutateAllowed()) return errText("error: test_runner requires POWERTOOLS_ALLOW_MUTATE=1 (writes artifacts)");
433
+ const runner = String(args?.runner || "npm");
434
+ const cwdR = args?.cwd ? await resolveUnderRoot(args.cwd) : { path: PROJECT_ROOT };
435
+ if (cwdR.error) return errText(cwdR.error);
436
+ const allowed = {
437
+ npm: { bin: B.npm, argv: ["test", "--", ...(Array.isArray(args?.extra) ? args.extra.map(String).slice(0, 4) : [])] },
438
+ pytest: { bin: B.pytest, argv: [".", ...(Array.isArray(args?.extra) ? args.extra.map(String).slice(0, 4) : [])] },
439
+ };
440
+ const spec = allowed[runner];
441
+ if (!spec) return errText("error: runner must be npm|pytest");
442
+ if (!spec.bin) return errText(`error: binary for ${runner} missing (soft-miss)`);
443
+ // run with cwd via spawn — extend runCapped? use spawn with cwd in a local helper
444
+ return runWithCwd(spec.bin, spec.argv, cwdR.path);
445
+ }
446
+
447
+ async function handleLintRunner(args) {
448
+ const runner = String(args?.runner || "biome");
449
+ const cwdR = args?.cwd ? await resolveUnderRoot(args.cwd) : { path: PROJECT_ROOT };
450
+ if (cwdR.error) return errText(cwdR.error);
451
+ const map = {
452
+ biome: { bin: B.biome, argv: ["check", "."] },
453
+ ruff: { bin: B.ruff, argv: ["check", "."] },
454
+ eslint: { bin: B.eslint, argv: ["."] },
455
+ };
456
+ const spec = map[runner];
457
+ if (!spec) return errText("error: runner must be biome|ruff|eslint");
458
+ if (!spec.bin) return errText(`error: binary for ${runner} missing (soft-miss)`);
459
+ return runWithCwd(spec.bin, spec.argv, cwdR.path, { okCodes: [0, 1] });
460
+ }
461
+
462
+ function runWithCwd(bin, argv, cwd, opts = {}) {
463
+ const okCodes = new Set(opts.okCodes || [0]);
464
+ return new Promise((resolvePromise) => {
465
+ const proc = spawn(bin, argv, { env: {}, cwd, stdio: ["ignore", "pipe", "pipe"] });
466
+ let stdout = "";
467
+ let stderr = "";
468
+ let bytes = 0;
469
+ let truncated = false;
470
+ const timer = setTimeout(() => {
471
+ try {
472
+ proc.kill("SIGKILL");
473
+ } catch {
474
+ /* */
475
+ }
476
+ resolvePromise(errText(`error: timed out after ${TIMEOUT_MS}ms`));
477
+ }, Math.max(TIMEOUT_MS, 60_000));
478
+ proc.stdout.on("data", (c) => {
479
+ bytes += c.length;
480
+ if (bytes <= 64 * 1024) stdout += c.toString("utf8");
481
+ else truncated = true;
482
+ });
483
+ proc.stderr.on("data", (c) => {
484
+ if (stderr.length < 8 * 1024) stderr += c.toString("utf8");
485
+ });
486
+ proc.on("close", (code) => {
487
+ clearTimeout(timer);
488
+ if (truncated) stdout += "\n[truncated: output exceeded 64 KiB cap]";
489
+ if (code !== null && !okCodes.has(code)) {
490
+ resolvePromise(errText(`error: exit ${code}: ${(stderr || stdout || "unknown").trim()}`));
491
+ return;
492
+ }
493
+ resolvePromise(okText((stdout || stderr).trimEnd()));
494
+ });
495
+ proc.on("error", (e) => {
496
+ clearTimeout(timer);
497
+ resolvePromise(errText(`error: ${e.message}`));
498
+ });
499
+ });
500
+ }
501
+
502
+ async function handleCoverageSummary(args) {
503
+ const r = await resolveUnderRoot(args?.path || "coverage/coverage-summary.json");
504
+ if (r.error) return errText(r.error);
505
+ const text = await readFile(r.path, "utf8");
506
+ if (r.path.endsWith(".json")) {
507
+ try {
508
+ const j = JSON.parse(text);
509
+ const total = j.total || j;
510
+ return okText(JSON.stringify(total, null, 2).slice(0, 16_000));
511
+ } catch (e) {
512
+ return errText(`error: invalid JSON: ${e.message}`);
513
+ }
514
+ }
515
+ // lcov: summarize LH/LF lines
516
+ let lh = 0;
517
+ let lf = 0;
518
+ for (const line of text.split("\n")) {
519
+ if (line.startsWith("LH:")) lh += Number(line.slice(3)) || 0;
520
+ if (line.startsWith("LF:")) lf += Number(line.slice(3)) || 0;
521
+ }
522
+ const pct = lf ? ((100 * lh) / lf).toFixed(2) : "n/a";
523
+ return okText(JSON.stringify({ lines_hit: lh, lines_found: lf, pct }));
524
+ }
525
+
526
+ async function handleHarExtract(args) {
527
+ const r = await resolveUnderRoot(args?.path);
528
+ if (r.error) return errText(r.error);
529
+ let har;
530
+ try {
531
+ har = JSON.parse(await readFile(r.path, "utf8"));
532
+ } catch (e) {
533
+ return errText(`error: invalid HAR JSON: ${e.message}`);
534
+ }
535
+ const entries = har?.log?.entries;
536
+ if (!Array.isArray(entries)) return errText("error: HAR missing log.entries");
537
+ const limit = clampInt(args?.max_results, 50, MAX_HAR_ENTRIES);
538
+ const rows = entries.slice(0, limit).map((e) => ({
539
+ method: e?.request?.method,
540
+ url: e?.request?.url,
541
+ status: e?.response?.status,
542
+ mime: e?.response?.content?.mimeType,
543
+ }));
544
+ return okText(JSON.stringify(rows, null, 2));
545
+ }
546
+
547
+ async function handleJwtDecode(args) {
548
+ const token = String(args?.token || "").trim();
549
+ if (!token || token.length > 8192) return errText("error: token required (≤8192)");
550
+ const parts = token.split(".");
551
+ if (parts.length < 2) return errText("error: not a JWT (need header.payload)");
552
+ const b64url = (s) => {
553
+ const pad = "=".repeat((4 - (s.length % 4)) % 4);
554
+ const b64 = (s + pad).replace(/-/g, "+").replace(/_/g, "/");
555
+ return Buffer.from(b64, "base64").toString("utf8");
556
+ };
557
+ try {
558
+ const header = JSON.parse(b64url(parts[0]));
559
+ const payload = JSON.parse(b64url(parts[1]));
560
+ // strip common secret-ish claims from display? keep as-is but mark unverified
561
+ return okText(
562
+ JSON.stringify({ verified: false, note: "decode-only; signature NOT verified", header, payload }, null, 2),
563
+ );
564
+ } catch (e) {
565
+ return errText(`error: decode failed: ${e.message}`);
566
+ }
567
+ }
568
+
569
+ async function handleEnvDiff(args) {
570
+ const a = await resolveUnderRoot(args?.path_a);
571
+ if (a.error) return errText(a.error);
572
+ const b = await resolveUnderRoot(args?.path_b);
573
+ if (b.error) return errText(b.error);
574
+ const allow = parseAllowlist(args?.keys || process.env.POWERTOOLS_ENV_KEYS || "");
575
+ if (!allow.size) return errText("error: provide keys (comma list) or POWERTOOLS_ENV_KEYS");
576
+ const parseEnv = (text) => {
577
+ const map = {};
578
+ for (const line of text.split("\n")) {
579
+ const m = /^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/.exec(line);
580
+ if (m) map[m[1]] = m[2];
581
+ }
582
+ return map;
583
+ };
584
+ const ea = parseEnv(await readFile(a.path, "utf8"));
585
+ const eb = parseEnv(await readFile(b.path, "utf8"));
586
+ const secretish = /TOKEN|SECRET|PASSWORD|KEY|PASSWD|CREDENTIAL/i;
587
+ const diff = [];
588
+ for (const k of allow) {
589
+ const va = ea[k];
590
+ const vb = eb[k];
591
+ const redact = (v) => (v == null ? null : secretish.test(k) ? "[REDACTED]" : v);
592
+ if (va !== vb) diff.push({ key: k, a: redact(va), b: redact(vb) });
593
+ }
594
+ return okText(JSON.stringify({ changed: diff.length, diff }, null, 2));
595
+ }
596
+
597
+ async function handleServiceList(args) {
598
+ const filter = args?.name != null ? String(args.name) : "";
599
+ if (filter && (filter.length > 64 || /[\0\n]/.test(filter))) return errText("error: bad name filter");
600
+ if (process.platform === "darwin") {
601
+ const miss = need("launchctl");
602
+ if (miss) return miss;
603
+ const result = await runCapped(B.launchctl, ["list"]);
604
+ if (result.isError) return result;
605
+ let lines = result.content[0].text.split("\n");
606
+ if (filter) {
607
+ const n = filter.toLowerCase();
608
+ lines = lines.filter((l) => l.toLowerCase().includes(n));
609
+ }
610
+ const limit = clampInt(args?.max_results, DEFAULT_MAX_RESULTS, HARD_MAX_RESULTS);
611
+ if (lines.length > limit) {
612
+ lines = lines.slice(0, limit);
613
+ lines.push(`[truncated: ${limit}]`);
614
+ }
615
+ return okText(lines.join("\n"));
616
+ }
617
+ const miss = need("systemctl");
618
+ if (miss) return miss;
619
+ return runCapped(B.systemctl, ["list-units", "--type=service", "--no-pager", "--no-legend"]);
620
+ }
621
+
622
+ async function handleContainerPs(args) {
623
+ const bin = B.docker || B.podman;
624
+ if (!bin) return errText("error: docker/podman not installed (soft-miss)");
625
+ return runCapped(bin, ["ps", "--format", "{{.ID}}\t{{.Names}}\t{{.Image}}\t{{.Status}}\t{{.Ports}}"]);
626
+ }
627
+
628
+ async function handleContainerLogs(args) {
629
+ const bin = B.docker || B.podman;
630
+ if (!bin) return errText("error: docker/podman not installed (soft-miss)");
631
+ const name = String(args?.name || "");
632
+ if (!CONTAINER_RE.test(name)) return errText("error: invalid container name");
633
+ const allow = parseAllowlist(process.env.POWERTOOLS_CONTAINERS);
634
+ if (allow.size && !allow.has(name)) {
635
+ return errText("error: container not in POWERTOOLS_CONTAINERS allowlist");
636
+ }
637
+ const tail = clampInt(args?.tail, 80, 500);
638
+ return runCapped(bin, ["logs", "--tail", String(tail), "--", name], { okCodes: [0, 1] });
639
+ }
640
+
641
+ async function handleGitStatusDiff(args) {
642
+ const miss = need("git");
643
+ if (miss) return miss;
644
+ const cwdR = args?.cwd ? await resolveUnderRoot(args.cwd) : { path: PROJECT_ROOT };
645
+ if (cwdR.error) return errText(cwdR.error);
646
+ const mode = String(args?.mode || "status");
647
+ if (mode === "status") return runWithCwd(B.git, ["status", "--short", "--branch"], cwdR.path);
648
+ if (mode === "diff") return runWithCwd(B.git, ["diff", "--stat"], cwdR.path);
649
+ return errText("error: mode must be status|diff");
650
+ }
651
+
652
+ async function handleAgentRespawnFixed(args) {
653
+ if (!mutateAllowed()) return errText("error: agent_respawn_safe requires POWERTOOLS_ALLOW_MUTATE=1");
654
+ const unit = String(args?.unit || "");
655
+ if (!UNIT_RE.test(unit)) return errText("error: invalid unit label");
656
+ const ua = unitAllowed(unit);
657
+ if (!ua.ok) return errText(ua.error);
658
+ if (process.platform === "darwin") {
659
+ const miss = need("launchctl");
660
+ if (miss) return miss;
661
+ const uid = typeof process.getuid === "function" ? process.getuid() : 501;
662
+ const target = `gui/${uid}/${unit}`;
663
+ return runCapped(B.launchctl, ["kickstart", "-k", target]);
664
+ }
665
+ const miss = need("systemctl");
666
+ if (miss) return miss;
667
+ // user units only — never system without explicit prefix check
668
+ if (!unit.endsWith(".service") && !unit.endsWith(".timer")) {
669
+ return errText("error: linux unit must end in .service or .timer");
670
+ }
671
+ return runCapped(B.systemctl, ["--user", "restart", "--", unit]);
672
+ }
673
+
674
+ async function handleWatchHealthLoop(args) {
675
+ const url = String(args?.url || "");
676
+ if (!/^https?:\/\//i.test(url) || url.length > 2048) return errText("error: bad url");
677
+ const n = clampInt(args?.times, 3, WATCH_MAX_N);
678
+ const interval = clampInt(args?.interval_ms, 1000, WATCH_MAX_INTERVAL_MS);
679
+ const expect = Number(args?.expect_status ?? 200);
680
+ const results = [];
681
+ for (let i = 0; i < n; i++) {
682
+ const t0 = Date.now();
683
+ try {
684
+ const ctrl = new AbortController();
685
+ const t = setTimeout(() => ctrl.abort(), 3000);
686
+ const res = await fetch(url, { method: "GET", signal: ctrl.signal });
687
+ clearTimeout(t);
688
+ results.push({ i, status: res.status, ms: Date.now() - t0, ok: res.status === expect });
689
+ } catch (e) {
690
+ results.push({ i, error: e.message, ms: Date.now() - t0, ok: false });
691
+ }
692
+ if (i + 1 < n) await new Promise((r) => setTimeout(r, interval));
693
+ }
694
+ const failures = results.filter((r) => !r.ok).length;
695
+ return okText(JSON.stringify({ url, expect, failures, results }, null, 2));
696
+ }
697
+
698
+ const toolDefs = [
699
+ {
700
+ name: "file_info",
701
+ needs: ["file"],
702
+ def: {
703
+ name: "file_info",
704
+ description: "file(1) type + stat metadata for a root-checked path. " + UNTRUSTED,
705
+ inputSchema: {
706
+ type: "object",
707
+ required: ["path"],
708
+ properties: { path: { type: "string" } },
709
+ },
710
+ },
711
+ handler: handleFileInfo,
712
+ },
713
+ {
714
+ name: "strings_scan",
715
+ needs: ["strings"],
716
+ def: {
717
+ name: "strings_scan",
718
+ description: "strings(1) printable runs from a root-checked file. " + UNTRUSTED,
719
+ inputSchema: {
720
+ type: "object",
721
+ required: ["path"],
722
+ properties: {
723
+ path: { type: "string" },
724
+ min_length: { type: "number", description: "default 4, max 64" },
725
+ },
726
+ },
727
+ },
728
+ handler: handleStringsScan,
729
+ },
730
+ {
731
+ name: "hash_tree",
732
+ needs: [],
733
+ def: {
734
+ name: "hash_tree",
735
+ description: "SHA-256 of files under a root path (depth/count capped). " + UNTRUSTED,
736
+ inputSchema: {
737
+ type: "object",
738
+ properties: {
739
+ path: { type: "string" },
740
+ max_depth: { type: "number" },
741
+ max_files: { type: "number" },
742
+ },
743
+ },
744
+ },
745
+ handler: handleHashTree,
746
+ },
747
+ {
748
+ name: "comm_join",
749
+ needs: [], // checked in handler
750
+ def: {
751
+ name: "comm_join",
752
+ description: "comm/join on two sorted root-checked files. mode=comm12|comm23|comm13|join. " + UNTRUSTED,
753
+ inputSchema: {
754
+ type: "object",
755
+ required: ["path_a", "path_b"],
756
+ properties: {
757
+ path_a: { type: "string" },
758
+ path_b: { type: "string" },
759
+ mode: { type: "string" },
760
+ },
761
+ },
762
+ },
763
+ handler: handleCommJoin,
764
+ },
765
+ {
766
+ name: "archive_list",
767
+ needs: [],
768
+ def: {
769
+ name: "archive_list",
770
+ description: "List tar/zip contents (no extract). " + UNTRUSTED,
771
+ inputSchema: {
772
+ type: "object",
773
+ required: ["path"],
774
+ properties: { path: { type: "string" } },
775
+ },
776
+ },
777
+ handler: handleArchiveList,
778
+ },
779
+ {
780
+ name: "archive_extract",
781
+ needs: [],
782
+ def: {
783
+ name: "archive_extract",
784
+ description: "Extract archive into sandbox. Requires POWERTOOLS_ALLOW_MUTATE=1. " + UNTRUSTED,
785
+ inputSchema: {
786
+ type: "object",
787
+ required: ["path"],
788
+ properties: { path: { type: "string" }, dest: { type: "string" } },
789
+ },
790
+ },
791
+ handler: handleArchiveExtract,
792
+ },
793
+ {
794
+ name: "base64_codec",
795
+ needs: ["base64"],
796
+ def: {
797
+ name: "base64_codec",
798
+ description: "Encode/decode small blobs (data or root path). " + UNTRUSTED,
799
+ inputSchema: {
800
+ type: "object",
801
+ properties: {
802
+ op: { type: "string", description: "encode|decode" },
803
+ data: { type: "string" },
804
+ path: { type: "string" },
805
+ },
806
+ },
807
+ },
808
+ handler: handleBase64Codec,
809
+ },
810
+ {
811
+ name: "http_probe",
812
+ needs: [],
813
+ def: {
814
+ name: "http_probe",
815
+ description: "HTTP(S) HEAD/GET probe — status + headers (or curl -D). " + UNTRUSTED,
816
+ inputSchema: {
817
+ type: "object",
818
+ required: ["url"],
819
+ properties: {
820
+ url: { type: "string" },
821
+ method: { type: "string" },
822
+ timeout_ms: { type: "number" },
823
+ },
824
+ },
825
+ },
826
+ handler: handleHttpProbe,
827
+ },
828
+ {
829
+ name: "tls_inspect",
830
+ needs: ["openssl"],
831
+ def: {
832
+ name: "tls_inspect",
833
+ description: "openssl s_client -brief against host:port (no private keys). " + UNTRUSTED,
834
+ inputSchema: {
835
+ type: "object",
836
+ required: ["host"],
837
+ properties: { host: { type: "string" }, port: { type: "number" } },
838
+ },
839
+ },
840
+ handler: handleTlsInspect,
841
+ },
842
+ {
843
+ name: "ssh_exec",
844
+ needs: ["ssh"],
845
+ def: {
846
+ name: "ssh_exec",
847
+ description:
848
+ "SSH BatchMode exec on allowlisted host+command (POWERTOOLS_SSH_HOSTS / POWERTOOLS_SSH_CMDS). " +
849
+ UNTRUSTED,
850
+ inputSchema: {
851
+ type: "object",
852
+ required: ["host", "command"],
853
+ properties: {
854
+ host: { type: "string" },
855
+ command: { type: "string" },
856
+ args: { type: "array", items: { type: "string" } },
857
+ },
858
+ },
859
+ },
860
+ handler: handleSshExec,
861
+ },
862
+ {
863
+ name: "scp_get",
864
+ needs: ["scp"],
865
+ def: {
866
+ name: "scp_get",
867
+ description: "SCP remote→local (host allowlist; local under root). " + UNTRUSTED,
868
+ inputSchema: {
869
+ type: "object",
870
+ required: ["host", "remote_path", "local_path"],
871
+ properties: {
872
+ host: { type: "string" },
873
+ remote_path: { type: "string" },
874
+ local_path: { type: "string" },
875
+ },
876
+ },
877
+ },
878
+ handler: handleScpGet,
879
+ },
880
+ {
881
+ name: "scp_put",
882
+ needs: ["scp"],
883
+ def: {
884
+ name: "scp_put",
885
+ description: "SCP local→remote. Requires POWERTOOLS_ALLOW_MUTATE=1 + host allowlist. " + UNTRUSTED,
886
+ inputSchema: {
887
+ type: "object",
888
+ required: ["host", "remote_path", "local_path"],
889
+ properties: {
890
+ host: { type: "string" },
891
+ remote_path: { type: "string" },
892
+ local_path: { type: "string" },
893
+ },
894
+ },
895
+ },
896
+ handler: handleScpPut,
897
+ },
898
+ {
899
+ name: "ssh_tunnel_local",
900
+ needs: ["ssh"],
901
+ def: {
902
+ name: "ssh_tunnel_local",
903
+ description: "ssh -L forward (mutate gate + host allowlist). " + UNTRUSTED,
904
+ inputSchema: {
905
+ type: "object",
906
+ required: ["host", "local_port", "remote_port"],
907
+ properties: {
908
+ host: { type: "string" },
909
+ local_port: { type: "number" },
910
+ remote_port: { type: "number" },
911
+ remote_host: { type: "string" },
912
+ },
913
+ },
914
+ },
915
+ handler: handleSshTunnelLocal,
916
+ },
917
+ {
918
+ name: "port_forward_status",
919
+ needs: [],
920
+ def: {
921
+ name: "port_forward_status",
922
+ description: "Listening TCP via lsof (optional port filter). " + UNTRUSTED,
923
+ inputSchema: {
924
+ type: "object",
925
+ properties: { port: { type: "number" } },
926
+ },
927
+ },
928
+ handler: handlePortForwardStatus,
929
+ },
930
+ {
931
+ name: "test_runner",
932
+ needs: [],
933
+ def: {
934
+ name: "test_runner",
935
+ description: "npm test | pytest under root. Requires POWERTOOLS_ALLOW_MUTATE=1. " + UNTRUSTED,
936
+ inputSchema: {
937
+ type: "object",
938
+ properties: {
939
+ runner: { type: "string" },
940
+ cwd: { type: "string" },
941
+ extra: { type: "array", items: { type: "string" } },
942
+ },
943
+ },
944
+ },
945
+ handler: handleTestRunner,
946
+ },
947
+ {
948
+ name: "lint_runner",
949
+ needs: [],
950
+ def: {
951
+ name: "lint_runner",
952
+ description: "biome|ruff|eslint check under root. " + UNTRUSTED,
953
+ inputSchema: {
954
+ type: "object",
955
+ properties: { runner: { type: "string" }, cwd: { type: "string" } },
956
+ },
957
+ },
958
+ handler: handleLintRunner,
959
+ },
960
+ {
961
+ name: "coverage_summary",
962
+ needs: [],
963
+ def: {
964
+ name: "coverage_summary",
965
+ description: "Summarize coverage-summary.json or lcov under root. " + UNTRUSTED,
966
+ inputSchema: {
967
+ type: "object",
968
+ properties: { path: { type: "string" } },
969
+ },
970
+ },
971
+ handler: handleCoverageSummary,
972
+ },
973
+ {
974
+ name: "har_extract",
975
+ needs: [],
976
+ def: {
977
+ name: "har_extract",
978
+ description: "Extract method/url/status from a HAR file (no cookie replay). " + UNTRUSTED,
979
+ inputSchema: {
980
+ type: "object",
981
+ required: ["path"],
982
+ properties: { path: { type: "string" }, max_results: { type: "number" } },
983
+ },
984
+ },
985
+ handler: handleHarExtract,
986
+ },
987
+ {
988
+ name: "jwt_decode",
989
+ needs: [],
990
+ def: {
991
+ name: "jwt_decode",
992
+ description: "Decode JWT header+payload only (signature NOT verified). " + UNTRUSTED,
993
+ inputSchema: {
994
+ type: "object",
995
+ required: ["token"],
996
+ properties: { token: { type: "string" } },
997
+ },
998
+ },
999
+ handler: handleJwtDecode,
1000
+ },
1001
+ {
1002
+ name: "env_diff",
1003
+ needs: [],
1004
+ def: {
1005
+ name: "env_diff",
1006
+ description: "Diff allowlisted KEY=VAL between two env files (secrets redacted). " + UNTRUSTED,
1007
+ inputSchema: {
1008
+ type: "object",
1009
+ required: ["path_a", "path_b"],
1010
+ properties: {
1011
+ path_a: { type: "string" },
1012
+ path_b: { type: "string" },
1013
+ keys: { type: "string", description: "comma-separated keys" },
1014
+ },
1015
+ },
1016
+ },
1017
+ handler: handleEnvDiff,
1018
+ },
1019
+ {
1020
+ name: "service_list",
1021
+ needs: [],
1022
+ def: {
1023
+ name: "service_list",
1024
+ description: "launchctl list (macOS) or systemctl list-units (Linux). Read-only. " + UNTRUSTED,
1025
+ inputSchema: {
1026
+ type: "object",
1027
+ properties: { name: { type: "string" }, max_results: { type: "number" } },
1028
+ },
1029
+ },
1030
+ handler: handleServiceList,
1031
+ },
1032
+ {
1033
+ name: "container_ps",
1034
+ needs: [],
1035
+ def: {
1036
+ name: "container_ps",
1037
+ description: "docker/podman ps (read-only). " + UNTRUSTED,
1038
+ inputSchema: { type: "object", properties: {} },
1039
+ },
1040
+ handler: handleContainerPs,
1041
+ },
1042
+ {
1043
+ name: "container_logs",
1044
+ needs: [],
1045
+ def: {
1046
+ name: "container_logs",
1047
+ description: "docker/podman logs --tail. Optional POWERTOOLS_CONTAINERS allowlist. " + UNTRUSTED,
1048
+ inputSchema: {
1049
+ type: "object",
1050
+ required: ["name"],
1051
+ properties: { name: { type: "string" }, tail: { type: "number" } },
1052
+ },
1053
+ },
1054
+ handler: handleContainerLogs,
1055
+ },
1056
+ {
1057
+ name: "git_status_diff",
1058
+ needs: ["git"],
1059
+ def: {
1060
+ name: "git_status_diff",
1061
+ description: "git status --short or diff --stat under root cwd. " + UNTRUSTED,
1062
+ inputSchema: {
1063
+ type: "object",
1064
+ properties: { cwd: { type: "string" }, mode: { type: "string" } },
1065
+ },
1066
+ },
1067
+ handler: handleGitStatusDiff,
1068
+ },
1069
+ {
1070
+ name: "agent_respawn_safe",
1071
+ needs: [],
1072
+ def: {
1073
+ name: "agent_respawn_safe",
1074
+ description:
1075
+ "Restart allowlisted launchd/systemd user unit. Requires POWERTOOLS_ALLOW_MUTATE=1 + POWERTOOLS_RESPAWN_UNITS. " +
1076
+ UNTRUSTED,
1077
+ inputSchema: {
1078
+ type: "object",
1079
+ required: ["unit"],
1080
+ properties: { unit: { type: "string" } },
1081
+ },
1082
+ },
1083
+ handler: handleAgentRespawnFixed,
1084
+ },
1085
+ {
1086
+ name: "watch_health_loop",
1087
+ needs: [],
1088
+ def: {
1089
+ name: "watch_health_loop",
1090
+ description: "Poll URL N times (capped); report failures. No beaconing. " + UNTRUSTED,
1091
+ inputSchema: {
1092
+ type: "object",
1093
+ required: ["url"],
1094
+ properties: {
1095
+ url: { type: "string" },
1096
+ times: { type: "number" },
1097
+ interval_ms: { type: "number" },
1098
+ expect_status: { type: "number" },
1099
+ },
1100
+ },
1101
+ },
1102
+ handler: handleWatchHealthLoop,
1103
+ },
1104
+ ];
1105
+
1106
+ // Filter soft-miss: tools with needs that aren't present are omitted
1107
+ // (handlers that check multiple bins keep needs:[] and soft-fail inside)
1108
+ const active = toolDefs.filter((t) => {
1109
+ if (!t.needs.length) return true;
1110
+ return t.needs.every((n) => B[n]);
1111
+ });
1112
+
1113
+ return { resolvedBins: B, toolDefs: active, allToolNames: toolDefs.map((t) => t.name) };
1114
+ }