@a2f0/agent-tool 0.1.64 → 0.1.65

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@a2f0/agent-tool",
3
- "version": "0.1.64",
3
+ "version": "0.1.65",
4
4
  "packageManager": "bun@1.4.4",
5
5
  "type": "module",
6
6
  "description": "Portable cross-agent review, PR workflows, and shared skills",
@@ -9,6 +9,7 @@ import { createLog } from "../commands/logFile";
9
9
  import { plainText } from "../commands/output";
10
10
  import { assert, git, output } from "../workflows/core";
11
11
  import { claimedBy, ledgerDirectory, membersOf, newId, observe, readRecords, removeRecord, saveRecord, type ProcessRecord, type ProcessState } from "./ledger";
12
+ import { hiddenCommand, sessionReport, type SessionShell } from "./session";
12
13
  import { ancestors, carrying, listeningPorts, processTable, startOf, workingDirectories, type ProcessRow } from "./table";
13
14
 
14
15
  const STOP_GRACE_MS = 5000;
@@ -213,11 +214,15 @@ export interface TeardownReport {
213
214
  /** Records whose processes have ended; --apply removes them. */
214
215
  finished: { id: string; label: string | null; state: ProcessState }[];
215
216
  stopped: { id: string; stopped: boolean; remaining: number[] }[];
216
- /** Processes started some other way whose working directory is in the repository. Listeners fail teardown. */
217
+ /** Processes started some other way whose working directory is in the repository. Listeners fail teardown. A session shell, or a sandbox the harness owns, has its arguments hidden. */
217
218
  untracked: { pid: number; command: string; cwd: string; ports: string[] }[];
219
+ /** The agent harness's other `-c` shells still running, never with their arguments. Listed only: they never fail teardown and are never stopped. */
220
+ sessionShells: SessionShell[];
218
221
  worktrees: { path: string; branch: string | null }[];
219
222
  unavailable: string[];
220
223
  skipped: { file: string; reason: string }[];
224
+ /** Why a list is empty without having been looked for, such as `sessionShells` outside an agent harness. */
225
+ notes: string[];
221
226
  }
222
227
 
223
228
  function survey(root: string, directory: string): Omit<TeardownReport, "ok" | "applied" | "stopped"> {
@@ -225,7 +230,7 @@ function survey(root: string, directory: string): Omit<TeardownReport, "ok" | "a
225
230
  const listening = listeningPorts(), cwd = workingDirectories(table.keys());
226
231
  const described = records.map(record => describe(record, table, listening.ports, records));
227
232
  const owned = new Set(described.flatMap(item => alive(item.state) ? item.members.map(member => member.pid) : []));
228
- const excluded = ancestors(table);
233
+ const excluded = ancestors(table), session = sessionReport(table, owned);
229
234
  const untracked = [...cwd.cwd].flatMap(([pid, directoryOf]) => {
230
235
  const row = table.get(pid);
231
236
  if (!row || excluded.has(pid) || owned.has(pid) || !within(root, directoryOf)) return [];
@@ -236,7 +241,10 @@ function survey(root: string, directory: string): Omit<TeardownReport, "ok" | "a
236
241
  // listens is still reported, since a server backgrounded from the same shell looks alike.
237
242
  const self = table.get(process.pid);
238
243
  if (self && row.pgid === self.pgid && row.ppid === self.ppid && ports.length === 0) return [];
239
- return [{ pid, command: row.command, cwd: directoryOf, ports }];
244
+ // The full command line, as `ps` shows it, except for what sessionShells covers, whose
245
+ // arguments the report never prints.
246
+ const covered = session.covered.get(pid);
247
+ return [{ pid, command: covered === undefined ? row.command : hiddenCommand(covered, pid), cwd: directoryOf, ports }];
240
248
  }).sort((a, b) => a.pid - b.pid);
241
249
  const worktrees: { path: string; branch: string | null }[] = [];
242
250
  let current: { path: string; branch: string | null } | undefined;
@@ -250,10 +258,12 @@ function survey(root: string, directory: string): Omit<TeardownReport, "ok" | "a
250
258
  kept: described.filter(item => alive(item.state) && item.keep),
251
259
  finished: described.filter(item => !alive(item.state)).map(item => ({ id: item.id, label: item.label, state: item.state })),
252
260
  untracked,
261
+ sessionShells: session.sessionShells,
253
262
  // The first entry is the main worktree; the rest were added and may need removing.
254
263
  worktrees: worktrees.slice(1),
255
264
  unavailable: [...(listening.available ? [] : ["listening ports (lsof)"]), ...(cwd.available ? [] : ["working directories (lsof)"])],
256
265
  skipped,
266
+ notes: session.notes,
257
267
  };
258
268
  }
259
269
 
@@ -276,7 +286,8 @@ export async function teardownCommand(args: string[]): Promise<number> {
276
286
  }
