ai-agentmanager 1.52.0 → 1.55.0

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.
@@ -0,0 +1,156 @@
1
+ // Models that run on this computer (Ollama, LM Studio, llama.cpp, MLX: see localmodels.js) as
2
+ // agent engines, one for each harness that can drive them:
3
+ // local-codex the Codex CLI, pointed at the local server instead of OpenAI
4
+ // local-opencode OpenCode (over ACP), given the server as a provider
5
+ // local-claude Claude Code, pointed at the server's Anthropic-style API (Ollama has one;
6
+ // Anthropic doesn't support Claude Code on other models)
7
+ // Each is its harness's engine (sessions, resume, usage, the inbox) with these differences:
8
+ // - The agent's model names the server: "ollama/qwen3-coder:30b".
9
+ // - bin/local-run.js starts the harness: it checks the server answers, on Ollama gives the
10
+ // model room for an agent's context first, and tells the harness where the model is.
11
+ // - Codex runs from a home of its own (~/.agentmanager/codex-local): your plugins and MCP
12
+ // servers would fill a local model's small context before the task starts. Its sessions are
13
+ // kept where Codex keeps yours, and your AGENTS.md is used. Claude Code leaves MCP servers out.
14
+ // - Summaries and reviews stay with an engine that is sure to manage them, and nothing is costed.
15
+ import fs from 'node:fs';
16
+ import os from 'node:os';
17
+ import path from 'node:path';
18
+ import { fileURLToPath } from 'node:url';
19
+ import { paths } from '../config.js';
20
+ import { lastSeen, localSettings, parseModel } from '../localmodels.js';
21
+ import { acpEngine } from './acp.js';
22
+ import claude from './claude.js';
23
+ import codex from './codex.js';
24
+
25
+ const RUNNER = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..', 'bin', 'local-run.js');
26
+ const SETUP = '--agentmgr-local';
27
+ const codexHome = () => process.env.CODEX_HOME || path.join(os.homedir(), '.codex');
28
+ export const localHome = () => path.join(paths.home, 'codex-local');
29
+
30
+ /** The home Codex runs local models from: its sessions folder and AGENTS.md are your Codex's own. */
31
+ export function ensureLocalHome() {
32
+ const home = localHome();
33
+ fs.mkdirSync(home, { recursive: true });
34
+ const link = (name, { dir = false } = {}) => {
35
+ const target = path.join(codexHome(), name);
36
+ const at = path.join(home, name);
37
+ if (dir) fs.mkdirSync(target, { recursive: true });
38
+ else if (!fs.existsSync(target)) return;
39
+ try {
40
+ if (fs.readlinkSync(at) === target) return;
41
+ fs.unlinkSync(at);
42
+ } catch (err) {
43
+ if (err.code !== 'ENOENT') return; // something of its own is there: leave it
44
+ }
45
+ fs.symlinkSync(target, at, dir ? 'junction' : 'file');
46
+ };
47
+ link('sessions', { dir: true });
48
+ link('AGENTS.md');
49
+ return home;
50
+ }
51
+
52
+ const bad = (message) => Object.assign(new Error(message), { status: 400 });
53
+
54
+ /** What a launch needs from the config (the servers, the context, the harness's command), carried in the extra arguments. */
55
+ const setupArgs = (config, command) => {
56
+ const s = localSettings(config);
57
+ return [SETUP, JSON.stringify({ command, context: s.context, servers: Object.fromEntries(Object.entries(s.servers).map(([id, x]) => [id, x.url])) })];
58
+ };
59
+ /** The starter's own arguments for a launch, the harness's command, and the other extra arguments. */
60
+ function starter(harness, extra, model) {
61
+ const at = extra.indexOf(SETUP);
62
+ const setup = at < 0 ? null : JSON.parse(extra[at + 1]);
63
+ const m = parseModel(model);
64
+ if (!setup || !m || !setup.servers[m.server]) throw bad('A local agent needs a model, written "<server>/<model>" (see `agentmgr models`)');
65
+ return { head: [RUNNER, '--harness', harness, '--url', setup.servers[m.server], '--model', m.name, '--context', String(setup.context), '--'], command: setup.command, rest: extra.filter((_, i) => i !== at && i !== at + 1) };
66
+ }
67
+
68
+ /** What every local engine shares. */
69
+ const shared = {
70
+ local: true,
71
+ bin: () => process.execPath,
72
+
73
+ /** The model an agent is created with: given or the default, on a known server, able to call tools. */
74
+ checkModel(model, config) {
75
+ const s = localSettings(config);
76
+ const id = String(model ?? '').trim() || s.default;
77
+ if (!id) throw bad('Choose a model for a local agent, written "<server>/<model>": `agentmgr models` lists what runs here');
78
+ const m = parseModel(id);
79
+ if (!m) throw bad(`"${id}" isn't a local model: write "<server>/<model>", say "ollama/${id}"`);
80
+ if (!s.servers[m.server]) throw bad(`No local server named "${m.server}" (known: ${Object.keys(s.servers).join(', ')})`);
81
+ const known = lastSeen()?.find((x) => x.id === m.server)?.models.find((x) => x.id === id);
82
+ if (known && !known.usable) throw bad(`${id}: ${known.notes[0]}`);
83
+ return id;
84
+ },
85
+
86
+ /** Offered in pickers only while a server with a model an agent can use is running here. */
87
+ available: (config) => localSettings(config).enabled && Boolean(lastSeen()?.some((x) => x.models.some((m) => m.usable))),
88
+ };
89
+
90
+ const localCodex = {
91
+ ...codex,
92
+ ...shared,
93
+ id: 'local-codex',
94
+ harness: 'codex',
95
+ label: 'Local · Codex',
96
+ supports: { ...codex.supports, oneShot: false },
97
+ install: 'Install the Codex CLI, which runs the local model (npm install -g @openai/codex)',
98
+ installedBin: (config) => codex.bin(config),
99
+ extraArgs: (config) => setupArgs(config, [codex.bin(config), ...codex.extraArgs(config)]),
100
+ launchArgs({ extra = [], model, ...opts }) {
101
+ const s = starter('codex', extra, model);
102
+ return [...s.head, s.command[0], ...codex.launchArgs({ ...opts, extra: [...s.command.slice(1), ...s.rest], model: null })];
103
+ },
104
+ env: () => ({ CODEX_HOME: ensureLocalHome() }),
105
+ trust: (dir) => codex.trust(dir, ensureLocalHome()),
106
+ };
107
+
108
+ const localClaude = {
109
+ ...claude,
110
+ ...shared,
111
+ id: 'local-claude',
112
+ harness: 'claude',
113
+ label: 'Local · Claude Code',
114
+ // The cost Claude Code works out for a model it doesn't know means nothing.
115
+ supports: { ...claude.supports, cost: false, oneShot: false, planHandoff: false },
116
+ install: 'Install Claude Code, which runs the local model (https://docs.claude.com/en/docs/claude-code)',
117
+ notice: () => "Anthropic doesn't support Claude Code on other models: expect rough edges. The server has to speak Anthropic's API (Ollama does)",
118
+ installedBin: (config) => claude.bin(config),
119
+ extraArgs: (config) => setupArgs(config, [claude.bin(config), ...claude.extraArgs(config)]),
120
+ launchArgs({ extra = [], model, ...opts }) {
121
+ const s = starter('claude', extra, model);
122
+ // MCP servers' tool lists would take much of a local model's context.
123
+ return [...s.head, s.command[0], ...claude.launchArgs({ ...opts, extra: [...s.command.slice(1), ...s.rest, '--strict-mcp-config'], model: null })];
124
+ },
125
+ scan(file, cursor, bugPatterns) {
126
+ const r = claude.scan(file, cursor, bugPatterns);
127
+ return r && 'cost' in r ? { ...r, cost: null } : r;
128
+ },
129
+ };
130
+
131
+ const opencode = acpEngine('local-opencode', { command: ['opencode', 'acp'], label: 'Local · OpenCode' });
132
+ /** OpenCode's command: the one config.json gives its ACP engine, if any. */
133
+ const opencodeCommand = (config) => {
134
+ const c = config.acp?.opencode;
135
+ return c?.command ? [c.command, ...(c.args ?? [])].flat().map(String) : ['opencode', 'acp'];
136
+ };
137
+ const localOpencode = {
138
+ ...opencode,
139
+ ...shared,
140
+ id: 'local-opencode',
141
+ harness: 'opencode',
142
+ // Not one of config's ACP agents: it stays when those are read again.
143
+ acp: false,
144
+ supports: { ...opencode.supports, oneShot: false },
145
+ install: 'Install OpenCode, which runs the local model (npm install -g opencode-ai)',
146
+ installedBin: (config) => opencodeCommand(config)[0],
147
+ extraArgs: (config) => setupArgs(config, opencodeCommand(config)),
148
+ launchArgs({ extra = [], model, ...opts }) {
149
+ const s = starter('opencode', extra, model);
150
+ const client = opencode.launchArgs(opts);
151
+ // Our ACP client, then the agent's command in place of the one the engine was made with.
152
+ return [...s.head, process.execPath, ...client.slice(0, client.lastIndexOf('--') + 1), ...s.command];
153
+ },
154
+ };
155
+
156
+ export const LOCAL_ENGINES = [localCodex, localOpencode, localClaude];
package/src/eval.js CHANGED
@@ -137,6 +137,29 @@ export function usualCommand(runs) {
137
137
  return best?.[0] ?? null;
138
138
  }
