ai-agentmanager 1.49.0 → 1.51.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,118 @@
1
+ // Usage: each engine's plan limits, how much is used and left, and when they reset. A chip by the
2
+ // connection light always shows the engine new agents start on; the window has every engine, the
3
+ // alert and hold levels, and which engine new agents start on.
4
+
5
+ const LEVEL = { ok: 'Fine', warn: 'Getting close', high: 'Nearly used up', held: 'Held for new work', limited: 'Stopped at a limit', unknown: 'No reading yet' };
6
+ const SHORT = { five_hour: '5h', seven_day: 'wk', primary: '5h', secondary: 'wk' };
7
+
8
+ export function initUsage({ api, $, esc, ago, toast }) {
9
+ const dialog = $('#usage-dialog');
10
+ const body = $('#usage-body');
11
+ const chip = $('#usage-chip');
12
+ let data = null;
13
+ let again = null;
14
+
15
+ async function load({ quiet = false } = {}) {
16
+ try {
17
+ data = await api('GET', '/usage');
18
+ } catch (e) {
19
+ if (!quiet) toast?.(e.message, 5000);
20
+ }
21
+ drawChip();
22
+ if (dialog.open) draw();
23
+ }
24
+
25
+ /** The engine new agents start on, or the one in the worst state when that is worse than fine. */
26
+ function drawChip() {
27
+ if (!chip || !data) return;
28
+ const mine = data.engines.find((e) => e.id === data.default);
29
+ const bad = data.worst && ['warn', 'high', 'held', 'limited'].includes(data.worst.level) ? data.worst : null;
30
+ const e = bad ?? mine;
31
+ const read = e?.windows.filter((w) => w.used !== null) ?? [];
32
+ chip.hidden = !e || (!read.length && !e.limited);
33
+ if (chip.hidden) return;
34
+ chip.className = `usage-chip ${e.level}`;
35
+ chip.textContent = e.limited ? `${e.label}: at its limit` : `${e.label} ${read.map((w) => `${SHORT[w.id] ?? w.label} ${Math.round(w.used)}%`).join(' · ')}`;
36
+ chip.title = `${e.label}: ${e.limited ? `stopped at a limit${e.limited.resetsIn ? `, resets ${e.limited.resetsIn}` : ''}` : read.map((w) => `${w.label}: ${Math.round(w.used)}% used, ${Math.round(w.left)}% left${w.resetsIn ? `, resets ${w.resetsIn}` : ''}`).join('; ')}. Click for every engine.`;
37
+ }
38
+
39
+ const tone = (used) => (used >= 95 ? 'heavy' : used >= (data.settings.warnAt ?? 101) ? 'busy' : 'light');
40
+ const when = (iso) => new Date(iso).toLocaleString([], { weekday: 'short', hour: 'numeric', minute: '2-digit' });
41
+
42
+ function engineHtml(e) {
43
+ const others = data.engines.filter((x) => x.installed && x.id !== e.id && !['held', 'limited', 'high'].includes(x.level));
44
+ const rows = e.windows
45
+ .map((w) => (w.used === null
46
+ ? `<div class="usage-window"><div class="usage-window-head"><b>${esc(w.label)}</b><span class="hint">It has reset since the last reading; the next reply brings a new one.</span></div></div>`
47
+ : `<div class="usage-window" data-usage-window="${esc(w.id)}">
48
+ <div class="usage-window-head"><b>${esc(w.label)}</b><span class="usage-num">${Math.round(w.used)}% used</span><span class="usage-left ${tone(w.used)}">${Math.round(w.left)}% left</span><span class="spacer"></span><span class="hint">${w.resetsAt ? `resets ${esc(w.resetsIn)} (${esc(when(w.resetsAt))})` : ''}${w.stale ? ' · an old reading' : ''}</span></div>
49
+ <div class="os-meter ${tone(w.used)}" role="img" aria-label="${Math.round(w.used)}% used"><span style="width:${w.used}%"></span></div>
50
+ </div>`))
51
+ .join('');
52
+ return `<div class="plan-project usage-engine" data-usage-engine="${esc(e.id)}">
53
+ <div class="plan-project-head"><h3>${esc(e.label)}</h3><span class="tag usage-level ${esc(e.level)}">${esc(LEVEL[e.level] ?? e.level)}</span>${e.id === data.default ? '<span class="tag">new agents start here</span>' : ''}${e.installed ? '' : '<span class="tag">not installed</span>'}
54
+ <span class="spacer"></span>${e.at ? `<span class="hint">read ${esc(ago(e.at))}${e.source ? ` from ${esc(e.source)}` : ''}</span>` : ''}
55
+ ${e.installed && e.id !== data.default ? `<button class="small" data-usage-default="${esc(e.id)}" title="New agents start on ${esc(e.label)} unless you pick another engine for them. Agents already running stay where they are">Start new agents here</button>` : ''}</div>
56
+ ${e.limited ? `<p class="issues-problem">An agent stopped at a limit${e.limited.resetsIn ? `; it resets ${esc(e.limited.resetsIn)}` : ''}: ${esc(e.limited.text)}</p>` : ''}
57
+ ${rows}
58
+ ${e.note ? `<p class="hint">${esc(e.note)}</p>` : ''}
59
+ ${['held', 'limited', 'high'].includes(e.level) && e.id === data.default && others.length ? `<p class="hint">New agents start here by default. ${others.map((o) => `<button class="link" data-usage-default="${esc(o.id)}">Switch new agents to ${esc(o.label)}</button>`).join(' · ')}</p>` : ''}
60
+ </div>`;
61
+ }
62
+
63
+ function draw() {
64
+ if (!data) return (body.innerHTML = '<div class="issues-head"><h2>Usage</h2><span class="spacer"></span><button class="small" data-usage="close">Close</button></div><p class="hint">Loading…</p>');
65
+ const s = data.settings;
66
+ const level = (name, v, off) => `<select data-usage-set="${name}" aria-label="${name}"><option value="off" ${v ? '' : 'selected'}>${off}</option>${[50, 60, 70, 75, 80, 85, 90, 95, 100].map((n) => `<option value="${n}" ${v === n ? 'selected' : ''}>${n}% used</option>`).join('')}${v && ![50, 60, 70, 75, 80, 85, 90, 95, 100].includes(v) ? `<option value="${v}" selected>${v}% used</option>` : ''}</select>`;
67
+ body.innerHTML = `
68
+ <div class="issues-head"><h2>Usage</h2><span class="hint">What is used and left of each engine's plan limits</span><span class="spacer"></span><button class="small" data-usage="refresh" title="Read again">↻</button><button class="small" data-usage="close" title="Close (Esc)">Close</button></div>
69
+ <div class="issues-scroll usage-scroll">
70
+ ${data.engines.map(engineHtml).join('') || '<p class="hint issues-empty">No engine is installed.</p>'}
71
+ <div class="usage-settings">
72
+ <label>Alert me at ${level('warnAt', s.warnAt, 'never')}</label>
73
+ <label title="No new agent starts on an engine at or past this much of a limit (the backlog waits, and New agents says why). Agents already running carry on.">Hold new work at ${level('holdAt', s.holdAt, 'never')}</label>
74
+ </div>
75
+ <p class="hint">These are numbers the engines hand out on this computer: Claude Code gives them to the status line of the sessions started here, Codex writes them in its session logs. No service is asked and no model is called. A limit an agent actually hits is shown for any engine until it resets, and the agent carries on by itself when it does.</p>
76
+ </div>`;
77
+ }
78
+
79
+ const save = async (patch, done) => {
80
+ try {
81
+ data = await api('PUT', '/usage', patch);
82
+ if (done) toast?.(done, 3000);
83
+ } catch (e) {
84
+ toast?.(e.message, 6000);
85
+ }
86
+ drawChip();
87
+ draw();
88
+ };
89
+
90
+ body.addEventListener('click', (e) => {
91
+ const d = e.target.closest('[data-usage-default]');
92
+ if (d) return save({ engine: d.dataset.usageDefault }, 'New agents start there from now on');
93
+ const b = e.target.closest('[data-usage]')?.dataset.usage;
94
+ if (b === 'close') dialog.close();
95
+ else if (b === 'refresh') load();
96
+ });
97
+ body.addEventListener('change', (e) => {
98
+ const s = e.target.closest('[data-usage-set]');
99
+ if (s) save({ [s.dataset.usageSet]: s.value }, 'Saved');
100
+ });
101
+ if (chip) chip.onclick = () => open();
102
+
103
+ function open() {
104
+ if (dialog.open) return dialog.close();
105
+ dialog.showModal();
106
+ draw();
107
+ load();
108
+ }
109
+ /** The daemon has a new reading. */
110
+ function changed() {
111
+ clearTimeout(again);
112
+ again = setTimeout(() => load({ quiet: true }), 400);
113
+ }
114
+ // "resets in 2h 10m" counts down, and a window that reset says so.
115
+ setInterval(() => (dialog.open || !chip?.hidden) && load({ quiet: true }), 60_000);
116
+ load({ quiet: true });
117
+ return { open, changed, isOpen: () => dialog.open };
118
+ }
package/src/brief.js CHANGED
@@ -721,7 +721,9 @@ export const BENCH_FILE = 'BENCHMARK.md';
721
721
  export const benchPath = (agentId) => path.join(briefDir(agentId), BENCH_FILE);
