@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
@@ -62,14 +62,21 @@ async function resolveBinaryFresh() {
62
62
  const override = process.env.KODE_CHAUFFEUR_BIN;
63
63
  if (override)
64
64
  return override;
65
- const { existsSync } = await import("node:fs");
66
- const { homedir } = await import("node:os");
65
+ // Variable-specifier dynamic imports — matches the mcp/config.ts + mcp/stdio.ts convention
66
+ // so esbuild cannot statically resolve "node:*" into a browser/JSCore graph. Required for
67
+ // test/neutral-graph.test.mts to pass when any chain (registry.ts → chauffeur-native.ts →
68
+ // chauffeur.ts) reaches this module from the shared engine bundle.
69
+ const nodeFs = "node:fs";
70
+ const nodeOs = "node:os";
71
+ const nodeChild = "node:child_process";
72
+ const { existsSync } = await import(nodeFs);
73
+ const { homedir } = await import(nodeOs);
67
74
  const local = `${homedir()}/.local/bin/chauffeur-local`;
68
75
  if (existsSync(local))
69
76
  return local;
70
77
  // Fall back to PATH resolution; if `chauffeur` isn't there either, give up (no dead hub, no failed spawn).
71
78
  try {
72
- const { execFile } = await import("node:child_process");
79
+ const { execFile } = await import(nodeChild);
73
80
  const p = await new Promise((resolve, reject) => {
74
81
  execFile("/bin/sh", ["-c", "command -v chauffeur"], { timeout: 3000, encoding: "utf8" }, (err, stdout) => (err ? reject(err) : resolve(stdout)));
75
82
  });
@@ -95,7 +102,11 @@ export async function buildChauffeurServer() {
95
102
  tools: [...CHAUFFEUR_TOOLS], // curated allowlist (the McpHub filters discovery to these)
96
103
  };
97
104
  }
105
+ let _hubPromise = null;
98
106
  export async function buildChauffeurHub() {
107
+ return (_hubPromise ??= buildChauffeurHubFresh());
108
+ }
109
+ async function buildChauffeurHubFresh() {
99
110
  const server = await buildChauffeurServer();
100
111
  return server ? new McpHub([server]) : null;
101
112
  }
@@ -0,0 +1,229 @@
1
+ // download_file: fetch a URL to disk the way a download is supposed to work, and say plainly when it did not.
2
+ // The failure this exists for: `curl -s … &` + `wait`, 0-byte files, then "Already downloaded" because nothing read the result back.
3
+ // So: fail loudly on any HTTP error, resume a partial file (`<dest>.part`), retry network drops and stalls, refuse an HTML page that
4
+ // is standing in for the file, verify length (and sha256 when the caller has one), and only then rename onto `dest` — a half
5
+ // download never sits at the final name. Node-only (no child process), so there is nothing to own or orphan.
6
+ import { createHash } from "node:crypto";
7
+ import { createReadStream } from "node:fs";
8
+ import { mkdir, open, rename, rm, stat } from "node:fs/promises";
9
+ import { basename, dirname, extname, join } from "node:path";
10
+ /** A page that is fine to save as text; anything else arriving as HTML is almost certainly an error or landing page. */
11
+ const TEXT_EXT = new Set([".html", ".htm", ".xhtml", ".php", ".asp", ".aspx", ".txt", ".md", ".json", ".xml", ".csv", ".svg", ".js", ".css", ".log", ".yaml", ".yml", ".toml", ".ini", ".sh", ".py"]);
12
+ const HTML_START = /^\s*(?:<!doctype\s+html|<html[\s>]|<head[\s>]|<body[\s>])/i;
13
+ class Fatal extends Error {
14
+ }
15
+ class Retryable extends Error {
16
+ }
17
+ const human = (n) => (n >= 1e9 ? `${(n / 1e9).toFixed(2)} GB` : n >= 1e6 ? `${(n / 1e6).toFixed(1)} MB` : n >= 1e3 ? `${(n / 1e3).toFixed(1)} KB` : `${n} B`);
18
+ const sleep = (ms, signal) => new Promise((res) => { const t = setTimeout(res, ms); signal?.addEventListener("abort", () => { clearTimeout(t); res(); }, { once: true }); });
19
+ async function sizeOf(path) {
20
+ try {
21
+ return (await stat(path)).size;
22
+ }
23
+ catch {
24
+ return 0;
25
+ }
26
+ }
27
+ async function exists(path) {
28
+ try {
29
+ await stat(path);
30
+ return true;
31
+ }
32
+ catch {
33
+ return false;
34
+ }
35
+ }
36
+ async function sha256OfFile(path) {
37
+ const h = createHash("sha256");
38
+ await new Promise((res, rej) => { const s = createReadStream(path); s.on("data", (c) => h.update(c)); s.on("end", () => res()); s.on("error", rej); });
39
+ return h;
40
+ }
41
+ function fileNameFromUrl(url) {
42
+ try {
43
+ const last = decodeURIComponent(basename(new URL(url).pathname));
44
+ return last && last !== "/" ? last.replace(/[\\/:*?"<>|\0]/g, "_") : "download";
45
+ }
46
+ catch {
47
+ return "download";
48
+ }
49
+ }
50
+ async function resolveDest(dest, url) {
51
+ let isDir = dest.endsWith("/");
52
+ if (!isDir) {
53
+ try {
54
+ isDir = (await stat(dest)).isDirectory();
55
+ }
56
+ catch { /* not there yet */ }
57
+ }
58
+ return isDir ? join(dest, fileNameFromUrl(url)) : dest;
59
+ }
60
+ export async function downloadFile(o) {
61
+ const t0 = Date.now();
62
+ const done = (r) => ({ ...r, seconds: Math.round((Date.now() - t0) / 100) / 10 });
63
+ let attempts = 0;
64
+ let url;
65
+ try {
66
+ url = new URL(o.url);
67
+ }
68
+ catch {
69
+ return done({ ok: false, attempts, message: `error: "${o.url}" is not a valid URL` });
70
+ }
71
+ if (url.protocol !== "http:" && url.protocol !== "https:")
72
+ return done({ ok: false, attempts, message: `error: only http(s) URLs can be downloaded, got ${url.protocol}` });
73
+ const finalPath = await resolveDest(o.dest, o.url);
74
+ const part = `${finalPath}.part`;
75
+ const doFetch = o.fetchImpl ?? fetch;
76
+ const retries = o.retries ?? 5;
77
+ const stallMs = o.stallMs ?? 30_000;
78
+ const wantSha = o.sha256?.trim().toLowerCase();
79
+ if (wantSha && !/^[0-9a-f]{64}$/.test(wantSha))
80
+ return done({ ok: false, attempts, message: "error: sha256 must be 64 hex characters" });
81
+ if (!o.overwrite && (await exists(finalPath))) {
82
+ return done({ ok: false, attempts, path: finalPath, message: `error: ${finalPath} already exists — pass overwrite:true to replace it, or choose another dest` });
83
+ }
84
+ await mkdir(dirname(finalPath), { recursive: true });
85
+ let resumedFrom;
86
+ let lastError = "";
87
+ let progressAt = 0;
88
+ for (let attempt = 0; attempt <= retries; attempt++) {
89
+ attempts = attempt + 1;
90
+ if (o.signal?.aborted)
91
+ return done({ ok: false, attempts, message: "cancelled", resumedFrom });
92
+ if (attempt > 0)
93
+ await sleep(Math.min((o.retryDelayMs ?? 1000) * 2 ** (attempt - 1), 30_000), o.signal);
94
+ if (o.signal?.aborted)
95
+ return done({ ok: false, attempts, message: "cancelled", resumedFrom });
96
+ const have = await sizeOf(part);
97
+ const ac = new AbortController();
98
+ const onAbort = () => ac.abort();
99
+ o.signal?.addEventListener("abort", onAbort, { once: true });
100
+ let stalled = false;
101
+ let discardPart = false; // set when what is on disk is known to be garbage (an HTML page), so it is not offered for resume
102
+ let stallTimer;
103
+ const kick = () => { if (stallTimer)
104
+ clearTimeout(stallTimer); stallTimer = setTimeout(() => { stalled = true; ac.abort(); }, stallMs); };
105
+ try {
106
+ kick();
107
+ const headers = { ...(o.headers ?? {}) };
108
+ if (have > 0)
109
+ headers.range = `bytes=${have}-`;
110
+ const res = await doFetch(url, { headers, redirect: "follow", signal: ac.signal });
111
+ const ctype = res.headers.get("content-type") ?? undefined;
112
+ if (res.status === 416) { // the .part is not a prefix of what the server has (or is already complete)
113
+ const m = /\/(\d+)\s*$/.exec(res.headers.get("content-range") ?? "");
114
+ if (m && Number(m[1]) === have) { /* complete already: fall through to verification below with no body */ }
115
+ else {
116
+ await rm(part, { force: true });
117
+ throw new Retryable("server rejected the resume range (HTTP 416) — restarting from zero");
118
+ }
119
+ }
120
+ else if (!res.ok) {
121
+ const msg = `HTTP ${res.status} ${res.statusText}`.trim();
122
+ if (res.status >= 500 || res.status === 408 || res.status === 429)
123
+ throw new Retryable(msg);
124
+ throw new Fatal(`${msg} for ${res.url || o.url} — nothing was saved`);
125
+ }
126
+ let start = have;
127
+ if (res.status === 200 && have > 0) {
128
+ start = 0;
129
+ await rm(part, { force: true });
130
+ } // server ignored Range: restart cleanly
131
+ if (res.status === 206) {
132
+ const m = /bytes\s+(\d+)-/.exec(res.headers.get("content-range") ?? "");
133
+ if (m && Number(m[1]) !== have) {
134
+ await rm(part, { force: true });
135
+ throw new Retryable("server resumed from the wrong offset — restarting from zero");
136
+ }
137
+ }
138
+ if (start > 0 && resumedFrom === undefined)
139
+ resumedFrom = start;
140
+ const len = Number(res.headers.get("content-length") ?? NaN);
141
+ const crTotal = /\/(\d+)\s*$/.exec(res.headers.get("content-range") ?? "");
142
+ const total = res.status === 416 ? have : crTotal ? Number(crTotal[1]) : Number.isFinite(len) ? len + (res.status === 206 ? start : 0) : undefined;
143
+ if (ctype && /^text\/html/i.test(ctype) && !TEXT_EXT.has(extname(finalPath).toLowerCase()) && res.status !== 416) {
144
+ throw new Fatal(`the server answered with an HTML page (${ctype}), not a "${extname(finalPath) || "file"}" — a landing/error/login page standing in for the download. Nothing was saved. Check the URL.`);
145
+ }
146
+ if (o.expectedBytes !== undefined && total !== undefined && total !== o.expectedBytes) {
147
+ throw new Fatal(`size mismatch before download: the server reports ${total} bytes, you expected ${o.expectedBytes}. Nothing was saved.`);
148
+ }
149
+ const hash = start > 0 ? await sha256OfFile(part) : createHash("sha256");
150
+ let got = start;
151
+ if (res.status !== 416) {
152
+ const fh = await open(part, start > 0 ? "a" : "w");
153
+ try {
154
+ let first = true;
155
+ const reader = res.body?.getReader();
156
+ if (!reader)
157
+ throw new Retryable("empty response body");
158
+ for (;;) {
159
+ const { done: eof, value } = await reader.read();
160
+ if (eof)
161
+ break;
162
+ kick();
163
+ if (first) {
164
+ first = false;
165
+ if (start === 0 && !TEXT_EXT.has(extname(finalPath).toLowerCase()) && HTML_START.test(Buffer.from(value.subarray(0, 512)).toString("utf8"))) {
166
+ await reader.cancel().catch(() => { });
167
+ discardPart = true;
168
+ throw new Fatal("the response body is an HTML page, not the file — a landing/error/login page standing in for the download. Nothing was saved. Check the URL.");
169
+ }
170
+ }
171
+ await fh.write(value);
172
+ hash.update(value);
173
+ got += value.byteLength;
174
+ const now = Date.now();
175
+ if (o.onProgress && now - progressAt >= 1000) {
176
+ progressAt = now;
177
+ o.onProgress({ bytes: got, total, bytesPerSec: (got - start) / Math.max(0.001, (now - t0) / 1000) });
178
+ }
179
+ }
180
+ }
181
+ finally {
182
+ await fh.close();
183
+ }
184
+ }
185
+ if (total !== undefined && got !== total)
186
+ throw new Retryable(`connection closed early: received ${got} of ${total} bytes`);
187
+ const digest = hash.digest("hex");
188
+ if (o.expectedBytes !== undefined && got !== o.expectedBytes) {
189
+ await rm(part, { force: true });
190
+ throw new Fatal(`size mismatch: got ${got} bytes, expected ${o.expectedBytes}. The partial file was deleted.`);
191
+ }
192
+ if (wantSha && digest !== wantSha) {
193
+ await rm(part, { force: true });
194
+ throw new Fatal(`sha256 mismatch: got ${digest}, expected ${wantSha}. The file was NOT kept — it is not the file you asked for.`);
195
+ }
196
+ if (got === 0) {
197
+ await rm(part, { force: true });
198
+ throw new Fatal("the server sent 0 bytes — nothing was saved.");
199
+ }
200
+ await rename(part, finalPath);
201
+ return done({
202
+ ok: true, attempts, path: finalPath, bytes: got, sha256: digest, contentType: ctype, finalUrl: res.url || o.url, resumedFrom,
203
+ message: `downloaded ${human(got)} to ${finalPath} (sha256 ${digest}${wantSha ? ", matches the one you gave" : ", not checked against a published hash"})` +
204
+ `${resumedFrom ? `; resumed from ${human(resumedFrom)}` : ""}${attempts > 1 ? `; ${attempts} attempts` : ""}.`,
205
+ });
206
+ }
207
+ catch (e) {
208
+ const err = e;
209
+ if (o.signal?.aborted)
210
+ return done({ ok: false, attempts, message: "cancelled", resumedFrom });
211
+ if (err instanceof Fatal) {
212
+ if (discardPart)
213
+ await rm(part, { force: true });
214
+ return done({ ok: false, attempts, path: finalPath, message: `error: ${err.message}`, resumedFrom });
215
+ }
216
+ lastError = stalled ? `stalled: no data for ${Math.round(stallMs / 1000)}s` : err.message || String(err);
217
+ }
218
+ finally {
219
+ if (stallTimer)
220
+ clearTimeout(stallTimer);
221
+ o.signal?.removeEventListener("abort", onAbort);
222
+ }
223
+ }
224
+ const kept = await sizeOf(part);
225
+ return done({
226
+ ok: false, attempts, path: finalPath, resumedFrom,
227
+ message: `error: gave up after ${attempts} attempts (${lastError}).${kept ? ` ${human(kept)} are kept at ${part} — call download_file again with the same dest to resume.` : ""}`,
228
+ });
229
+ }
@@ -122,7 +122,7 @@ export class Executor {
122
122
  // reads wait only for conflicting prior writes, device tools barrier-serialize, independent
123
123
  // bash/shell_exec overlap (shell kind). This replaces the 0.1.225 contiguous walk.
124
124
  //
125
- // Cursor-parity for shells: when this round has ≥2 bash/shell_exec calls, run them as ephemeral
125
+ // Matching Cursor for shells: when this round has ≥2 bash/shell_exec calls, run them as ephemeral
126
126
  // one-shots so the persistent ShellSession FIFO cannot serialize wall-clock. A lone bash still
127
127
  // uses the persistent session (cwd/env + ctrl+b detach stick). See shellExecMode.
128
128
  const SHELL_TOOLS = new Set(["bash", "shell_exec"]);
@@ -0,0 +1,312 @@
1
+ import { expandPath } from "./paths.js";
2
+ import { pexecFile } from "./exec.js";
3
+ const nodeImport = (m) => import(/* @vite-ignore */ m);
4
+ const BODY_CAP = 2 * 1024; // 2 KiB
5
+ const DEFAULT_TIMEOUT_MS = 3_000;
6
+ const MAX_TIMEOUT_MS = 15_000;
7
+ const DEFAULT_TAIL_LINES = 80;
8
+ const HARD_TAIL_LINES = 500;
9
+ const DEFAULT_PS_MAX = 50;
10
+ const HARD_PS_MAX = 200;
11
+ const TITLE_CAP = 100;
12
+ const BODY_NOTIFY_CAP = 500;
13
+ const PS_ARGV = ["-axo", "pid=,ppid=,user=,pcpu=,pmem=,state=,comm="];
14
+ const PS_BINS = ["/bin/ps", "/usr/bin/ps"];
15
+ const SENSITIVE_PATHS = [
16
+ "/etc/shadow",
17
+ "/etc/passwd",
18
+ "/etc/master.passwd",
19
+ "/etc/sudoers",
20
+ ];
21
+ function str(v, fallback = "") {
22
+ return v === undefined || v === null ? fallback : String(v);
23
+ }
24
+ function clampInt(v, fallback, hardMax, hardMin = 1) {
25
+ const n = Number(v);
26
+ if (!Number.isFinite(n) || n < hardMin)
27
+ return fallback;
28
+ return Math.min(Math.floor(n), hardMax);
29
+ }
30
+ function underRoot(realPath, root) {
31
+ return realPath === root || realPath.startsWith(root.endsWith("/") ? root : root + "/");
32
+ }
33
+ /** Resolve allowed sandbox roots for log_tail: $HOME (or cwd if home unavailable), plus
34
+ * POWERTOOLS_ROOT / KODE_HOME when set. */
35
+ async function logAllowedRoots() {
36
+ const { realpath } = await nodeImport("node:fs/promises");
37
+ const pathMod = await nodeImport("node:path");
38
+ const roots = [];
39
+ const push = async (raw) => {
40
+ if (!raw || typeof raw !== "string" || !raw.trim())
41
+ return;
42
+ const abs = pathMod.resolve(raw);
43
+ try {
44
+ roots.push(await realpath(abs));
45
+ }
46
+ catch {
47
+ roots.push(abs);
48
+ }
49
+ };
50
+ const home = process.env.HOME || process.env.USERPROFILE;
51
+ if (home)
52
+ await push(home);
53
+ else
54
+ await push(process.cwd());
55
+ await push(process.env.POWERTOOLS_ROOT || process.env.CLI_POWER_ROOT);
56
+ await push(process.env.KODE_HOME);
57
+ return [...new Set(roots)];
58
+ }
59
+ async function resolveLogPath(userPath) {
60
+ if (!userPath.trim())
61
+ return { error: "error: path required" };
62
+ const pathMod = await nodeImport("node:path");
63
+ const { realpath } = await nodeImport("node:fs/promises");
64
+ const expanded = expandPath(userPath.trim());
65
+ const abs = pathMod.resolve(expanded);
66
+ const norm = pathMod.normalize(abs);
67
+ for (const bad of SENSITIVE_PATHS) {
68
+ if (norm === bad || norm.endsWith(bad)) {
69
+ return { error: `error: refused sensitive path: ${userPath}` };
70
+ }
71
+ }
72
+ let real;
73
+ try {
74
+ real = await realpath(abs);
75
+ }
76
+ catch (e) {
77
+ return { error: `error: cannot resolve path: ${userPath} — ${e.message || e}` };
78
+ }
79
+ for (const bad of SENSITIVE_PATHS) {
80
+ if (real === bad || real.endsWith(bad)) {
81
+ return { error: `error: refused sensitive path: ${userPath}` };
82
+ }
83
+ }
84
+ const roots = await logAllowedRoots();
85
+ if (!roots.some((r) => underRoot(real, r))) {
86
+ return { error: `error: path escape: ${userPath} is outside allowed roots (your home, the powertools root, or the Operator home)` };
87
+ }
88
+ return { path: real };
89
+ }
90
+ function applescriptString(s) {
91
+ return `"${s.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`;
92
+ }
93
+ // ── health_check ─────────────────────────────────────────────────────────────
94
+ async function healthCheck(args) {
95
+ const url = str(args.url).trim();
96
+ if (!url)
97
+ return JSON.stringify({ ok: false, error: "url required" });
98
+ if (!/^https?:\/\//i.test(url)) {
99
+ return JSON.stringify({ ok: false, error: "only http(s) URLs allowed", url });
100
+ }
101
+ const expectStatus = Number(args.expect_status ?? 200);
102
+ const expect = Number.isFinite(expectStatus) ? Math.floor(expectStatus) : 200;
103
+ let timeoutMs = Number(args.timeout_ms ?? DEFAULT_TIMEOUT_MS);
104
+ if (!Number.isFinite(timeoutMs) || timeoutMs <= 0)
105
+ timeoutMs = DEFAULT_TIMEOUT_MS;
106
+ timeoutMs = Math.min(Math.floor(timeoutMs), MAX_TIMEOUT_MS);
107
+ const ctrl = new AbortController();
108
+ const timer = setTimeout(() => ctrl.abort(), timeoutMs);
109
+ const started = Date.now();
110
+ try {
111
+ const res = await fetch(url, {
112
+ method: "GET",
113
+ signal: ctrl.signal,
114
+ redirect: "follow",
115
+ headers: { "User-Agent": "operator/health_check" },
116
+ });
117
+ const latency_ms = Date.now() - started;
118
+ const raw = await res.text().catch(() => "");
119
+ const truncated = raw.length > BODY_CAP;
120
+ const body = truncated ? raw.slice(0, BODY_CAP) : raw;
121
+ const ok = res.status === expect;
122
+ return JSON.stringify({
123
+ ok,
124
+ status: res.status,
125
+ expect_status: expect,
126
+ latency_ms,
127
+ truncated,
128
+ body,
129
+ ...(ok ? {} : { error: `expected status ${expect}, got ${res.status}` }),
130
+ });
131
+ }
132
+ catch (e) {
133
+ const latency_ms = Date.now() - started;
134
+ const m = e instanceof Error ? e.message : String(e);
135
+ const timedOut = /abort/i.test(m);
136
+ return JSON.stringify({
137
+ ok: false,
138
+ error: timedOut ? `timed out after ${timeoutMs}ms` : m,
139
+ url,
140
+ latency_ms,
141
+ expect_status: expect,
142
+ });
143
+ }
144
+ finally {
145
+ clearTimeout(timer);
146
+ }
147
+ }
148
+ // ── log_tail ─────────────────────────────────────────────────────────────────
149
+ async function logTail(args) {
150
+ const userPath = str(args.path);
151
+ const lines = clampInt(args.lines, DEFAULT_TAIL_LINES, HARD_TAIL_LINES);
152
+ const resolved = await resolveLogPath(userPath);
153
+ if ("error" in resolved)
154
+ return resolved.error;
155
+ try {
156
+ const fs = await nodeImport("node:fs/promises");
157
+ const text = await fs.readFile(resolved.path, "utf8");
158
+ const all = text.split(/\r?\n/);
159
+ if (all.length && all[all.length - 1] === "")
160
+ all.pop();
161
+ const slice = all.slice(-lines);
162
+ return slice.join("\n") || "(empty)";
163
+ }
164
+ catch (e) {
165
+ return `error: cannot read ${userPath}: ${e.message || e}`;
166
+ }
167
+ }
168
+ // ── process_snapshot ─────────────────────────────────────────────────────────
169
+ async function findPs() {
170
+ const { access } = await nodeImport("node:fs/promises");
171
+ const { constants } = await nodeImport("node:fs");
172
+ for (const bin of PS_BINS) {
173
+ try {
174
+ await access(bin, constants.X_OK);
175
+ return bin;
176
+ }
177
+ catch { /* next */ }
178
+ }
179
+ return null;
180
+ }
181
+ async function processSnapshot(args) {
182
+ const name = args.name != null ? str(args.name) : "";
183
+ if (name && (name.length > 64 || /[\0\n]/.test(name))) {
184
+ return "error: name must be a short string (no newlines)";
185
+ }
186
+ const limit = clampInt(args.max_results, DEFAULT_PS_MAX, HARD_PS_MAX);
187
+ const bin = await findPs();
188
+ if (!bin)
189
+ return "error: ps binary not found";
190
+ try {
191
+ const { stdout } = await pexecFile(bin, [...PS_ARGV], {
192
+ encoding: "utf8",
193
+ env: {}, // cleared — no secret exfil via child env
194
+ maxBuffer: 2 * 1024 * 1024,
195
+ timeout: 10_000,
196
+ });
197
+ let rows = String(stdout || "").split("\n").filter((l) => l.trim());
198
+ if (name) {
199
+ const needle = name.toLowerCase();
200
+ rows = rows.filter((l) => l.toLowerCase().includes(needle));
201
+ }
202
+ const truncated = rows.length > limit;
203
+ if (truncated)
204
+ rows = rows.slice(0, limit);
205
+ const body = rows.join("\n") || "(no matching processes)";
206
+ return truncated ? `${body}\n[truncated: showing ${limit} lines]` : body;
207
+ }
208
+ catch (e) {
209
+ return `error: ps failed: ${e.message || e.stderr || e}`;
210
+ }
211
+ }
212
+ // ── notify_local ─────────────────────────────────────────────────────────────
213
+ async function notifyLocal(args) {
214
+ let title = str(args.title, "Operator").trim() || "Operator";
215
+ let body = str(args.body).trim();
216
+ if (!body)
217
+ return "error: body required";
218
+ if (title.length > TITLE_CAP)
219
+ title = title.slice(0, TITLE_CAP);
220
+ if (body.length > BODY_NOTIFY_CAP)
221
+ body = body.slice(0, BODY_NOTIFY_CAP);
222
+ if (process.platform === "darwin") {
223
+ const script = `display notification ${applescriptString(body)} with title ${applescriptString(title)}`;
224
+ try {
225
+ await pexecFile("/usr/bin/osascript", ["-e", script], {
226
+ encoding: "utf8",
227
+ env: {},
228
+ timeout: 5_000,
229
+ });
230
+ return `notified (macos): ${title}`;
231
+ }
232
+ catch (e) {
233
+ // fall through to log on osascript failure
234
+ const msg = e.message || String(e);
235
+ return appendNotifyLog(title, body, `osascript failed (${msg}); logged`);
236
+ }
237
+ }
238
+ return appendNotifyLog(title, body, "logged");
239
+ }
240
+ async function appendNotifyLog(title, body, how) {
241
+ const { operatorPath } = await import("../config/home.js");
242
+ const fs = await nodeImport("node:fs/promises");
243
+ const file = operatorPath("notifications.log");
244
+ const line = `${new Date().toISOString()}\t${title}\t${body.replace(/\n/g, " ")}\n`;
245
+ try {
246
+ await fs.mkdir(await (await nodeImport("node:path")).dirname(file), { recursive: true });
247
+ await fs.appendFile(file, line, "utf8");
248
+ return `notified (${how}): ${title} → ${file}`;
249
+ }
250
+ catch (e) {
251
+ return `error: notify log write failed: ${e.message || e}`;
252
+ }
253
+ }
254
+ export const MONITORING_TOOLS = [
255
+ {
256
+ name: "health_check", safe: true,
257
+ description: "HTTP(S) GET health probe of a URL. Returns JSON with status, latency_ms, and a truncated body (2 KiB). " +
258
+ "Default timeout 3s (max 15s). Optional expect_status (default 200). Rejects non-http(s) URLs.",
259
+ parameters: {
260
+ type: "object",
261
+ properties: {
262
+ url: { type: "string", description: "http(s) URL to GET" },
263
+ expect_status: { type: "number", description: "expected HTTP status (default 200)" },
264
+ timeout_ms: { type: "number", description: "timeout in ms (default 3000, max 15000)" },
265
+ },
266
+ required: ["url"],
267
+ },
268
+ run: healthCheck,
269
+ },
270
+ {
271
+ name: "log_tail", safe: true,
272
+ description: "Read the last N lines of a log file (default 80, hard cap 500). Path is realpath'd and must stay " +
273
+ "under $HOME (or cwd), or under the powertools root or the Operator home when set. No shell. Sensitive system paths refused.",
274
+ parameters: {
275
+ type: "object",
276
+ properties: {
277
+ path: { type: "string", description: "file path to tail" },
278
+ lines: { type: "number", description: "lines from end (default 80, max 500)" },
279
+ },
280
+ required: ["path"],
281
+ },
282
+ run: logTail,
283
+ },
284
+ {
285
+ name: "process_snapshot", safe: true,
286
+ description: "Process table snapshot via ps with fixed columns (pid,ppid,user,pcpu,pmem,state,comm). " +
287
+ "Optional case-insensitive name substring filter applied in-process. max_results default 50 (hard 200). " +
288
+ "Native — works without the powertools MCP.",
289
+ parameters: {
290
+ type: "object",
291
+ properties: {
292
+ name: { type: "string", description: "optional case-insensitive substring of command name" },
293
+ max_results: { type: "number", description: "max lines after filter (default 50, hard 200)" },
294
+ },
295
+ },
296
+ run: processSnapshot,
297
+ },
298
+ {
299
+ name: "notify_local", safe: false,
300
+ description: "Local notification — macOS Notification Center via osascript, or append to operator notifications.log. " +
301
+ "Title/body length capped. Gated (safe:false).",
302
+ parameters: {
303
+ type: "object",
304
+ properties: {
305
+ title: { type: "string", description: "notification title (default Operator, max 100)" },
306
+ body: { type: "string", description: "notification body (required, max 500)" },
307
+ },
308
+ required: ["body"],
309
+ },
310
+ run: notifyLocal,
311
+ },
312
+ ];