ai-agentmanager 1.50.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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,12 @@
1
1
  # Changelog
2
2
 
3
+ ## 1.51.0 (2026-11-14)
4
+
5
+ - **Usage: what is left of each engine's plan.** A chip by the connection light shows the engine new agents start on with what is used of its limits (`Claude Code 5h 23% · wk 41%`), amber then red as a limit nears. Click it (or **Usage…** in the menu, `z`, `agentmgr usage`) for every engine: each limit's percent used, percent left, and when it resets.
6
+ - **Where the numbers come from.** Claude Code's 5-hour session and 7-day limits, which it hands a session's status line (Pro, Max and Ultra plans, once a session has had a reply): sessions started here get a status line that records them, and your own status line still shows. Codex's limits from its session logs, when it reports them. For any engine, a limit an agent actually hit, until it resets. No service is asked and no model is called.
7
+ - **Alert, hold, switch.** An alert once per limit at 80% used (adjustable; the new *usage* alert). **Hold new work at** a percent (off by default): no new agent starts on an engine at or past it, and agents already running carry on. **Start new agents here** makes another installed engine the default for new agents.
8
+ - Turn it off with `"usage": { "enabled": false }` in config.json.
9
+
3
10
  ## 1.50.0 (2026-11-14)
4
11
 
5
12
  - **Reverse engineer.** **🔍 Reverse engineer** in an agent's detail (or the **Reverse** tab of the split, or `agentmgr reverse`) puts the agent's session on the left and a pane on the right. Name a target (an app's folder, a binary's path, a website's address) and what you want to understand; the agent investigates in its own session with the tools of [REA](https://github.com/morluto/rea), the "Reverse Engineer Anything" MCP server, and changes nothing.
package/README.md CHANGED
@@ -30,6 +30,7 @@ Run one background [Claude Code](https://claude.com/claude-code) agent per inten
30
30
  - **Plan.** A project's commitment dates (code complete, release candidate, GA) with a checklist of what is still open for each, reminders as they come near, and an at-risk or late flag. A **decision log** gathered from plan reviews, your answers and design docs. A **tech debt radar** from git history and the code. What is open can be handed to an agent.
31
31
  - **Your day.** Connect your calendar and Today lays the day out around your meetings: the free time between them with what needs you placed in it, and what each meeting is about.
32
32
  - **Debug.** Say what to debug (a failure, E2E instability at max scale, slowness under load) in the **Debug** tab beside an agent's session. The agent investigates there and writes a report next to it: animated diagrams of the code path and the data flow with where it breaks, findings with evidence, likely causes and recommended fixes. It changes no code until you press **Apply fixes**.
33
+ - **Usage.** How much of each engine's plan limits is used and left (Claude Code's 5-hour session and week, Codex's), and when they reset: a chip by the connection light, an alert near a limit, an option to hold new work at a percent, and one click to start new agents on another engine.
33
34
  - **Reverse engineer.** Name a target (an app's folder, a binary, a website) and what you want to understand, in the **Reverse** tab beside an agent's session: the agent investigates with [REA](https://github.com/morluto/rea)'s tools and keeps a report with animated diagrams of how it works, the evidence, what could not be determined, and a plan to build your own version.
34
35
  - **Runbooks for support.** A runbook for the support team written from a release ticket, every ticket of an epic, or a project's code changes in a time frame: what changed, what customers may see, how to check it, troubleshooting, rollback, when to escalate, and what to confirm with engineering.
35
36
  - **Decide.** Help with the decisions, not only the tasks: a plan to review or an agent's question arrives with its options, the one recommended, why, and the risk; calls you keep making become standing decisions that are handled for you and reported; the backlog is ranked by impact; a date at risk is laid out as choices; and past decisions are looked back on.
@@ -194,6 +195,7 @@ agentmgr reverse <agent> -t /path/to/app "how does search work" # reverse engin
194
195
  agentmgr dates <project> --cc 2026-12-01 --rc 2026-12-10 --ga 2026-12-20 # commitment dates; no dates: where each stands
195
196
  agentmgr decisions [project] [--md] # the decision log; --add "<question>" --decision "<what>" adds one
196
197
  agentmgr debt <project> --scan # the tech debt radar: files that change often and are hard to read
198
+ agentmgr usage # each engine's plan limits: used, left, resets (--warn 80, --hold 95, --default codex)
197
199
  agentmgr runbook --ticket REL-42 # a support runbook from a release ticket (or --epic KEY, or --since 2026-10-01 -p <project>; -o file.md)
198
200
  agentmgr decide # what waits for your decision, with its recommendation (--do <n>, --handled, --standing, --autonomy p=level, --priority, --risk)
199
201
  agentmgr os # this computer and its load: processor, memory, disks, what each open session takes (--json)
@@ -1221,6 +1223,19 @@ With it, Today opens with **Your day**:
1221
1223
 
1222
1224
  Repeating meetings, time zones, moved or cancelled occurrences and events marked *free* are understood. Several calendars can be added; **Disconnect** forgets them. In config.json: `"calendar": { "ics": ["https://…"], "workStart": "09:00", "workEnd": "18:00" }`.
1223
1225
 
1226
+ ## Usage: what is left of each engine's plan
1227
+
1228
+ A chip by the connection light shows the engine new agents start on with what is used of its limits (`Claude Code 5h 23% · wk 41%`), turning amber and red as a limit nears. Click it (or **Usage…** in the menu, `z`, or `agentmgr usage`) for every engine: each limit with the percent used, the percent left, and when it resets.
1229
+
1230
+ - **Claude Code**: its 5-hour session and 7-day limits. Claude Code hands these to a session's status line command (for Pro, Max and Ultra plans, once the session has had a reply), so the sessions started here get a status line that records them. Your own status line, if you have one, still shows: it is run with the same input. Without one you get a short line with the model and the two percentages. Not for agents in a container.
1231
+ - **Codex**: the limits Codex writes in its session logs, when it reports them.
1232
+ - **Any engine**: a limit an agent actually hits is shown until it resets (and the agent carries on by itself when it does, as before).
1233
+ - **Alert me at** a percent used (80% by default): one alert per limit and reset, in Slack if alerts are on (the *usage* alert).
1234
+ - **Hold new work at** a percent (off by default): no new agent starts on an engine at or past it; the backlog waits and New agents says why. Agents already running carry on.
1235
+ - **Start new agents here** makes another installed engine the default for new agents; agents already running stay where they are (**Continue on** moves one).
1236
+
1237
+ These are numbers the engines hand out on this computer: no service is asked and no model is called. Turn it off with `"usage": { "enabled": false }` in config.json.
1238
+
1224
1239
  ## Reverse engineer
1225
1240
 
1226
1241
  **🔍 Reverse engineer** in an agent's detail (or the **Reverse** tab of the split) puts the agent's session on the left and a pane on the right. Name a **target** (an app's folder or `.asar`, a binary's path, a website's address) and what you want to understand ("how does search work in this app"). The agent investigates in its own session with the tools of [REA](https://github.com/morluto/rea), the "Reverse Engineer Anything" MCP server, and changes nothing.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ai-agentmanager",
3
- "version": "1.50.0",
3
+ "version": "1.51.0",
4
4
  "description": "Run background coding agents (Claude Code, Codex) per intent, and keep track of them from a web UI, your phone or the CLI",
5
5
  "keywords": [
6
6
  "claude",
package/public/app.js CHANGED
@@ -42,6 +42,7 @@ import { initNews } from '/news.js';
42
42
  import { initPlan } from '/plan.js';
43
43
  import { initSystem } from '/system.js';
44
44
  import { adviceHtml, initDecide } from '/decide.js';
45
+ import { initUsage } from '/usage.js';
45
46
  import { initMcp } from '/mcp.js';
46
47
  import { initCodeMap } from '/codemap.js';
47
48
  import { initKeys } from '/keys.js';
@@ -350,6 +351,9 @@ decideUi = initDecide({
350
351
  onData: () => (renderInbox(), selectedId && renderDetail()),
351
352
  });
352
353
  $('#decide-btn').onclick = () => decideUi.open();
354
+ // Usage: each engine's plan limits, used and left (the chip by the connection light opens it).
355
+ const usageUi = initUsage({ api, $, esc, ago, toast: (m, ms) => toast(m, ms) });
356
+ $('#usage-btn').onclick = () => usageUi.open();
353
357
  // MCP: the MCP servers and tools Claude Code has in a folder, and running one.
354
358
  const mcpUi = initMcp({ api, $, esc, ago, md: (t) => md(t), toast: (m, ms) => toast(m, ms), agents: () => [...agents.values()] });
355
359
  $('#mcp-btn').onclick = () => mcpUi.open(selectedId && agents.get(selectedId)?.workdir ? selectedId : null);
@@ -407,6 +411,7 @@ function shortcut(act) {
407
411
  if (act === 'plan') return planUi.open();
408
412
  if (act === 'os') return osUi.open();
409
413
  if (act === 'decide') return decideUi.open();
414
+ if (act === 'usage') return usageUi.open();
410
415
  if (act === 'today') return todayUi.open();
411
416
  if (act.startsWith('tab:')) return showTab(act.slice(4));
412
417
  return false;
@@ -4554,6 +4559,8 @@ function handleEvent(msg) {
4554
4559
  valueUi.changed();
4555
4560
  } else if (msg.t === 'news') {
4556
4561
  newsUi.changed();
4562
+ } else if (msg.t === 'usage') {
4563
+ usageUi.changed();
4557
4564
  } else if (msg.t === 'advisor') {
4558
4565
  decideUi.changed();
4559
4566
  } else if (msg.t === 'plan') {
package/public/index.html CHANGED
@@ -26,6 +26,7 @@
26
26
  <button id="about-btn" class="about-btn" type="button" title="About AI Agent Manager: version, release, links">About</button>
27
27
  <button id="update-btn" class="update-btn" type="button" hidden></button>
28
28
  <span id="conn" class="conn" title="Daemon connection">connecting…</span>
29
+ <button id="usage-chip" class="usage-chip" type="button" hidden></button>
29
30
  </div>
30
31
  <div class="top-actions">
31
32
  <input id="filter" type="search" placeholder="Filter agents" aria-label="Filter agents" />
@@ -65,6 +66,7 @@
65
66
  <span id="me-email" class="hint"></span>
66
67
  <span id="me-where" class="hint"></span>
67
68
  </div>
69
+ <button role="menuitem" id="usage-btn" title="What is used and left of each engine's plan limits (Claude Code's 5-hour session and week, Codex's), and when they reset">Usage…</button>
68
70
  <button role="menuitem" id="settings-btn">Settings…</button>
69
71
  <button role="menuitem" id="worklog-btn" title="What your agents got done: pull requests, bugs fixed, issues filed; kept in a spreadsheet for reviews">Work record…</button>
70
72
  <button role="menuitem" id="cleanup-btn" title="Close agents idle for a while, and delete old closed ones">Clean up…</button>
@@ -424,6 +426,9 @@
424
426
  <dialog id="plan-dialog" class="issues-dialog plan-dialog" aria-label="Plan">
425
427
  <div id="plan-body"></div>
426
428
  </dialog>
429
+ <dialog id="usage-dialog" class="issues-dialog usage-dialog" aria-label="Usage">
430
+ <div id="usage-body"></div>
431
+ </dialog>
427
432
  <dialog id="decide-dialog" class="issues-dialog decide-dialog" aria-label="Decide">
428
433
  <div id="decide-body"></div>
429
434
  </dialog>
@@ -608,6 +613,7 @@
608
613
  <label class="check"><input type="checkbox" name="ev_budget" /> nears or reaches its budget, or today's spend reaches the daily limit</label>
609
614
  <label class="check"><input type="checkbox" name="ev_standup" /> the daily standup is ready (with a link to play it)</label>
610
615
  <label class="check"><input type="checkbox" name="ev_value" /> value reports (weekly, monthly, quarterly, as set in Value)</label>
616
+ <label class="check"><input type="checkbox" name="ev_usage" /> an engine's plan limit (Claude Code's 5-hour session or week, Codex's) is nearly used up (Usage)</label>
611
617
  <label class="check"><input type="checkbox" name="ev_decided" /> something was decided for you: a standing decision of yours applied, or it was within the autonomy you set (Decide)</label>
612
618
  <label class="check"><input type="checkbox" name="ev_milestone" /> a project's date (code complete, RC, GA) is 14, 7, 3 or 1 days away, today, or late (Plan → Dates)</label>
613
619
  <label class="check"><input type="checkbox" name="ev_waiting" /> finished its turn and is idle after <input name="waitingDelaySec" type="number" min="0" class="num" />s</label>
package/public/keys.js CHANGED
@@ -31,6 +31,7 @@ export const SHORTCUTS = [
31
31
  [['c'], 'Plan: project dates, decisions and tech debt', 'plan'],
32
32
  [['u'], 'OS: this computer and its load', 'os'],
33
33
  [['q'], 'Decide: recommendations, standing decisions, impact, dates at risk', 'decide'],
34
+ [['z'], "Usage: each engine's plan limits, used and left", 'usage'],
34
35
  [['1'], 'Agents tab', 'tab:agents'],
35
36
  [['2'], 'Inbox: what needs you', 'tab:inbox'],
36
37
  [['3'], 'Backlog', 'tab:backlog'],
@@ -74,11 +75,11 @@ export const SHORTCUTS = [
74
75
  // A single key, as an event names it, to its action.
75
76
  export const SINGLE = {
76
77
  j: 'next', k: 'prev', Enter: 'terminal', t: 'terminal',
77
- r: 'changes', s: 'start', X: 'stop', e: 'edit', n: 'new', a: 'ask', '/': 'filter', w: 'watch', p: 'standup', m: 'map', i: 'issues', o: 'actions', h: 'assistant', ',': 'settings', d: 'designs', g: 'reviews', v: 'value', l: 'news', c: 'plan', u: 'os', q: 'decide', y: 'today', b: 'bugs', '?': 'help',
78
+ r: 'changes', s: 'start', X: 'stop', e: 'edit', n: 'new', a: 'ask', '/': 'filter', w: 'watch', p: 'standup', m: 'map', i: 'issues', o: 'actions', h: 'assistant', ',': 'settings', d: 'designs', g: 'reviews', v: 'value', l: 'news', c: 'plan', u: 'os', q: 'decide', z: 'usage', y: 'today', b: 'bugs', '?': 'help',
78
79
  1: 'tab:agents', 2: 'tab:inbox', 3: 'tab:backlog', 4: 'tab:land', 5: 'tab:built',
79
80
  };
80
81
  // While Watch is open: only what makes sense there.
81
- const ON_WATCH = new Set(['today', 'new', 'ask', 'watch', 'standup', 'map', 'issues', 'actions', 'assistant', 'settings', 'designs', 'reviews', 'value', 'news', 'plan', 'os', 'decide', 'bugs', 'help']);
82
+ const ON_WATCH = new Set(['today', 'new', 'ask', 'watch', 'standup', 'map', 'issues', 'actions', 'assistant', 'settings', 'designs', 'reviews', 'value', 'news', 'plan', 'os', 'decide', 'usage', 'bugs', 'help']);
82
83
 
83
84
  /** Typing somewhere: a field, an editor or a terminal (xterm types through a textarea). */
84
85
  const typing = (el) => Boolean(el?.closest?.('input, textarea, select, [contenteditable=""], [contenteditable="true"], .xterm, .cm-editor'));
package/public/style.css CHANGED
@@ -1295,7 +1295,7 @@ table.bench-cases tr.faster td:nth-child(5) { color: var(--green); font-weight:
1295
1295
  .issues-dialog { width: min(1100px, calc(100% - 32px)); max-height: calc(100% - 32px); padding: 16px; }
1296
1296
  /* Only while open: a display on the dialog itself would keep a closed one on screen. */
1297
1297
  .issues-dialog[open] { display: flex; flex-direction: column; }
1298
- #issues-body, #actions-body, #designs-body, #reviews-body, #bugs-body, #plan-body, #news-body, #os-body, #decide-body { display: flex; flex-direction: column; min-height: 0; flex: 1; }
1298
+ #issues-body, #actions-body, #designs-body, #reviews-body, #bugs-body, #plan-body, #news-body, #os-body, #decide-body, #usage-body { display: flex; flex-direction: column; min-height: 0; flex: 1; }
1299
1299
  /* The lists: drag the corner to any size, or fill the window (⤢ or f). */
1300
1300
  .issues-dialog { resize: both; overflow: hidden; min-width: min(520px, calc(100% - 32px)); min-height: 240px; max-width: calc(100% - 16px); max-height: calc(100% - 16px); }
1301
1301
  .issues-dialog.expanded { width: calc(100% - 16px); height: calc(100% - 16px); }
@@ -1452,6 +1452,26 @@ table.plan-debt .plan-score b { position: relative; padding-left: 6px; }
1452
1452
  .plan-bar-fill { position: absolute; left: 0; top: 6px; bottom: 6px; background: color-mix(in srgb, var(--red) 22%, transparent); border-radius: 3px; }
1453
1453
  table.plan-debt code { overflow-wrap: anywhere; }
1454
1454
  /* AI News: a day heading, then each release with its lab, summary and links. */
1455
+ /* ---------- Usage: each engine's plan limits, used and left */
1456
+ .usage-chip { font-size: 12px; padding: 2px 8px; border-radius: 999px; border: 1px solid var(--border); background: var(--panel); color: var(--muted); white-space: nowrap; cursor: pointer; font-variant-numeric: tabular-nums; }
1457
+ .usage-chip.warn { color: var(--yellow); border-color: var(--yellow); }
1458
+ .usage-chip.high, .usage-chip.held, .usage-chip.limited { color: var(--red); border-color: var(--red); }
1459
+ .usage-dialog { width: min(760px, calc(100% - 32px)); }
1460
+ .usage-scroll { border: 0; }
1461
+ .usage-window { margin: 8px 0 2px; }
1462
+ .usage-window-head { display: flex; gap: 10px; align-items: baseline; flex-wrap: wrap; font-size: 13px; }
1463
+ .usage-num { font-variant-numeric: tabular-nums; }
1464
+ .usage-left { font-weight: 600; font-variant-numeric: tabular-nums; color: var(--green); }
1465
+ .usage-left.busy { color: var(--yellow); }
1466
+ .usage-left.heavy { color: var(--red); }
1467
+ .usage-level.ok { color: var(--green); }
1468
+ .usage-level.warn { color: var(--yellow); border-color: var(--yellow); }
1469
+ .usage-level.high, .usage-level.held, .usage-level.limited { color: var(--red); border-color: var(--red); }
1470
+ .usage-settings { display: flex; gap: 18px; flex-wrap: wrap; margin: 6px 0 8px; font-size: 13px; }
1471
+ .usage-settings label { display: flex; flex-direction: row; align-items: center; gap: 6px; margin: 0; }
1472
+ .usage-settings select { width: auto; }
1473
+ @media (max-width: 760px) { .usage-chip { display: none; } }
1474
+
1455
1475
  /* ---------- Runbooks for the support team (a tab of Plan) */
1456
1476
  .rb-form input[name="key"] { flex: 1 1 240px; min-width: 0; }
1457
1477
  .rb-form input[name="note"] { flex: 2 1 260px; min-width: 0; }
@@ -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/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')
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';
@@ -1426,7 +1428,8 @@ export class AgentManager extends EventEmitter {
1426
1428
  const dir = fs.realpathSync(uploads);
1427
1429
  writableDir = writableDir ? [writableDir, dir].flat() : dir;
1428
1430
  }
1429
- 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 };
1430
1433
  }
1431
1434
 
1432
1435
  /** Spawn the agent's engine in a PTY, reusing its terminal clients and scrollback. */
@@ -1716,7 +1719,7 @@ export class AgentManager extends EventEmitter {
1716
1719
  }
1717
1720
 
1718
1721
  childEnv(agent) {
1719
- 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() };
1720
1723
  for (const key of STRIP_ENV) delete env[key];
1721
1724
  return env;
1722
1725
  }
@@ -2888,6 +2891,8 @@ export class AgentManager extends EventEmitter {
2888
2891
  const cursor = this.cursors.get(key) ?? { offset: 0 };
2889
2892
  this.cursors.set(key, cursor);
2890
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 });
2891
2896
  const subMaps = engine.subagentFiles(sessionDir, session.id).map((sub) => {
2892
2897
  const c = this.cursors.get(sub) ?? { offset: 0 };
2893
2898
  this.cursors.set(sub, c);
@@ -3575,6 +3580,7 @@ export class AgentManager extends EventEmitter {
3575
3580
  if (prev && !prev.resumedAt && prev.text === found.text) return (rt.lastLimit = prev);
3576
3581
  const agent = this.store.get(id);
3577
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 });
3578
3584
  return (rt.lastLimit = { ...found, at: new Date(t).toISOString(), resumedAt: null });
3579
3585
  }
3580
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/server.js CHANGED
@@ -54,6 +54,7 @@ import { System } from './system.js';
54
54
  import { Advisor } from './advisor.js';
55
55
  import { Runbooks } from './runbooks.js';
56
56
  import { reaStatus } from './rea.js';
57
+ import { EngineUsage, codexWindows } from './usage.js';
57
58
  import { Milestones } from './milestones.js';
58
59
  import { Decisions } from './decisions.js';
59
60
  import { Debt } from './debt.js';
@@ -323,6 +324,23 @@ export async function startServer({ port = PORT, host = HOST, evalTimer = true }
323
324
  await sendSlack(text, n, plain);
324
325
  },
325
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();
326
344
  // Runbooks for the support team, from a release ticket, an epic, or the code changes of a time frame (runbooks.js).
327
345
  const runbooks = new Runbooks({
328
346
  store,
@@ -1115,6 +1133,21 @@ export async function startServer({ port = PORT, host = HOST, evalTimer = true }
1115
1133
  api.post('/milestones/:project/reach', wrap((req) => milestones.reach(req.params.project, req.body?.stage, req.body?.reached !== false)));
1116
1134
  api.post('/milestones/:project/task', wrap((req) => milestones.task(req.params.project, req.body?.stage, req.body?.item)));
1117
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
+ }));
1118
1151
  api.get('/runbooks', wrap(() => runbooks.list()));
1119
1152
  api.post('/runbooks', wrap((req) => runbooks.create(req.body ?? {})));
1120
1153
  api.get('/runbooks/:id', (req, res) => {
@@ -1532,6 +1565,7 @@ export async function startServer({ port = PORT, host = HOST, evalTimer = true }
1532
1565
  pushNews = () => broadcast({ t: 'news' });
1533
1566
  pushPlan = () => broadcast({ t: 'plan' });
1534
1567
  pushAdvisor = () => broadcast({ t: 'advisor' });
1568
+ pushUsage = () => broadcast({ t: 'usage' });
1535
1569
  reports.on('change', () => broadcast({ t: 'built', reports: reports.list() }));
1536
1570
  manager.rules.on('change', (rules) => broadcast({ t: 'rules', rules }));
1537
1571
  repeats.on('change', (view) => broadcast({ t: 'repeats', repeats: view }));
@@ -1674,6 +1708,7 @@ export async function startServer({ port = PORT, host = HOST, evalTimer = true }
1674
1708
  milestones.close();
1675
1709
  decisions.close();
1676
1710
  advisor.close();
1711
+ usage.close();
1677
1712
  debt.close();
1678
1713
  reviews.close();
1679
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
+ }
package/src/usage.js ADDED
@@ -0,0 +1,225 @@
1
+ // Engine usage: how much of each engine's plan limits is used and how much is left, so you know
2
+ // before an agent stops, and can hold new work or move it to another engine.
3
+ // Claude Code - its 5-hour and 7-day windows (percent used, when each resets), which it gives its
4
+ // status line command for Pro, Max and Ultra plans once a session has had a reply.
5
+ // Sessions started here get a status line that records them (statusline.js).
6
+ // Codex - the rate limits Codex writes in its session logs, when it reports them.
7
+ // any engine - a limit an agent actually hit ("usage limit reached… resets 3pm") counts as used
8
+ // up until it resets.
9
+ // Engines that report nothing are listed as that. Nothing is asked of any service, and no model is
10
+ // called: these are numbers the engines already hand out on this computer.
11
+
12
+ import fs from 'node:fs';
13
+ import path from 'node:path';
14
+ import { fileURLToPath } from 'node:url';
15
+ import { paths } from './config.js';
16
+
17
+ export const USAGE_DEFAULTS = { enabled: true, warnAt: 80, holdAt: null };
18
+ export const usageFile = () => path.join(paths.home, 'usage', 'claude.json');
19
+ export const statusLineScript = () => path.join(path.dirname(fileURLToPath(import.meta.url)), 'statusline.js');
20
+ const STALE_MS = 6 * 3_600_000;
21
+ const err = (status, message) => Object.assign(new Error(message), { status });
22
+ const pct = (n) => (typeof n === 'number' && Number.isFinite(n) ? Math.max(0, Math.min(100, Math.round(n * 10) / 10)) : null);
23
+ const iso = (sec) => (typeof sec === 'number' && sec > 0 ? new Date(sec * 1000).toISOString() : null);
24
+
25
+ export function usageSettings(config = {}) {
26
+ const u = { ...USAGE_DEFAULTS, ...config.usage };
27
+ const level = (v) => (v === null || v === '' || v === undefined || v === 'off' ? null : Math.max(1, Math.min(100, Math.round(Number(v)) || 0)) || null);
28
+ return { enabled: u.enabled !== false, warnAt: level(u.warnAt), holdAt: level(u.holdAt) };
29
+ }
30
+
31
+ /** Claude Code's `rate_limits` (from its status line input) as windows. */
32
+ export function claudeWindows(limits) {
33
+ const out = [];
34
+ for (const [id, label] of [['five_hour', '5-hour session'], ['seven_day', 'Week']]) {
35
+ const used = pct(limits?.[id]?.used_percentage);
36
+ if (used !== null) out.push({ id, label, used, resetsAt: iso(limits[id].resets_at) });
37
+ }
38
+ return out;
39
+ }
40
+
41
+ /** Codex's `rate_limits` (from a token_count record of its session log, written at `at`) as windows. */
42
+ export function codexWindows(limits, at = Date.now()) {
43
+ const out = [];
44
+ for (const [id, fallback] of [['primary', '5-hour session'], ['secondary', 'Week']]) {
45
+ const w = limits?.[id];
46
+ const used = pct(w?.used_percent);
47
+ if (used === null) continue;
48
+ const min = Number(w.window_minutes) || null;
49
+ const label = !min ? fallback : min >= 10_000 ? 'Week' : min >= 1440 ? `${Math.round(min / 1440)}-day` : min % 60 === 0 ? `${min / 60}-hour session` : `${min}-minute window`;
50
+ const resetsAt = iso(w.resets_at) ?? (typeof w.resets_in_seconds === 'number' ? new Date(at + w.resets_in_seconds * 1000).toISOString() : null);
51
+ out.push({ id, label, used, resetsAt });
52
+ }
53
+ return out;
54
+ }
55
+
56
+ /** "in 2h 10m", "in 3 days", "now". */
57
+ export function untilWords(when, now = Date.now()) {
58
+ const ms = Date.parse(when) - now;
59
+ if (!(ms > 0)) return 'now';
60
+ const m = Math.round(ms / 60_000);
61
+ if (m < 60) return `in ${m}m`;
62
+ if (m < 48 * 60) return `in ${Math.floor(m / 60)}h${m % 60 ? ` ${m % 60}m` : ''}`;
63
+ return `in ${Math.round(m / 1440)} days`;
64
+ }
65
+
66
+ const NOTES = {
67
+ claude: 'Claude Code reports this for Pro, Max and Ultra plans, to sessions started here, once a session has had its first reply.',
68
+ codex: 'Read from Codex\'s session logs when Codex reports its limits (ChatGPT plans).',
69
+ };
70
+
71
+ export class EngineUsage {
72
+ /**
73
+ * `engines()`: the engines as listEngines gives them ({ id, label, installed }); `notify(text,
74
+ * plain)`: an alert; `store`: where the readings are kept between restarts.
75
+ */
76
+ constructor({ store, config, engines, notify = null, onChange = () => {}, file = usageFile(), now = () => Date.now(), log = (m) => console.log(`[agentmgr] ${m}`), timer = true }) {
77
+ Object.assign(this, { store, config, engines, notify, onChange, file, now, log });
78
+ this.fileAt = null;
79
+ if (timer) {
80
+ this.timer = setInterval(() => this.tick(), 20_000);
81
+ this.timer.unref?.();
82
+ }
83
+ }
84
+
85
+ close() {
86
+ clearInterval(this.timer);
87
+ }
88
+
89
+ get settings() {
90
+ return usageSettings(this.config);
91
+ }
92
+
93
+ get state() {
94
+ const s = (this.store.data.usage ??= {});
95
+ s.engines ??= {};
96
+ s.alerted ??= {};
97
+ return s;
98
+ }
99
+
100
+ update(patch = {}) {
101
+ const next = { ...this.config.usage };
102
+ for (const k of ['warnAt', 'holdAt']) {
103
+ if (!(k in patch)) continue;
104
+ const v = patch[k];
105
+ if (v === null || v === '' || v === 'off') next[k] = null;
106
+ else if (!(Number(v) >= 1 && Number(v) <= 100)) throw err(400, `${k} must be 1 to 100, or off`);
107
+ else next[k] = Math.round(Number(v));
108
+ }
109
+ if ('enabled' in patch) next.enabled = patch.enabled !== false;
110
+ this.config.usage = next;
111
+ this.onChange();
112
+ return next;
113
+ }
114
+
115
+ /** A reading for an engine: its windows as they are at `at`. A window not in this reading keeps its last one. */
116
+ record(engineId, windows, { at = new Date(this.now()).toISOString(), source = null } = {}) {
117
+ if (!windows.length) return false;
118
+ const e = (this.state.engines[engineId] ??= { windows: {} });
119
+ if (e.at && at < e.at) return false; // an older log read late
120
+ let changed = false;
121
+ for (const w of windows) {
122
+ const prev = e.windows[w.id];
123
+ if (!prev || prev.used !== w.used || prev.resetsAt !== w.resetsAt) changed = true;
124
+ e.windows[w.id] = { id: w.id, label: w.label, used: w.used, resetsAt: w.resetsAt ?? null, at };
125
+ }
126
+ Object.assign(e, { at, source });
127
+ if (changed) {
128
+ this.store.save();
129
+ this.onChange();
130
+ this.alert(engineId);
131
+ }
132
+ return changed;
133
+ }
134
+
135
+ /** An agent on this engine stopped at a usage limit: used up until it resets. */
136
+ limited(engineId, { text, resetAt = null } = {}) {
137
+ const e = (this.state.engines[engineId] ??= { windows: {} });
138
+ if (e.limited?.text === text && e.limited?.until === resetAt) return;
139
+ e.limited = { text: String(text ?? '').slice(0, 200), until: resetAt, at: new Date(this.now()).toISOString() };
140
+ this.store.save();
141
+ this.onChange();
142
+ }
143
+
144
+ /** Claude Code's numbers, as its status line last wrote them. */
145
+ readClaude() {
146
+ let at;
147
+ try {
148
+ at = fs.statSync(this.file).mtimeMs;
149
+ } catch {
150
+ return false;
151
+ }
152
+ if (at === this.fileAt) return false;
153
+ this.fileAt = at;
154
+ try {
155
+ const d = JSON.parse(fs.readFileSync(this.file, 'utf8'));
156
+ return this.record('claude', claudeWindows(d.rate_limits), { at: d.at ?? new Date(at).toISOString(), source: `Claude Code${d.version ? ` ${d.version}` : ''}` });
157
+ } catch {
158
+ return false;
159
+ }
160
+ }
161
+
162
+ tick() {
163
+ if (!this.settings.enabled) return;
164
+ this.readClaude();
165
+ }
166
+
167
+ /** One engine as it stands now: its windows with what is left, and how worried to be. */
168
+ engineView(def) {
169
+ const now = this.now();
170
+ const { warnAt, holdAt } = this.settings;
171
+ const e = this.state.engines[def.id] ?? { windows: {} };
172
+ const windows = Object.values(e.windows).map((w) => {
173
+ // Past its reset, the old number no longer holds: unknown until the next reading.
174
+ const reset = Boolean(w.resetsAt && Date.parse(w.resetsAt) <= now);
175
+ return { id: w.id, label: w.label, used: reset ? null : w.used, left: reset ? null : Math.round((100 - w.used) * 10) / 10, resetsAt: w.resetsAt, resetsIn: w.resetsAt && !reset ? untilWords(w.resetsAt, now) : null, reset, at: w.at, stale: !reset && now - Date.parse(w.at) > STALE_MS };
176
+ });
177
+ const limited = e.limited && (!e.limited.until || Date.parse(e.limited.until) > now) && now - Date.parse(e.limited.at) < 24 * 3_600_000 ? { ...e.limited, resetsIn: e.limited.until ? untilWords(e.limited.until, now) : null } : null;
178
+ const top = Math.max(-1, ...windows.filter((w) => w.used !== null).map((w) => w.used));
179
+ const level = limited ? 'limited' : top < 0 ? 'unknown' : holdAt && top >= holdAt ? 'held' : top >= 95 ? 'high' : warnAt && top >= warnAt ? 'warn' : 'ok';
180
+ return { id: def.id, label: def.label, installed: def.installed !== false, windows, limited, level, top: top < 0 ? null : top, at: e.at ?? null, source: e.source ?? null, note: windows.length ? null : NOTES[def.id] ?? 'This engine does not report its limits here. A limit it hits is still noticed, and shown until it resets.' };
181
+ }
182
+
183
+ view() {
184
+ const defs = this.engines();
185
+ const list = defs.filter((d) => d.installed !== false || this.state.engines[d.id]).map((d) => this.engineView(d));
186
+ return { settings: this.settings, default: this.config.engine ?? 'claude', engines: list, worst: list.reduce((a, b) => (rank(b.level) > rank(a?.level) ? b : a), null) };
187
+ }
188
+
189
+ /** Near a limit, once per window and reset: an alert. */
190
+ alert(engineId) {
191
+ const { warnAt } = this.settings;
192
+ if (!warnAt) return;
193
+ const def = this.engines().find((d) => d.id === engineId) ?? { id: engineId, label: engineId };
194
+ const v = this.engineView(def);
195
+ for (const w of v.windows) {
196
+ if (w.used === null || w.used < warnAt) continue;
197
+ const key = `${engineId}:${w.id}:${w.resetsAt ?? ''}`;
198
+ if (this.state.alerted[key]) continue;
199
+ this.state.alerted[key] = new Date(this.now()).toISOString();
200
+ const keys = Object.keys(this.state.alerted);
201
+ for (const k of keys.slice(0, Math.max(0, keys.length - 50))) delete this.state.alerted[k];
202
+ this.store.save();
203
+ const words = `${def.label}: ${Math.round(w.used)}% of the ${w.label.toLowerCase()} limit is used (${Math.round(w.left)}% left)${w.resetsIn ? `; it resets ${w.resetsIn}` : ''}`;
204
+ this.log(words);
205
+ this.notify?.(`:hourglass_flowing_sand: *${words}*`, words)?.catch?.(() => {});
206
+ }
207
+ }
208
+
209
+ /** With "hold new work" set: no new agent on an engine at or past that much of a limit. */
210
+ policy(action, details) {
211
+ if (action !== 'agent.create') return undefined;
212
+ const { enabled, holdAt } = this.settings;
213
+ if (!enabled || !holdAt) return undefined;
214
+ const id = details.input?.engine ?? 'claude';
215
+ const def = this.engines().find((d) => d.id === id);
216
+ if (!def) return undefined;
217
+ const v = this.engineView(def);
218
+ const w = v.windows.filter((x) => x.used !== null && x.used >= holdAt).sort((a, b) => b.used - a.used)[0];
219
+ if (!w && !v.limited) return undefined;
220
+ const why = w ? `${Math.round(w.used)}% of its ${w.label.toLowerCase()} limit is used${w.resetsIn ? ` (resets ${w.resetsIn})` : ''}` : `it stopped at a limit${v.limited.resetsIn ? ` (resets ${v.limited.resetsIn})` : ''}`;
221
+ return { allow: false, reason: `${def.label} is held for new work: ${why}. Start it on another engine, wait for the reset, or change "hold new work" in Usage` };
222
+ }
223
+ }
224
+
225
+ const rank = (level) => ({ unknown: 0, ok: 1, warn: 2, high: 3, held: 4, limited: 5 }[level] ?? -1);