722
722
  export const DEBUG_FILE = 'DEBUG.md';
723
723
  export const debugPath = (agentId) => path.join(briefDir(agentId), DEBUG_FILE);
724
- export const SPEC_DOCS = { intent: intentPath, spec: specPath, plan: planPath, designdoc: designPath, benchmark: benchPath, demo: demoPath, debug: debugPath };
724
+ export const REVERSE_FILE = 'REVERSE.md';
725
+ export const reversePath = (agentId) => path.join(briefDir(agentId), REVERSE_FILE);
726
+ export const SPEC_DOCS = { intent: intentPath, spec: specPath, plan: planPath, designdoc: designPath, benchmark: benchPath, demo: demoPath, debug: debugPath, reverse: reversePath };
725
727
 
726
728
  // ------------------------------------------------------------------ debug
727
729
 
@@ -788,6 +790,79 @@ export function debugFixPrompt(file, which) {
788
790
  );
789
791
  }
790
792
 
793
+ // ------------------------------------------------------------------ reverse engineering
794
+
795
+ // Reverse engineer: you name a target (an app's folder, a binary, a website) and what you want to
796
+ // understand about it; the agent investigates in its own session with REA's tools (the "Reverse
797
+ // Engineer Anything" MCP server, github.com/morluto/rea) and keeps a report at REVERSE.md: how the
798
+ // feature works with animated diagrams, the evidence behind each claim, what could not be
799
+ // determined, and a plan for building your own version. It changes nothing until you ask it to build.
800
+
801
+ const REVERSE_SHAPE = [
802
+ '# Reverse engineering: <the feature> in <the target>',
803
+ '## Summary',
804
+ 'Two or three sentences: how it works, and how sure you are.',
805
+ '## Target',
806
+ 'What it is (name, version, platform), what kind (Electron or JavaScript app, native binary, .NET assembly, website), and which tools and providers you used on it.',
807
+ '## How it works',
808
+ 'One ```mermaid flowchart of the path the feature takes through the real modules, functions or components you found, from what the user does to the result.',
809
+ '## Data and interfaces',
810
+ 'One ```mermaid flowchart LR or sequenceDiagram of the data on that path: what is stored and where, formats, the calls between processes, and the network requests. Then a short list of the formats and endpoints by name.',
811
+ '## Findings',
812
+ 'Numbered. Each with its evidence (a module or file path, a function or symbol, an address, a string, a request) and "confirmed" (seen directly) or "inferred" (reasoned from what was seen).',
813
+ '## What could not be determined',
814
+ 'What is obfuscated, missing, server-side or out of reach of the tools you had, and what would be needed to find out.',
815
+ '## Build it',
816
+ 'A plan for our own version in this project, from the behaviour described above: the pieces, where they go in this codebase, the order, effort (S, M, L) for each, and what to do differently or better. No code, text or assets taken from the target.',
817
+ '## Next checks',
818
+ 'What to look at next, and what you need from the user (another build of the app, a sample file, an account).',
819
+ ].join('\n');
820
+
821
+ const REVERSE_DIAGRAMS =
822
+ 'Diagrams: valid Mermaid, at most about 15 nodes each, labels of five words or fewer (quote labels with punctuation, e.g. A["Parse (JSON)"]), no HTML in labels, real names from the target. ' +
823
+ 'Animate the path in every flowchart: give its edges ids and animate them, e.g.\n' +
824
+ ' A e1@--> B\n B e2@-->|"rows"| C\n e1@{ animate: true }\n e2@{ animate: true }\n' +
825
+ 'Mark what is only inferred: `classDef inferred stroke:#f59e0b,stroke-width:3px,stroke-dasharray:4`, then `class Y inferred`; and what could not be seen: `classDef unknown stroke:#9ca3af,stroke-dasharray:2`, then `class Z unknown`.';
826
+
827
+ const REVERSE_RULES =
828
+ 'Rules: this is for understanding how something works so we can build our own. Analyse only: do not modify, patch or redistribute the target, and do not change this repository yet. ' +
829
+ 'Do not work on getting around licence checks, copy protection, sign-in or other access controls, and do not collect credentials, keys or personal data you come across: if that is what is asked, or the only way forward, stop and tell me. ' +
830
+ 'Say what you saw, not what you assume: every claim in the report names its evidence.';
831
+
832
+ /** The message that starts (or continues) a reverse-engineering investigation in the agent's session. */
833
+ export function reversePrompt(file, { target = '', question = '', again = false } = {}) {
834
+ const q = String(question ?? '').trim();
835
+ const t = String(target ?? '').trim();
836
+ if (again) {
837
+ return (
838
+ `Reverse engineering, continued: ${q}${t ? `\nTarget: ${t}` : ''}\n` +
839
+ `Carry on and bring the report at ${file} up to date: same sections, diagrams redrawn where the picture changed, findings re-marked confirmed or inferred. ` +
840
+ 'Still analysis only, and no changes to this repository unless I ask you to build. Answer me here in a few lines, and say what changed in the report.'
841
+ );
842
+ }
843
+ return (
844
+ `Reverse engineer this: ${q}\nTarget: ${t}\n` +
845
+ "Use REA's tools (the \"Reverse Engineer Anything\" MCP server) to inspect the target: start with what kind of target it is, then follow the feature from what the user does down to the code and data behind it. " +
846
+ "If REA's tools are not available in this session, say so in one line and stop: it is set up with `npx rea-agents setup` (which I run myself, then restart this session); do not install it or anything else yourself. " +
847
+ 'For a native binary REA needs a provider (Hopper, Ghidra, IDA or Kuna): if none is configured, say which is missing rather than guessing from strings alone.\n' +
848
+ `${REVERSE_RULES}\n` +
849
+ `Keep a report at ${file} (Markdown; the file is outside the repository: never copy it in or commit it). Write a first version as soon as you know the shape of the target, and update it as you learn. Short and specific, in these sections:\n` +
850
+ `${REVERSE_SHAPE}\n${REVERSE_DIAGRAMS}\n` +
851
+ 'When the report is written, tell me in a few lines how it works and what you could not determine.'
852
+ );
853
+ }
854
+
855
+ /** The message that asks for our own version to be built from the report. */
856
+ export function reverseBuildPrompt(file, what) {
857
+ const w = String(what ?? '').trim();
858
+ return (
859
+ `Build our own version from your reverse-engineering report at ${file}: ${w || 'the plan under "Build it", the smallest useful piece first'}.\n` +
860
+ 'Write it from the behaviour the report describes, in this project\'s own style: copy no code, text, names of internal symbols or assets from the target, and add no dependency on it. ' +
861
+ 'Add tests for the behaviour, run them, and where the report says the target does something badly, do it better. ' +
862
+ 'Then update the report: add a "## Built" section (what was built, where, how it was verified, and what differs from the target on purpose).'
863
+ );
864
+ }
865
+
791
866
  /** INTENT.md: the request as given, and where it came from. */