277
287
  const found = survey(root, directory);
278
288
  // A clean report needs every inspection: without lsof a listening server would go unseen.
279
- // Unreadable records may name running processes, so they fail teardown too.
289
+ // Unreadable records may name running processes, so they fail teardown too. Session shells
290
+ // never do: they may be another delegate's live work.
280
291
  const ok = found.leftover.length === 0 && found.untracked.every(item => item.ports.length === 0) && found.unavailable.length === 0 && found.skipped.length === 0;
281
292
  output({ ok, applied: apply, ...found, stopped } satisfies TeardownReport);
282
293
  return ok ? 0 : 1;
@@ -0,0 +1,126 @@
1
+ // The agent session's background shells. An agent harness (Claude Code, Codex, OpenCode and
2
+ // others) runs each command it is given, in the background or not, as a `-c` shell of its own
3
+ // process, so a wait loop or watcher an agent leaves behind is one of the harness's children.
4
+ // Teardown lists them by pid, age and shell name so a person or agent notices them, and never
5
+ // prints their arguments, which may carry secrets. Nothing here judges whether one can finish or
6
+ // signals it: some may be another delegate's live work in the same harness.
7
+ import path from "node:path";
8
+ import { ancestors, type ProcessRow } from "./table";
9
+
10
+ const SHELLS = new Set(["sh", "bash", "zsh", "dash", "ash", "ksh", "mksh", "pdksh", "oksh", "lksh", "yash", "posh", "osh", "ysh", "csh", "tcsh", "fish", "nu", "elvish", "xonsh"]);
11
+ // Agent harnesses by program name.
12
+ const HARNESSES = new Set(["claude", "codex", "opencode", "hermes", "omp", "gemini", "cursor-agent", "amp", "goose", "aider", "crush", "qwen"]);
13
+ // Sandboxes a harness may start a shell through, which stay running as the shell's parent.
14
+ const SANDBOXES = new Set(["bwrap", "sandbox-exec", "codex-linux-sandbox"]);
15
+ const INTERPRETER = /^(?:node|nodejs|bun|deno|python[0-9.]*|ruby|perl)$/;
16
+ // Shell options that take the next word as their value.
17
+ const WITH_VALUE = new Set(["-o", "+o", "-O", "+O", "--rcfile", "--init-file", "--emulate", "--init-command"]);
18
+ const NO_HARNESS = "No known agent harness (Claude Code, Codex, OpenCode or another) is above teardown, so sessionShells lists nothing.";
19
+
20
+ /**
21
+ * Whether a program name is a shell: a known one, perhaps with a version (`bash5.2`, `zsh-5.9`,
22
+ * `ksh93`) or as its restricted form (`rbash`).
23
+ */
24
+ function isShell(name: string): boolean {
25
+ // Shell names are short; the bound keeps the version pattern cheap on any word.
26
+ if (name.length > 32) return false;
27
+ const base = name.replace(/[-.]?\d[\d.]*$/, "");
28
+ return SHELLS.has(base) || (base.startsWith("r") && SHELLS.has(base.slice(1)));
29
+ }
30
+
31
+ /** The program a `ps` command line runs: its executable, or the script an interpreter runs. */
32
+ export function programOf(command: string): string {
33
+ const [first = "", second] = command.split(" ", 2);
34
+ const name = path.basename(first).replace(/^-/, "");
35
+ return INTERPRETER.test(name) && second && !second.startsWith("-") ? path.basename(second).replace(/\.[cm]?[jt]s$|\.py$/, "") : name;
36
+ }
37
+
38
+ /**
39
+ * The shell's own name, and how many characters of arguments follow it, when a `ps` command line
40
+ * is a shell given `-c` (`zsh -c`, `bash -lc`, `bash -O extglob -c`, `fish --command=…`): its
41
+ * first word names a shell, and a `-c` option comes before any script file operand or `--`.
42
+ * Anything else is undefined, including a shell renamed with `exec -a`, one whose path holds a
43
+ * space, and a shell a wrapper runs; such a shell is left out of the list rather than guessed at.
44
+ */
45
+ export function scriptShell(command: string): { shell: string; chars: number } | undefined {
46
+ const words = command.split(" "), first = words[0] ?? "", shell = path.basename(first).replace(/^-/, "");
47
+ return isShell(shell) && givenScript(words) ? { shell, chars: command.length - first.length - 1 } : undefined;
48
+ }
49
+
50
+ /** Whether a shell's argv, as `ps` joins it, has a `-c` option before any operand or `--`. */
51
+ function givenScript(words: string[]): boolean {
52
+ for (let index = 1; index < words.length; index += 1) {
53
+ const word = words[index]!;
54
+ if (word === "--command" || word.startsWith("--command=")) return true;
55
+ if (WITH_VALUE.has(word) || (word === "-C" && words[0]!.endsWith("fish"))) { index += 1; continue; }
56
+ // Any other long option.
57
+ if (/^--[A-Za-z][\w-]*(?:=.*)?$/.test(word)) continue;
58
+ // `--`, `-`, or a script file: no `-c` came before it.
59
+ if (!/^[-+][A-Za-z]+$/.test(word)) return false;
60
+ // `-c` alone or among other single-letter options (`-lc`, `-ec`).
61
+ if (word.startsWith("-") && word.includes("c")) return true;
62
+ // A cluster ending in an option that takes a value (`-eo pipefail`, `-xO extglob`).
63
+ if (/[oO]$/.test(word)) index += 1;
64
+ }
65
+ return false;
66
+ }
67
+
68
+ /** A background shell: never its arguments, which `ps -ww -o command= -p <pid>` shows. */
69
+ export interface SessionShell { pid: number; ageSeconds: number; shell: string; chars: number }
70
+
71
+ /** The nearest process above `self` whose program is a known agent harness. */
72
+ export function harnessAbove(table: Map<number, ProcessRow>, self = process.pid): ProcessRow | undefined {
73
+ const seen = new Set([self]);
74
+ // PID 1 is checked too: in a container the harness may be it.
75
+ for (let row = table.get(table.get(self)?.ppid ?? -1); row && !seen.has(row.pid); row = table.get(row.ppid)) {
76
+ seen.add(row.pid);
77
+ if (HARNESSES.has(programOf(row.command))) return row;
78
+ }
79
+ return undefined;
80
+ }
81
+
82
+ /** How a report shows a process it never prints the arguments of. */
83
+ export const hiddenCommand = (name: string, pid: number) => `${name} <arguments hidden; ps -ww -o command= -p ${pid} shows them>`;
84
+
85
+ /**
86
+ * The `-c` shells the harness above `self` still runs, directly or through a sandbox that stays
87
+ * their parent, oldest first; undefined when no known harness is above it. The shell that ran
88
+ * `self` is its ancestor and is left out; what `self` started are its own children, never the
89
+ * harness's. Recorded processes are left out too: they are reported, and stopped, as records,
90
+ * even where the harness has adopted them as PID 1. `covered` names each listed shell and each
91
+ * sandbox the harness owns, by pid, so no other field prints their arguments: a sandbox keeps
92
+ * the script it was given even after the shell inside it has replaced itself with a program.
93
+ */
94
+ export function sessionShells(table: Map<number, ProcessRow>, self = process.pid, now = Date.now(), recorded: ReadonlySet<number> = new Set()): { shells: SessionShell[]; covered: Map<number, string> } | undefined {
95
+ const harness = harnessAbove(table, self);
96
+ if (!harness) return undefined;
97
+ const own = ancestors(table, self);
98
+ const sandboxes = new Set([...table.values()].filter(row => SANDBOXES.has(programOf(row.command))).map(row => row.pid));
99
+ const startedByHarness = (row: ProcessRow) => {
100
+ for (let parent = row.ppid, steps = 0; steps < table.size; parent = table.get(parent)?.ppid ?? -1, steps += 1) {
101
+ if (parent === harness.pid) return true;
102
+ if (!sandboxes.has(parent)) return false;
103
+ }
104
+ return false;
105
+ };
106
+ const covered = new Map<number, string>();
107
+ for (const pid of sandboxes) {
108
+ const row = table.get(pid)!;
109
+ if (startedByHarness(row)) covered.set(pid, programOf(row.command));
110
+ }
111
+ const shells = [...table.values()].flatMap(row => {
112
+ if (own.has(row.pid) || recorded.has(row.pid) || sandboxes.has(row.pid) || !startedByHarness(row)) return [];
113
+ const found = scriptShell(row.command);
114
+ if (!found) return [];
115
+ covered.set(row.pid, found.shell);
116
+ const started = Date.parse(`${row.started} UTC`);
117
+ return [{ pid: row.pid, ageSeconds: Number.isNaN(started) ? 0 : Math.max(0, Math.floor((now - started) / 1000)), shell: found.shell, chars: found.chars }];
118
+ }).sort((a, b) => b.ageSeconds - a.ageSeconds || a.pid - b.pid);
119
+ return { shells, covered };
120
+ }
121
+
122
+ /** Teardown's `sessionShells`, a note when no harness is above it, and the processes they cover. */
123
+ export function sessionReport(table: Map<number, ProcessRow>, recorded: ReadonlySet<number>, self = process.pid, now = Date.now()): { sessionShells: SessionShell[]; notes: string[]; covered: Map<number, string> } {
124
+ const found = sessionShells(table, self, now, recorded);
125
+ return { sessionShells: found?.shells ?? [], notes: found ? [] : [NO_HARNESS], covered: found?.covered ?? new Map() };
126
+ }