@0perator/operator 0.0.6 → 0.1.17

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.
@@ -1,12 +1,23 @@
1
1
  // Tool registry — SPEC §2. Lean core set; unknown/failing tools never crash the turn (executor.ts
2
2
  // wraps run() in try/catch too, but each tool also guards its own I/O and returns an error string).
3
- import { execFile } from "node:child_process";
4
- import { promisify } from "node:util";
5
- import { readFile, writeFile, mkdir, readdir } from "node:fs/promises";
6
- import { dirname } from "node:path";
3
+ // Node builtins load LAZILY via a variable-specifier dynamic import. A static top-level
4
+ // `import "node:..."` breaks the platform:neutral bundle: this module is pulled into the mobile
5
+ // JSCore engine for tool SCHEMAS (toSchemas), but the run() bodies below never execute there — the
6
+ // mobile app runs tools natively in Swift. nodeImport() keeps esbuild from statically resolving them.
7
+ const nodeImport = (m) => import(m);
7
8
  import { MemoryStore } from "../memory/index.js";
8
- import { deniedWrite, wrapShell } from "./sandbox.js";
9
- const pexecFile = promisify(execFile);
9
+ import { deniedWriteAsync, deniedReadAsync, wrapShell } from "./sandbox.js";
10
+ // Lazily built + cached on first use (node only). Same contract as promisify(execFile): resolves
11
+ // {stdout,stderr}, rejects with the error object (stdout/stderr attached) on non-zero exit.
12
+ let _pexec = null;
13
+ async function pexecFile(file, args, opts) {
14
+ if (!_pexec) {
15
+ const { execFile } = await nodeImport("node:child_process");
16
+ const { promisify } = await nodeImport("node:util");
17
+ _pexec = promisify(execFile);
18
+ }
19
+ return _pexec(file, args, opts);
20
+ }
10
21
  function str(v, fallback = "") {
11
22
  return v === undefined || v === null ? fallback : String(v);
12
23
  }
@@ -41,16 +52,35 @@ async function shellExec(args) {
41
52
  return `(no output; exit ${e.code ?? "?"})`; // grep no-match etc. — honest, not alarming
42
53
  }
43
54
  }
