ai-agentmanager 1.50.0 → 1.51.1

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,18 @@
1
1
  # Changelog
2
2
 
3
+ ## 1.51.1 (2026-11-14)
4
+
5
+ - **Usage: Read now.** The Usage window's ↻ only re-read the last saved reading, which is as old as the last reply of a session started here; Claude Code used elsewhere moved the real numbers on meanwhile. **↻ Read now** (or `agentmgr usage --now`) takes a reading on the spot. Claude Code only reports its limits to a session that has had a reply, so it starts a short session that says one word on its smallest model (a very small amount of usage) and removes it after. The chip and the once-a-minute update never start a session.
6
+ - **The engine new agents start on** shows a pressed **✓ New agents start here** button where the other engines have **Start new agents here**, instead of a label that looked like a button that did nothing.
7
+ - **Debug:** the examples no longer name E2E tests.
8
+
9
+ ## 1.51.0 (2026-11-14)
10
+
11
+ - **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.
12
+ - **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.
13
+ - **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.
14
+ - Turn it off with `"usage": { "enabled": false }` in config.json.
15
+
3
16
  ## 1.50.0 (2026-11-14)
4
17
 
5
18
  - **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
@@ -29,7 +29,8 @@ Run one background [Claude Code](https://claude.com/claude-code) agent per inten
29
29
  - **Share for review.** One click writes an **Analysis**, **Design**, **Flow** or **Proposal** document from the agent's work, a human time **Estimate** for planning, or the change's **Documentation** with an OpenAPI spec of any API changes. Copy it as Markdown, download it, or print it to PDF with diagrams.
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
- - **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**.
32
+ - **Debug.** Say what to debug (a failure, 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 (--now, --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, so a reading is as old as the last reply of a session started here; Claude Code you use elsewhere moves the real numbers on meanwhile. **↻ Read now** (or `agentmgr usage --now`) brings them up to date: Claude Code only reports its limits to a session that has had a reply, so it starts a short one that says one word on its smallest model (a very small amount of usage) and removes it after. Nothing else calls a model. 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.
@@ -1234,7 +1249,7 @@ Repeating meetings, time zones, moved or cancelled occurrences and events marked
1234
1249
 
1235
1250
  ## Debug
1236
1251
 
1237
- **🐞 Debug** in an agent's detail (or the **Debug** tab of the split, **◫ Split** in the terminal bar) puts the agent's session on the left and the debug pane on the right. Type what is going wrong, for example *E2E tests fail at max scale after about 20 minutes* or *p99 latency triples under load*, and press **Debug** (or Enter).
1252
+ **🐞 Debug** in an agent's detail (or the **Debug** tab of the split, **◫ Split** in the terminal bar) puts the agent's session on the left and the debug pane on the right. Type what is going wrong, for example *imports fail at max scale after about 20 minutes* or *p99 latency triples under load*, and press **Debug** (or Enter).
1238
1253
 
1239
1254
  The agent investigates in its own session, with everything it already knows about the work: it reads the code on the path, the logs and the tests, reproduces the problem where it can (the failing test, a small load, a script) and measures. It keeps a report, drawn in the pane as it grows:
1240
1255
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ai-agentmanager",
3
- "version": "1.50.0",
3
+ "version": "1.51.1",
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/side.js CHANGED
@@ -78,8 +78,8 @@ export function initSide({ api, esc, toast, $, agents, codeUi, docHtml, renderDi
78
78
  // your own), and Reverse engineer also names a target and needs REA's tools.
79
79
  const ASK = {
80
80
  debug: {
81
- ideas: ['E2E tests unstable at max scale', 'Slow or failing under load', 'A flaky test', 'A memory or connection leak', 'Wrong data end to end'],
82
- first: 'What should it debug? For example: E2E tests fail at max scale after about 20 minutes',
81
+ ideas: ['Unstable at max scale', 'Slow or failing under load', 'A flaky test', 'A memory or connection leak', 'Wrong data end to end'],
82
+ first: 'What should it debug? For example: imports fail at max scale after about 20 minutes',
83
83
  more: 'A follow-up: what you know, what to look at next, or which fixes to apply',
84
84
  go: 'Debug',
85
85
  short: 'Say what to debug',
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,27 @@ 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-default-on, .usage-default-on:hover { color: var(--green); border-color: var(--green); }
1471
+ .usage-settings { display: flex; gap: 18px; flex-wrap: wrap; margin: 6px 0 8px; font-size: 13px; }
1472
+ .usage-settings label { display: flex; flex-direction: row; align-items: center; gap: 6px; margin: 0; }
1473
+ .usage-settings select { width: auto; }
1474
+ @media (max-width: 760px) { .usage-chip { display: none; } }
1475
+
1455
1476
  /* ---------- Runbooks for the support team (a tab of Plan) */
1456
1477
  .rb-form input[name="key"] { flex: 1 1 240px; min-width: 0; }
1457
1478
  .rb-form input[name="note"] { flex: 2 1 260px; min-width: 0; }
@@ -0,0 +1,138 @@
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
+ let reading = false;
15
+
16
+ async function load({ quiet = false } = {}) {
17
+ try {
18
+ data = await api('GET', '/usage');
19
+ } catch (e) {
20
+ if (!quiet) toast?.(e.message, 5000);
21
+ }
22
+ drawChip();
23
+ if (dialog.open) draw();
24
+ }
25
+
26
+ /** The engine new agents start on, or the one in the worst state when that is worse than fine. */
27
+ function drawChip() {
28
+ if (!chip || !data) return;
29
+ const mine = data.engines.find((e) => e.id === data.default);
30
+ const bad = data.worst && ['warn', 'high', 'held', 'limited'].includes(data.worst.level) ? data.worst : null;
31
+ const e = bad ?? mine;
32
+ const read = e?.windows.filter((w) => w.used !== null) ?? [];
33
+ chip.hidden = !e || (!read.length && !e.limited);
34
+ if (chip.hidden) return;
35
+ chip.className = `usage-chip ${e.level}`;
36
+ chip.textContent = e.limited ? `${e.label}: at its limit` : `${e.label} ${read.map((w) => `${SHORT[w.id] ?? w.label} ${Math.round(w.used)}%`).join(' · ')}`;
37
+ 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.`;
38
+ }
39
+
40
+ const tone = (used) => (used >= 95 ? 'heavy' : used >= (data.settings.warnAt ?? 101) ? 'busy' : 'light');
41
+ const when = (iso) => new Date(iso).toLocaleString([], { weekday: 'short', hour: 'numeric', minute: '2-digit' });
42
+
43
+ function engineHtml(e) {
44
+ const others = data.engines.filter((x) => x.installed && x.id !== e.id && !['held', 'limited', 'high'].includes(x.level));
45
+ const rows = e.windows
46
+ .map((w) => (w.used === null
47
+ ? `<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>`
48
+ : `<div class="usage-window" data-usage-window="${esc(w.id)}">
49
+ <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>
50
+ <div class="os-meter ${tone(w.used)}" role="img" aria-label="${Math.round(w.used)}% used"><span style="width:${w.used}%"></span></div>
51
+ </div>`))
52
+ .join('');
53
+ return `<div class="plan-project usage-engine" data-usage-engine="${esc(e.id)}">
54
+ <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.installed ? '' : '<span class="tag">not installed</span>'}
55
+ <span class="spacer"></span>${e.at ? `<span class="hint">read ${esc(ago(e.at))}${e.source ? ` from ${esc(e.source)}` : ''}</span>` : ''}
56
+ ${e.id === data.default ? `<button class="small usage-default-on" aria-pressed="true" data-usage-is-default="${esc(e.label)}" title="New agents start on ${esc(e.label)} unless you pick another engine for them. Press the button on another engine to move them there">✓ New agents start here</button>` : ''}
57
+ ${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>
58
+ ${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>` : ''}
59
+ ${rows}
60
+ ${e.note ? `<p class="hint">${esc(e.note)}</p>` : ''}
61
+ ${['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>` : ''}
62
+ </div>`;
63
+ }
64
+
65
+ function draw() {
66
+ 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>');
67
+ const s = data.settings;
68
+ 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>`;
69
+ body.innerHTML = `
70
+ <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" ${reading ? 'disabled' : ''} title="Take a reading now. Claude Code only reports its limits to a session that has had a reply, so this starts a short one that says one word on its smallest model (a very small amount of usage)">${reading ? 'Reading…' : '↻ Read now'}</button><button class="small" data-usage="close" title="Close (Esc)">Close</button></div>
71
+ <div class="issues-scroll usage-scroll">
72
+ ${data.engines.map(engineHtml).join('') || '<p class="hint issues-empty">No engine is installed.</p>'}
73
+ <div class="usage-settings">
74
+ <label>Alert me at ${level('warnAt', s.warnAt, 'never')}</label>
75
+ <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>
76
+ </div>
77
+ <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, so a reading is as old as the last reply of a session started here; Claude Code you use elsewhere moves the real numbers on meanwhile. <b>Read now</b> brings them up to date with a one-word session on Claude Code's smallest model. 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>
78
+ </div>`;
79
+ }
80
+
81
+ const save = async (patch, done) => {
82
+ try {
83
+ data = await api('PUT', '/usage', patch);
84
+ if (done) toast?.(done, 3000);
85
+ } catch (e) {
86
+ toast?.(e.message, 6000);
87
+ }
88
+ drawChip();
89
+ draw();
90
+ };
91
+
92
+ /** A reading as of now, not the last one a session happened to bring. */
93
+ async function readNow() {
94
+ if (reading) return;
95
+ reading = true;
96
+ draw();
97
+ try {
98
+ data = await api('POST', '/usage/refresh');
99
+ toast?.(data.problem ?? 'Read just now', data.problem ? 7000 : 2500);
100
+ } catch (e) {
101
+ toast?.(e.message, 6000);
102
+ }
103
+ reading = false;
104
+ drawChip();
105
+ if (dialog.open) draw();
106
+ }
107
+
108
+ body.addEventListener('click', (e) => {
109
+ const on = e.target.closest('[data-usage-is-default]');
110
+ if (on) return toast?.(`New agents already start on ${on.dataset.usageIsDefault}. Press "Start new agents here" on another engine to move them`, 4000);
111
+ const d = e.target.closest('[data-usage-default]');
112
+ if (d) return save({ engine: d.dataset.usageDefault }, 'New agents start there from now on');
113
+ const b = e.target.closest('[data-usage]')?.dataset.usage;
114
+ if (b === 'close') dialog.close();
115
+ else if (b === 'refresh') readNow();
116
+ });
117
+ body.addEventListener('change', (e) => {
118
+ const s = e.target.closest('[data-usage-set]');
119
+ if (s) save({ [s.dataset.usageSet]: s.value }, 'Saved');
120
+ });
121
+ if (chip) chip.onclick = () => open();
122
+
123
+ function open() {
124
+ if (dialog.open) return dialog.close();
125
+ dialog.showModal();
126
+ draw();
127
+ load();
128
+ }
129
+ /** The daemon has a new reading. */
130
+ function changed() {
131
+ clearTimeout(again);
132
+ again = setTimeout(() => load({ quiet: true }), 400);
133
+ }
134
+ // "resets in 2h 10m" counts down, and a window that reset says so.
135
+ setInterval(() => (dialog.open || !chip?.hidden) && load({ quiet: true }), 60_000);
136
+ load({ quiet: true });
137
+ return { open, changed, isOpen: () => dialog.open };
138
+ }
package/src/cli.js CHANGED
@@ -823,6 +823,31 @@ 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('--now', 'take a reading now: a one-word Claude Code session on its smallest model (a very small amount of usage)')
833
+ .option('--json', 'print JSON')
834
+ .action(async (opts) => {
835
+ await daemon();
836
+ const patch = { ...(opts.warn !== undefined ? { warnAt: opts.warn } : {}), ...(opts.hold !== undefined ? { holdAt: opts.hold } : {}), ...(opts.default ? { engine: opts.default } : {}) };
837
+ let v = Object.keys(patch).length ? await api('PUT', '/usage', patch) : await api('GET', '/usage');
838
+ if (opts.now) v = await api('POST', '/usage/refresh');
839
+ if (opts.json) return console.log(JSON.stringify(v, null, 2));
840
+ if (v.problem) console.log(yellow(v.problem));
841
+ const tone = { ok: green, warn: yellow, high: red, held: red, limited: red };
842
+ for (const e of v.engines) {
843
+ console.log(`${bold(e.label)}${e.id === v.default ? dim(' (default)') : ''}${e.level === 'held' ? red(' held for new work') : ''}`);
844
+ if (e.limited) console.log(` ${red('stopped at a limit')}${e.limited.resetsIn ? `, resets ${e.limited.resetsIn}` : ''} ${dim(e.limited.text)}`);
845
+ for (const w of e.windows) console.log(` ${w.label.padEnd(16)} ${w.used === null ? dim('reset; no reading since') : (tone[e.level] ?? ((x) => x))(`${String(Math.round(w.used)).padStart(3)}% used ${String(Math.round(w.left)).padStart(3)}% left`)}${w.resetsIn ? dim(` resets ${w.resetsIn}`) : ''}${w.stale ? dim(' (an old reading)') : ''}`);
846
+ if (e.note) console.log(` ${dim(e.note)}`);
847
+ }
848
+ console.log(dim(`Warn at ${v.settings.warnAt ?? 'off'}${v.settings.warnAt ? '%' : ''} · hold new work at ${v.settings.holdAt ?? 'off'}${v.settings.holdAt ? '%' : ''}`));
849
+ });
850
+
826
851
  program
827
852
  .command('runbook [id]')
828
853
  .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,13 @@ 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
+ /** A session that says one word on the smallest model, so the status line has a reply to report after. */
24
+ usageProbeArgs: (sessionId) => ['--model', 'haiku', '--strict-mcp-config', '--session-id', sessionId, '--', 'Reply with the single word: ok'],
25
+ usageArgs: (config, script) => (config.usage?.enabled === false ? [] : ['--settings', JSON.stringify({ statusLine: { type: 'command', command: `${JSON.stringify(process.execPath)} ${JSON.stringify(script)}` } })]),
19
26
 
20
27
  /** Options for every launch: permissions, model, a folder it may write to, extra instructions. */
21
28
  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. */
@@ -1715,8 +1718,62 @@ export class AgentManager extends EventEmitter {
1715
1718
  return resumed;
1716
1719
  }
1717
1720
 
1721
+ /**
1722
+ * A reading of Claude Code's plan limits taken now: a short session that says one word, so its
1723
+ * status line (statusline.js) writes the numbers. In a folder of its own; its transcript is
1724
+ * removed after. Resolves true once the reading is written.
1725
+ */
1726
+ readUsage({ timeoutMs = 45_000, settleMs = 3000 } = {}) {
1727
+ const engine = engineOf(DEFAULT_ENGINE);
1728
+ if (!engine.usageProbeArgs || !installed(engine, this.config)) return Promise.resolve(false);
1729
+ const dir = path.join(path.dirname(usageFile()), 'probe');
1730
+ fs.mkdirSync(dir, { recursive: true });
1731
+ const cwd = fs.realpathSync(dir);
1732
+ try {
1733
+ engine.trust(cwd); // the app's own empty folder: no "do you trust this folder?" to answer
1734
+ } catch {}
1735
+ const sessionId = crypto.randomUUID();
1736
+ const mtime = () => {
1737
+ try {
1738
+ return fs.statSync(usageFile()).mtimeMs;
1739
+ } catch {
1740
+ return 0;
1741
+ }
1742
+ };
1743
+ const before = mtime();
1744
+ return new Promise((resolve) => {
1745
+ let proc;
1746
+ try {
1747
+ proc = pty.spawn(engine.bin(this.config), [...engine.extraArgs(this.config), ...engine.usageArgs(this.config, statusLineScript()), ...engine.usageProbeArgs(sessionId)], { name: 'xterm-256color', cols: 120, rows: 34, cwd, env: this.childEnv(null) });
1748
+ } catch {
1749
+ return resolve(false);
1750
+ }
1751
+ const started = Date.now();
1752
+ let wrote = null;
1753
+ let done = false;
1754
+ const finish = (ok) => {
1755
+ if (done) return;
1756
+ done = true;
1757
+ clearInterval(timer);
1758
+ try {
1759
+ proc.kill();
1760
+ } catch {}
1761
+ fs.rm(engine.sessionFile(cwd, sessionId), { force: true }, () => {});
1762
+ resolve(ok);
1763
+ };
1764
+ // The first reading can come as the reply starts; a moment more catches the one after it.
1765
+ const timer = setInterval(() => {
1766
+ if (!wrote && mtime() > before) wrote = Date.now();
1767
+ if (wrote && Date.now() - wrote >= settleMs) finish(true);
1768
+ else if (Date.now() - started > timeoutMs) finish(Boolean(wrote));
1769
+ }, 250);
1770
+ proc.onData(() => {});
1771
+ proc.onExit(() => finish(Boolean(wrote) || mtime() > before));
1772
+ });
1773
+ }
1774
+
1718
1775
  childEnv(agent) {
1719
- const env = { ...process.env, ...(agent ? { AGENTMGR_AGENT_ID: agent.id } : {}), TERM: 'xterm-256color', COLORTERM: 'truecolor', AGENTMGR_TERMINAL: '1' };
1776
+ 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
1777
  for (const key of STRIP_ENV) delete env[key];
1721
1778
  return env;
1722
1779
  }
@@ -2888,6 +2945,8 @@ export class AgentManager extends EventEmitter {
2888
2945
  const cursor = this.cursors.get(key) ?? { offset: 0 };
2889
2946
  this.cursors.set(key, cursor);
2890
2947
  const res = engine.scan(file, cursor, this.config.bugPatterns);
2948
+ // The engine's plan limits, when its log has them (usage.js).
2949
+ if (res.rateLimits) this.emit('usage', { engine: engine.id, ...res.rateLimits });
2891
2950
  const subMaps = engine.subagentFiles(sessionDir, session.id).map((sub) => {
2892
2951
  const c = this.cursors.get(sub) ?? { offset: 0 };
2893
2952
  this.cursors.set(sub, c);
@@ -3575,6 +3634,7 @@ export class AgentManager extends EventEmitter {
3575
3634
  if (prev && !prev.resumedAt && prev.text === found.text) return (rt.lastLimit = prev);
3576
3635
  const agent = this.store.get(id);
3577
3636
  if (agent) console.log(`[agentmgr] ${agent.name}: ${engineOf(agent).label} stopped at a limit (${found.text})${found.resetAt ? `; resets ${found.resetAt}` : ''}`);
3637
+ if (agent && found.kind === 'limit') this.emit('limit', { engine: engineOf(agent).id, text: found.text, resetAt: found.resetAt ?? null });
3578
3638
  return (rt.lastLimit = { ...found, at: new Date(t).toISOString(), resumedAt: null });
3579
3639
  }
3580
3640
 
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,24 @@ 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
+ probe: () => manager.readUsage(),
334
+ onChange: () => pushUsage(),
335
+ notify: async (text, plain) => {
336
+ const n = loadNotify();
337
+ if (!n.enabled || !n.events.usage) return;
338
+ await sendSlack(text, n, plain);
339
+ },
340
+ });
341
+ 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' }));
342
+ manager.on('limit', ({ engine, text, resetAt }) => usage.limited(engine, { text, resetAt }));
343
+ manager.plugins.api('usage', config).policy((action, details) => usage.policy(action, details));
344
+ usage.tick();
326
345
  // Runbooks for the support team, from a release ticket, an epic, or the code changes of a time frame (runbooks.js).
327
346
  const runbooks = new Runbooks({
328
347
  store,
@@ -1115,6 +1134,23 @@ export async function startServer({ port = PORT, host = HOST, evalTimer = true }
1115
1134
  api.post('/milestones/:project/reach', wrap((req) => milestones.reach(req.params.project, req.body?.stage, req.body?.reached !== false)));
1116
1135
  api.post('/milestones/:project/task', wrap((req) => milestones.task(req.params.project, req.body?.stage, req.body?.item)));
1117
1136
  // Plan → Decisions: the log (?project=<key>&q=<words>; ?format=markdown), one of your own, and removal.
1137
+ api.get('/usage', wrap(() => usage.view()));
1138
+ // A reading taken now (a one-word Claude Code session, so its status line reports).
1139
+ api.post('/usage/refresh', wrap(() => usage.refresh()));
1140
+ api.put('/usage', wrap((req) => {
1141
+ const b = req.body ?? {};
1142
+ const next = usage.update(b);
1143
+ const patch = { usage: next };
1144
+ // The engine new agents start on, when none is named.
1145
+ if (typeof b.engine === 'string') {
1146
+ if (!listEngines(config).some((e) => e.id === b.engine && e.installed)) throw fail(400, 'No such engine installed');
1147
+ config.engine = b.engine;
1148
+ patch.engine = b.engine;
1149
+ }
1150
+ saveConfig(patch);
1151
+ pushUsage();
1152
+ return usage.view();
1153
+ }));
1118
1154
  api.get('/runbooks', wrap(() => runbooks.list()));
1119
1155
  api.post('/runbooks', wrap((req) => runbooks.create(req.body ?? {})));
1120
1156
  api.get('/runbooks/:id', (req, res) => {
@@ -1532,6 +1568,7 @@ export async function startServer({ port = PORT, host = HOST, evalTimer = true }
1532
1568
  pushNews = () => broadcast({ t: 'news' });
1533
1569
  pushPlan = () => broadcast({ t: 'plan' });
1534
1570
  pushAdvisor = () => broadcast({ t: 'advisor' });
1571
+ pushUsage = () => broadcast({ t: 'usage' });
1535
1572
  reports.on('change', () => broadcast({ t: 'built', reports: reports.list() }));
1536
1573
  manager.rules.on('change', (rules) => broadcast({ t: 'rules', rules }));
1537
1574
  repeats.on('change', (view) => broadcast({ t: 'repeats', repeats: view }));
@@ -1674,6 +1711,7 @@ export async function startServer({ port = PORT, host = HOST, evalTimer = true }
1674
1711
  milestones.close();
1675
1712
  decisions.close();
1676
1713
  advisor.close();
1714
+ usage.close();
1677
1715
  debt.close();
1678
1716
  reviews.close();
1679
1717
  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,253 @@
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. These are numbers the engines already hand out on
10
+ // this computer; nothing else is asked of any service. "Read now" is the one thing that uses a
11
+ // model: a one-word session on Claude Code's smallest model, so there is a reply to report after.
12
+
13
+ import fs from 'node:fs';
14
+ import path from 'node:path';
15
+ import { fileURLToPath } from 'node:url';
16
+ import { paths } from './config.js';
17
+
18
+ export const USAGE_DEFAULTS = { enabled: true, warnAt: 80, holdAt: null };
19
+ export const usageFile = () => path.join(paths.home, 'usage', 'claude.json');
20
+ export const statusLineScript = () => path.join(path.dirname(fileURLToPath(import.meta.url)), 'statusline.js');
21
+ const STALE_MS = 6 * 3_600_000;
22
+ const err = (status, message) => Object.assign(new Error(message), { status });
23
+ const pct = (n) => (typeof n === 'number' && Number.isFinite(n) ? Math.max(0, Math.min(100, Math.round(n * 10) / 10)) : null);
24
+ const iso = (sec) => (typeof sec === 'number' && sec > 0 ? new Date(sec * 1000).toISOString() : null);
25
+
26
+ export function usageSettings(config = {}) {
27
+ const u = { ...USAGE_DEFAULTS, ...config.usage };
28
+ const level = (v) => (v === null || v === '' || v === undefined || v === 'off' ? null : Math.max(1, Math.min(100, Math.round(Number(v)) || 0)) || null);
29
+ return { enabled: u.enabled !== false, warnAt: level(u.warnAt), holdAt: level(u.holdAt) };
30
+ }
31
+
32
+ /** Claude Code's `rate_limits` (from its status line input) as windows. */
33
+ export function claudeWindows(limits) {
34
+ const out = [];
35
+ for (const [id, label] of [['five_hour', '5-hour session'], ['seven_day', 'Week']]) {
36
+ const used = pct(limits?.[id]?.used_percentage);
37
+ if (used !== null) out.push({ id, label, used, resetsAt: iso(limits[id].resets_at) });
38
+ }
39
+ return out;
40
+ }
41
+
42
+ /** Codex's `rate_limits` (from a token_count record of its session log, written at `at`) as windows. */
43
+ export function codexWindows(limits, at = Date.now()) {
44
+ const out = [];
45
+ for (const [id, fallback] of [['primary', '5-hour session'], ['secondary', 'Week']]) {
46
+ const w = limits?.[id];
47
+ const used = pct(w?.used_percent);
48
+ if (used === null) continue;
49
+ const min = Number(w.window_minutes) || null;
50
+ 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`;
51
+ const resetsAt = iso(w.resets_at) ?? (typeof w.resets_in_seconds === 'number' ? new Date(at + w.resets_in_seconds * 1000).toISOString() : null);
52
+ out.push({ id, label, used, resetsAt });
53
+ }
54
+ return out;
55
+ }
56
+
57
+ /** "in 2h 10m", "in 3 days", "now". */
58
+ export function untilWords(when, now = Date.now()) {
59
+ const ms = Date.parse(when) - now;
60
+ if (!(ms > 0)) return 'now';
61
+ const m = Math.round(ms / 60_000);
62
+ if (m < 60) return `in ${m}m`;
63
+ if (m < 48 * 60) return `in ${Math.floor(m / 60)}h${m % 60 ? ` ${m % 60}m` : ''}`;
64
+ return `in ${Math.round(m / 1440)} days`;
65
+ }
66
+
67
+ const NOTES = {
68
+ claude: 'Claude Code reports this for Pro, Max and Ultra plans, to sessions started here, once a session has had its first reply.',
69
+ codex: 'Read from Codex\'s session logs when Codex reports its limits (ChatGPT plans).',
70
+ };
71
+
72
+ export class EngineUsage {
73
+ /**
74
+ * `engines()`: the engines as listEngines gives them ({ id, label, installed }); `notify(text,
75
+ * plain)`: an alert; `store`: where the readings are kept between restarts; `probe()`: takes a
76
+ * reading of Claude Code's limits now (a short session), resolving true once it is written.
77
+ */
78
+ constructor({ store, config, engines, notify = null, probe = null, onChange = () => {}, file = usageFile(), now = () => Date.now(), log = (m) => console.log(`[agentmgr] ${m}`), timer = true }) {
79
+ Object.assign(this, { store, config, engines, notify, probe, onChange, file, now, log });
80
+ this.fileAt = null;
81
+ if (timer) {
82
+ this.timer = setInterval(() => this.tick(), 20_000);
83
+ this.timer.unref?.();
84
+ }
85
+ }
86
+
87
+ close() {
88
+ clearInterval(this.timer);
89
+ }
90
+
91
+ get settings() {
92
+ return usageSettings(this.config);
93
+ }
94
+
95
+ get state() {
96
+ const s = (this.store.data.usage ??= {});
97
+ s.engines ??= {};
98
+ s.alerted ??= {};
99
+ return s;
100
+ }
101
+
102
+ update(patch = {}) {
103
+ const next = { ...this.config.usage };
104
+ for (const k of ['warnAt', 'holdAt']) {
105
+ if (!(k in patch)) continue;
106
+ const v = patch[k];
107
+ if (v === null || v === '' || v === 'off') next[k] = null;
108
+ else if (!(Number(v) >= 1 && Number(v) <= 100)) throw err(400, `${k} must be 1 to 100, or off`);
109
+ else next[k] = Math.round(Number(v));
110
+ }
111
+ if ('enabled' in patch) next.enabled = patch.enabled !== false;
112
+ this.config.usage = next;
113
+ this.onChange();
114
+ return next;
115
+ }
116
+
117
+ /** A reading for an engine: its windows as they are at `at`. A window not in this reading keeps its last one. */
118
+ record(engineId, windows, { at = new Date(this.now()).toISOString(), source = null } = {}) {
119
+ if (!windows.length) return false;
120
+ const e = (this.state.engines[engineId] ??= { windows: {} });
121
+ if (e.at && at < e.at) return false; // an older log read late
122
+ let changed = false;
123
+ for (const w of windows) {
124
+ const prev = e.windows[w.id];
125
+ if (!prev || prev.used !== w.used || prev.resetsAt !== w.resetsAt) changed = true;
126
+ e.windows[w.id] = { id: w.id, label: w.label, used: w.used, resetsAt: w.resetsAt ?? null, at };
127
+ }
128
+ Object.assign(e, { at, source });
129
+ if (changed) {
130
+ this.store.save();
131
+ this.onChange();
132
+ this.alert(engineId);
133
+ }
134
+ return changed;
135
+ }
136
+
137
+ /** An agent on this engine stopped at a usage limit: used up until it resets. */
138
+ limited(engineId, { text, resetAt = null } = {}) {
139
+ const e = (this.state.engines[engineId] ??= { windows: {} });
140
+ if (e.limited?.text === text && e.limited?.until === resetAt) return;
141
+ e.limited = { text: String(text ?? '').slice(0, 200), until: resetAt, at: new Date(this.now()).toISOString() };
142
+ this.store.save();
143
+ this.onChange();
144
+ }
145
+
146
+ /** Claude Code's numbers, as its status line last wrote them. */
147
+ readClaude() {
148
+ let at;
149
+ try {
150
+ at = fs.statSync(this.file).mtimeMs;
151
+ } catch {
152
+ return false;
153
+ }
154
+ if (at === this.fileAt) return false;
155
+ this.fileAt = at;
156
+ try {
157
+ const d = JSON.parse(fs.readFileSync(this.file, 'utf8'));
158
+ return this.record('claude', claudeWindows(d.rate_limits), { at: d.at ?? new Date(at).toISOString(), source: `Claude Code${d.version ? ` ${d.version}` : ''}` });
159
+ } catch {
160
+ return false;
161
+ }
162
+ }
163
+
164
+ tick() {
165
+ if (!this.settings.enabled) return;
166
+ this.readClaude();
167
+ }
168
+
169
+ /**
170
+ * A reading taken now. Claude Code only gives its numbers to a session that has had a reply, so
171
+ * this starts a short one that says one word (the probe).
172
+ * One at a time: asked again meanwhile, it is the same reading.
173
+ */
174
+ refresh() {
175
+ return (this.refreshing ??= (async () => {
176
+ let fresh = false;
177
+ let problem = null;
178
+ try {
179
+ const claude = this.engines().find((d) => d.id === 'claude');
180
+ if (!this.settings.enabled) problem = 'Usage readings are switched off';
181
+ else if (!this.probe || !claude || claude.installed === false) problem = 'Claude Code is not installed here, and no other engine can be asked for a reading';
182
+ else {
183
+ fresh = await this.probe();
184
+ this.readClaude();
185
+ if (!fresh) problem = 'Claude Code gave no reading. It reports its limits for Pro, Max and Ultra plans, once signed in';
186
+ }
187
+ } catch (e) {
188
+ problem = e.message;
189
+ }
190
+ this.onChange();
191
+ return { ...this.view(), fresh, problem };
192
+ })().finally(() => (this.refreshing = null)));
193
+ }
194
+
195
+ /** One engine as it stands now: its windows with what is left, and how worried to be. */
196
+ engineView(def) {
197
+ const now = this.now();
198
+ const { warnAt, holdAt } = this.settings;
199
+ const e = this.state.engines[def.id] ?? { windows: {} };
200
+ const windows = Object.values(e.windows).map((w) => {
201
+ // Past its reset, the old number no longer holds: unknown until the next reading.
202
+ const reset = Boolean(w.resetsAt && Date.parse(w.resetsAt) <= now);
203
+ 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 };
204
+ });
205
+ 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;
206
+ const top = Math.max(-1, ...windows.filter((w) => w.used !== null).map((w) => w.used));
207
+ const level = limited ? 'limited' : top < 0 ? 'unknown' : holdAt && top >= holdAt ? 'held' : top >= 95 ? 'high' : warnAt && top >= warnAt ? 'warn' : 'ok';
208
+ 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.' };
209
+ }
210
+
211
+ view() {
212
+ const defs = this.engines();
213
+ const list = defs.filter((d) => d.installed !== false || this.state.engines[d.id]).map((d) => this.engineView(d));
214
+ 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) };
215
+ }
216
+
217
+ /** Near a limit, once per window and reset: an alert. */
218
+ alert(engineId) {
219
+ const { warnAt } = this.settings;
220
+ if (!warnAt) return;
221
+ const def = this.engines().find((d) => d.id === engineId) ?? { id: engineId, label: engineId };
222
+ const v = this.engineView(def);
223
+ for (const w of v.windows) {
224
+ if (w.used === null || w.used < warnAt) continue;
225
+ const key = `${engineId}:${w.id}:${w.resetsAt ?? ''}`;
226
+ if (this.state.alerted[key]) continue;
227
+ this.state.alerted[key] = new Date(this.now()).toISOString();
228
+ const keys = Object.keys(this.state.alerted);
229
+ for (const k of keys.slice(0, Math.max(0, keys.length - 50))) delete this.state.alerted[k];
230
+ this.store.save();
231
+ 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}` : ''}`;
232
+ this.log(words);
233
+ this.notify?.(`:hourglass_flowing_sand: *${words}*`, words)?.catch?.(() => {});
234
+ }
235
+ }
236
+
237
+ /** With "hold new work" set: no new agent on an engine at or past that much of a limit. */
238
+ policy(action, details) {
239
+ if (action !== 'agent.create') return undefined;
240
+ const { enabled, holdAt } = this.settings;
241
+ if (!enabled || !holdAt) return undefined;
242
+ const id = details.input?.engine ?? 'claude';
243
+ const def = this.engines().find((d) => d.id === id);
244
+ if (!def) return undefined;
245
+ const v = this.engineView(def);
246
+ const w = v.windows.filter((x) => x.used !== null && x.used >= holdAt).sort((a, b) => b.used - a.used)[0];
247
+ if (!w && !v.limited) return undefined;
248
+ 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})` : ''}`;
249
+ 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` };
250
+ }
251
+ }
252
+
253
+ const rank = (level) => ({ unknown: 0, ok: 1, warn: 2, high: 3, held: 4, limited: 5 }[level] ?? -1);