792
867
  export function intentMarkdown(agent) {
793
868
  const by = agent.startedBy ? 'the assistant' : agent.trigger ? (agent.trigger.source === 'github' ? 'a labeled GitHub issue' : 'a webhook') : agent.playbook ? `the playbook ${agent.playbook.name}` : agent.team ? `team ${agent.team.id} (${agent.team.role})` : agent.raceId ? `race ${agent.raceId}` : 'you';
package/src/cli.js CHANGED
@@ -823,6 +823,28 @@ export async function main(argv) {
823
823
  }
824
824
  });
825
825
 
826
+ program
827
+ .command('usage')
828
+ .description("Each engine's plan limits: how much is used and left, and when it resets")
829
+ .option('--warn <percent>', 'alert when a limit is this much used (or off)')
830
+ .option('--hold <percent>', 'start no new agents on an engine this much used (or off)')
831
+ .option('--default <engine>', 'the engine new agents start on')
832
+ .option('--json', 'print JSON')
833
+ .action(async (opts) => {
834
+ await daemon();
835
+ const patch = { ...(opts.warn !== undefined ? { warnAt: opts.warn } : {}), ...(opts.hold !== undefined ? { holdAt: opts.hold } : {}), ...(opts.default ? { engine: opts.default } : {}) };
836
+ const v = Object.keys(patch).length ? await api('PUT', '/usage', patch) : await api('GET', '/usage');
837
+ if (opts.json) return console.log(JSON.stringify(v, null, 2));
838
+ const tone = { ok: green, warn: yellow, high: red, held: red, limited: red };
839
+ for (const e of v.engines) {
840
+ console.log(`${bold(e.label)}${e.id === v.default ? dim(' (default)') : ''}${e.level === 'held' ? red(' held for new work') : ''}`);
841
+ if (e.limited) console.log(` ${red('stopped at a limit')}${e.limited.resetsIn ? `, resets ${e.limited.resetsIn}` : ''} ${dim(e.limited.text)}`);
842
+ 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)') : ''}`);
843
+ if (e.note) console.log(` ${dim(e.note)}`);
844
+ }
845
+ console.log(dim(`Warn at ${v.settings.warnAt ?? 'off'}${v.settings.warnAt ? '%' : ''} · hold new work at ${v.settings.holdAt ?? 'off'}${v.settings.holdAt ? '%' : ''}`));
846
+ });
847
+
826
848
  program