139
139
 
140
+ /** How many times a test command is run: 1 to 5. */
141
+ const MAX_REPEATS = 5;
142
+ export const cleanRuns = (v) => (Number.isInteger(Number(v)) && Number(v) >= 1 && Number(v) <= MAX_REPEATS ? Number(v) : 1);
143
+
144
+ /**
145
+ * Run a test command more than once, since one run can pass or fail by chance. `once()` →
146
+ * { passed, output, timedOut }. With `runs` of 1, a run that fails is run once more, which tells
147
+ * a flaky test from a broken one; a run that timed out is not repeated. Returns { passed (every
148
+ * run), runs, passes, flaky (some passed, some failed), shown (the last failed run, else the last) }.
149
+ */
150
+ export async function repeatRuns(once, runs = 1) {
151
+ const results = [];
152
+ let want = cleanRuns(runs);
153
+ for (let i = 0; i < want; i++) {
154
+ const r = await once(i);
155
+ results.push(r);
156
+ if (r.timedOut) break;
157
+ if (want === 1 && !r.passed) want = 2;
158
+ }
159
+ const passes = results.filter((r) => r.passed).length;
160
+ return { passed: passes === results.length, runs: results.length, passes, flaky: passes > 0 && passes < results.length, shown: results.findLast((r) => !r.passed) ?? results.at(-1) };
161
+ }
162
+
140
163
  // What each item weighs in the confidence; "na" items don't count either way.
