ai-agentmanager 1.49.0 → 1.51.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +15 -0
- package/README.md +28 -0
- package/package.json +1 -1
- package/public/app.js +11 -0
- package/public/index.html +7 -0
- package/public/keys.js +3 -2
- package/public/side.js +113 -52
- package/public/style.css +25 -1
- package/public/usage.js +118 -0
- package/src/brief.js +76 -1
- package/src/cli.js +49 -0
- package/src/config.js +2 -0
- package/src/engines/claude.js +5 -0
- package/src/engines/codex.js +3 -1
- package/src/manager.js +45 -3
- package/src/notify.js +1 -0
- package/src/rea.js +47 -0
- package/src/server.js +40 -0
- package/src/statusline.js +40 -0
- package/src/trust.js +10 -0
- package/src/usage.js +225 -0
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);
|