55
+ // Un-ranged reads default to a bounded window (like the host Read tool) instead of dumping an entire
56
+ // file — a multi-MB log or generated file would otherwise blow up context in one call. FILE_READ_MAX_CHARS
57
+ // is a second, hard backstop for when even the (possibly explicit) line range is enormous (e.g. a few
58
+ // giant minified lines): the central executor cap (src/tools/executor.ts) also applies after this, but
59
+ // capping here first lets us tell the model specifically to use offset/limit rather than "narrow your query".
60
+ const FILE_READ_DEFAULT_LIMIT_LINES = 2000;
61
+ const FILE_READ_MAX_CHARS = 40_000;
44
62
  async function fileRead(args) {
45
63
  const path = str(args.path);
46
64
  if (!path)
47
65
  return "error: no path given";
66
+ const blocked = await deniedReadAsync(path); // sandbox on: refuse reads of credential paths (exfil guard)
67
+ if (blocked)
68
+ return `error: ${blocked}`;
48
69
  try {
70
+ const { readFile } = await nodeImport("node:fs/promises");
49
71
  const src = await readFile(path, "utf8");
50
72
  const lines = src.split("\n");
51
73
  const offset = Number(args.offset ?? 0);
52
- const limit = Number(args.limit ?? lines.length);
53
- return lines.slice(offset, offset + limit).map((l, i) => `${offset + i + 1}\t${l}`).join("\n");
74
+ const explicitLimit = args.limit !== undefined;
75
+ const limit = Number(args.limit ?? Math.min(lines.length, FILE_READ_DEFAULT_LIMIT_LINES));
76
+ let out = lines.slice(offset, offset + limit).map((l, i) => `${offset + i + 1}\t${l}`).join("\n");
77
+ if (out.length > FILE_READ_MAX_CHARS) {
78
+ out = `${out.slice(0, FILE_READ_MAX_CHARS)}\n…[result truncated: ${FILE_READ_MAX_CHARS} of ${out.length} chars — pass a smaller offset/limit]`;
79
+ }
80
+ else if (!explicitLimit && offset + limit < lines.length) {
81
+ out += `\n…[showing lines ${offset + 1}-${offset + limit} of ${lines.length} — pass offset/limit to see the rest]`;
82
+ }
83
+ return out;
54
84
  }
55
85
  catch (e) {
56
86
  return `error: ${e.message}`;
@@ -60,10 +90,12 @@ async function fileWrite(args) {
60
90
  const path = str(args.path);
61
91
  if (!path)
62
92
  return "error: no path given";
63
- const blocked = deniedWrite(path);
93
+ const blocked = await deniedWriteAsync(path); // async: realpath closes the symlink-laundering gap
64
94
  if (blocked)
65
95
  return `error: ${blocked}`;
66
96
  try {
97
+ const { mkdir, writeFile } = await nodeImport("node:fs/promises");
98
+ const { dirname } = await nodeImport("node:path");
67
99
  await mkdir(dirname(path), { recursive: true });
68
100
  await writeFile(path, str(args.content), "utf8");
69
101
  return `wrote ${path}`;
@@ -79,10 +111,11 @@ async function fileEdit(args) {
79
111
  const replaceAll = Boolean(args.replace_all);
80
112
  if (!path || !oldStr)
81
113
  return "error: path and old_string are required";
82
- const blocked = deniedWrite(path);
114
+ const blocked = await deniedWriteAsync(path); // async: realpath closes the symlink-laundering gap
83
115
  if (blocked)
84
116
  return `error: ${blocked}`;
85
117
  try {
118
+ const { readFile, writeFile } = await nodeImport("node:fs/promises");
86
119
  const src = await readFile(path, "utf8");
87
120
  const count = src.split(oldStr).length - 1;
88
121
  if (count === 0)
@@ -103,12 +136,12 @@ async function grepSearch(args) {
103
136
  const path = str(args.path, ".");
104
137
  if (!pattern)
105
138
  return "error: no pattern given";
106
- const flags = ["-rn", "-I", "--exclude-dir=.git", "--exclude-dir=node_modules"];
139
+ const flags = ["-rn", "-I", "--exclude-dir=.git", "--exclude-dir=node_modules", "--exclude=.operator-session.json"];
107
140
  if (args.glob)
108
141
  flags.push(`--include=${str(args.glob)}`);
109
142
  try {
110
143
  const { stdout } = await pexecFile("grep", [...flags, "-E", pattern, path], { maxBuffer: 10 * 1024 * 1024 });
111
- return stdout.trim() || "(no matches)";
144
+ return capMatches(stdout);
112
145
  }
113
146
  catch (e) {
114
147
  if (e.code === 1)
@@ -116,11 +149,35 @@ async function grepSearch(args) {
116
149
  return `error: ${e.stderr || e.message}`;
117
150
  }
118
151
  }
152
+ // Cap grep output so a single pathological line (minified JS, one-line JSON, a persisted session file)
153
+ // can never balloon the model's context. Per-line truncation is the load-bearing guard: a 300KB
154
+ // single-line match becomes ~500 chars, not 75K tokens. Total-line cap keeps broad matches sane too.
155
+ const GREP_MAXLINE = 500;
156
+ const GREP_MAXLINES = 200;
157
+ function capMatches(stdout) {
158
+ const lines = stdout.split("\n");
159
+ const shown = lines.slice(0, GREP_MAXLINES).map((l) => l.length > GREP_MAXLINE ? `${l.slice(0, GREP_MAXLINE)} …[line truncated, ${l.length - GREP_MAXLINE} more chars]` : l);
160
+ let out = shown.join("\n").trim();
161
+ if (!out)
162
+ return "(no matches)";
163
+ if (lines.length > GREP_MAXLINES)
164
+ out += `\n…[${lines.length - GREP_MAXLINES} more matching lines — narrow the pattern or pass a path/glob]`;
165
+ return out;
166
+ }
167
+ const LIST_DIR_MAX_ENTRIES = 1000; // a directory with 100k entries (node_modules, a data dump) should
168
+ // not dump one line each into context — this is a fan-out cap, independent of the executor's byte cap.
119
169
  async function listDirectory(args) {
120
170
  const path = str(args.path, ".");
121
171
  try {
172
+ const { readdir } = await nodeImport("node:fs/promises");
122
173
  const entries = await readdir(path, { withFileTypes: true });
123
- return entries.map(e => `${e.isDirectory() ? "d" : "f"} ${e.name}`).join("\n") || "(empty)";
174
+ if (!entries.length)
175
+ return "(empty)";
176
+ const lines = entries.map((e) => `${e.isDirectory() ? "d" : "f"} ${e.name}`);
177
+ if (lines.length > LIST_DIR_MAX_ENTRIES) {
178
+ return `${lines.slice(0, LIST_DIR_MAX_ENTRIES).join("\n")}\n…[${lines.length - LIST_DIR_MAX_ENTRIES} more entries not shown — narrow the path]`;
179
+ }
180
+ return lines.join("\n");
124
181
  }
125
182
  catch (e) {
126
183
  return `error: ${e.message}`;
@@ -188,6 +245,55 @@ function htmlToText(html) {
188
245
  .replace(/&nbsp;/g, " ").replace(/&amp;/g, "&").replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&#39;/g, "'").replace(/&quot;/g, '"')
189
246
  .replace(/[ \t]{2,}/g, " ").replace(/\n{3,}/g, "\n\n").trim();
190
247
  }
248
+ function fmtResults(rows, n) {
249
+ const out = rows.slice(0, n).map((r, i) => {
250
+ const snip = String(r.snippet ?? r.content ?? "").replace(/\s+/g, " ").slice(0, 200);
251
+ return `${i + 1}. ${r.title ?? "(untitled)"}\n ${r.url ?? ""}${snip ? `\n ${snip}` : ""}`;
252
+ }).join("\n");
253
+ return out || "(no results)";
254
+ }
255
+ async function webSearch(args) {
256
+ const q = str(args.query ?? args.q);
257
+ if (!q)
258
+ return "error: web_search needs a query";
259
+ const n = Math.min(Math.max(Number(args.count ?? 8), 1), 20);
260
+ const engine = str(args.engine) || "google";
261
+ const ctrl = new AbortController();
262
+ const timer = setTimeout(() => ctrl.abort(), Number(args.timeout_ms ?? 25_000));
263
+ try {
264
+ const ap = process.env.KODE_AUTOPILOT_URL;
265
+ if (ap) {
266
+ const res = await fetch(`${ap.replace(/\/$/, "")}/serp`, {
267
+ method: "POST", signal: ctrl.signal,
268
+ headers: { "Content-Type": "application/json", "User-Agent": "operator/kode-tsi" },
269
+ body: JSON.stringify({ query: q, num: n, engine }),
270
+ });
271
+ if (res.ok) {
272
+ const j = await res.json().catch(() => null);
273
+ const rows = Array.isArray(j) ? j : (j?.results ?? j?.data);
274
+ if (Array.isArray(rows))
275
+ return fmtResults(rows, n);
276
+ }
277
+ // autopilot configured but errored/odd-shaped — try SearXNG next rather than fail hard.
278
+ }
279
+ const searx = process.env.KODE_SEARXNG_URL;
280
+ if (searx) {
281
+ const res = await fetch(`${searx.replace(/\/$/, "")}/search?q=${encodeURIComponent(q)}&format=json`, { signal: ctrl.signal, headers: { "User-Agent": "operator/kode-tsi" } });
282
+ if (res.ok) {
283
+ const j = await res.json().catch(() => ({}));
284
+ return fmtResults(j.results ?? [], n);
285
+ }
286
+ }
287
+ return "error: web_search has no backend configured — set KODE_AUTOPILOT_URL (AXE autopilot SERP service) or KODE_SEARXNG_URL (self-hosted SearXNG). Raw DDG/Playwright scraping is intentionally not used.";
288
+ }
289
+ catch (e) {
290
+ const msg = e instanceof Error ? e.message : String(e);
291
+ return `error searching: ${/abort/i.test(msg) ? "timed out" : msg}`;
292
+ }
293
+ finally {
294
+ clearTimeout(timer);
295
+ }
296
+ }
191
297
  async function webFetch(args) {
192
298
  const url = str(args.url);
193
299
  if (!/^https?:\/\//i.test(url))
@@ -213,6 +319,94 @@ async function webFetch(args) {
213
319
  clearTimeout(timer);
214
320
  }
215
321
  }
322
+ const bgJobs = new Map();
323
+ let bgSeq = 0;
324
+ const BG_MAX_RUNNING = 8; // cap concurrent live jobs — a background tool must never let the agent fork-bomb the host
325
+ const BG_KEEP_FINISHED = 16; // retain a bounded history of finished jobs so bash_output can still report an exit
326
+ const BG_BUF_CAP = 200_000; // per-job ring: keep the last ~200KB so a chatty job can't grow memory without bound
327
+ // Drop the oldest finished jobs once we exceed the retention budget — keeps `bgJobs` from growing across a
328
+ // long session. Running jobs are never pruned; insertion order (Map) makes "oldest finished" cheap.
329
+ function pruneBgJobs() {
330
+ const finished = [...bgJobs.entries()].filter(([, j]) => j.done);
331
+ for (let i = 0; i < finished.length - BG_KEEP_FINISHED; i++)
332
+ bgJobs.delete(finished[i][0]);
333
+ }
334
+ async function shellBackground(args) {
335
+ const command = str(args.command);
336
+ if (!command)
337
+ return "error: no command given";
338
+ pruneBgJobs();
339
+ const running = [...bgJobs.values()].filter((j) => !j.done).length;
340
+ if (running >= BG_MAX_RUNNING)
341
+ return `error: ${BG_MAX_RUNNING} background jobs already running — bash_kill one before starting another`;
342
+ const cwd = args.cwd ? str(args.cwd) : undefined;
343
+ const { spawn } = await nodeImport("node:child_process");
344
+ const { file, args: argv } = await wrapShell(command); // same OS sandbox wrap as shell_exec
345
+ const id = `sh${++bgSeq}`;
346
+ const p = spawn(file, argv, { cwd }); // NOT detached: the job dies with Operator, so we never orphan a process
347
+ const job = { proc: p, buf: "", done: false, code: null, started: Date.now(), cmd: command };
348
+ const cap = (d) => { job.buf += d.toString("utf8"); if (job.buf.length > BG_BUF_CAP)
349
+ job.buf = job.buf.slice(-BG_BUF_CAP); };
350
+ p.stdout?.on("data", cap);
351
+ p.stderr?.on("data", cap);
352
+ p.on("close", (c) => { job.done = true; job.code = c; });
353
+ p.on("error", (e) => { job.buf += `\n[spawn error: ${e.message}]`; job.done = true; job.code = -1; });
354
+ bgJobs.set(id, job);
355
+ return `started background job ${id}: ${command}\nPoll it with bash_output {"id":"${id}"}; stop it with bash_kill {"id":"${id}"}.`;
356
+ }
357
+ async function bashOutput(args) {
358
+ const id = str(args.id);
359
+ const job = bgJobs.get(id);
360
+ if (!job)
361
+ return `error: no background job "${id}" (list ids from shell_background's return)`;
362
+ const out = job.buf;
363
+ job.buf = ""; // drain what's arrived since the last poll
364
+ const status = job.done ? `[job ${id} finished — exit ${job.code}]` : `[job ${id} running — ${Math.round((Date.now() - job.started) / 1000)}s elapsed]`;
365
+ return `${status}\n${out || "(no new output since last poll)"}`;
366
+ }
367
+ async function bashKill(args) {
368
+ const id = str(args.id);
369
+ const job = bgJobs.get(id);
370
+ if (!job)
371
+ return `error: no background job "${id}"`;
372
+ if (job.done)
373
+ return `job ${id} already finished (exit ${job.code})`;
374
+ try {
375
+ job.proc.kill("SIGTERM");
376
+ return `sent SIGTERM to background job ${id}`;
377
+ }
378
+ catch (e) {
379
+ return `error killing ${id}: ${e?.message ?? e}`;
380
+ }
381
+ }
382
+ const agentTasks = [];
383
+ let taskSeq = 0;
384
+ function renderTasks() {
385
+ if (!agentTasks.length)
386
+ return "(no tasks yet)";
387
+ const mark = { pending: "[ ]", in_progress: "[~]", done: "[x]" };
388
+ return agentTasks.map((t) => `${mark[t.status]} #${t.id} ${t.text}`).join("\n");
389
+ }
390
+ async function taskAdd(args) {
391
+ const items = Array.isArray(args.tasks) ? args.tasks.map(String) : [str(args.text)].filter(Boolean);
392
+ if (!items.length)
393
+ return "error: task_add needs `text` or `tasks` (array)";
394
+ for (const t of items)
395
+ agentTasks.push({ id: ++taskSeq, text: t, status: "pending" });
396
+ return `added ${items.length} task(s):\n${renderTasks()}`;
397
+ }
398
+ async function taskList() { return renderTasks(); }
399
+ async function taskUpdate(args) {
400
+ const id = Number(args.id);
401
+ const status = str(args.status);
402
+ const t = agentTasks.find((x) => x.id === id);
403
+ if (!t)
404
+ return `error: no task #${id}`;
405
+ if (status !== "pending" && status !== "in_progress" && status !== "done")
406
+ return "error: status must be pending | in_progress | done";
407
+ t.status = status;
408
+ return `task #${id} → ${status}\n${renderTasks()}`;
409
+ }
216
410
  const TOOLS = [
217
411
  {
218
412
  name: "shell_exec", safe: false,
@@ -222,9 +416,45 @@ const TOOLS = [
222
416
  }, required: ["command"] },
223
417
  run: shellExec,
224
418
  },
419
+ {
420
+ name: "shell_background", safe: false,
421
+ description: "Start a long-running shell command DETACHED and return a job id immediately (does not block). Poll it with bash_output, stop it with bash_kill. Use for servers, builds, watchers.",
422
+ parameters: { type: "object", properties: { command: { type: "string" }, cwd: { type: "string" } }, required: ["command"] },
423
+ run: shellBackground,
424
+ },
425
+ {
426
+ name: "bash_output", safe: true,
427
+ description: "Read new stdout/stderr from a background job started by shell_background (drains what's arrived since the last poll) and whether it's still running.",
428
+ parameters: { type: "object", properties: { id: { type: "string", description: "the job id from shell_background" } }, required: ["id"] },
429
+ run: bashOutput,
430
+ },
431
+ {
432
+ name: "bash_kill", safe: false,
433
+ description: "Stop a running background job (SIGTERM) started by shell_background.",
434
+ parameters: { type: "object", properties: { id: { type: "string" } }, required: ["id"] },
435
+ run: bashKill,
436
+ },
437
+ {
438
+ name: "task_add", safe: false,
439
+ description: "Add one or more tasks to the session TODO list (multi-step work tracking the user can see). Give `text` for one or `tasks` (array) for several.",
440
+ parameters: { type: "object", properties: { text: { type: "string" }, tasks: { type: "array", items: { type: "string" } } } },
441
+ run: taskAdd,
442
+ },
443
+ {
444
+ name: "task_list", safe: true,
445
+ description: "Show the session TODO list with each task's status ([ ] pending, [~] in progress, [x] done).",
446
+ parameters: { type: "object", properties: {} },
447
+ run: taskList,
448
+ },
449
+ {
450
+ name: "task_update", safe: false,
451
+ description: "Set a task's status. status = pending | in_progress | done.",
452
+ parameters: { type: "object", properties: { id: { type: "number" }, status: { type: "string", enum: ["pending", "in_progress", "done"] } }, required: ["id", "status"] },
453
+ run: taskUpdate,
454
+ },
225
455
  {
226
456
  name: "file_read", safe: true,
227
- description: "Read a file, optionally a line range, with line numbers.",
457
+ description: "Read a file, optionally a line range, with line numbers. Without offset/limit, only the first 2000 lines are returned — pass offset/limit to page through a larger file.",
228
458
  parameters: { type: "object", properties: {
229
459
  path: { type: "string" }, offset: { type: "number" }, limit: { type: "number" },
230
460
  }, required: ["path"] },
@@ -302,6 +532,17 @@ const TOOLS = [
302
532
  }, required: ["url"] },
303
533
  run: webFetch,
304
534
  },
535
+ {
536
+ name: "web_search", safe: true,
537
+ description: "Search the web (via the AXE autopilot SERP service, or a self-hosted SearXNG) and return ranked title/url/snippet results. Read-only. Follow up with web_fetch to read a result.",
538
+ parameters: { type: "object", properties: {
539
+ query: { type: "string", description: "the search query" },
540
+ count: { type: "number", description: "max results (1-20, default 8)" },
541
+ engine: { type: "string", enum: ["google", "bing", "ddg"], description: "search engine for the autopilot backend (default google)" },
542
+ timeout_ms: { type: "number" },
543
+ }, required: ["query"] },
544
+ run: webSearch,
545
+ },
305
546
  {
306
547
  name: "skill_list", safe: true,
307
548
  description: "List or search AXE skills from the Operator registry (operator.axe.onl /v1/skills) — reusable playbooks for code review, security audit, debugging, architecture, and more. Read-only.",
@@ -327,8 +568,9 @@ async function operatorToken() {
327
568
  if (process.env.OPERATOR_TOKEN)
328
569
  return process.env.OPERATOR_TOKEN;
329
570
  try {
330
- const { homedir } = await import("node:os");
331
- const { join } = await import("node:path");
571
+ const { homedir } = await nodeImport("node:os");
572
+ const { join } = await nodeImport("node:path");
573
+ const { readFile } = await nodeImport("node:fs/promises");
332
574
  for (const fn of ["operator_token.txt", "axeclaw_token.txt"]) {
333
575
  try {
334
576
  return (await readFile(join(homedir(), ".axe", "secrets", fn), "utf8")).trim();
@@ -11,13 +11,28 @@
11
11
  //
12
12
  // Mode: KODE_SANDBOX = "off" (default) | "workspace" (deny sensitive writes, allow network) | "strict"
13
13
  // (confine writes to workspace/tmp, deny network).
14
- import { homedir } from "node:os";
15
- import { resolve } from "node:path";
14
+ // No static node:os / node:path imports — a top-level `import "node:..."` breaks the platform:neutral
15
+ // bundle (registry.ts pulls this module in, and it reaches the mobile JSCore engine). HOME comes from
16
+ // the env; a minimal single-arg POSIX resolve() is inlined below. These sandbox functions only ever
17
+ // run on the node CLI (tools execute natively on mobile), so this changes no behavior there.
18
+ function resolve(p) {
19
+ const abs = p.startsWith("/") ? p : `${process.cwd()}/${p}`;
20
+ const out = [];
21
+ for (const seg of abs.split("/")) {
22
+ if (seg === "" || seg === ".")
23
+ continue;
24
+ if (seg === "..")
25
+ out.pop();
26
+ else
27
+ out.push(seg);
28
+ }
29
+ return "/" + out.join("/");
30
+ }
16
31
  export function sandboxMode() {
17
32
  const m = (process.env.KODE_SANDBOX ?? "off").toLowerCase();
18
33
  return m === "workspace" || m === "strict" ? m : "off";
19
34
  }
20
- const HOME = homedir();
35
+ const HOME = process.env.HOME ?? "";
21
36
  // Never writable when the sandbox is on, even inside home — protects credentials/keys/shell rc from an
22
37
  // errant model action. (Reads are unaffected; only writes are blocked.)
23
38
  const DENY_WRITE_SUBPATHS = [
@@ -29,39 +44,129 @@ const DENY_WRITE_FILES = [
29
44
  `${HOME}/.zshrc`, `${HOME}/.zshenv`, `${HOME}/.zprofile`, `${HOME}/.bashrc`,
30
45
  `${HOME}/.bash_profile`, `${HOME}/.profile`, `${HOME}/.netrc`, `${HOME}/.git-credentials`,
31
46
  ];
47
+ // Credential/secret paths that must never be READ when the sandbox is on — the exfiltration vector
48
+ // (an agent reads ~/.ssh/id_rsa or ~/.aws/credentials and ships it out via a tool, the network, or the
49
+ // model context). A SUBSET of the write-denylist: only true secrets — NOT /etc,/usr,/bin, which the
50
+ // shell must read to run. Reads outside these stay allowed so normal commands work.
51
+ const SECRET_READ_SUBPATHS = [
52
+ `${HOME}/.ssh`, `${HOME}/.aws`, `${HOME}/.gnupg`, `${HOME}/.config/gcloud`,
53
+ `${HOME}/.axe/secrets`, `${HOME}/.kube`, `${HOME}/.docker`,
54
+ ];
55
+ const SECRET_READ_FILES = [`${HOME}/.netrc`, `${HOME}/.git-credentials`];
32
56
  // In strict mode, writes must land under one of these roots.
33
57
  function allowedWriteRoots() {
34
58
  return [process.cwd(), HOME + "/.axe/operator", "/tmp", "/private/tmp", process.env.TMPDIR ?? "/tmp"].map((p) => resolve(p));
35
59
  }
36
- /** Return an error string if `path` is a forbidden write target under the active mode, else null.
37
- * Resolves `..`/sym* to a real path first so a traversal can't slip past the check. */
38
- export function deniedWrite(path) {
39
- if (sandboxMode() === "off")
40
- return null;
41
- const p = resolve(path);
60
+ /** Core check on an already-resolved absolute path (lexical or realpath'd). */
61
+ function checkDenied(p, original) {
42
62
  const under = (root) => p === root || p.startsWith(root.endsWith("/") ? root : root + "/");
43
63
  for (const f of DENY_WRITE_FILES)
44
64
  if (p === resolve(f))
45
- return `sandbox: writing ${path} is blocked (protected file)`;
65
+ return `sandbox: writing ${original} is blocked (protected file)`;
46
66
  for (const d of DENY_WRITE_SUBPATHS)
47
67
  if (under(resolve(d)))
48
68
  return `sandbox: writing under ${d} is blocked (protected path)`;
49
69
  if (sandboxMode() === "strict" && !allowedWriteRoots().some(under)) {
50
- return `sandbox(strict): writes are confined to the workspace + tmp — ${path} is outside`;
70
+ return `sandbox(strict): writes are confined to the workspace + tmp — ${original} is outside`;
71
+ }
72
+ return null;
73
+ }
74
+ /** Sync, lexical guard (no fs access — safe anywhere, incl. the JSCore bundle). Catches `..` traversal
75
+ * and direct writes to protected paths, but NOT symlinks pointing at protected paths. Callers on the
76
+ * node CLI must prefer deniedWriteAsync, which closes that gap with realpath resolution. */
77
+ export function deniedWrite(path) {
78
+ if (sandboxMode() === "off")
79
+ return null;
80
+ return checkDenied(resolve(path), path);
81
+ }
82
+ // node:fs imported LAZILY via an opaque specifier (same pattern as permissions/audit.ts) so the
83
+ // platform:neutral mobile bundle never resolves it statically; this path only runs on the node CLI.
84
+ const nodeImport = (m) => import(/* @vite-ignore */ m);
85
+ /** realpath the deepest EXISTING ancestor, then re-append the non-existent tail lexically.
86
+ * Handles `file_write` to a brand-new path whose parent dir is itself a symlink into a denylisted
87
+ * root (e.g. workspace/keys_dir -> ~/.ssh, writing keys_dir/id_rsa.new). */
88
+ async function realPathOf(p) {
89
+ const parts = p.split("/");
90
+ for (let i = parts.length; i >= 2; i--) {
91
+ const head = parts.slice(0, i).join("/");
92
+ const tail = parts.slice(i).join("/");
93
+ try {
94
+ const { realpath } = await nodeImport("node:fs/promises");
95
+ const base = await realpath(head);
96
+ return tail ? `${base}/${tail}` : base;
97
+ }
98
+ catch {
99
+ /* this ancestor doesn't exist; walk up one level */
100
+ }
101
+ }
102
+ return p;
103
+ }
104
+ /** The full guard: lexical check, then — only when it passes — a realpath re-check so a symlink
105
+ * cannot launder a write into a protected path (proven bypass, 2026-09-17 review). */
106
+ export async function deniedWriteAsync(path) {
107
+ const fast = deniedWrite(path);
108
+ if (fast)
109
+ return fast;
110
+ if (sandboxMode() === "off")
111
+ return null;
112
+ const lex = resolve(path);
113
+ const real = await realPathOf(lex);
114
+ if (real !== lex) {
115
+ const via = checkDenied(real, path);
116
+ if (via)
117
+ return via + " (symlink resolves to a protected path)";
51
118
  }
52
119
  return null;
53
120
  }
54
121
  /** Build a macOS seatbelt profile string for the active mode (workspace = deny-list, strict = deny writes
55
122
  * outside the workspace + deny network). */
123
+ /** Core secret-read check on an already-resolved absolute path. */
124
+ function checkReadDenied(p, original) {
125
+ const under = (root) => p === root || p.startsWith(root.endsWith("/") ? root : root + "/");
126
+ for (const f of SECRET_READ_FILES)
127
+ if (p === resolve(f))
128
+ return `sandbox: reading ${original} is blocked (secret file)`;
129
+ for (const d of SECRET_READ_SUBPATHS)
130
+ if (under(resolve(d)))
131
+ return `sandbox: reading under ${d} is blocked (secret path)`;
132
+ return null;
133
+ }
134
+ /** Sync, lexical read-guard (no fs — safe in the neutral bundle). Prefer deniedReadAsync on the CLI. */
135
+ export function deniedRead(path) {
136
+ if (sandboxMode() === "off")
137
+ return null;
138
+ return checkReadDenied(resolve(path), path);
139
+ }
140
+ /** Full read-guard: lexical, then a realpath re-check so a symlink can't launder a read of a secret. */
141
+ export async function deniedReadAsync(path) {
142
+ const fast = deniedRead(path);
143
+ if (fast)
144
+ return fast;
145
+ if (sandboxMode() === "off")
146
+ return null;
147
+ const lex = resolve(path);
148
+ const real = await realPathOf(lex);
149
+ if (real !== lex) {
150
+ const via = checkReadDenied(real, path);
151
+ if (via)
152
+ return via + " (symlink resolves to a secret path)";
153
+ }
154
+ return null;
155
+ }
56
156
  export function seatbeltProfile(mode) {
57
157
  const q = (s) => s.replace(/"/g, '\\"');
58
158
  const denySub = DENY_WRITE_SUBPATHS.map((d) => `(subpath "${q(d)}")`).join(" ");
59
159
  const denyFiles = DENY_WRITE_FILES.map((f) => `(literal "${q(f)}")`).join(" ");
160
+ // Read-containment: block reads of credential paths in BOTH modes so a shell command can't read+exfil
161
+ // secrets. Scoped to real secrets so /usr,/etc,/bin stay readable and normal commands still run.
162
+ const denyReadSub = SECRET_READ_SUBPATHS.map((d) => `(subpath "${q(d)}")`).join(" ");
163
+ const denyReadFiles = SECRET_READ_FILES.map((f) => `(literal "${q(f)}")`).join(" ");
164
+ const denyRead = `(deny file-read* ${denyReadSub} ${denyReadFiles})`;
60
165
  if (mode === "strict") {
61
166
  const allow = allowedWriteRoots().concat("/dev").map((r) => `(subpath "${q(r)}")`).join(" ");
62
- return `(version 1)(allow default)(deny file-write*)(allow file-write* ${allow})(deny network*)`;
167
+ return `(version 1)(allow default)(deny file-write*)(allow file-write* ${allow})${denyRead}(deny network*)`;
63
168
  }
64
- return `(version 1)(allow default)(deny file-write* ${denySub} ${denyFiles})`;
169
+ return `(version 1)(allow default)(deny file-write* ${denySub} ${denyFiles})${denyRead}`;
65
170
  }
66
171
  let _sbExec = null; // cache: is sandbox-exec present on this host?
67
172
  async function hasSandboxExec() {
package/dist/ui/App.js CHANGED
@@ -1,16 +1,18 @@
1
1
  import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
2
  import { Box } from "ink";
3
3
  import { StatusRule } from "./StatusRule.js";
4
+ import { InputRule } from "./InputRule.js";
4
5
  import { Transcript } from "./Transcript.js";
5
6
  import { Composer } from "./Composer.js";
6
7
  import { ThinkingSpinner } from "./ThinkingSpinner.js";
7
8
  import { StepSpinner, RecoverSpinner } from "./ActivitySpinner.js";
8
9
  import { BgPanel } from "./BgPanel.js";
10
+ import { ApprovalPrompt } from "./ApprovalPrompt.js";
9
11
  export function App(props) {
10
- const { messages, live = null, status, thinkingVerb, verbs, stepLabel, route, ctxPct, version, build, metrics, authUser, bgAgents, onSubmit, onQueue, onInterrupt } = props;
12
+ const { messages, live = null, status, thinkingVerb, verbs, stepLabel, route, ctxPct, version, build, metrics, authUser, bgAgents, onSubmit, onQueue, onInterrupt, approval = null, onApprovalDecide } = props;
11
13
  const thinking = status === "thinking" || status === "streaming";
12
- return (_jsxs(Box, { flexDirection: "column", children: [_jsx(Transcript, { entries: messages, live: live }), status === "recovering" ? _jsx(RecoverSpinner, { active: true, label: stepLabel })
13
- : status === "executing" ? _jsx(StepSpinner, { active: true, label: stepLabel })
14
- : thinking ? _jsx(ThinkingSpinner, { active: true, verb: thinkingVerb, verbs: verbs })
15
- : null, _jsx(BgPanel, { agents: bgAgents }), _jsx(StatusRule, { route: route, ctxPct: ctxPct, version: version, build: build, metrics: metrics, user: authUser }), _jsx(Composer, { onSubmit: onSubmit, onQueue: onQueue, onInterrupt: onInterrupt, disabled: status !== "idle" })] }));
14
+ const showSpinner = status === "recovering" || status === "executing" || thinking;
15
+ return (_jsxs(Box, { flexDirection: "column", children: [_jsx(Transcript, { entries: messages, live: live }), showSpinner && (_jsx(Box, { marginTop: 1, marginBottom: 1, children: status === "recovering" ? _jsx(RecoverSpinner, { active: true, label: stepLabel })
16
+ : status === "executing" ? _jsx(StepSpinner, { active: true, label: stepLabel })
17
+ : _jsx(ThinkingSpinner, { active: true, verb: thinkingVerb, verbs: verbs, metrics: metrics }) })), _jsx(BgPanel, { agents: bgAgents }), _jsx(ApprovalPrompt, { approval: approval, onDecide: onApprovalDecide ?? (() => { }) }), _jsx(StatusRule, { route: route, ctxPct: ctxPct, version: version, build: build, user: authUser }), _jsx(Composer, { onSubmit: onSubmit, onQueue: onQueue, onInterrupt: onInterrupt, disabled: status !== "idle", suspended: !!approval }), _jsx(InputRule, {})] }));
16
18
  }
@@ -0,0 +1,45 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { Box, Text, useInput } from "ink";
3
+ // A short, human summary of what the tool is about to do — the args that matter, truncated. Keeps the
4
+ // prompt to a couple of lines instead of dumping raw JSON.
5
+ function summarize(name, args) {
6
+ const s = (v, n = 80) => {
7
+ const str = typeof v === "string" ? v : JSON.stringify(v);
8
+ return str && str.length > n ? str.slice(0, n) + "…" : str ?? "";
9
+ };
10
+ switch (name) {
11
+ case "app_open":
12
+ case "app_activate": return `app: ${s(args.app)}`;
13
+ case "computer_applescript": return `AppleScript: ${s(args.script, 120)}`;
14
+ case "computer_type": return `type${args.app ? ` into ${s(args.app)}` : ""}: "${s(args.text)}"`;
15
+ case "computer_key": return `key: ${s(args.key)}${Array.isArray(args.modifiers) && args.modifiers.length ? ` +${args.modifiers.join("+")}` : ""}`;
16
+ case "computer_click": return `click at ${s(args.x)},${s(args.y)}`;
17
+ case "computer_screenshot": return "capture the screen to a file";
18
+ case "shell_exec": return `$ ${s(args.command, 120)}`;
19
+ case "file_write": return `write ${s(args.path)}`;
20
+ case "file_edit": return `edit ${s(args.path)}`;
21
+ default: {
22
+ const keys = Object.keys(args);
23
+ return keys.length ? keys.map((k) => `${k}: ${s(args[k], 40)}`).join(" ") : "";
24
+ }
25
+ }
26
+ }
27
+ export function ApprovalPrompt({ approval, onDecide }) {
28
+ useInput((input, key) => {
29
+ if (!approval)
30
+ return;
31
+ const c = input.toLowerCase();
32
+ if (key.ctrl && c === "c")
33
+ onDecide(false, false); // Ctrl-C at the prompt = deny (bail out safely)
34
+ else if (c === "a" || key.return)
35
+ onDecide(true, false); // allow once
36
+ else if (c === "s")
37
+ onDecide(true, true); // allow always (this session)
38
+ else if (c === "d" || key.escape)
39
+ onDecide(false, false); // deny
40
+ }, { isActive: !!approval });
41
+ if (!approval)
42
+ return null;
43
+ const detail = summarize(approval.name, approval.args);
44
+ return (_jsxs(Box, { flexDirection: "column", marginTop: 1, marginBottom: 1, borderStyle: "round", borderColor: "yellow", paddingX: 1, children: [_jsxs(Text, { color: "yellow", bold: true, children: ["⚠ Operator wants to run ", _jsx(Text, { color: "magenta", children: approval.name })] }), detail ? _jsx(Text, { dimColor: true, children: " " + detail }) : null, _jsxs(Text, { children: [" ", _jsx(Text, { color: "green", children: "[a]" }), " allow once ", _jsx(Text, { color: "cyan", children: "[s]" }), " allow always ", _jsx(Text, { color: "red", children: "[d]" }), " deny ", _jsx(Text, { dimColor: true, children: "(Enter=allow \u00B7 Esc=deny)" })] })] }));
45
+ }
@@ -17,8 +17,19 @@ function metrics(a) {
17
17
  parts.push(`${(ms / 1000).toFixed(ms < 10000 ? 1 : 0)}s`);
18
18
  return parts.join(" · ");
19
19
  }
20
+ // Grandmaster sub-agent line (SPEC/grandmaster-subagents.md §6a): model/lane chip +
21
+ // verified badge + malformed warning. Terminals have no hover, so the verify failure
22
+ // reason is shown inline (capped) instead of as a tooltip; success collapses to a bare ✓.
23
+ const cap = (s, n = 60) => (s.length > n ? `${s.slice(0, n - 1)}…` : s);
24
+ function GrandmasterLine({ a }) {
25
+ const hasModel = a.model != null || a.lane != null;
26
+ const hasVerify = a.verified != null;
27
+ if (!hasModel && !hasVerify && !a.malformed)
28
+ return null;
29
+ return (_jsxs(Box, { paddingLeft: 2, children: [hasModel && _jsxs(Text, { dimColor: true, children: [a.model ?? "?", a.lane != null ? ` · ${a.lane}` : ""] }), hasVerify && (_jsxs(Text, { color: a.verified ? "green" : "red", children: [hasModel ? " " : "", a.verified ? "✓ verified" : `✗ unverified${a.verifyDetail ? `: ${cap(a.verifyDetail)}` : ""}`] })), a.malformed ? _jsxs(Text, { color: "yellow", children: [(hasModel || hasVerify) ? " " : "", "\u26A0 malformed"] }) : null] }));
30
+ }
20
31
  export function BgPanel({ agents, title = "background" }) {
21
32
  if (agents.length === 0)
22
33
  return null;
23
- return (_jsxs(Box, { flexDirection: "column", borderStyle: "round", borderColor: "gray", paddingX: 1, children: [_jsxs(Text, { dimColor: true, children: [title, " (", agents.length, ")"] }), agents.map((a) => (_jsxs(Box, { justifyContent: "space-between", children: [_jsxs(Text, { children: [a.status === "working" ? _jsx(OrbitGlyph, {}) : _jsx(Text, { color: COLOR[a.status], children: GLYPH[a.status] }), " ", a.label, a.round != null ? ` · round ${a.round}` : ""] }), _jsx(Text, { dimColor: true, children: (() => { const m = metrics(a); return m ? `${m} · ${a.status}` : a.status; })() })] }, a.id)))] }));
34
+ return (_jsxs(Box, { flexDirection: "column", borderStyle: "round", borderColor: "gray", paddingX: 1, children: [_jsxs(Text, { dimColor: true, children: [title, " (", agents.length, ")"] }), agents.map((a) => (_jsxs(Box, { flexDirection: "column", children: [_jsxs(Box, { justifyContent: "space-between", children: [_jsxs(Text, { children: [a.status === "working" ? _jsx(OrbitGlyph, {}) : _jsx(Text, { color: COLOR[a.status], children: GLYPH[a.status] }), " ", a.label, a.round != null ? ` · round ${a.round}` : ""] }), _jsx(Text, { dimColor: true, children: (() => { const m = metrics(a); return m ? `${m} · ${a.status}` : a.status; })() })] }), _jsx(GrandmasterLine, { a: a })] }, a.id)))] }));
24
35
  }