ai-agentmanager 1.46.0 → 1.48.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/system.js ADDED
@@ -0,0 +1,239 @@
1
+ // OS: the computer the agents run on, and how loaded it is right now. The basics (name, system,
2
+ // processor, memory, disks, uptime), the load (processor, load average, memory, swap) with the last
3
+ // ten minutes of it, what each open agent session takes (its whole process tree), and the busiest
4
+ // processes. Read from the system itself with `ps` and the like; nothing is sent anywhere.
5
+
6
+ import { execFile } from 'node:child_process';
7
+ import fs from 'node:fs';
8
+ import os from 'node:os';
9
+ import path from 'node:path';
10
+
11
+ const SAMPLE_MS = 5000;
12
+ const KEEP = 120; // ten minutes of samples
13
+ const run = (cmd, args, timeout = 4000) =>
14
+ new Promise((resolve) => execFile(cmd, args, { timeout, maxBuffer: 8 * 1024 * 1024 }, (e, out) => resolve(e ? '' : String(out))));
15
+ const pct = (part, whole) => (whole > 0 ? Math.round((part / whole) * 1000) / 10 : 0);
16
+
17
+ /** Processor time so far, summed over the cores: { busy, total } in ms. */
18
+ export function cpuTimes(cpus = os.cpus()) {
19
+ let busy = 0;
20
+ let total = 0;
21
+ for (const c of cpus) {
22
+ const t = c.times;
23
+ const all = t.user + t.nice + t.sys + t.irq + t.idle;
24
+ total += all;
25
+ busy += all - t.idle;
26
+ }
27
+ return { busy, total };
28
+ }
29
+
30
+ /** `vm_stat` (macOS) as bytes: what is free or can be freed at once, and what is compressed. */
31
+ export function parseVmStat(text) {
32
+ const page = Number(text.match(/page size of (\d+) bytes/)?.[1] ?? 4096);
33
+ const n = (name) => Number(text.match(new RegExp(`^${name}:\\s+(\\d+)`, 'm'))?.[1] ?? 0) * page;
34
+ if (!/^Pages free:/m.test(text)) return null;
35
+ return {
36
+ available: n('Pages free') + n('Pages inactive') + n('Pages purgeable') + n('Pages speculative'),
37
+ wired: n('Pages wired down'),
38
+ compressed: n('Pages occupied by compressor'),
39
+ };
40
+ }
41
+
42
+ /** `/proc/meminfo` (Linux) as bytes. */
43
+ export function parseMeminfo(text) {
44
+ const n = (name) => {
45
+ const m = text.match(new RegExp(`^${name}:\\s+(\\d+)\\s*kB`, 'm'));
46
+ return m ? Number(m[1]) * 1024 : null;
47
+ };
48
+ const total = n('MemTotal');
49
+ if (total === null) return null;
50
+ const swapTotal = n('SwapTotal') ?? 0;
51
+ return { total, available: n('MemAvailable') ?? (n('MemFree') ?? 0) + (n('Buffers') ?? 0) + (n('Cached') ?? 0), swap: { total: swapTotal, used: swapTotal - (n('SwapFree') ?? 0) } };
52
+ }
53
+
54
+ /** `sysctl -n vm.swapusage` (macOS): "total = 2048.00M used = 1024.50M free = …". */
55
+ export function parseSwapUsage(text) {
56
+ const n = (name) => {
57
+ const m = text.match(new RegExp(`${name} = ([\\d.]+)([KMG])`));
58
+ return m ? Math.round(Number(m[1]) * { K: 1024, M: 1024 ** 2, G: 1024 ** 3 }[m[2]]) : null;
59
+ };
60
+ const total = n('total');
61
+ return total === null ? null : { total, used: n('used') ?? 0 };
62
+ }
63
+
64
+ /** `ps -Ao pid=,ppid=,pcpu=,rss=,comm=` as [{ pid, ppid, cpu (% of one core), mem (bytes), name, command }]. */
65
+ export function parsePs(text) {
66
+ const out = [];
67
+ for (const line of String(text).split('\n')) {
68
+ const m = line.match(/^\s*(\d+)\s+(\d+)\s+([\d.,]+)\s+(\d+)\s+(.+?)\s*$/);
69
+ if (!m) continue;
70
+ const command = m[5];
71
+ out.push({ pid: Number(m[1]), ppid: Number(m[2]), cpu: Number(m[3].replace(',', '.')) || 0, mem: Number(m[4]) * 1024, name: command.startsWith('/') ? path.basename(command) : command, command });
72
+ }
73
+ return out;
74
+ }
75
+
76
+ /** What a process and everything under it takes: { cpu, mem, count }. */
77
+ export function treeUsage(procs, rootPid) {
78
+ const kids = new Map();
79
+ for (const p of procs) kids.set(p.ppid, [...(kids.get(p.ppid) ?? []), p]);
80
+ const root = procs.find((p) => p.pid === rootPid);
81
+ if (!root) return null;
82
+ let cpu = 0;
83
+ let mem = 0;
84
+ let count = 0;
85
+ const seen = new Set();
86
+ for (const todo = [root]; todo.length; ) {
87
+ const p = todo.pop();
88
+ if (seen.has(p.pid)) continue;
89
+ seen.add(p.pid);
90
+ cpu += p.cpu;
91
+ mem += p.mem;
92
+ count++;
93
+ todo.push(...(kids.get(p.pid) ?? []));
94
+ }
95
+ return { cpu: Math.round(cpu * 10) / 10, mem, count };
96
+ }
97
+
98
+ /** How busy a computer is, in a word: load per core and memory in use decide it. */
99
+ export function loadLevel({ cpuPercent = 0, load1 = 0, cores = 1, memPercent = 0 } = {}) {
100
+ const perCore = load1 / Math.max(1, cores);
101
+ if (cpuPercent >= 90 || perCore >= 1.5 || memPercent >= 92) return 'heavy';
102
+ if (cpuPercent >= 60 || perCore >= 0.8 || memPercent >= 80) return 'busy';
103
+ return 'light';
104
+ }
105
+
106
+ /** "macOS 15.1", "Ubuntu 24.04.1 LTS", or what the system calls itself. */
107
+ async function osName() {
108
+ if (process.platform === 'darwin') {
109
+ const v = (await run('sw_vers', ['-productVersion'])).trim();
110
+ if (v) return `macOS ${v}`;
111
+ }
112
+ if (process.platform === 'linux') {
113
+ try {
114
+ const pretty = fs.readFileSync('/etc/os-release', 'utf8').match(/^PRETTY_NAME="?([^"\n]+)"?/m)?.[1];
115
+ if (pretty) return pretty;
116
+ } catch {}
117
+ }
118
+ return `${os.type()} ${os.release()}`;
119
+ }
120
+
121
+ async function memory() {
122
+ const total = os.totalmem();
123
+ let available = os.freemem();
124
+ let swap = null;
125
+ let compressed = null;
126
+ if (process.platform === 'darwin') {
127
+ const [vm, sw] = await Promise.all([run('vm_stat', []), run('sysctl', ['-n', 'vm.swapusage'])]);
128
+ const v = parseVmStat(vm);
129
+ if (v) ({ available, compressed } = v);
130
+ swap = parseSwapUsage(sw);
131
+ } else if (process.platform === 'linux') {
132
+ try {
133
+ const m = parseMeminfo(fs.readFileSync('/proc/meminfo', 'utf8'));
134
+ if (m) ({ available, swap } = m);
135
+ } catch {}
136
+ }
137
+ available = Math.min(total, Math.max(0, available));
138
+ return { total, available, used: total - available, percent: pct(total - available, total), compressed, swap: swap?.total ? { ...swap, percent: pct(swap.used, swap.total) } : null };
139
+ }
140
+
141
+ /** The disks behind the folders named, one row a disk: [{ label, path, total, free, used, percent }]. */
142
+ async function disks(folders) {
143
+ const out = [];
144
+ const seen = new Set();
145
+ for (const [label, dir] of folders) {
146
+ try {
147
+ const s = await fs.promises.statfs(dir);
148
+ const total = s.blocks * s.bsize;
149
+ const free = s.bavail * s.bsize;
150
+ const key = `${total}:${s.bfree}`;
151
+ if (!total || seen.has(key)) continue;
152
+ seen.add(key);
153
+ out.push({ label, path: dir, total, free, used: total - free, percent: pct(total - free, total) });
154
+ } catch {}
155
+ }
156
+ return out;
157
+ }
158
+
159
+ export class System {
160
+ /** `agents()` lists the agent records (id, name, pid of its open session); `folders()` the [label, dir] pairs whose disks to show. */
161
+ constructor({ agents = () => [], folders = () => [['Home', os.homedir()]], version = null, timer = true } = {}) {
162
+ Object.assign(this, { agents, folders, version });
163
+ this.history = [];
164
+ this.last = cpuTimes();
165
+ this.cpuPercent = 0;
166
+ this.started = Date.now();
167
+ if (timer) {
168
+ this.timer = setInterval(() => this.sample(), SAMPLE_MS);
169
+ this.timer.unref?.();
170
+ }
171
+ }
172
+
173
+ close() {
174
+ clearInterval(this.timer);
175
+ }
176
+
177
+ /** One more point of the last ten minutes: processor and memory in use. */
178
+ sample() {
179
+ const now = cpuTimes();
180
+ const total = now.total - this.last.total;
181
+ if (total > 0) this.cpuPercent = pct(now.busy - this.last.busy, total);
182
+ this.last = now;
183
+ this.history.push({ at: Date.now(), cpu: this.cpuPercent, mem: pct(os.totalmem() - os.freemem(), os.totalmem()), load: Math.round(os.loadavg()[0] * 100) / 100 });
184
+ if (this.history.length > KEEP) this.history.splice(0, this.history.length - KEEP);
185
+ }
186
+
187
+ async view() {
188
+ const cpus = os.cpus();
189
+ const cores = cpus.length || 1;
190
+ const [name, mem, disk, ps] = await Promise.all([(this.osName ??= osName()), memory(), disks(this.folders()), run('ps', ['-Ao', 'pid=,ppid=,pcpu=,rss=,comm='])]);
191
+ const procs = parsePs(ps);
192
+ // The memory in the history is the same measure as the one shown (what can't be freed at once).
193
+ if (this.history.length) this.history[this.history.length - 1].mem = mem.percent;
194
+ const load = os.loadavg().map((n) => Math.round(n * 100) / 100);
195
+ const sessions = this.agents()
196
+ .filter((a) => a.pid)
197
+ .map((a) => ({ id: a.id, name: a.name, pid: a.pid, ...(treeUsage(procs, a.pid) ?? { cpu: 0, mem: 0, count: 0 }) }))
198
+ .filter((a) => a.count)
199
+ .sort((x, y) => y.cpu - x.cpu || y.mem - x.mem);
200
+ const self = treeUsage(procs, process.pid);
201
+ const nets = Object.entries(os.networkInterfaces())
202
+ .flatMap(([nic, list]) => (list ?? []).filter((n) => !n.internal && n.family === 'IPv4').map((n) => ({ nic, address: n.address })));
203
+ return {
204
+ at: new Date().toISOString(),
205
+ level: loadLevel({ cpuPercent: this.cpuPercent, load1: load[0], cores, memPercent: mem.percent }),
206
+ host: {
207
+ name: os.hostname(),
208
+ os: name,
209
+ kernel: `${os.type()} ${os.release()}`,
210
+ arch: os.arch(),
211
+ uptime: Math.round(os.uptime()),
212
+ user: (() => {
213
+ try {
214
+ return os.userInfo().username;
215
+ } catch {
216
+ return null;
217
+ }
218
+ })(),
219
+ addresses: nets,
220
+ },
221
+ cpu: { model: cpus[0]?.model?.trim() || null, cores, percent: this.cpuPercent, load, loadPerCore: Math.round((load[0] / cores) * 100) / 100 },
222
+ memory: mem,
223
+ disks: disk,
224
+ app: { version: this.version, node: process.version, pid: process.pid, uptime: Math.round((Date.now() - this.started) / 1000), mem: process.memoryUsage().rss, cpu: self?.cpu ?? null },
225
+ agents: {
226
+ open: sessions.length,
227
+ cpu: Math.round(sessions.reduce((n, a) => n + a.cpu, 0) * 10) / 10,
228
+ mem: sessions.reduce((n, a) => n + a.mem, 0),
229
+ list: sessions,
230
+ },
231
+ processes: {
232
+ count: procs.length,
233
+ top: [...procs].sort((x, y) => y.cpu - x.cpu || y.mem - x.mem).slice(0, 12).map(({ pid, cpu, mem: m, name: n, command }) => ({ pid, cpu, mem: m, name: n, command })),
234
+ },
235
+ history: this.history,
236
+ sampleSeconds: SAMPLE_MS / 1000,
237
+ };
238
+ }
239
+ }
package/src/today.js CHANGED
@@ -68,7 +68,7 @@ const INBOX = {
68
68
  * The list: [{ id, kind, label, title, why, score, at, agentId?, url?, actionId?, issueKey?, reviewUrl? }],
69
69
  * most pressing first. Each source may be missing (turned off, or it couldn't be had).
70
70
  */
71
- export function todayItems({ inbox = [], issues = [], actions = [], reviews = [], findings = [], slower = [], unsure = [], now = new Date() } = {}) {
71
+ export function todayItems({ inbox = [], issues = [], actions = [], reviews = [], findings = [], slower = [], unsure = [], milestones = [], now = new Date() } = {}) {
72
72
  const items = [];
73
73
  // The issue each agent works on: named on its questions, and not listed twice.
74
74
  const issueOfAgent = new Map(issues.filter((r) => r.agent?.id).map((r) => [r.agent.id, r]));
@@ -141,6 +141,8 @@ export function todayItems({ inbox = [], issues = [], actions = [], reviews = []
141
141
  const why = `Micro benchmarks${r.agent && r.agent !== r.issue ? ` by ${r.agent}` : ''}${worst ? `: ${worst.name} ${worst.before} → ${worst.after}${worst.unit ? ` ${worst.unit}` : ''}` : ''}${worst?.note ? ` · its note: ${worst.note}` : ''}`;
142
142
  items.push({ id: `bench:${r.id}`, kind: 'bench', label: 'Slower', title, why, score: r.worst > 20 ? 27 : 36, at: r.at ?? null, agentId: r.agentId, runId: r.id, issueKey: r.issue ?? null });
143
143
  }
144
+ // A project's dates coming up, at risk or late (milestones.js), already scored.
145
+ items.push(...milestones);
144
146
  return items.sort((x, y) => x.score - y.score || String(y.at ?? '').localeCompare(String(x.at ?? '')));
145
147
  }
146
148