827
849
  .command('runbook [id]')
828
850
  .description('Runbooks for the support team, written from a release ticket, an epic, or the code changes of a time frame')
@@ -1698,6 +1720,33 @@ export async function main(argv) {
1698
1720
  console.log(dim(`\n(updated ${new Date(r.updatedAt).toLocaleString()})`));
1699
1721
  });
1700
1722
 
1723
+ program
1724
+ .command('reverse')
1725
+ .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")
1726
+ .argument('<agent>')
1727
+ .argument('[question...]', 'what to understand, or a follow-up once there is a report')
1728
+ .option('-t, --target <target>', "the app's folder, the binary's path or the website's address (needed the first time)")
1729
+ .option('--build [what]', 'build your own version from the report: which part in words, or its plan')
1730
+ .action(async (ref, question, opts) => {
1731
+ await daemon();
1732
+ const a = await resolveAgent(ref);
1733
+ const q = question.join(' ').trim();
1734
+ if (opts.build) {
1735
+ await api('POST', `/agents/${a.id}/reverse`, { build: opts.build === true ? q || true : opts.build });
1736
+ return console.log(`${green('✓')} asked ${a.name} to build it from the report, in this project's own code`);
1737
+ }
1738
+ if (q) {
1739
+ const rea = await api('GET', `/agents/${a.id}/reverse/rea`);
1740
+ if (!rea.registered) console.log(yellow(`REA was not found in Claude Code's settings for this agent. If it isn't set up: ${rea.setup} (then restart the agent's session).`));
1741
+ await api('POST', `/agents/${a.id}/reverse`, { question: q, target: opts.target });
1742
+ return console.log(`${green('✓')} sent to ${a.name}; it investigates in its session. The report: agentmgr reverse ${ref}`);
1743
+ }
1744
+ const r = await api('GET', `/agents/${a.id}/specs/reverse`);
1745
+ if (!r.markdown) return console.log(dim(`No report yet. Start one: agentmgr reverse ${ref} -t /path/to/app "how does search work"`));
1746
+ console.log(r.markdown.trimEnd());
1747
+ console.log(dim(`\n(updated ${new Date(r.updatedAt).toLocaleString()})`));
1748
+ });
1749
+
1701
1750
  program
1702
1751
  .command('fork')
1703
1752
  .description("A new agent with this one's code and conversation, in its own worktree")
