ai-agentmanager 1.51.1 → 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/src/cli.js CHANGED
@@ -823,17 +823,84 @@ export async function main(argv) {
823
823
  }
824
824
  });
825
825
 
826
+ program
827
+ .command('skills [action] [arg] [names...]')
828
+ .description("Claude Code's Agent Skills here: ls (default), show <id>, look <repo>, add <repo> <names...>, check <id>, update <id>, rm <id>")
829
+ .option('--to <place>', 'where to add: personal (default) or project:<shortcut>', 'personal')
830
+ .option('--json', 'print JSON')
831
+ .action(async (action = 'ls', arg, names, opts) => {
832
+ await daemon();
833
+ const out = (v) => console.log(JSON.stringify(v, null, 2));
834
+ const print = (v) => {
835
+ if (opts.json) return out(v);
836
+ for (const p of v.places) {
837
+ console.log(`${bold(p.label)} ${dim(p.dir)}`);
838
+ for (const s of p.skills) console.log(` ${s.id.padEnd(34)} ${dim((s.description ?? 'no description').slice(0, 80))}${s.scripts.length ? yellow(` ${s.scripts.length} script(s)`) : ''}${s.source ? dim(` · ${s.source.repo.replace(/^https:\/\/github\.com\//, '').replace(/\.git$/, '')}@${s.source.commit ?? '?'}`) : ''}${s.edited ? yellow(' · edited here') : ''}${s.usedBy.length ? dim(` · used by ${s.usedBy.length}`) : ''}`);
839
+ if (!p.skills.length) console.log(dim(' none'));
840
+ }
841
+ };
842
+ if (action === 'ls') return print(await api('GET', '/skills'));
843
+ if (!arg) throw new Error(`agentmgr skills ${action} needs ${['look', 'add'].includes(action) ? 'a repository' : "a skill's id (see agentmgr skills)"}`);
844
+ if (action === 'show') {
845
+ const s = await api('GET', `/skills/one?id=${encodeURIComponent(arg)}`);
846
+ return opts.json ? out(s) : console.log(s.markdown.trimEnd());
847
+ }
848
+ if (action === 'look') {
849
+ const o = await api('POST', '/skills/preview', { repo: arg });
850
+ if (opts.json) return out(o);
851
+ console.log(`${bold(o.repo)} ${dim(o.commit ?? '')}`);
852
+ for (const s of o.skills) console.log(` ${s.folder.padEnd(28)} ${dim((s.description ?? 'no description').slice(0, 90))}${s.scripts.length ? yellow(` ${s.scripts.length} script(s)`) : ''}`);
853
+ return console.log(dim(`Add some: agentmgr skills add ${arg} <names...> (read a skill before you add it: its scripts run with your access)`));
854
+ }
855
+ if (action === 'add') {
856
+ if (!names.length) throw new Error('Name the skills to add (agentmgr skills look <repo> lists them)');
857
+ const r = await api('POST', '/skills', { repo: arg, names, place: opts.to });
858
+ if (opts.json) return out(r);
859
+ if (r.added.length) console.log(`${green('+')} ${r.added.join(', ')} ${dim(`in ${r.place}`)}`);
860
+ if (r.skipped.length) console.log(yellow(`Already there, left as they are: ${r.skipped.join(', ')} (agentmgr skills update <id> brings one up to date)`));
861
+ return;
862
+ }
863
+ if (action === 'check') {
864
+ const c = await api('POST', '/skills/check', { id: arg });
865
+ return opts.json ? out(c) : console.log(c.gone ? yellow('No longer in its repository') : c.changed ? yellow(`A newer version is there (${c.latest}); you have ${c.current}${c.edited ? ', edited here' : ''}`) : green('Up to date'));
866
+ }
867
+ if (action === 'update') return print(await api('POST', '/skills/update', { id: arg }));
868
+ if (action === 'rm') return print(await api('DELETE', `/skills?id=${encodeURIComponent(arg)}`));
869
+ throw new Error(`Unknown action ${action} (ls, show, look, add, check, update, rm)`);
870
+ });
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
+
826
892
  program
827
893
  .command('usage')
828
894
  .description("Each engine's plan limits: how much is used and left, and when it resets")
829
895
  .option('--warn <percent>', 'alert when a limit is this much used (or off)')
830
896
  .option('--hold <percent>', 'start no new agents on an engine this much used (or off)')
831
897
  .option('--default <engine>', 'the engine new agents start on')
898
+ .option('--lean <on|off>', 'lean output: trim long command output before the agent reads it (Claude Code; sessions started from now on)')
832
899
  .option('--now', 'take a reading now: a one-word Claude Code session on its smallest model (a very small amount of usage)')
833
900
  .option('--json', 'print JSON')
834
901
  .action(async (opts) => {
835
902
  await daemon();
836
- const patch = { ...(opts.warn !== undefined ? { warnAt: opts.warn } : {}), ...(opts.hold !== undefined ? { holdAt: opts.hold } : {}), ...(opts.default ? { engine: opts.default } : {}) };
903
+ const patch = { ...(opts.warn !== undefined ? { warnAt: opts.warn } : {}), ...(opts.hold !== undefined ? { holdAt: opts.hold } : {}), ...(opts.default ? { engine: opts.default } : {}), ...(opts.lean !== undefined ? { lean: /^(on|true|yes|1)$/i.test(opts.lean) } : {}) };
837
904
  let v = Object.keys(patch).length ? await api('PUT', '/usage', patch) : await api('GET', '/usage');
838
905
  if (opts.now) v = await api('POST', '/usage/refresh');
839
906
  if (opts.json) return console.log(JSON.stringify(v, null, 2));
@@ -845,6 +912,7 @@ export async function main(argv) {
845
912
  for (const w of e.windows) console.log(` ${w.label.padEnd(16)} ${w.used === null ? dim('reset; no reading since') : (tone[e.level] ?? ((x) => x))(`${String(Math.round(w.used)).padStart(3)}% used ${String(Math.round(w.left)).padStart(3)}% left`)}${w.resetsIn ? dim(` resets ${w.resetsIn}`) : ''}${w.stale ? dim(' (an old reading)') : ''}`);
846
913
  if (e.note) console.log(` ${dim(e.note)}`);
847
914
  }
915
+ if (v.lean) console.log(dim(`Lean output ${v.lean.enabled ? 'on' : 'off'}${v.lean.calls ? ` · ${v.lean.calls} outputs trimmed, about ${v.lean.tokens.toLocaleString()} tokens not read` : ''}`));
848
916
  console.log(dim(`Warn at ${v.settings.warnAt ?? 'off'}${v.settings.warnAt ? '%' : ''} · hold new work at ${v.settings.holdAt ?? 'off'}${v.settings.holdAt ? '%' : ''}`));
849
917
  });
850
918
 
@@ -1723,6 +1791,31 @@ export async function main(argv) {
1723
1791
  console.log(dim(`\n(updated ${new Date(r.updatedAt).toLocaleString()})`));
1724
1792
  });
1725
1793
 
1794
+ program
1795
+ .command('audit')
1796
+ .description("Security audit with an agent: it goes through the code in its session, checks each finding a second time, and keeps a report with the attack surface, findings by severity with evidence, and fixes. With no question and a report already there: print the report")
1797
+ .argument('<agent>')
1798
+ .argument('[scope...]', 'what to audit (nothing: the whole project), or a follow-up once there is a report')
1799
+ .option('--start', 'start an audit of the whole project (when no scope is given)')
1800
+ .option('--fix [which]', "fix the report's findings: which ones in words (\"1 and 3\"), or the verified ones")
1801
+ .action(async (ref, scope, opts) => {
1802
+ await daemon();
1803
+ const a = await resolveAgent(ref);
1804
+ const q = scope.join(' ').trim();
1805
+ if (opts.fix) {
1806
+ await api('POST', `/agents/${a.id}/security`, { fix: opts.fix === true ? q || true : opts.fix });
1807
+ return console.log(`${green('✓')} asked ${a.name} to fix the findings, each with a test, and record it in the report`);
1808
+ }
1809
+ if (q || opts.start) {
1810
+ await api('POST', `/agents/${a.id}/security`, { question: q });
1811
+ return console.log(`${green('✓')} sent to ${a.name}; it audits in its session. The report: agentmgr audit ${ref}`);
1812
+ }
1813
+ const r = await api('GET', `/agents/${a.id}/specs/security`);
1814
+ if (!r.markdown) return console.log(dim(`No audit report yet. Start one: agentmgr audit ${ref} --start, or agentmgr audit ${ref} "the import API"`));
1815
+ console.log(r.markdown.trimEnd());
1816
+ console.log(dim(`\n(updated ${new Date(r.updatedAt).toLocaleString()})`));
1817
+ });
1818
+
1726
1819
  program
1727
1820
  .command('reverse')
1728
1821
  .description("Reverse engineer with an agent and REA's tools: name a target and what to understand; it keeps a report with diagrams, the evidence, what could not be determined and a plan to build your own. With no question: print the report")
@@ -1839,9 +1932,10 @@ export async function main(argv) {
1839
1932
  .description("Run the race's test command in every attempt's worktree")
1840
1933
  .argument('<race>')
1841
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')
1842
1936
  .action(async (id, opts) => {
1843
1937
  await daemon();
1844
- 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) } : {}) });
1845
1939
  console.log(`${green('…')} running; see agentmgr race show ${id}`);
