ai-agentmanager 1.52.0 → 1.54.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.
package/public/system.js CHANGED
@@ -13,7 +13,7 @@ export const bytes = (n) => (n >= 1024 ** 3 ? `${(n / 1024 ** 3).toFixed(1)} GB`
13
13
  /** 3d 4h, 5h 12m, 9m. */
14
14
  export const span = (sec) => (sec >= 86400 ? `${Math.floor(sec / 86400)}d ${Math.floor((sec % 86400) / 3600)}h` : sec >= 3600 ? `${Math.floor(sec / 3600)}h ${Math.floor((sec % 3600) / 60)}m` : `${Math.floor(sec / 60)}m`);
15
15
 
16
- export function initSystem({ api, $, esc, toast, openAgent }) {
16
+ export function initSystem({ api, $, esc, toast, openAgent, openPort }) {
17
17
  const dialog = $('#os-dialog');
18
18
  const body = $('#os-body');
19
19
  let data = null;
@@ -33,6 +33,14 @@ export function initSystem({ api, $, esc, toast, openAgent }) {
33
33
  const tone = (p) => (p >= 90 ? 'heavy' : p >= 70 ? 'busy' : 'light');
34
34
  const meter = (p) => `<div class="os-meter ${tone(p)}" role="img" aria-label="${p}%"><span style="width:${Math.min(100, Math.max(0, p))}%"></span></div>`;
35
35
 
36
+ /** An agent's lane, what it listens on (a port outside its lane marked), and who else holds a port of its lane. */
37
+ function portsCell(a) {
38
+ const open = (a.ports ?? []).map((p) => `<button class="link${a.lane && !p.inLane ? ' os-port-out' : ''}" data-os-port="${p.port}" data-os-port-agent="${esc(a.id)}" title="${esc(p.name)} (PID ${p.pid}) listens on ${p.port}${a.lane && !p.inLane ? ': outside its lane' : ''}. Open it">${p.port}</button>`).join(' ');
39
+ const taken = (a.taken ?? []).map((t) => `<span class="os-port-out" title="${esc(t.name)} (PID ${t.pid})${t.by ? ', started by another agent,' : ''} holds ${t.port}, a port of this agent's lane">${t.port} taken</span>`).join(' ');
40
+ const lane = a.lane ? `<span class="hint" title="Lane ${a.lane.n}: its own ports. Names it creates end with ${esc(a.lane.suffix)}">${a.lane.first}–${a.lane.last}</span>` : '';
41
+ return [lane, open, taken].filter(Boolean).join(' · ') || '<span class="hint">—</span>';
42
+ }
43
+
36
44
  /** The last ten minutes of one measure (0 to 100) as a small line. */
37
45
  function spark(points, label) {
38
46
  if (points.length < 2) return '<div class="os-spark hint">Its last ten minutes are drawn as they pass.</div>';
@@ -48,7 +56,7 @@ export function initSystem({ api, $, esc, toast, openAgent }) {
48
56
 
49
57
  function draw() {
50
58
  if (!data) return `<div class="issues-head"><h2>OS</h2><span class="spacer"></span><button class="small" data-os="close">Close</button></div><p class="hint">${problem ? esc(problem) : 'Loading…'}</p>`;
51
- const { host, cpu, memory: mem, disks, agents, processes, app, history } = data;
59
+ const { host, cpu, memory: mem, disks, agents, processes, app, history, lanes } = data;
52
60
  const minutes = Math.max(1, Math.round((history.length * data.sampleSeconds) / 60));
53
61
  return `
54
62
  <div class="issues-head">
@@ -107,10 +115,11 @@ export function initSystem({ api, $, esc, toast, openAgent }) {
107
115
  <section>
108
116
  <h3>Agent sessions <span class="hint">${agents.open}</span></h3>
109
117
  ${agents.list.length
110
- ? `<table class="issues os-table"><thead><tr><th>Agent</th><th class="num" title="Of one core: 200% is two cores busy">Processor</th><th class="num">Memory</th><th class="num" title="The session and everything it started">Processes</th></tr></thead><tbody>
111
- ${agents.list.map((a) => `<tr><td><button class="link" data-os-agent="${esc(a.id)}">${esc(a.name)}</button></td><td class="num">${a.cpu}%</td><td class="num">${bytes(a.mem)}</td><td class="num">${a.count}</td></tr>`).join('')}
118
+ ? `<table class="issues os-table"><thead><tr><th>Agent</th><th class="num" title="Of one core: 200% is two cores busy">Processor</th><th class="num">Memory</th><th class="num" title="The session and everything it started">Processes</th><th title="Its own range of ports, and what it listens on now">Ports</th></tr></thead><tbody>
119
+ ${agents.list.map((a) => `<tr><td><button class="link" data-os-agent="${esc(a.id)}">${esc(a.name)}</button></td><td class="num">${a.cpu}%</td><td class="num">${bytes(a.mem)}</td><td class="num">${a.count}</td><td class="os-ports">${portsCell(a)}</td></tr>`).join('')}
112
120
  </tbody></table>`
113
121
  : '<p class="hint">No agent session is open.</p>'}
122
+ ${lanes ? `<div class="os-lanes"><label title="Each agent gets a range of ports and a name ending no other agent has, in its environment (AGENT_PORTS, AGENT_SUFFIX) and its instructions, so dev servers and test databases of agents working side by side don't collide. For sessions started from now on"><input type="checkbox" data-os-lanes="enabled" ${lanes.enabled ? 'checked' : ''} /> A lane of ports for each agent</label>${lanes.enabled ? `<label title="Many dev servers listen on PORT when it is set. Turn off if your projects use PORT for something else"><input type="checkbox" data-os-lanes="port" ${lanes.port ? 'checked' : ''} /> Set PORT to its first port</label><span class="hint">${lanes.size} port${lanes.size === 1 ? '' : 's'} each, from ${lanes.base}</span>` : ''}</div>` : ''}
114
123
  <h3>Busiest processes <span class="hint">of ${processes.count}</span></h3>
115
124
  <table class="issues os-table"><thead><tr><th>Process</th><th class="num" title="Of one core: 200% is two cores busy">Processor</th><th class="num">Memory</th><th class="num">PID</th></tr></thead><tbody>
116
125
  ${processes.top.map((p) => `<tr><td title="${esc(p.command)}">${esc(p.name)}</td><td class="num">${p.cpu}%</td><td class="num">${bytes(p.mem)}</td><td class="num hint">${p.pid}</td></tr>`).join('')}
@@ -126,12 +135,30 @@ export function initSystem({ api, $, esc, toast, openAgent }) {
126
135
 
127
136
  body.addEventListener('click', (e) => {
128
137
  if (e.target.closest('[data-os="close"]')) return dialog.close();
138
+ const port = e.target.closest('[data-os-port]');
139
+ if (port) {
140
+ dialog.close();
141
+ return openPort?.(port.dataset.osPortAgent, Number(port.dataset.osPort));
142
+ }
129
143
  const a = e.target.closest('[data-os-agent]');
130
144
  if (a) {
131
145
  dialog.close();
132
146
  openAgent?.(a.dataset.osAgent);
133
147
  }
134
148
  });
149
+ // Lanes on or off, and PORT with them: for the sessions started from now on.
150
+ body.addEventListener('change', async (e) => {
151
+ const key = e.target.dataset?.osLanes;
152
+ if (!key) return;
153
+ try {
154
+ const { enabled, base, size, port } = await api('PUT', '/lanes', { [key]: e.target.checked });
155
+ if (data) data.lanes = { enabled, base, size, port };
156
+ toast?.(key === 'port' ? (port ? 'PORT is set for sessions started from now on' : 'PORT is left alone in sessions started from now on') : enabled ? 'Each agent gets its own ports, in sessions started from now on' : 'No lanes for sessions started from now on', 4000);
157
+ } catch (err) {
158
+ toast?.(err.message, 5000);
159
+ }
160
+ render();
161
+ });
135
162
 
136
163
  dialog.addEventListener('close', () => {
137
164
  clearInterval(timer);
package/src/cli.js CHANGED
@@ -869,6 +869,26 @@ export async function main(argv) {
869
869
  throw new Error(`Unknown action ${action} (ls, show, look, add, check, update, rm)`);
870
870
  });
871
871
 
872
+ program
873
+ .command('lanes')
874
+ .description("Every agent's own ports and name ending, so dev servers and test databases of agents working side by side don't collide")
875
+ .option('--on', 'give each agent a lane (sessions started from now on)')
876
+ .option('--off', 'stop giving agents lanes')
877
+ .option('--port <on|off>', "also set PORT to the lane's first port in the agent's environment")
878
+ .option('--base <port>', 'the first port of the first lane')
879
+ .option('--size <ports>', 'how many ports a lane has')
880
+ .option('--json', 'print JSON')
881
+ .action(async (opts) => {
882
+ await daemon();
883
+ const patch = { ...(opts.on ? { enabled: true } : opts.off ? { enabled: false } : {}), ...(opts.port !== undefined ? { port: /^(on|true|yes|1)$/i.test(opts.port) } : {}), ...(opts.base !== undefined ? { base: opts.base } : {}), ...(opts.size !== undefined ? { size: opts.size } : {}) };
884
+ const v = Object.keys(patch).length ? await api('PUT', '/lanes', patch) : await api('GET', '/lanes');
885
+ if (opts.json) return console.log(JSON.stringify(v, null, 2));
886
+ console.log(`Lanes ${v.enabled ? green('on') : dim('off')}${v.enabled ? dim(` · ${v.size} port${v.size === 1 ? '' : 's'} each from ${v.base} · PORT ${v.port ? 'set' : 'not set'}`) : ''}`);
887
+ if (!v.enabled) return;
888
+ for (const a of v.agents) console.log(` ${String(a.n).padStart(3)} ${`${a.first}-${a.last}`.padEnd(12)} ${a.suffix.padEnd(6)} ${a.name}${a.running ? '' : dim(' (closed)')}`);
889
+ if (!v.agents.length) console.log(dim(' No agent has a lane yet: one is given when a session starts.'));
890
+ });
891
+
872
892
  program
873
893
  .command('usage')
874
894
  .description("Each engine's plan limits: how much is used and left, and when it resets")
@@ -1912,9 +1932,10 @@ export async function main(argv) {
1912
1932
  .description("Run the race's test command in every attempt's worktree")
1913
1933
  .argument('<race>')
1914
1934
  .option('-t, --test <command>', 'set or change the test command')
1935
+ .option('--runs <n>', 'run it this many times in each attempt (1 to 5), to tell a flaky test from a broken one; with 1, a failed run is run once more')
1915
1936
  .action(async (id, opts) => {
1916
1937
  await daemon();
1917
- await api('POST', `/races/${id}/tests`, opts.test ? { command: opts.test } : {});
1938
+ await api('POST', `/races/${id}/tests`, { ...(opts.test ? { command: opts.test } : {}), ...(opts.runs !== undefined ? { runs: Number(opts.runs) } : {}) });
1918
1939
  console.log(`${green('…')} running; see agentmgr race show ${id}`);
1919
1940
  });
1920
1941
  raceCmd
package/src/config.js CHANGED
@@ -80,6 +80,8 @@ const DEFAULTS = {
80
80
  // Usage: each engine's plan limits, used and left; warn at a percent, hold new work at a percent (usage.js).
81
81
  usage: { enabled: true, warnAt: 80, holdAt: null },
82
82
  calendar: { ics: [], workStart: '09:00', workEnd: '18:00' },
83
+ // Lanes: every agent's own range of ports and name ending; `port` also sets PORT to its first port (lanes.js).
84
+ lanes: { enabled: true, base: 21000, size: 10, port: true },
83
85
  // AI News: the frontier labs' latest releases, summarized; see NEWS_DEFAULTS in news.js for every field.
84
86
  news: { enabled: true },
85
87
  demoPage: false,
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/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
+ }
package/src/manager.js CHANGED
@@ -3,11 +3,12 @@ import { EventEmitter } from 'node:events';
3
3
  import { ownStatusLine } from './trust.js';
4
4
  import { statusLineScript, usageFile } from './usage.js';
5
5
  import { leanScript } from './lean.js';
6
+ import { laneEnv, laneOf, lanePrompt, laneSettings, nextLane } from './lanes.js';
6
7
  import fs from 'node:fs';
7
8
  import os from 'node:os';
8
9
  import path from 'node:path';
9
10
  import pty from 'node-pty';
10
- import { expandHome, paths } from './config.js';
11
+ import { PORT, expandHome, paths } from './config.js';
11
12
  import { DEFAULT_ENGINE, ENGINES, engineOf, installed, notInstalled } from './engines/index.js';
12
13
  import {
13
14
  DOC_KINDS,
@@ -389,6 +390,8 @@ export class AgentManager extends EventEmitter {
389
390
  priority: agent.priority ?? 2,
390
391
  activeAt: this.activeAt(agent, rt),
391
392
  projectInfo: this.projectInfo(agent),
393
+ // Its ports and name ending (lanes.js), once it has been started with lanes on.
394
+ laneInfo: laneSettings(this.config).enabled ? laneOf(agent.lane, laneSettings(this.config)) : null,
392
395
  usage,
393
396
  // Claude Code's own cost figure from the transcripts (absent until it records one).
394
397
  costUsd: costs.length ? costs.reduce((a, b) => a + b, 0) : null,
@@ -1450,6 +1453,9 @@ export class AgentManager extends EventEmitter {
1450
1453
  prompts.push(teamPrompt(agent.team.role, dir));
1451
1454
  }
1452
1455
  }
1456
+ // Its own ports and name ending, so what it starts doesn't collide with another agent's.
1457
+ const lane = this.laneFor(agent);
1458
+ if (lane && task) prompts.push(lanePrompt(lane, laneSettings(this.config)));
1453
1459
  // Appended system prompts last only for the process they're passed to, so they go on every launch.
1454
1460
  // Files attached for it (at creation or in its terminal): readable without a permission prompt.
1455
1461
  const uploads = path.join(paths.uploads, agent.id);
@@ -1808,8 +1814,24 @@ export class AgentManager extends EventEmitter {
1808
1814
  });
1809
1815
  }
1810
1816
 
1817
+ /**
1818
+ * The agent's lane: ports and a name ending no other agent has (lanes.js). Given the first time
1819
+ * it is asked for and kept until the agent is deleted. Null with lanes off, or in a container,
1820
+ * which has its own ports.
1821
+ */
1822
+ laneFor(agent) {
1823
+ const settings = laneSettings(this.config);
1824
+ if (!agent || !settings.enabled || agent.isolation === 'container' || agent.machine) return null;
1825
+ if (!laneOf(agent.lane, settings)) {
1826
+ const n = nextLane(this.store.list().map((a) => a.lane).filter(Boolean), settings, [PORT]);
1827
+ if (!n || !this.store.patch(agent.id, { lane: n })) return null;
1828
+ agent.lane = n;
1829
+ }
1830
+ return laneOf(agent.lane, settings);
1831
+ }
1832
+
1811
1833
  childEnv(agent) {
1812
- const env = { ...process.env, ...(agent ? { AGENTMGR_AGENT_ID: agent.id, AGENTMGR_LEAN_DIR: leanDir(agent.id) } : {}), TERM: 'xterm-256color', COLORTERM: 'truecolor', AGENTMGR_TERMINAL: '1', AGENTMGR_USAGE_FILE: usageFile(), AGENTMGR_USER_STATUSLINE: ownStatusLine() };
1834
+ const env = { ...process.env, ...(agent ? { AGENTMGR_AGENT_ID: agent.id, AGENTMGR_LEAN_DIR: leanDir(agent.id), ...laneEnv(this.laneFor(agent), laneSettings(this.config)) } : {}), TERM: 'xterm-256color', COLORTERM: 'truecolor', AGENTMGR_TERMINAL: '1', AGENTMGR_USAGE_FILE: usageFile(), AGENTMGR_USER_STATUSLINE: ownStatusLine() };
1813
1835
  for (const key of STRIP_ENV) delete env[key];
1814
1836
  return env;
1815
1837
  }
package/src/races.js CHANGED
@@ -5,6 +5,7 @@ import crypto from 'node:crypto';
5
5
  import { spawn } from 'node:child_process';
6
6
  import { EventEmitter } from 'node:events';
7
7
  import * as git from './git.js';
8
+ import { cleanRuns, repeatRuns } from './eval.js';
8
9
 
9
10
  const err = (status, message) => Object.assign(new Error(message), { status });
10
11
  const now = () => new Date().toISOString();
@@ -112,9 +113,10 @@ export class Races extends EventEmitter {
112
113
  }
113
114
 
114
115
  /** Run the race's test command in every attempt's worktree (two at a time). */
115
- async runTests(id, { command } = {}) {
116
+ async runTests(id, { command, runs } = {}) {
116
117
  const race = this.get(id);
117
118
  if (command !== undefined) race.testCommand = command.trim() || null;
119
+ if (runs !== undefined) race.testRuns = cleanRuns(runs);
118
120
  if (!race.testCommand) throw err(400, 'Set a test command first');
119
121
  const queue = race.members.map((m) => this.manager.store.get(m)).filter((a) => a?.workdir);
120
122
  for (const a of queue) race.tests[a.id] = { status: 'queued', at: now() };
@@ -126,9 +128,22 @@ export class Races extends EventEmitter {
126
128
  return this.view(id);
127
129
  }
128
130
 
129
- runOne(race, agent) {
131
+ /**
132
+ * The test command in one attempt's folder, as many times as the race asks (eval.js: one run
133
+ * that fails is run once more). Passed in some runs and failed in others is "flaky".
134
+ */
135
+ async runOne(race, agent) {
130
136
  race.tests[agent.id] = { status: 'running', at: now() };
131
137
  this.save(race);
138
+ const started = Date.now();
139
+ const all = await repeatRuns(() => this.runOnce(race, agent), race.testRuns);
140
+ const { exitCode, output, at, status } = all.shown;
141
+ race.tests[agent.id] = { status: status === 'error' ? 'error' : all.passed ? 'passed' : all.flaky ? 'flaky' : 'failed', exitCode, runs: all.runs, passes: all.passes, seconds: Math.round((Date.now() - started) / 1000), output, at };
142
+ this.save(race);
143
+ }
144
+
145
+ /** One run: { status, exitCode, output, at, passed, timedOut }. */
146
+ runOnce(race, agent) {
132
147
  return new Promise((resolve) => {
133
148
  const child = spawn(process.env.SHELL || '/bin/sh', ['-lc', race.testCommand], { cwd: agent.workdir, env: this.manager.childEnv(agent), detached: true });
134
149
  this.running.set(`${race.id}:${agent.id}`, child);
@@ -136,8 +151,9 @@ export class Races extends EventEmitter {
136
151
  const keep = (d) => (out = (out + d).slice(-6000));
137
152
  child.stdout.on('data', keep);
138
153
  child.stderr.on('data', keep);
139
- const started = Date.now();
154
+ let timedOut = false;
140
155
  const timer = setTimeout(() => {
156
+ timedOut = true;
141
157
  try {
142
158
  process.kill(-child.pid, 'SIGKILL');
143
159
  } catch {}
@@ -145,15 +161,8 @@ export class Races extends EventEmitter {
145
161
  const finish = (code, error) => {
146
162
  clearTimeout(timer);
147
163
  this.running.delete(`${race.id}:${agent.id}`);
148
- race.tests[agent.id] = {
149
- status: error ? 'error' : code === 0 ? 'passed' : 'failed',
150
- exitCode: code,
151
- seconds: Math.round((Date.now() - started) / 1000),
152
- output: (error ? `${error}\n` : '') + out.slice(-4000),
153
- at: now(),
154
- };
155
- this.save(race);
156
- resolve();
164
+ // A command that could not be started is not run again.
165
+ resolve({ status: error ? 'error' : code === 0 ? 'passed' : 'failed', exitCode: code, output: (error ? `${error}\n` : '') + out.slice(-4000), at: now(), passed: !error && code === 0, timedOut: timedOut || Boolean(error) });
157
166
  };
158
167
  child.on('error', (e) => finish(null, e.message));
159
168
  child.on('close', (code) => finish(code));
package/src/server.js CHANGED
@@ -56,6 +56,7 @@ import { Runbooks } from './runbooks.js';
56
56
  import { reaStatus } from './rea.js';
57
57
  import { EngineUsage, codexWindows } from './usage.js';
58
58
  import { leanSettings, leanStats, leanSweep } from './lean.js';
59
+ import { laneOf, laneSettings } from './lanes.js';
59
60
  import { Skills } from './skills.js';
60
61
  import { Milestones } from './milestones.js';
61
62
  import { Decisions } from './decisions.js';
@@ -423,7 +424,8 @@ export async function startServer({ port = PORT, host = HOST, evalTimer = true }
423
424
  // "Open on this machine" links from the hub point at remote access, when it's on.
424
425
  // OS: this computer and its load right now, and what each open session takes (system.js).
425
426
  const system = new System({
426
- agents: () => store.list().map((x) => ({ id: x.id, name: x.name, pid: x.pid })),
427
+ agents: () => store.list().map((x) => ({ id: x.id, name: x.name, pid: x.pid, lane: laneSettings(config).enabled ? laneOf(x.lane, laneSettings(config)) : null })),
428
+ lanes: () => laneSettings(config),
427
429
  folders: () => [['Home', os.homedir()], ['Agents and data', paths.home]],
428
430
  version: pkgVersion,
429
431
  });
@@ -1050,7 +1052,7 @@ export async function startServer({ port = PORT, host = HOST, evalTimer = true }
1050
1052
  evals.verify(a.id).catch((e) => console.log(`[agentmgr] eval: ${e.message}`));
1051
1053
  return { started: true };
1052
1054
  }));
1053
- api.put('/agents/:id/eval/command', wrap((req) => evals.setTestCommand(req.params.id, req.body?.command)));
1055
+ api.put('/agents/:id/eval/command', wrap((req) => evals.setTestCommand(req.params.id, req.body?.command, req.body?.runs)));
1054
1056
  api.post('/agents/:id/eval/gaps', wrap((req) => evals.closeGaps(req.params.id)));
1055
1057
  api.post('/agents/:id/eval/seen', wrap((req) => evals.seen(req.params.id, req.body?.seen !== false)));
1056
1058
  api.post('/agents/:id/eval/post', wrap((req) => review.postEval(req.params.id, evals.view(manager.mustGet(req.params.id).id)?.markdown)));
@@ -1236,6 +1238,29 @@ export async function startServer({ port = PORT, host = HOST, evalTimer = true }
1236
1238
  api.put('/calendar', wrap((req) => calendar.set(req.body ?? {}, saveConfig)));
1237
1239
  // AI News: the entries, a refresh now (answers at once; the page hears when it's done), and "seen".
1238
1240
  api.get('/system', wrap(() => system.view()));
1241
+ // Lanes: every agent's own ports and name ending (lanes.js), and the settings for them. A change
1242
+ // reaches a session the next time it starts.
1243
+ const lanesView = () => {
1244
+ const settings = laneSettings(config);
1245
+ return { ...settings, agents: store.list().filter((a) => laneOf(a.lane, settings)).map((a) => ({ id: a.id, name: a.name, running: Boolean(a.pid), ...laneOf(a.lane, settings) })).sort((x, y) => x.n - y.n) };
1246
+ };
1247
+ api.get('/lanes', wrap(() => lanesView()));
1248
+ api.put('/lanes', wrap((req) => {
1249
+ const b = req.body ?? {};
1250
+ const on = (v) => v === true || v === 'on';
1251
+ const next = { ...config.lanes };
1252
+ if ('enabled' in b) next.enabled = on(b.enabled);
1253
+ if ('port' in b) next.port = on(b.port);
1254
+ for (const k of ['base', 'size']) {
1255
+ if (!(k in b)) continue;
1256
+ if (laneSettings({ lanes: { [k]: b[k] } })[k] !== Number(b[k])) throw fail(400, k === 'base' ? 'The first port is a number from 1024 to 32667' : 'A lane has 1 to 100 ports');
1257
+ next[k] = Number(b[k]);
1258
+ }
1259
+ config.lanes = next;
1260
+ saveConfig({ lanes: next });
1261
+ for (const a of store.list()) manager.changed?.(a);
1262
+ return lanesView();
1263
+ }));
1239
1264
  api.get('/news', wrap(() => news.view()));
1240
1265
  api.post('/news/refresh', wrap((req) => {
1241
1266
  news.refresh({ search: req.body?.search === true ? true : null }).catch(() => {});
package/src/system.js CHANGED
@@ -7,6 +7,7 @@ import { execFile } from 'node:child_process';
7
7
  import fs from 'node:fs';
8
8
  import os from 'node:os';
9
9
  import path from 'node:path';
10
+ import { listeners, portsBySession } from './lanes.js';
10
11
 
11
12
  const SAMPLE_MS = 5000;
12
13
  const KEEP = 120; // ten minutes of samples
@@ -157,9 +158,12 @@ async function disks(folders) {
157
158
  }
158
159
 
159
160
  export class System {
160
- /** `agents()` lists the agent records (id, name, pid of its open session); `folders()` the [label, dir] pairs whose disks to show. */
161
- constructor({ agents = () => [], folders = () => [['Home', os.homedir()]], version = null, timer = true } = {}) {
162
- Object.assign(this, { agents, folders, version });
161
+ /**
162
+ * `agents()` lists the agent records (id, name, pid of its open session, its lane or null);
163
+ * `folders()` the [label, dir] pairs whose disks to show; `lanes()` the lane settings (lanes.js).
164
+ */
165
+ constructor({ agents = () => [], folders = () => [['Home', os.homedir()]], lanes = () => null, version = null, timer = true } = {}) {
166
+ Object.assign(this, { agents, folders, lanes, version });
163
167
  this.history = [];
164
168
  this.last = cpuTimes();
165
169
  this.cpuPercent = 0;
@@ -187,16 +191,20 @@ export class System {
187
191
  async view() {
188
192
  const cpus = os.cpus();
189
193
  const cores = cpus.length || 1;
190
- const [name, mem, disk, ps] = await Promise.all([(this.osName ??= osName()), memory(), disks(this.folders()), run('ps', ['-Ao', 'pid=,ppid=,pcpu=,rss=,comm='])]);
194
+ const [name, mem, disk, ps, listening] = await Promise.all([(this.osName ??= osName()), memory(), disks(this.folders()), run('ps', ['-Ao', 'pid=,ppid=,pcpu=,rss=,comm=']), listeners()]);
191
195
  const procs = parsePs(ps);
192
196
  // The memory in the history is the same measure as the one shown (what can't be freed at once).
193
197
  if (this.history.length) this.history[this.history.length - 1].mem = mem.percent;
194
198
  const load = os.loadavg().map((n) => Math.round(n * 100) / 100);
195
- const sessions = this.agents()
196
- .filter((a) => a.pid)
197
- .map((a) => ({ id: a.id, name: a.name, pid: a.pid, ...(treeUsage(procs, a.pid) ?? { cpu: 0, mem: 0, count: 0 }) }))
198
- .filter((a) => a.count)
199
- .sort((x, y) => y.cpu - x.cpu || y.mem - x.mem);
199
+ // With what each listens on, and whether that is inside its own lane of ports.
200
+ const sessions = portsBySession(
201
+ this.agents()
202
+ .filter((a) => a.pid)
203
+ .map((a) => ({ id: a.id, name: a.name, pid: a.pid, lane: a.lane ?? null, ...(treeUsage(procs, a.pid) ?? { cpu: 0, mem: 0, count: 0 }) }))
204
+ .filter((a) => a.count),
205
+ procs,
206
+ listening,
207
+ ).sort((x, y) => y.cpu - x.cpu || y.mem - x.mem);
200
208
  const self = treeUsage(procs, process.pid);
201
209
  const nets = Object.entries(os.networkInterfaces())
202
210
  .flatMap(([nic, list]) => (list ?? []).filter((n) => !n.internal && n.family === 'IPv4').map((n) => ({ nic, address: n.address })));
@@ -232,6 +240,7 @@ export class System {
232
240
  count: procs.length,
233
241
  top: [...procs].sort((x, y) => y.cpu - x.cpu || y.mem - x.mem).slice(0, 12).map(({ pid, cpu, mem: m, name: n, command }) => ({ pid, cpu, mem: m, name: n, command })),
234
242
  },
243
+ lanes: this.lanes(),
235
244
  history: this.history,
236
245
  sampleSeconds: SAMPLE_MS / 1000,
237
246
  };