package/src/config.js CHANGED
@@ -77,6 +77,8 @@ const DEFAULTS = {
77
77
  debt: { enabled: true },
78
78
  // Decide: recommendations on what waits for you, standing decisions, impact and trade-offs (advisor.js).
79
79
  decide: { enabled: true },
80
+ // Usage: each engine's plan limits, used and left; warn at a percent, hold new work at a percent (usage.js).
81
+ usage: { enabled: true, warnAt: 80, holdAt: null },
80
82
  calendar: { ics: [], workStart: '09:00', workEnd: '18:00' },
81
83
  // AI News: the frontier labs' latest releases, summarized; see NEWS_DEFAULTS in news.js for every field.
82
84
  news: { enabled: true },
@@ -16,6 +16,11 @@ export default {
16
16
 
17
17
  bin: (config) => config.engines?.claude?.bin ?? config.claudeBin ?? 'claude',
18
18
  extraArgs: (config) => [...(config.engines?.claude?.args ?? config.claudeArgs ?? [])],
19
+ /**
20
+ * For the sessions started here (not one-off calls): a status line that records the plan's usage
21
+ * (usage.js). `script` is its path; your own status line still shows (see statusline.js).
22
+ */
23
+ usageArgs: (config, script) => (config.usage?.enabled === false ? [] : ['--settings', JSON.stringify({ statusLine: { type: 'command', command: `${JSON.stringify(process.execPath)} ${JSON.stringify(script)}` } })]),
19
24
 
20
25
  /** Options for every launch: permissions, model, a folder it may write to, extra instructions. */
21
26
  optionArgs({ permissionMode, model, writableDir, instructions, agents, allowedTools }) {
@@ -196,7 +196,7 @@ export default {
196
196
 
197
197
  /** Usage (one entry per model response), PR and bug links from messages and command output. */
198
198
  scan(file, cursor, bugPatterns = []) {
199
- const result = { prs: [], bugs: [], title: null, lastPrompt: null, cost: null, lastActivity: null };
199
+ const result = { prs: [], bugs: [], title: null, lastPrompt: null, cost: null, lastActivity: null, rateLimits: null };
200
200
  cursor.usage ??= new Map();
201
201
  cursor.offset ??= 0;
202
202
  const recs = newRecords(file, cursor);
@@ -204,6 +204,8 @@ export default {
204
204
  if (!recs) return result;
205
205
  for (const { rec, at } of recs) {
206
206
  const p = rec.payload ?? {};
207
+ // The plan's limits as Codex last reported them (usage.js): { primary, secondary } with used_percent.
208
+ if (p.type === 'token_count' && p.rate_limits && typeof p.rate_limits === 'object') result.rateLimits = { limits: p.rate_limits, at: rec.timestamp ?? null };
207
209
  if (p.type === 'token_count' && p.info?.last_token_usage) {
208
210
  const u = p.info.last_token_usage;
209
211
  const cached = u.cached_input_tokens ?? 0;
package/src/manager.js CHANGED
@@ -1,5 +1,7 @@
1
1
  import crypto from 'node:crypto';
2
2
  import { EventEmitter } from 'node:events';
3
+ import { ownStatusLine } from './trust.js';
4
+ import { statusLineScript, usageFile } from './usage.js';
3
5
  import fs from 'node:fs';
4
6
  import os from 'node:os';
5
7
  import path from 'node:path';
@@ -35,6 +37,9 @@ import {
35
37
  debugPath,
36
38
  debugPrompt,
37
39
  debugFixPrompt,
40
+ reversePath,
41
+ reversePrompt,
42
+ reverseBuildPrompt,
38
43
  specDocsInfo,
39
44
  specPath,
40
45
  specPrompt,
@@ -833,7 +838,7 @@ export class AgentManager extends EventEmitter {
833
838
  /** One of an agent's intent, spec and plan files. */
834
839
  specDoc(ref, name) {
835
840
  const agent = this.mustGet(ref);
836
- if (!['intent', 'spec', 'plan', 'designdoc', 'benchmark', 'debug'].includes(name)) throw Object.assign(new Error('Unknown file (intent, spec, plan, designdoc, benchmark or debug)'), { status: 400 });
841
+ if (!['intent', 'spec', 'plan', 'designdoc', 'benchmark', 'debug', 'reverse'].includes(name)) throw Object.assign(new Error('Unknown file (intent, spec, plan, designdoc, benchmark, debug or reverse)'), { status: 400 });
837
842
  return readSpecDoc(agent.id, name) ?? { name, markdown: null };
838
843
  }
839
844
 
@@ -859,6 +864,31 @@ export class AgentManager extends EventEmitter {
859
864
  return this.view(this.patch(agent.id, { debug: { asks, startedAt: agent.debug?.startedAt ?? now() } }));
860
865
  }
861
866
 
867
+ /**
868
+ * Reverse engineer: ask the agent to work out how something in a target (an app's folder, a
869
+ * binary, a website) works, with REA's tools, and keep a report (REVERSE.md) with diagrams, the
870
+ * evidence, what could not be determined and a plan to build our own. `question`: what to
871
+ * understand, or a follow-up once there is a report. `build`: build our own version from the
872
+ * report (which part, in words; true for its plan). The message waits in the agent's queue.
873
+ */
874
+ reverse(ref, { target = '', question = '', build = null } = {}) {
875
+ const agent = this.mustGet(ref);
876
+ if (!agent.workdir || agent.status === 'preparing') throw Object.assign(new Error('The agent has no folder to work in yet'), { status: 409 });
877
+ const q = String(question ?? '').replace(/\s+/g, ' ').trim().slice(0, 2000);
878
+ const has = Boolean(readSpecDoc(agent.id, 'reverse')?.markdown?.trim());
879
+ // The target as given the first time stands for the follow-ups.
880
+ const t = String(target ?? '').replace(/\s+/g, ' ').trim().slice(0, 500) || agent.reverse?.target || '';
881
+ if (build && !has) throw Object.assign(new Error('There is no report yet: say what to reverse engineer first'), { status: 409 });
882
+ if (!build && q.length < 3) throw Object.assign(new Error('Say what you want to understand'), { status: 400 });
883
+ if (!build && !t) throw Object.assign(new Error("Name the target: an app's folder, a binary's path, or a website's address"), { status: 400 });
884
+ fs.mkdirSync(briefDir(agent.id), { recursive: true });
885
+ const file = path.join(fs.realpathSync(briefDir(agent.id)), path.basename(reversePath(agent.id)));
886
+ const which = build === true ? '' : String(build ?? '').replace(/\s+/g, ' ').trim().slice(0, 500);
887
+ this.tell(agent.id, build ? reverseBuildPrompt(file, which) : reversePrompt(file, { target: t, question: q, again: has }), { source: 'reverse' });
888
+ const asks = [...(agent.reverse?.asks ?? []), { text: build ? `Build it${which ? `: ${which}` : ''}` : q, kind: build ? 'build' : has ? 'follow-up' : 'reverse', at: now() }].slice(-20);
889
+ return this.view(this.patch(agent.id, { reverse: { ...agent.reverse, target: t, asks, startedAt: agent.reverse?.startedAt ?? now() } }));
890
+ }
891
+
862
892
  /** The agent's sample demo page (HTML), once it has written one. */
863
893
  demoPage(ref) {
864
894
  const agent = this.mustGet(ref);
@@ -1398,7 +1428,8 @@ export class AgentManager extends EventEmitter {
1398
1428
  const dir = fs.realpathSync(uploads);
1399
1429
  writableDir = writableDir ? [writableDir, dir].flat() : dir;
1400
1430
  }
1401
- return { extra: engine.extraArgs(this.config), permissionMode: agent.permissionMode, model: agent.model, writableDir, instructions: prompts.join('\n\n') || null, agents, allowedTools };
1431
+ // A status line that records the plan's usage (not in a container: the script isn't there).
1432
+ return { extra: [...engine.extraArgs(this.config), ...(agent.isolation === 'container' ? [] : engine.usageArgs?.(this.config, statusLineScript()) ?? [])], permissionMode: agent.permissionMode, model: agent.model, writableDir, instructions: prompts.join('\n\n') || null, agents, allowedTools };
1402
1433
  }
1403
1434
 
1404
1435
  /** Spawn the agent's engine in a PTY, reusing its terminal clients and scrollback. */
@@ -1688,7 +1719,7 @@ export class AgentManager extends EventEmitter {
1688
1719
  }
1689
1720
 
1690
1721
  childEnv(agent) {
1691
- const env = { ...process.env, ...(agent ? { AGENTMGR_AGENT_ID: agent.id } : {}), TERM: 'xterm-256color', COLORTERM: 'truecolor', AGENTMGR_TERMINAL: '1' };
1722
+ const env = { ...process.env, ...(agent ? { AGENTMGR_AGENT_ID: agent.id } : {}), TERM: 'xterm-256color', COLORTERM: 'truecolor', AGENTMGR_TERMINAL: '1', AGENTMGR_USAGE_FILE: usageFile(), AGENTMGR_USER_STATUSLINE: ownStatusLine() };
1692
1723
  for (const key of STRIP_ENV) delete env[key];
1693
1724
  return env;
1694
1725
  }
@@ -2357,6 +2388,14 @@ export class AgentManager extends EventEmitter {
2357
2388
  } catch {}
2358
2389
  if (at !== (agent.debug.reportAt ?? null)) this.patch(id, { debug: { ...this.store.get(id).debug, reportAt: at } });
2359
2390
  }
2391
+ // The same for a reverse-engineering report.
2392
+ if (agent.reverse) {
2393
+ let at = null;
2394
+ try {
2395
+ at = fs.statSync(reversePath(id)).mtime.toISOString();
2396
+ } catch {}
2397
+ if (at !== (agent.reverse.reportAt ?? null)) this.patch(id, { reverse: { ...this.store.get(id).reverse, reportAt: at } });
2398
+ }
2360
2399
  }
2361
2400
 
2362
2401
  // -------------------------------------------------------------- plan review
@@ -2852,6 +2891,8 @@ export class AgentManager extends EventEmitter {
2852
2891
  const cursor = this.cursors.get(key) ?? { offset: 0 };
2853
2892
  this.cursors.set(key, cursor);
2854
2893
  const res = engine.scan(file, cursor, this.config.bugPatterns);
2894
+ // The engine's plan limits, when its log has them (usage.js).
2895
+ if (res.rateLimits) this.emit('usage', { engine: engine.id, ...res.rateLimits });
2855
2896
  const subMaps = engine.subagentFiles(sessionDir, session.id).map((sub) => {
2856
2897
  const c = this.cursors.get(sub) ?? { offset: 0 };
2857
2898
  this.cursors.set(sub, c);
@@ -3539,6 +3580,7 @@ export class AgentManager extends EventEmitter {
3539
3580
  if (prev && !prev.resumedAt && prev.text === found.text) return (rt.lastLimit = prev);
3540
3581
  const agent = this.store.get(id);
3541
3582
  if (agent) console.log(`[agentmgr] ${agent.name}: ${engineOf(agent).label} stopped at a limit (${found.text})${found.resetAt ? `; resets ${found.resetAt}` : ''}`);
3583
+ if (agent && found.kind === 'limit') this.emit('limit', { engine: engineOf(agent).id, text: found.text, resetAt: found.resetAt ?? null });
3542
3584
  return (rt.lastLimit = { ...found, at: new Date(t).toISOString(), resumedAt: null });
3543
3585
  }
3544
3586
 
package/src/notify.js CHANGED
@@ -21,6 +21,7 @@ export const EVENT_DEFAULTS = {
21
21
  standup: true, // the daily standup is ready to play
22
22
  value: true, // a scheduled value report (week, month, quarter)
23
23
  milestone: true, // a project's date (code complete, RC, GA) is coming up, at risk or late
24
+ usage: true, // an engine's plan limit is nearly used up (Usage)
24
25
  decided: true, // something was decided for you (a standing decision, or within the autonomy you set)
25
26
  };
26
27
 
package/src/rea.js ADDED
@@ -0,0 +1,47 @@
1
+ // Whether REA (the "Reverse Engineer Anything" MCP server, github.com/morluto/rea) is registered
2
+ // with Claude Code, read from Claude Code's own files: your settings (~/.claude.json, for every
3
+ // folder and for one), and a project's .mcp.json. Nothing is run and nothing is installed here:
4
+ // setup is `npx rea-agents setup`, which you run yourself. A plugin that brings REA is not seen
5
+ // here, so "not found" is said as that, not as "not installed".
6
+
7
+ import fs from 'node:fs';
8
+ import path from 'node:path';
9
+ import { claudeConfigFile } from './trust.js';
10
+
11
+ export const REA_SETUP = 'npx rea-agents setup';
12
+ const read = (file) => {
13
+ try {
14
+ return JSON.parse(fs.readFileSync(file, 'utf8'));
15
+ } catch {
16
+ return null;
17
+ }
18
+ };
19
+
20
+ /** A registered MCP server that is REA: by its name, or by the package it runs. */
21
+ export function isRea(name, server) {
22
+ if (/^rea([-_]agents)?$/i.test(String(name))) return true;
23
+ const words = [server?.command, ...(Array.isArray(server?.args) ? server.args : [])].filter((x) => typeof x === 'string').join(' ');
24
+ return /(^|[\s/\\@])rea-agents(\b|@)/.test(words);
25
+ }
26
+
27
+ /** { registered, where, name } for a folder (an agent's workspace): where REA is registered, if it is. */
28
+ export function reaStatus(dir = null, { config = claudeConfigFile() } = {}) {
29
+ const c = read(config) ?? {};
30
+ const real = (() => {
31
+ try {
32
+ return dir ? fs.realpathSync(dir) : null;
33
+ } catch {
34
+ return dir;
35
+ }
36
+ })();
37
+ const places = [
38
+ ['your Claude Code settings', c.mcpServers],
39
+ ...(real ? [['this folder, in your Claude Code settings', c.projects?.[real]?.mcpServers ?? c.projects?.[dir]?.mcpServers], ["the project's .mcp.json", read(path.join(real, '.mcp.json'))?.mcpServers]] : []),
40
+ ];
41
+ for (const [where, servers] of places) {
42
+ for (const [name, server] of Object.entries(servers && typeof servers === 'object' ? servers : {})) {
43
+ if (isRea(name, server)) return { registered: true, where, name, setup: REA_SETUP };
44
+ }
45
+ }
46
+ return { registered: false, where: null, name: null, setup: REA_SETUP };
47
+ }
package/src/server.js CHANGED
@@ -53,6 +53,8 @@ import { News } from './news.js';
53
53
  import { System } from './system.js';
54
54
  import { Advisor } from './advisor.js';
55
55
  import { Runbooks } from './runbooks.js';
56
+ import { reaStatus } from './rea.js';
57
+ import { EngineUsage, codexWindows } from './usage.js';
56
58
  import { Milestones } from './milestones.js';
57
59
  import { Decisions } from './decisions.js';
58
60
  import { Debt } from './debt.js';
@@ -322,6 +324,23 @@ export async function startServer({ port = PORT, host = HOST, evalTimer = true }
322
324
  await sendSlack(text, n, plain);
323
325
  },
324
326
  });
327
+ // Usage: each engine's plan limits, used and left (usage.js).
328
+ let pushUsage = () => {};
329
+ const usage = new EngineUsage({
330
+ store,
331
+ config,
332
+ engines: () => listEngines(config),
333
+ onChange: () => pushUsage(),
334
+ notify: async (text, plain) => {
335
+ const n = loadNotify();
336
+ if (!n.enabled || !n.events.usage) return;
337
+ await sendSlack(text, n, plain);
338
+ },
339
+ });
340
+ manager.on('usage', ({ engine, limits, at }) => engine === 'codex' && usage.record('codex', codexWindows(limits, Date.parse(at) || Date.now()), { at: at ?? undefined, source: 'Codex session log' }));
341
+ manager.on('limit', ({ engine, text, resetAt }) => usage.limited(engine, { text, resetAt }));
342
+ manager.plugins.api('usage', config).policy((action, details) => usage.policy(action, details));
343
+ usage.tick();
325
344
  // Runbooks for the support team, from a release ticket, an epic, or the code changes of a time frame (runbooks.js).
326
345
  const runbooks = new Runbooks({
327
346
  store,
@@ -743,6 +762,10 @@ export async function startServer({ port = PORT, host = HOST, evalTimer = true }
743
762
  api.post('/rules/dismiss', wrap((req) => (manager.rules.dismiss(...ruleArgs(req)), manager.rules.view())));
744
763
  api.post('/rules/remove', wrap((req) => (manager.rules.remove(...ruleArgs(req)), manager.rules.view())));
745
764
  api.post('/agents/:id/tell', wrap((req) => manager.tell(req.params.id, req.body?.text)));
765
+ // Reverse engineer: a target and what to understand (or a follow-up), or `build` to build our own from the report; the report is /specs/reverse.
766
+ api.post('/agents/:id/reverse', wrap((req) => manager.reverse(req.params.id, { target: req.body?.target, question: req.body?.question, build: req.body?.build ?? null })));
767
+ // Whether REA is registered with Claude Code for this agent's folder (read from Claude Code's files; nothing is run).
768
+ api.get('/agents/:id/reverse/rea', wrap((req) => reaStatus(manager.mustGet(req.params.id).workdir ?? null)));
746
769
  // Debug: what to debug (or a follow-up), or `fix` to apply the report's fixes; the report is /specs/debug.
747
770
  api.post('/agents/:id/debug', wrap((req) => manager.debug(req.params.id, { question: req.body?.question, fix: req.body?.fix ?? null })));
748
771
  api.post('/agents/:id/answer', wrap((req) => manager.answerQuestion(req.params.id, req.body?.question, req.body?.text)));
@@ -1110,6 +1133,21 @@ export async function startServer({ port = PORT, host = HOST, evalTimer = true }
1110
1133
  api.post('/milestones/:project/reach', wrap((req) => milestones.reach(req.params.project, req.body?.stage, req.body?.reached !== false)));
1111
1134
  api.post('/milestones/:project/task', wrap((req) => milestones.task(req.params.project, req.body?.stage, req.body?.item)));
1112
1135
  // Plan → Decisions: the log (?project=<key>&q=<words>; ?format=markdown), one of your own, and removal.
1136
+ api.get('/usage', wrap(() => usage.view()));
1137
+ api.put('/usage', wrap((req) => {
1138
+ const b = req.body ?? {};
1139
+ const next = usage.update(b);
1140
+ const patch = { usage: next };
1141
+ // The engine new agents start on, when none is named.
1142
+ if (typeof b.engine === 'string') {
1143
+ if (!listEngines(config).some((e) => e.id === b.engine && e.installed)) throw fail(400, 'No such engine installed');
1144
+ config.engine = b.engine;
1145
+ patch.engine = b.engine;
1146
+ }
1147
+ saveConfig(patch);
1148
+ pushUsage();
1149
+ return usage.view();
1150
+ }));
1113
1151
  api.get('/runbooks', wrap(() => runbooks.list()));
1114
1152
  api.post('/runbooks', wrap((req) => runbooks.create(req.body ?? {})));
1115
1153
  api.get('/runbooks/:id', (req, res) => {
@@ -1527,6 +1565,7 @@ export async function startServer({ port = PORT, host = HOST, evalTimer = true }
1527
1565
  pushNews = () => broadcast({ t: 'news' });
1528
1566
  pushPlan = () => broadcast({ t: 'plan' });
1529
1567
  pushAdvisor = () => broadcast({ t: 'advisor' });
1568
+ pushUsage = () => broadcast({ t: 'usage' });
1530
1569
  reports.on('change', () => broadcast({ t: 'built', reports: reports.list() }));
1531
1570
  manager.rules.on('change', (rules) => broadcast({ t: 'rules', rules }));
1532
1571
  repeats.on('change', (view) => broadcast({ t: 'repeats', repeats: view }));
@@ -1669,6 +1708,7 @@ export async function startServer({ port = PORT, host = HOST, evalTimer = true }
1669
1708
  milestones.close();
1670
1709
  decisions.close();
1671
1710
  advisor.close();
1711
+ usage.close();
1672
1712
  debt.close();
1673
1713
  reviews.close();
1674
1714
  hunts.close();
@@ -0,0 +1,40 @@
1
+ #!/usr/bin/env node
2
+ // Claude Code's status line for the sessions AI Agent Manager starts. Claude Code hands its status
3
+ // line command a JSON object on stdin; for Pro, Max and Ultra plans it carries `rate_limits` (the
4
+ // 5-hour and 7-day windows: used_percentage and resets_at). This writes those numbers where the
5
+ // daemon reads them (AGENTMGR_USAGE_FILE), then prints the status line: your own status line
6
+ // command's output if you have one (AGENTMGR_USER_STATUSLINE, given the same JSON), else a short
7
+ // line with the model and what is used. Nothing is sent anywhere. Standalone: node built-ins only.
8
+ import { spawnSync } from 'node:child_process';
9
+ import fs from 'node:fs';
10
+ import path from 'node:path';
11
+
12
+ let text = '';
13
+ try {
14
+ text = fs.readFileSync(0, 'utf8');
15
+ } catch {}
16
+ let input = {};
17
+ try {
18
+ input = JSON.parse(text);
19
+ } catch {}
20
+
21
+ const file = process.env.AGENTMGR_USAGE_FILE;
22
+ const limits = input?.rate_limits;
23
+ if (file && limits && typeof limits === 'object') {
24
+ try {
25
+ fs.mkdirSync(path.dirname(file), { recursive: true });
26
+ const tmp = `${file}.${process.pid}.tmp`;
27
+ fs.writeFileSync(tmp, JSON.stringify({ at: new Date().toISOString(), rate_limits: limits, version: input.version ?? null, model: input.model?.display_name ?? input.model?.id ?? null }));
28
+ fs.renameSync(tmp, file);
29
+ } catch {}
30
+ }
31
+
32
+ const own = process.env.AGENTMGR_USER_STATUSLINE;
33
+ if (own) {
34
+ const r = spawnSync(own, { shell: true, input: text, encoding: 'utf8', timeout: 5000, env: { ...process.env, AGENTMGR_USER_STATUSLINE: '' } });
35
+ if (r.stdout) process.stdout.write(r.stdout);
36
+ } else {
37
+ const pc = (w) => (typeof w?.used_percentage === 'number' ? `${Math.round(w.used_percentage)}%` : null);
38
+ const parts = [input?.model?.display_name, pc(limits?.five_hour) && `5h ${pc(limits.five_hour)}`, pc(limits?.seven_day) && `week ${pc(limits.seven_day)}`].filter(Boolean);
39
+ process.stdout.write(parts.join(' · '));
40
+ }
package/src/trust.js CHANGED
@@ -41,3 +41,13 @@ export function trustFolder(dir, file = claudeConfigFile()) {
41
41
  fs.renameSync(tmp, file);
42
42
  return true;
43
43
  }
44
+
45
+ /** Your own status line command in Claude Code's settings (~/.claude/settings.json), or ''. */
46
+ export function ownStatusLine(dir = process.env.CLAUDE_CONFIG_DIR || path.join(os.homedir(), '.claude')) {
47
+ try {
48
+ const sl = JSON.parse(fs.readFileSync(path.join(dir, 'settings.json'), 'utf8')).statusLine;
49
+ return sl?.type === 'command' && typeof sl.command === 'string' ? sl.command : '';
50
+ } catch {
51
+ return '';
52
+ }
53
+ }