1846
1940
  });
1847
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,
@@ -22,7 +22,21 @@ export default {
22
22
  */
23
23
  /** A session that says one word on the smallest model, so the status line has a reply to report after. */
24
24
  usageProbeArgs: (sessionId) => ['--model', 'haiku', '--strict-mcp-config', '--session-id', sessionId, '--', 'Reply with the single word: ok'],
25
- usageArgs: (config, script) => (config.usage?.enabled === false ? [] : ['--settings', JSON.stringify({ statusLine: { type: 'command', command: `${JSON.stringify(process.execPath)} ${JSON.stringify(script)}` } })]),
25
+ usageArgs(config, script) {
26
+ return this.settingsArgs(config, { statusLine: script });
27
+ },
28
+ /**
29
+ * The one --settings of a session started here: the status line that records the plan's usage,
30
+ * and, with lean output on, the hook that trims long command output before the agent reads it
31
+ * (lean.js). Both are commands run with this daemon's Node.
32
+ */
33
+ settingsArgs(config, { statusLine = null, lean = null } = {}) {
34
+ const run = (script) => `${JSON.stringify(process.execPath)} ${JSON.stringify(script)}`;
35
+ const s = {};
36
+ if (statusLine && config.usage?.enabled !== false) s.statusLine = { type: 'command', command: run(statusLine) };
37
+ if (lean && config.lean?.enabled === true) s.hooks = { PostToolUse: [{ matcher: 'Bash', hooks: [{ type: 'command', command: run(lean), timeout: 15 }] }] };
38
+ return Object.keys(s).length ? ['--settings', JSON.stringify(s)] : [];
39
+ },
26
40
 
27
41
  /** Options for every launch: permissions, model, a folder it may write to, extra instructions. */
28
42
  optionArgs({ permissionMode, model, writableDir, instructions, agents, allowedTools }) {
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/lean.js ADDED
@@ -0,0 +1,151 @@
1
+ #!/usr/bin/env node
2
+ // Lean output: long command output, trimmed before the agent reads it, so a plan's limits last
3
+ // longer. Claude Code runs this after each shell command of a session started here (a PostToolUse
4
+ // hook) with the command and its output as JSON on stdin; when the output is long, what comes back
5
+ // is a shorter version: colour codes and progress redraws gone, runs of near-identical lines
6
+ // folded, and of a long middle only the lines that look like errors or warnings. The start and the
7
+ // end stay, and the whole output is saved to a file the trimmed version names, so nothing is lost:
8
+ // the agent reads the file when it needs a part that was left out. No model is called.
9
+ // Standalone when run by Claude Code (node built-ins only); the daemon imports the helpers.
10
+ import fs from 'node:fs';
11
+ import path from 'node:path';
12
+ import { fileURLToPath } from 'node:url';
13
+
14
+ export const LEAN_DEFAULTS = { enabled: false, minLines: 80, head: 30, tail: 50, keep: 60 };
15
+ const MAX_LINE = 400;
16
+ const KEEP_DAYS = 2;
17
+ // Lines worth keeping from the middle of a long output.
18
+ const IMPORTANT = /\b(error|errors|err!|fail(ed|ure|ures|ing)?|fatal|panic(ked)?|exception|traceback|warn(ing|ings)?|denied|refused|timed? ?out|not ok|cannot|can't|unable to|undefined reference|segmentation fault|assert(ion)?|deprecated)\b|✗|✖|×|FAIL|\bE\d{3,4}\b/i;
19
+
20
+ export const leanScript = () => fileURLToPath(import.meta.url);
21
+ export const leanSettings = (config = {}) => ({ ...LEAN_DEFAULTS, ...config.lean, enabled: config.lean?.enabled === true });
22
+
23
+ /** Colour codes and cursor moves out; of a line redrawn in place (a progress bar), what it ended as. */
24
+ export function plain(text) {
25
+ return String(text ?? '')
26
+ .replace(/\x1b\][^\x07\x1b]*(\x07|\x1b\\)/g, '')
27
+ .replace(/\x1b\[[0-9;?]*[ -/]*[@-~]/g, '')
28
+ .replace(/\x1b[@-_]/g, '')
29
+ .replace(/\r\n/g, '\n')
30
+ .split('\n')
31
+ .map((l) => (l.includes('\r') ? l.split('\r').filter(Boolean).pop() ?? '' : l))
32
+ .join('\n');
33
+ }
34
+
35
+ /** A line with its numbers, hashes and times taken out: lines alike but for those are one kind. */
36
+ const kind = (line) => line.replace(/0x[0-9a-f]+|\b[0-9a-f]{7,40}\b|\d+([.,:]\d+)*/gi, '#').replace(/\s+/g, ' ').trim();
37
+
38
+ /** Runs of three or more lines of one kind: the first, how many followed, and the last. */
39
+ export function fold(lines) {
40
+ const out = [];
41
+ for (let i = 0; i < lines.length; ) {
42
+ const k = kind(lines[i]);
43
+ let j = i + 1;
44
+ while (j < lines.length && k && kind(lines[j]) === k) j++;
45
+ if (j - i >= 4 && !IMPORTANT.test(lines[i])) {
46
+ out.push(lines[i], ` … ${j - i - 2} more lines like it …`, lines[j - 1]);
47
+ } else {
48
+ for (let n = i; n < j; n++) out.push(lines[n]);
49
+ }
50
+ i = j;
51
+ }
52
+ return out;
53
+ }
54
+
55
+ /**
56
+ * The trimmed version of a command's output, or null when it is short enough as it is.
57
+ * { text, before, after } with the counts in lines; `where` is the file the whole output is in.
58
+ */
59
+ export function leanText(text, { minLines = LEAN_DEFAULTS.minLines, head = LEAN_DEFAULTS.head, tail = LEAN_DEFAULTS.tail, keep = LEAN_DEFAULTS.keep, where = null } = {}) {
60
+ const raw = String(text ?? '');
61
+ const all = plain(raw).split('\n');
62
+ if (all.length < minLines && raw.length < minLines * 100) return null;
63
+ let lines = fold(all.map((l) => (l.length > MAX_LINE ? `${l.slice(0, MAX_LINE)} … (${l.length - MAX_LINE} more characters)` : l)));
64
+ if (lines.length > head + tail + 10) {
65
+ const mid = lines.slice(head, lines.length - tail);
66
+ // From the middle: the lines that look like trouble, each with the line before it.
67
+ const want = new Set();
68
+ for (let i = 0; i < mid.length && want.size < keep; i++) {
69
+ if (!IMPORTANT.test(mid[i])) continue;
70
+ if (i > 0) want.add(i - 1);
71
+ want.add(i);
72
+ }
73
+ const kept = [];
74
+ let last = -1;
75
+ for (const i of [...want].sort((a, b) => a - b)) {
76
+ if (i - last > 1) kept.push(` … ${i - last - 1} lines left out …`);
77
+ kept.push(mid[i]);
78
+ last = i;
79
+ }
80
+ if (mid.length - last > 1) kept.push(` … ${mid.length - last - 1} lines left out …`);
81
+ lines = [...lines.slice(0, head), ...kept, ...lines.slice(lines.length - tail)];
82
+ }
83
+ const body = lines.join('\n');
84
+ // Not worth it unless a good part goes.
85
+ if (body.length > raw.length * 0.7) return null;
86
+ const note = `[lean output: ${all.length.toLocaleString('en-US')} lines trimmed to ${lines.length.toLocaleString('en-US')}; errors and warnings kept.${where ? ` The whole output is in ${where}: read it (or search it) if you need a part that was left out.` : ''}]`;
87
+ return { text: `${body}\n${note}`, before: all.length, after: lines.length, saved: raw.length - body.length - note.length };
88
+ }
89
+
90
+ /** What trimming has saved in a folder of agents' outputs: { calls, saved (characters), tokens (about) }. */
91
+ export function leanStats(dir) {
92
+ let calls = 0;
93
+ let saved = 0;
94
+ try {
95
+ for (const d of fs.readdirSync(dir)) {
96
+ try {
97
+ const s = JSON.parse(fs.readFileSync(path.join(dir, d, 'stats.json'), 'utf8'));
98
+ calls += s.calls ?? 0;
99
+ saved += s.saved ?? 0;
100
+ } catch {}
101
+ }
102
+ } catch {}
103
+ return { calls, saved, tokens: Math.round(saved / 4) };
104
+ }
105
+
106
+ /** Whole outputs older than a couple of days go (the counts stay). */
107
+ export function leanSweep(dir, now = Date.now()) {
108
+ let n = 0;
109
+ try {
110
+ for (const d of fs.readdirSync(dir)) {
111
+ for (const f of fs.readdirSync(path.join(dir, d))) {
112
+ if (!f.endsWith('.txt')) continue;
113
+ const file = path.join(dir, d, f);
114
+ if (now - fs.statSync(file).mtimeMs > KEEP_DAYS * 86_400_000) {
115
+ fs.rmSync(file, { force: true });
116
+ n++;
117
+ }
118
+ }
119
+ }
120
+ } catch {}
121
+ return n;
122
+ }
123
+
124
+ /** The hook's answer to one PostToolUse event (the JSON Claude Code gave), or null to leave the output alone. */
125
+ export function leanHook(input, { dir = null, settings = LEAN_DEFAULTS } = {}) {
126
+ const r = input?.tool_response;
127
+ if (input?.tool_name !== 'Bash' || !r || typeof r.stdout !== 'string' || r.isImage || !dir) return null;
128
+ const id = String(input.tool_use_id ?? Date.now()).replace(/[^\w-]/g, '').slice(-40) || String(Date.now());
129
+ const file = path.join(dir, `${id}.txt`);
130
+ const out = leanText(r.stdout, { ...settings, where: file });
131
+ if (!out) return null;
132
+ fs.mkdirSync(dir, { recursive: true });
133
+ fs.writeFileSync(file, `$ ${input.tool_input?.command ?? ''}\n\n${r.stdout}${r.stderr ? `\n\n--- stderr ---\n${r.stderr}` : ''}`);
134
+ const stats = path.join(dir, 'stats.json');
135
+ let s = { calls: 0, saved: 0 };
136
+ try {
137
+ s = JSON.parse(fs.readFileSync(stats, 'utf8'));
138
+ } catch {}
139
+ fs.writeFileSync(stats, JSON.stringify({ calls: (s.calls ?? 0) + 1, saved: (s.saved ?? 0) + Math.max(0, out.saved), at: new Date().toISOString() }));
140
+ return { hookSpecificOutput: { hookEventName: 'PostToolUse', updatedToolOutput: { ...r, stdout: out.text } } };
141
+ }
142
+
143
+ // Run by Claude Code: the event on stdin, the answer on stdout. Any trouble: say nothing, and the output stands.
144
+ if (process.argv[1] && fs.realpathSync(process.argv[1]) === fs.realpathSync(fileURLToPath(import.meta.url))) {
145
+ try {
146
+ const n = (v, d) => (Number(v) > 0 ? Number(v) : d);
147
+ const settings = { ...LEAN_DEFAULTS, minLines: n(process.env.AGENTMGR_LEAN_MIN, LEAN_DEFAULTS.minLines) };
148
+ const answer = leanHook(JSON.parse(fs.readFileSync(0, 'utf8')), { dir: process.env.AGENTMGR_LEAN_DIR || null, settings });
149
+ if (answer) process.stdout.write(JSON.stringify(answer));
150
+ } catch {}
151
+ }