141
164
  export const WEIGHTS = { rerun: 25, criteria: 25, agentTests: 10, coverage: 10, ci: 10, judge: 10, checks: 5, bench: 5 };
142
165
  export const LABELS = {
@@ -162,8 +185,10 @@ export function evaluate({ runs = [], rerun = null, state = null, scorecard = nu
162
185
  if (rerun?.running) add('rerun', 'pending', 0, `Running ${rerun.command}…`);
163
186
  else if (!rerun) add('rerun', 'pending', 0, testCommand ? `Not run yet (${testCommand})` : 'No test command found for this project: set one');
164
187
  else if (state && rerun.state !== state) add('rerun', 'pending', 0, `The code changed after the last run (${rerun.passed ? 'passed' : 'failed'} ${rerun.at}): run again`);
165
- else if (rerun.passed) add('rerun', 'ok', 1, `${rerun.command} passed${rerun.counts ? `: ${rerun.counts.passed} passed` : ''}`);
166
- else add('rerun', 'failed', 0, `${rerun.command} failed${rerun.counts ? `: ${rerun.counts.failed} failed, ${rerun.counts.passed} passed` : rerun.timedOut ? ' (timed out)' : ''}`);
188
+ else if (rerun.passed) add('rerun', 'ok', 1, `${rerun.command} passed${rerun.runs > 1 ? ` in all ${rerun.runs} runs` : ''}${rerun.counts ? `: ${rerun.counts.passed} passed` : ''}`);
189
+ // Passed in some runs and failed in others: not something to merge on, and not the same as broken.
190
+ else if (rerun.flaky) add('rerun', 'partial', rerun.passes / rerun.runs, `${rerun.command} is flaky: it passed ${rerun.passes} of ${rerun.runs} runs on the same code`);
191
+ else add('rerun', 'failed', 0, `${rerun.command} failed${rerun.runs > 1 ? ` in all ${rerun.runs} runs` : ''}${rerun.counts ? `: ${rerun.counts.failed} failed, ${rerun.counts.passed} passed` : rerun.timedOut ? ' (timed out)' : ''}`);
167
192
 
168
193
  // Acceptance criteria, as the scorecard found them.
169
194
  const crit = scorecard?.criteria ?? [];
@@ -241,7 +266,7 @@ export function evalMarkdown(ev, title = '') {
241
266
  ...ev.items.map((i) => `| ${MARK[i.state]} | ${i.label} | ${String(i.detail).replace(/\|/g, '/').replace(/\n/g, ' ')} |`),
242
267
  '',
243
268
  ...(ev.criteria.length ? ['**Acceptance criteria**', '', ...ev.criteria.map((c) => `- ${c.status === 'met' ? '✅' : c.status === 'not_met' ? '❌' : '⏳'} ${c.criterion}${c.evidence ? ` — ${c.evidence}` : ''}`), ''] : []),
244
- ...(last.size ? ['**Tests run**', '', ...[...last.values()].map((r) => `- ${r.passed ? '✅' : '❌'} \`${r.command}\`${r.counts ? ` (${r.counts.passed} passed, ${r.counts.failed} failed)` : ''}`), ...(ev.rerun && !ev.rerun.running ? [`- ${ev.rerun.passed ? '✅' : '❌'} \`${ev.rerun.command}\` run again by AI Agent Manager on the final change${ev.rerun.counts ? ` (${ev.rerun.counts.passed} passed, ${ev.rerun.counts.failed} failed)` : ''}`] : []), ''] : []),
269
+ ...(last.size ? ['**Tests run**', '', ...[...last.values()].map((r) => `- ${r.passed ? '✅' : '❌'} \`${r.command}\`${r.counts ? ` (${r.counts.passed} passed, ${r.counts.failed} failed)` : ''}`), ...(ev.rerun && !ev.rerun.running ? [`- ${ev.rerun.passed ? '✅' : ev.rerun.flaky ? '🟡' : '❌'} \`${ev.rerun.command}\` run again by AI Agent Manager on the final change${ev.rerun.runs > 1 ? (ev.rerun.flaky ? `, flaky: passed ${ev.rerun.passes} of ${ev.rerun.runs} runs` : `, ${ev.rerun.runs} runs`) : ''}${ev.rerun.counts ? ` (${ev.rerun.counts.passed} passed, ${ev.rerun.counts.failed} failed)` : ''}`] : []), ''] : []),
245
270
  ...(ev.pending.length ? ['**Pending**', '', ...ev.pending.map((p) => `- ${p}`), ''] : ['Nothing pending.', '']),
246
271
  ].join('\n');
247
272
  }
@@ -309,8 +334,14 @@ export class Evals {
309
334
  return found ?? usualCommand(runs);
310
335
  }
311
336
 
312
- /** Set the test command for an agent's project (empty: back to finding it). */
313
- setTestCommand(ref, command) {
337
+ /** How many times the project's tests are run each time (1: once, and once more when that fails). */
338
+ testRuns(agent) {
339
+ const p = this.manager.projectInfo(agent);
340
+ return cleanRuns(Object.values(this.store.data.projects ?? {}).find((x) => x.key === p?.key)?.testRuns);
341
+ }
342
+
343
+ /** Set the test command for an agent's project (empty: back to finding it), and how many times it is run. */
344
+ setTestCommand(ref, command, runs) {
314
345
  const agent = this.manager.mustGet(ref);
315
346
  const p = this.manager.projectInfo(agent);
316
347
  const entry = Object.values(this.store.data.projects ?? {}).find((x) => x.key === p?.key);
@@ -318,8 +349,12 @@ export class Evals {
318
349
  const c = String(command ?? '').trim().slice(0, 300);
319
350
  if (c) entry.testCommand = c;
320
351
  else delete entry.testCommand;
352
+ if (runs !== undefined) {
353
+ if (cleanRuns(runs) > 1) entry.testRuns = cleanRuns(runs);
354
+ else delete entry.testRuns;
355
+ }
321
356
  this.store.save();
322
- return { testCommand: this.testCommand(agent) };
357
+ return { testCommand: this.testCommand(agent), testRuns: this.testRuns(agent) };
323
358
  }
324
359
 
325
360
  /** Run the tests on the agent's change as it is now, then work the Eval out. */
@@ -337,8 +372,9 @@ export class Evals {
337
372
  const started = Date.now();
338
373
  const st = await this.state(agent).catch(() => null);
339
374
  const at = await this.commit(agent).catch(() => null);
340
- const res = await this.run(agent, command);
341
- rerun = { command, passed: Boolean(res.passed), counts: countsOf(res.output), tail: clip(String(res.output ?? '').split('\n').slice(-15).join('\n'), 2000), timedOut: Boolean(res.timedOut), state: st, head: at?.head ?? null, clean: at?.clean ?? null, at: now(), ms: Date.now() - started };
375
+ const all = await repeatRuns(() => this.run(agent, command), this.testRuns(agent));
376
+ const res = all.shown;
377
+ rerun = { command, passed: all.passed, runs: all.runs, passes: all.passes, flaky: all.flaky, counts: countsOf(res.output), tail: clip(String(res.output ?? '').split('\n').slice(-15).join('\n'), 2000), timedOut: Boolean(res.timedOut), state: st, head: at?.head ?? null, clean: at?.clean ?? null, at: now(), ms: Date.now() - started };
342
378
  } catch (e) {
343
379
  rerun = { command, passed: false, counts: null, tail: clip(String(e?.message ?? e), 2000), timedOut: false, state: null, at: now(), ms: 0 };
344
380
  } finally {
@@ -387,6 +423,7 @@ export class Evals {
387
423
  ev.sig = this.signature(agent);
388
424
  ev.markdown = evalMarkdown(ev, agent.name);
389
425
  ev.testCommand = this.testCommand(agent, runs ?? []);
426
+ ev.testRuns = this.testRuns(agent);
390
427
  const cur = this.store.get(id);
391
428
  if (!cur) return null;
392
429
  // A test run ended while this was worked out: the one it ended with has the newer answer.
package/src/git.js CHANGED
@@ -2,8 +2,10 @@ import { execFile, spawn } from 'node:child_process';
2
2
  import fs from 'node:fs';
3
3
  import path from 'node:path';
4
4
 
5
- // Never wait on a username/password prompt nobody can see; fail instead.
6
- const baseEnv = () => ({ ...process.env, GIT_TERMINAL_PROMPT: '0' });
5
+ // Never wait on a username/password prompt nobody can see; fail instead. And no optional locks:
6
+ // a `git status` here in the background would otherwise hold the index lock for a moment, and an
7
+ // agent's own `git add` or `git commit` at that moment fails with "index.lock: File exists".
8
+ const baseEnv = () => ({ ...process.env, GIT_TERMINAL_PROMPT: '0', GIT_OPTIONAL_LOCKS: '0' });
7
9
 
8
10
  const cancelled = () => Object.assign(new Error('Cancelled'), { cancelled: true });
9
11
 
package/src/lanes.js ADDED
@@ -0,0 +1,156 @@
1
+ // Lanes: a range of ports and a name ending of its own for every agent. Worktrees keep agents'
2
+ // files apart, but two dev servers still want the same port and two test runs the same database.
3
+ // An agent's lane is in its environment (PORT, AGENT_PORT, AGENT_PORTS, AGENT_SUFFIX) and in its
4
+ // instructions; a lane is free again when its agent is deleted. What each open session listens on
5
+ // is read from the system itself (`lsof`, or `ss` on Linux), so a port outside a lane shows.
6
+
7
+ import { execFile } from 'node:child_process';
8
+
9
+ export const LANE_DEFAULTS = { enabled: true, base: 21000, size: 10, port: true };
10
+ const TOP = 32767; // below the ports systems hand out on their own
11
+
12
+ const int = (v, min, max, fallback) => (Number.isInteger(Number(v)) && Number(v) >= min && Number(v) <= max ? Number(v) : fallback);
13
+
14
+ export function laneSettings(config = {}) {
15
+ const c = config.lanes ?? {};
16
+ return {
17
+ enabled: c.enabled !== false,
18
+ base: int(c.base, 1024, TOP - 100, LANE_DEFAULTS.base),
19
+ size: int(c.size, 1, 100, LANE_DEFAULTS.size),
20
+ port: c.port !== false,
21
+ };
22
+ }
23
+
24
+ /** Lane n (from 1): its ports and the ending for names, or null when it runs past the top. */
25
+ export function laneOf(n, settings = LANE_DEFAULTS) {
26
+ if (!Number.isInteger(n) || n < 1) return null;
27
+ const first = settings.base + (n - 1) * settings.size;
28
+ const last = first + settings.size - 1;
29
+ return last > TOP ? null : { n, first, last, suffix: `_a${n}` };
30
+ }
31
+
32
+ /** The lowest lane no agent has, passing over lanes that hold a port of this app's own. */
33
+ export function nextLane(taken, settings = LANE_DEFAULTS, reserved = []) {
34
+ const used = new Set(taken);
35
+ for (let n = 1; ; n++) {
36
+ const lane = laneOf(n, settings);
37
+ if (!lane) return null;
38
+ if (used.has(n) || reserved.some((p) => p >= lane.first && p <= lane.last)) continue;
39
+ return n;
40
+ }
41
+ }
42
+
43
+ /** What a lane adds to its agent's environment. PORT only when asked: many dev servers read it. */
44
+ export function laneEnv(lane, settings = LANE_DEFAULTS) {
45
+ if (!lane) return {};
46
+ return {
47
+ AGENT_LANE: String(lane.n),
48
+ AGENT_PORT: String(lane.first),
49
+ AGENT_PORT_END: String(lane.last),
50
+ AGENT_PORTS: `${lane.first}-${lane.last}`,
51
+ AGENT_SUFFIX: lane.suffix,
52
+ ...(settings.port ? { PORT: String(lane.first) } : {}),
53
+ };
54
+ }
55
+
56
+ /** The lane, said to the agent with its other instructions. */
57
+ export function lanePrompt(lane, settings = LANE_DEFAULTS) {
58
+ const range = lane.first === lane.last ? `port ${lane.first}` : `a port from ${lane.first} to ${lane.last}`;
59
+ return [
60
+ 'Other agents work on this computer at the same time as you, each in its own copy of the code.',
61
+ `For anything you start that listens on a port (a dev server, an API, a database, a test server), use ${range}: only you have ${lane.first === lane.last ? 'it' : 'them'} (AGENT_PORTS${settings.port ? `; PORT is already ${lane.first}` : ''}). Pass the port explicitly when the tool ignores PORT.`,
62
+ 'If a port outside that range is taken, leave what holds it running: it belongs to another agent or to the user.',
63
+ `For anything you create by name outside your folder (a database, a schema, a container, a compose project, a temp folder), end its name with ${lane.suffix} (AGENT_SUFFIX).`,
64
+ ].join(' ');
65
+ }
66
+
67
+ const portOf = (addr) => {
68
+ const m = String(addr).match(/:(\d{1,5})$/);
69
+ return m ? Number(m[1]) : null;
70
+ };
71
+
72
+ /** `lsof -nP -iTCP -sTCP:LISTEN -Fpcn` as [{ pid, name, port, address }], one row a process and port. */
73
+ export function parseLsof(text) {
74
+ const out = [];
75
+ const seen = new Set();
76
+ let pid = null;
77
+ let name = '';
78
+ for (const line of String(text).split('\n')) {
79
+ const v = line.slice(1);
80
+ if (line[0] === 'p') {
81
+ pid = Number(v);
82
+ name = '';
83
+ } else if (line[0] === 'c') name = v;
84
+ else if (line[0] === 'n' && pid) {
85
+ const port = portOf(v);
86
+ if (!port || seen.has(`${pid}:${port}`)) continue;
87
+ seen.add(`${pid}:${port}`);
88
+ out.push({ pid, name, port, address: v.slice(0, v.lastIndexOf(':')) });
89
+ }
90
+ }
91
+ return out;
92
+ }
93
+
94
+ /** `ss -ltnpH` (Linux) as the same rows. Sockets of other users come without a process and are left out. */
95
+ export function parseSs(text) {
96
+ const out = [];
97
+ const seen = new Set();
98
+ for (const line of String(text).split('\n')) {
99
+ const cols = line.trim().split(/\s+/);
100
+ const port = portOf(cols[3] ?? '');
101
+ if (cols[0] !== 'LISTEN' || !port) continue;
102
+ for (const m of line.matchAll(/\("([^"]*)",pid=(\d+)/g)) {
103
+ const pid = Number(m[2]);
104
+ if (seen.has(`${pid}:${port}`)) continue;
105
+ seen.add(`${pid}:${port}`);
106
+ out.push({ pid, name: m[1], port, address: cols[3].slice(0, cols[3].lastIndexOf(':')) });
107
+ }
108
+ }
109
+ return out;
110
+ }
111
+
112
+ /** Every process under one (itself included). */
113
+ export function treePids(procs, rootPid) {
114
+ const kids = new Map();
115
+ for (const p of procs) kids.set(p.ppid, [...(kids.get(p.ppid) ?? []), p.pid]);
116
+ const seen = new Set();
117
+ for (const todo = [rootPid]; todo.length; ) {
118
+ const pid = todo.pop();
119
+ if (seen.has(pid)) continue;
120
+ seen.add(pid);
121
+ todo.push(...(kids.get(pid) ?? []));
122
+ }
123
+ return seen;
124
+ }
125
+
126
+ /**
127
+ * What each open session listens on. `sessions`: [{ id, name, pid, lane }] (lane from laneOf, or
128
+ * null). Each gets `ports` [{ port, pid, name, inLane }], lowest first, and `taken`: ports of its
129
+ * lane that something else holds [{ port, pid, name, by }] (`by`: the other agent's id, or null).
130
+ */
131
+ export function portsBySession(sessions, procs, listeners) {
132
+ const owner = new Map(); // pid -> session id
133
+ for (const s of sessions) if (s.pid) for (const pid of treePids(procs, s.pid)) if (!owner.has(pid)) owner.set(pid, s.id);
134
+ const within = (lane, port) => Boolean(lane && port >= lane.first && port <= lane.last);
135
+ return sessions.map((s) => ({
136
+ ...s,
137
+ ports: listeners
138
+ .filter((l) => owner.get(l.pid) === s.id)
139
+ .map((l) => ({ port: l.port, pid: l.pid, name: l.name, inLane: within(s.lane, l.port) }))
140
+ .sort((a, b) => a.port - b.port),
141
+ taken: listeners
142
+ .filter((l) => within(s.lane, l.port) && owner.get(l.pid) !== s.id)
143
+ .map((l) => ({ port: l.port, pid: l.pid, name: l.name, by: owner.get(l.pid) ?? null }))
144
+ .sort((a, b) => a.port - b.port),
145
+ }));
146
+ }
147
+
148
+ const run = (cmd, args) => new Promise((resolve) => execFile(cmd, args, { timeout: 4000, maxBuffer: 8 * 1024 * 1024 }, (e, out) => resolve(e && !out ? '' : String(out))));
149
+
150
+ /** What listens on this computer now, among the processes this user may see. */
151
+ export async function listeners() {
152
+ // lsof ends with an error when there is nothing to list; what it printed still counts.
153
+ const lsof = parseLsof(await run('lsof', ['-nP', '-iTCP', '-sTCP:LISTEN', '-Fpcn']));
154
+ if (lsof.length || process.platform !== 'linux') return lsof;
155
+ return parseSs(await run('ss', ['-ltnpH']));
156
+ }