@point-seven-studio/jq-agents 0.0.0-stage → 0.1.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.
@@ -0,0 +1,722 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/cli.ts
4
+ import { spawn } from "child_process";
5
+ import { writeFileSync } from "fs";
6
+ import { createServer } from "http";
7
+
8
+ // src/collect.ts
9
+ import { execFile as execFile2 } from "child_process";
10
+ import { existsSync } from "fs";
11
+ import { open, readdir, stat } from "fs/promises";
12
+ import os2 from "os";
13
+ import path from "path";
14
+ import { promisify as promisify2 } from "util";
15
+
16
+ // src/agent-status.ts
17
+ var META_RECORD_TYPES = /* @__PURE__ */ new Set([
18
+ "last-prompt",
19
+ "pr-link",
20
+ "queue-operation",
21
+ "mode",
22
+ "ai-title",
23
+ "attachment",
24
+ "result",
25
+ "summary"
26
+ ]);
27
+ var LIVE_WITHIN_S = 15 * 60;
28
+ var IDLE_WITHIN_S = 2 * 60 * 60;
29
+ var QUESTION_MAX_CHARS = 400;
30
+ var REDACTIONS = [
31
+ // Connection strings carrying user:password@host (the real finding on this machine).
32
+ { name: "db-url", re: /\b(postgres(?:ql)?|mysql|mongodb(?:\+srv)?|redis|amqp):\/\/[^\s:@/]+:[^\s:@/]+@/gi },
33
+ // Real 3-segment JWTs only — header.payload.signature.
34
+ { name: "jwt", re: /\beyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{20,}\b/g },
35
+ { name: "stripe-key", re: /\b(sk|rk)_(live|test)_[A-Za-z0-9]{20,}\b/g },
36
+ { name: "openai-key", re: /\bsk-(?:proj-)?[A-Za-z0-9_-]{32,}\b/g },
37
+ { name: "gh-token", re: /\bgh[pousr]_[A-Za-z0-9]{30,}\b/g },
38
+ { name: "aws-akid", re: /\bAKIA[0-9A-Z]{16}\b/g },
39
+ { name: "supabase-key", re: /\bsb_(?:publishable|secret)_[A-Za-z0-9_-]{20,}\b/g },
40
+ {
41
+ name: "slack-token",
42
+ re: /\bxox[baprs]-[A-Za-z0-9-]{10,}\b/g
43
+ },
44
+ // KEY=… / TOKEN=… / SECRET=… / PASSWORD=… assignments with a realistic value.
45
+ { name: "env-assign", re: /\b([A-Z0-9_]*(?:KEY|TOKEN|SECRET|PASSWORD|PASSWD|CREDENTIAL)S?)\s*[=:]\s*["']?[^\s"']{12,}/g }
46
+ ];
47
+ function redactSecrets(text) {
48
+ let out = text;
49
+ let redacted = false;
50
+ for (const { name, re } of REDACTIONS) {
51
+ out = out.replace(re, (match) => {
52
+ redacted = true;
53
+ if (name === "env-assign") {
54
+ const varName = match.split(/[=:]/)[0].trim();
55
+ return `${varName}=[redacted]`;
56
+ }
57
+ return `[redacted:${name}]`;
58
+ });
59
+ }
60
+ return { text: out, redacted };
61
+ }
62
+ function messageText(rec) {
63
+ const content = rec.message?.content;
64
+ if (typeof content === "string") return content;
65
+ if (Array.isArray(content)) {
66
+ return content.filter(
67
+ (b) => !!b && typeof b === "object" && b.type === "text" && typeof b.text === "string"
68
+ ).map((b) => b.text).join("\n");
69
+ }
70
+ return "";
71
+ }
72
+ function endsWithQuestion(text) {
73
+ const tail = text.trimEnd().split("\n").filter((l) => l.trim()).slice(-3).join(" ");
74
+ if (/\?\s*$/.test(text.trimEnd())) return true;
75
+ return /\?/.test(tail);
76
+ }
77
+ function lastSubstantive(records) {
78
+ for (let i = records.length - 1; i >= 0; i--) {
79
+ const r = records[i];
80
+ if (!r?.type) continue;
81
+ if (META_RECORD_TYPES.has(r.type)) continue;
82
+ if (r.type === "assistant" || r.type === "user") return r;
83
+ }
84
+ return null;
85
+ }
86
+ function lastAssistant(records) {
87
+ for (let i = records.length - 1; i >= 0; i--) {
88
+ if (records[i]?.type === "assistant") return records[i];
89
+ }
90
+ return null;
91
+ }
92
+ function lastActivityAt(records) {
93
+ for (let i = records.length - 1; i >= 0; i--) {
94
+ const r = records[i];
95
+ if (!r?.timestamp || r.type && META_RECORD_TYPES.has(r.type)) continue;
96
+ return r.timestamp;
97
+ }
98
+ return null;
99
+ }
100
+ function deriveState(alive, lastActivityIso, now) {
101
+ if (!alive) return "dead";
102
+ if (!lastActivityIso) return "stale";
103
+ const ageS = Math.max(0, (now - Date.parse(lastActivityIso)) / 1e3);
104
+ if (ageS <= LIVE_WITHIN_S) return "live";
105
+ if (ageS <= IDLE_WITHIN_S) return "idle";
106
+ return "stale";
107
+ }
108
+ function deriveWaiting(rec, alive) {
109
+ if (!alive || !rec || rec.type !== "assistant") return false;
110
+ return rec.message?.stop_reason === "end_turn";
111
+ }
112
+ function deriveAttention(state, waiting) {
113
+ if (!waiting) return "none";
114
+ if (state === "live" || state === "idle") return "needs-you";
115
+ if (state === "stale") return "abandoned";
116
+ return "none";
117
+ }
118
+ function isTreeAllowed(workingTree, allowlist) {
119
+ if (!workingTree) return false;
120
+ return allowlist.some((t) => t && (workingTree === t || workingTree.startsWith(t.replace(/\/+$/, "") + "/")));
121
+ }
122
+ function buildStatusRow(opts) {
123
+ const { machine, records, sessionIdFallback, alive, pid, allowlist, now, workingTreeOverride } = opts;
124
+ const withCwd = [...records].reverse().find((r) => r?.cwd);
125
+ const workingTree = workingTreeOverride || withCwd?.cwd || "";
126
+ if (!workingTree) return null;
127
+ const sessionId = [...records].reverse().find((r) => r?.sessionId)?.sessionId || sessionIdFallback;
128
+ if (!sessionId) return null;
129
+ const branch = [...records].reverse().find((r) => r?.gitBranch)?.gitBranch || null;
130
+ const substantive = lastSubstantive(records);
131
+ const assistant = lastAssistant(records);
132
+ const activity = lastActivityAt(records);
133
+ const state = deriveState(alive, activity, now);
134
+ const waiting = deriveWaiting(substantive, alive);
135
+ const rawText = assistant ? messageText(assistant) : "";
136
+ const allowed = isTreeAllowed(workingTree, allowlist);
137
+ let blocked_question = null;
138
+ let question_redacted = false;
139
+ if (allowed && waiting && rawText.trim()) {
140
+ const { text, redacted } = redactSecrets(rawText.trim());
141
+ question_redacted = redacted;
142
+ blocked_question = text.length > QUESTION_MAX_CHARS ? text.slice(0, QUESTION_MAX_CHARS).trimEnd() + "\u2026" : text;
143
+ }
144
+ return {
145
+ machine,
146
+ product: workingTree.split("/").filter(Boolean).pop() || workingTree,
147
+ working_tree: workingTree,
148
+ branch,
149
+ session_id: sessionId,
150
+ pid,
151
+ state,
152
+ last_activity_at: activity,
153
+ waiting,
154
+ stop_reason: substantive?.type === "assistant" ? substantive.message?.stop_reason ?? null : null,
155
+ ends_with_question: rawText ? endsWithQuestion(rawText) : false,
156
+ blocked_question,
157
+ question_redacted,
158
+ question_allowed: allowed
159
+ };
160
+ }
161
+
162
+ // src/host-metrics.ts
163
+ function parsePs(stdout) {
164
+ const out = /* @__PURE__ */ new Map();
165
+ for (const line of stdout.split("\n")) {
166
+ const m = line.trim().match(/^(\d+)\s+([\d.]+)\s+(\d+)$/);
167
+ if (!m) continue;
168
+ out.set(Number(m[1]), { cpuPct: Number(m[2]), rssMb: Number(m[3]) / 1024 });
169
+ }
170
+ return out;
171
+ }
172
+ function parseNettop(stdout) {
173
+ const out = /* @__PURE__ */ new Map();
174
+ for (const line of stdout.split("\n")) {
175
+ const f = line.trim().split(/\s+/);
176
+ if (f.length < 4) continue;
177
+ const name = f[1];
178
+ if (!name || !name.includes(".")) continue;
179
+ const pid = Number(name.slice(name.lastIndexOf(".") + 1));
180
+ const bytesIn = Number(f[2]);
181
+ const bytesOut = Number(f[3]);
182
+ if (!Number.isInteger(pid) || pid <= 0) continue;
183
+ if (!Number.isFinite(bytesIn) || !Number.isFinite(bytesOut)) continue;
184
+ out.set(pid, { bytesIn, bytesOut });
185
+ }
186
+ return out;
187
+ }
188
+ function rateBps(prev, cur, seconds) {
189
+ if (prev == null || !Number.isFinite(prev) || seconds <= 0) return null;
190
+ if (cur < prev) return null;
191
+ return Math.round((cur - prev) / seconds);
192
+ }
193
+ function parseVmStat(stdout, memTotalBytes) {
194
+ const pageSize = Number(stdout.match(/page size of (\d+) bytes/)?.[1] || 0);
195
+ if (!pageSize || !memTotalBytes) return 0;
196
+ const pages = (label) => Number(stdout.match(new RegExp(`${label}:\\s+(\\d+)`))?.[1] || 0);
197
+ const used = (pages("Pages wired down") + pages("Pages active") + pages("Pages occupied by compressor")) * pageSize;
198
+ return Math.min(100, Math.round(used / memTotalBytes * 1e3) / 10);
199
+ }
200
+ function parseLoadAvg(stdout) {
201
+ return Number(stdout.replace(/[{}]/g, "").trim().split(/\s+/)[0] || 0);
202
+ }
203
+ function parseSwapUsedMb(stdout) {
204
+ const m = stdout.match(/used\s*=\s*([\d.]+)([MG])/);
205
+ if (!m) return 0;
206
+ const v = Number(m[1]);
207
+ return Math.round(m[2] === "G" ? v * 1024 : v);
208
+ }
209
+ function parseIostat(stdout) {
210
+ const rows = stdout.split("\n").map((l) => l.trim()).filter((l) => /^[\d.\s]+$/.test(l) && l.length > 0);
211
+ const last = rows[rows.length - 1];
212
+ if (!last) return null;
213
+ const f = last.split(/\s+/).map(Number);
214
+ let mbs = 0;
215
+ for (let i = 2; i < f.length; i += 3) if (Number.isFinite(f[i])) mbs += f[i];
216
+ if (!Number.isFinite(mbs)) return null;
217
+ return { readMbs: Math.round(mbs * 100) / 100, writeMbs: Math.round(mbs * 100) / 100 };
218
+ }
219
+ var THRESHOLDS = {
220
+ /** load per core above which the machine is genuinely contended */
221
+ loadPerCore: 1.5,
222
+ /** % of RAM in wired+active+compressed */
223
+ memUsedPct: 90,
224
+ /**
225
+ * Swap in use, MB. Paired with memUsedPct because on its own it is a WEAK
226
+ * signal, and this machine proves it: measured 23.9 GB of swap used on 16 GB
227
+ * of RAM while memory sat at 67% and the machine was responsive. macOS
228
+ * swapusage is close to cumulative — it reflects what has been paged out at
229
+ * some point, not what is being paged now — so a high figure alone says
230
+ * little about current pressure.
231
+ *
232
+ * The RIGHT current-pressure signal is the swapin/swapout RATE, which needs
233
+ * two vm_stat samples the way byte counters need two nettop samples. Until
234
+ * that exists, this stays conservative and deliberately under-reports: a
235
+ * false 'memory-bound' on a healthy machine would teach people to ignore the
236
+ * chip, which is the failure this whole feature is trying to avoid.
237
+ */
238
+ swapUsedMb: 1024,
239
+ /*
240
+ * NO DISK THRESHOLD — deliberately removed after it produced a wrong verdict
241
+ * against real data.
242
+ *
243
+ * First live sample on prod (2026-08-20) read disk 118 MB/s alongside
244
+ * 376ms ±378 to the API. It returned 'disk'. That is backwards: 376ms of
245
+ * latency with more jitter than latency is the thing costing that session
246
+ * time, while 118 MB/s on an NVMe drive that does multiple GB/s is a disk
247
+ * that is busy, not one that is saturated.
248
+ *
249
+ * The deeper problem is that throughput is the wrong measure entirely.
250
+ * Saturation is utilisation or queue wait — %util and await on Linux — and
251
+ * macOS iostat reports neither. There is no honest disk verdict to be had
252
+ * from the numbers available, so disk_read_mbs / disk_write_mbs are still
253
+ * sampled and still displayed for context, and they no longer vote.
254
+ *
255
+ * This is the rule that keeps the board trustworthy: a signal that cannot
256
+ * justify its verdict is reported, not ruled on.
257
+ */
258
+ /** TLS connect jitter, ms — variance hurts an agentic loop more than latency */
259
+ jitterMs: 60,
260
+ /** TLS connect time, ms */
261
+ rttMs: 400
262
+ };
263
+ function deriveBottleneck(host) {
264
+ if (!host.cpuCount) return { kind: "unknown", reason: null };
265
+ if (host.swapUsedMb > THRESHOLDS.swapUsedMb && host.memUsedPct > THRESHOLDS.memUsedPct) {
266
+ return {
267
+ kind: "memory",
268
+ reason: `${host.memUsedPct}% RAM in use, ${host.swapUsedMb}MB swapped`
269
+ };
270
+ }
271
+ const perCore = host.load1 / host.cpuCount;
272
+ if (perCore > THRESHOLDS.loadPerCore) {
273
+ return {
274
+ kind: "cpu",
275
+ reason: `load ${host.load1.toFixed(2)} across ${host.cpuCount} cores (${perCore.toFixed(1)}x)`
276
+ };
277
+ }
278
+ if (host.jitterMs != null && host.jitterMs > THRESHOLDS.jitterMs) {
279
+ return { kind: "network", reason: `${host.rttMs}ms \xB1${host.jitterMs} to the API` };
280
+ }
281
+ if (host.rttMs != null && host.rttMs > THRESHOLDS.rttMs) {
282
+ return { kind: "network", reason: `${host.rttMs}ms to the API` };
283
+ }
284
+ return { kind: "none", reason: null };
285
+ }
286
+
287
+ // src/host-sampler.ts
288
+ import { execFile } from "child_process";
289
+ import { promisify } from "util";
290
+ import os from "os";
291
+ var execFileAsync = promisify(execFile);
292
+ var PROBE_URL = "https://api.anthropic.com/";
293
+ async function run(cmd, args2, timeoutMs = 8e3) {
294
+ try {
295
+ const { stdout } = await execFileAsync(cmd, args2, { timeout: timeoutMs, maxBuffer: 8 * 1024 * 1024 });
296
+ return stdout;
297
+ } catch {
298
+ return "";
299
+ }
300
+ }
301
+ async function probeLatency() {
302
+ const samples = [];
303
+ for (let i = 0; i < 3; i++) {
304
+ const out = await run(
305
+ "curl",
306
+ ["-sS", "-o", "/dev/null", "-w", "%{time_connect}", "--max-time", "3", PROBE_URL],
307
+ 5e3
308
+ );
309
+ const t = Number(out);
310
+ if (Number.isFinite(t) && t > 0) samples.push(t * 1e3);
311
+ }
312
+ if (samples.length === 0) return { rttMs: null, jitterMs: null };
313
+ const mean = samples.reduce((a, b) => a + b, 0) / samples.length;
314
+ const variance = samples.length > 1 ? samples.reduce((a, b) => a + (b - mean) ** 2, 0) / (samples.length - 1) : 0;
315
+ return { rttMs: Math.round(mean), jitterMs: Math.round(Math.sqrt(variance)) };
316
+ }
317
+ async function sampleHost(probe = false) {
318
+ const [vmstat, swap, load, iostat, latency] = await Promise.all([
319
+ run("vm_stat", []),
320
+ run("sysctl", ["-n", "vm.swapusage"]),
321
+ run("sysctl", ["-n", "vm.loadavg"]),
322
+ // Two samples a second apart: the first row iostat prints is a since-boot
323
+ // average that never moves, so a single-shot call reads as a flat line.
324
+ run("iostat", ["-d", "-w", "1", "-c", "2"], 6e3),
325
+ probe ? probeLatency() : Promise.resolve({ rttMs: null, jitterMs: null })
326
+ ]);
327
+ const disk = parseIostat(iostat);
328
+ return {
329
+ cpuCount: os.cpus()?.length || 0,
330
+ load1: parseLoadAvg(load) || os.loadavg()[0] || 0,
331
+ memUsedPct: parseVmStat(vmstat, os.totalmem()),
332
+ swapUsedMb: parseSwapUsedMb(swap),
333
+ diskReadMbs: disk?.readMbs ?? null,
334
+ diskWriteMbs: disk?.writeMbs ?? null,
335
+ rttMs: latency.rttMs,
336
+ jitterMs: latency.jitterMs
337
+ };
338
+ }
339
+ async function sampleProcs(pids) {
340
+ if (pids.length === 0) return { procs: /* @__PURE__ */ new Map(), net: /* @__PURE__ */ new Map() };
341
+ const [ps, nettop] = await Promise.all([
342
+ run("ps", ["-o", "pid=,pcpu=,rss=", "-p", pids.join(",")]),
343
+ run("nettop", ["-P", "-x", "-l", "1"], 1e4)
344
+ ]);
345
+ const all = parseNettop(nettop);
346
+ const net = /* @__PURE__ */ new Map();
347
+ for (const pid of pids) {
348
+ const s = all.get(pid);
349
+ if (s) net.set(pid, s);
350
+ }
351
+ return { procs: parsePs(ps), net };
352
+ }
353
+
354
+ // src/collect.ts
355
+ var execFileAsync2 = promisify2(execFile2);
356
+ function defaultProjectsDir() {
357
+ return path.join(process.env.CLAUDE_CONFIG_DIR || path.join(os2.homedir(), ".claude"), "projects");
358
+ }
359
+ var TAIL_RECORDS = 60;
360
+ async function findTranscripts(dir, out = []) {
361
+ let entries;
362
+ try {
363
+ entries = await readdir(dir, { withFileTypes: true });
364
+ } catch {
365
+ return out;
366
+ }
367
+ for (const e of entries) {
368
+ const full = path.join(dir, e.name);
369
+ if (e.isDirectory()) await findTranscripts(full, out);
370
+ else if (e.isFile() && e.name.endsWith(".jsonl")) out.push(full);
371
+ }
372
+ return out;
373
+ }
374
+ var rootCache = /* @__PURE__ */ new Map();
375
+ async function repoRoot(dir) {
376
+ if (!dir) return dir;
377
+ const cached = rootCache.get(dir);
378
+ if (cached) return cached;
379
+ let cur = dir;
380
+ for (let i = 0; i < 12; i++) {
381
+ try {
382
+ await stat(path.join(cur, ".git"));
383
+ break;
384
+ } catch {
385
+ const parent = path.dirname(cur);
386
+ if (parent === cur) {
387
+ cur = dir;
388
+ break;
389
+ }
390
+ cur = parent;
391
+ }
392
+ }
393
+ rootCache.set(dir, cur);
394
+ return cur;
395
+ }
396
+ async function tailRecords(file, n = TAIL_RECORDS) {
397
+ const fh = await open(file, "r");
398
+ try {
399
+ const { size } = await fh.stat();
400
+ const chunk = 128 * 1024;
401
+ let pos = size;
402
+ let buf = Buffer.alloc(0);
403
+ while (pos > 0 && buf.toString("utf8").split("\n").length <= n + 1) {
404
+ const start = Math.max(0, pos - chunk);
405
+ const len = pos - start;
406
+ const b = Buffer.alloc(len);
407
+ await fh.read(b, 0, len, start);
408
+ buf = Buffer.concat([b, buf]);
409
+ pos = start;
410
+ if (buf.length > 8 * 1024 * 1024) break;
411
+ }
412
+ const recs = [];
413
+ for (const line of buf.toString("utf8").split("\n").filter((l) => l.trim()).slice(-n)) {
414
+ try {
415
+ recs.push(JSON.parse(line));
416
+ } catch {
417
+ }
418
+ }
419
+ return recs;
420
+ } finally {
421
+ await fh.close();
422
+ }
423
+ }
424
+ async function liveSessionPids(sockDir) {
425
+ let files = [];
426
+ try {
427
+ files = await readdir(sockDir);
428
+ } catch {
429
+ return [];
430
+ }
431
+ return files.filter((f) => f.endsWith(".sock")).map((f) => Number(f.replace(".sock", ""))).filter((p) => Number.isInteger(p) && p > 0).filter((pid) => {
432
+ try {
433
+ process.kill(pid, 0);
434
+ return true;
435
+ } catch {
436
+ return false;
437
+ }
438
+ });
439
+ }
440
+ async function pidCwds(pids) {
441
+ const byCwd = /* @__PURE__ */ new Map();
442
+ if (pids.length === 0) return byCwd;
443
+ try {
444
+ const lsof = existsSync("/usr/sbin/lsof") ? "/usr/sbin/lsof" : "lsof";
445
+ const { stdout } = await execFileAsync2(lsof, ["-a", "-p", pids.join(","), "-d", "cwd", "-Fn"], { maxBuffer: 4 * 1024 * 1024 });
446
+ let current = null;
447
+ for (const line of stdout.split("\n")) {
448
+ if (line.startsWith("p")) current = Number(line.slice(1));
449
+ else if (line.startsWith("n") && current) {
450
+ const cwd = await repoRoot(line.slice(1));
451
+ if (!byCwd.has(cwd)) byCwd.set(cwd, current);
452
+ }
453
+ }
454
+ } catch {
455
+ }
456
+ return byCwd;
457
+ }
458
+ async function collectRows(opts = {}) {
459
+ const now = opts.now ?? Date.now();
460
+ const machine = opts.machine ?? os2.hostname();
461
+ const files = await findTranscripts(opts.projectsDir ?? defaultProjectsDir());
462
+ const cwdToPid = await pidCwds(await liveSessionPids(opts.sockDir ?? "/tmp/cc-socks"));
463
+ const cutoff = now - (opts.maxAgeDays ?? 3) * 864e5;
464
+ const rows = [];
465
+ for (const file of files) {
466
+ try {
467
+ if ((await stat(file)).mtimeMs < cutoff) continue;
468
+ const records = await tailRecords(file);
469
+ if (records.length === 0) continue;
470
+ const rawCwd = [...records].reverse().find((r) => r?.cwd)?.cwd || "";
471
+ const tree = rawCwd ? await repoRoot(rawCwd) : "";
472
+ const pid = tree ? cwdToPid.get(tree) ?? null : null;
473
+ const row = buildStatusRow({
474
+ machine,
475
+ records,
476
+ workingTreeOverride: tree || void 0,
477
+ sessionIdFallback: path.basename(file, ".jsonl"),
478
+ alive: pid !== null,
479
+ pid,
480
+ allowlist: opts.questionTrees ?? [],
481
+ now
482
+ });
483
+ if (row) rows.push(row);
484
+ } catch {
485
+ }
486
+ }
487
+ const byKey = /* @__PURE__ */ new Map();
488
+ for (const r of rows) {
489
+ const prev = byKey.get(r.session_id);
490
+ if (!prev || (r.last_activity_at || "") > (prev.last_activity_at || "")) byKey.set(r.session_id, r);
491
+ }
492
+ return [...byKey.values()];
493
+ }
494
+ var prevNet = /* @__PURE__ */ new Map();
495
+ async function snapshot(opts = {}) {
496
+ const sessions = await collectRows(opts);
497
+ let host = null;
498
+ let bottleneck = null;
499
+ if (opts.sample !== false) {
500
+ try {
501
+ const pids = sessions.map((r) => r.pid).filter((p) => typeof p === "number");
502
+ const [h, proc] = await Promise.all([sampleHost(opts.probe === true), sampleProcs(pids)]);
503
+ const at = Date.now();
504
+ for (const row of sessions) {
505
+ if (row.pid == null) continue;
506
+ const p = proc.procs.get(row.pid);
507
+ if (p) {
508
+ row.cpu_pct = p.cpuPct;
509
+ row.rss_mb = Math.round(p.rssMb * 10) / 10;
510
+ }
511
+ const cur = proc.net.get(row.pid);
512
+ const prev = prevNet.get(row.pid);
513
+ if (cur && prev) {
514
+ const seconds = (at - prev.at) / 1e3;
515
+ row.net_rx_bps = rateBps(prev.sample.bytesIn, cur.bytesIn, seconds);
516
+ row.net_tx_bps = rateBps(prev.sample.bytesOut, cur.bytesOut, seconds);
517
+ }
518
+ }
519
+ prevNet = new Map([...proc.net].map(([pid, sample]) => [pid, { sample, at }]));
520
+ host = h;
521
+ bottleneck = deriveBottleneck(h);
522
+ } catch {
523
+ host = null;
524
+ bottleneck = null;
525
+ }
526
+ }
527
+ return { machine: opts.machine ?? os2.hostname(), generated_at: new Date(opts.now ?? Date.now()).toISOString(), sessions, host, bottleneck };
528
+ }
529
+
530
+ // src/page.ts
531
+ var esc = (s) => String(s ?? "").replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[c]);
532
+ function ago(iso, now) {
533
+ if (!iso) return "unknown";
534
+ const s = Math.max(0, Math.floor((now - Date.parse(iso)) / 1e3));
535
+ if (s < 60) return `${s}s`;
536
+ if (s < 3600) return `${Math.floor(s / 60)}m`;
537
+ if (s < 86400) return `${Math.floor(s / 3600)}h`;
538
+ return `${Math.floor(s / 86400)}d`;
539
+ }
540
+ function totals(rows) {
541
+ const attention = rows.map((r) => deriveAttention(r.state, r.waiting));
542
+ return {
543
+ sessions: rows.length,
544
+ live: rows.filter((r) => r.state === "live").length,
545
+ // Counted from the derived attention, never the raw waiting flag: a session
546
+ // that asked something days ago and was left is not waiting on you now.
547
+ needs_you: attention.filter((a) => a === "needs-you").length,
548
+ abandoned: attention.filter((a) => a === "abandoned").length,
549
+ trees: new Set(rows.map((r) => r.working_tree)).size
550
+ };
551
+ }
552
+ function groupByTree(rows) {
553
+ const by = /* @__PURE__ */ new Map();
554
+ for (const r of rows) by.set(r.working_tree, [...by.get(r.working_tree) ?? [], r]);
555
+ const needs = (list2) => list2.some((r) => deriveAttention(r.state, r.waiting) === "needs-you");
556
+ const latest = (list2) => list2.map((r) => r.last_activity_at || "").sort().pop() || "";
557
+ return [...by.entries()].map(([tree, list2]) => ({
558
+ tree,
559
+ product: list2[0].product,
560
+ rows: list2.sort((a, b) => (b.last_activity_at || "").localeCompare(a.last_activity_at || ""))
561
+ })).sort((a, b) => Number(needs(b.rows)) - Number(needs(a.rows)) || latest(b.rows).localeCompare(latest(a.rows)));
562
+ }
563
+ function sessionRow(r, now) {
564
+ const attention = deriveAttention(r.state, r.waiting);
565
+ const badge = attention === "needs-you" ? '<span class="b need">waiting on a person</span>' : attention === "abandoned" ? '<span class="b old">asked, then left</span>' : "";
566
+ const res = r.cpu_pct != null || r.rss_mb != null ? `<span class="mut">${r.cpu_pct ?? "?"}% cpu \xB7 ${r.rss_mb ?? "?"} MB</span>` : "";
567
+ const question = r.blocked_question ? `<pre>${esc(r.blocked_question)}${r.question_redacted ? "\n[a secret-shaped string was removed]" : ""}</pre>` : attention !== "none" && !r.question_allowed ? '<p class="mut q">Question text is off for this tree.</p>' : "";
568
+ return `<li><span class="s ${r.state}">${r.state}</span> <span class="mut">${esc(r.branch || "no branch")} \xB7 active ${ago(r.last_activity_at, now)} ago</span> ${badge} ${res}${question}</li>`;
569
+ }
570
+ function renderPage(snap, now = Date.now()) {
571
+ const t = totals(snap.sessions);
572
+ const b = snap.bottleneck;
573
+ const chip = !b ? '<p class="mut">Host not sampled.</p>' : b.kind === "none" ? "" : `<p class="chip">${b.kind === "unknown" ? "Could not tell what this machine is short of." : `Bottleneck: ${esc(b.kind)}${b.reason ? ` (${esc(b.reason)})` : ""}`}</p>`;
574
+ const trees = groupByTree(snap.sessions).map((g) => `<section class="card"><h2>${esc(g.product)} <span class="mut">${esc(g.tree)}</span></h2><ul>${g.rows.map((r) => sessionRow(r, now)).join("")}</ul></section>`).join("");
575
+ return `<!doctype html>
576
+ <html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
577
+ <title>JQ Agents</title>
578
+ <style>
579
+ :root{--bg:#f7f6f2;--card:#fff;--fg:#1d1c19;--mut:#6b675e;--line:#dedbd2;--well:#f1efe9;--need:#a1500a;--ok:#1f6b45;--bad:#a3262b}
580
+ @media (prefers-color-scheme:dark){:root{--bg:#161512;--card:#1f1e1a;--fg:#ece9e1;--mut:#a09c91;--line:#35332d;--well:#161512;--need:#e0a25a;--ok:#7ccba0;--bad:#ef8a8e}}
581
+ body{margin:0;background:var(--bg);color:var(--fg);font:15px/1.5 system-ui,sans-serif}
582
+ main{max-width:820px;margin:0 auto;padding:24px 16px 60px}
583
+ h1{font-size:24px;margin:0}h2{font-size:15px;margin:0;padding:10px 12px;word-break:break-all}
584
+ .mut{color:var(--mut);font-size:12px;font-weight:400}.tot{display:grid;grid-template-columns:repeat(4,1fr);gap:8px;margin:16px 0}
585
+ .tot div{background:var(--card);border:1px solid var(--line);border-radius:10px;padding:10px}.tot b{display:block;font-size:22px}
586
+ .card{background:var(--card);border:1px solid var(--line);border-radius:12px;margin:10px 0;overflow:hidden}
587
+ ul{list-style:none;margin:0;padding:0}li{border-top:1px solid var(--line);padding:8px 12px}
588
+ .s{font-size:11px;font-weight:700;text-transform:uppercase;border-radius:4px;padding:1px 6px;border:1px solid var(--line)}.s.live{color:var(--ok)}.s.dead{color:var(--mut)}
589
+ .b{font-size:12px;font-weight:600}.b.need{color:var(--need)}.b.old{color:var(--mut)}
590
+ .chip{border:1px solid var(--line);border-radius:8px;padding:6px 10px;font-size:13px}
591
+ pre{white-space:pre-wrap;word-break:break-word;background:var(--well);margin:8px 0 2px;padding:10px;border-radius:8px;font-size:12px}.q{margin:6px 0 0}
592
+ </style></head><body><main>
593
+ <h1>JQ Agents</h1>
594
+ <p class="mut">${esc(snap.machine)} \xB7 read ${esc(snap.generated_at)}. Refresh to read again. Read-only: answer a session where it is running.</p>
595
+ <div class="tot"><div><b>${t.needs_you}</b><span class="mut">waiting on a person</span></div><div><b>${t.abandoned}</b><span class="mut">asked, then left</span></div><div><b>${t.live}</b><span class="mut">live</span></div><div><b>${t.sessions}</b><span class="mut">sessions in ${t.trees} ${t.trees === 1 ? "tree" : "trees"}</span></div></div>
596
+ ${chip}
597
+ ${trees || '<p class="mut">No session has been active in the window read.</p>'}
598
+ </main></body></html>`;
599
+ }
600
+
601
+ // src/cli.ts
602
+ var DEFAULT_PORT = 4319;
603
+ var list = (s) => (s || "").split(",").map((x) => x.trim()).filter(Boolean);
604
+ function parseArgs(argv, env = {}) {
605
+ const a = {
606
+ json: false,
607
+ html: null,
608
+ watch: false,
609
+ exec: null,
610
+ intervalS: Number(env.JQ_AGENTS_INTERVAL_S) || 60,
611
+ port: DEFAULT_PORT,
612
+ probe: false,
613
+ sample: true,
614
+ questionTrees: list(env.JQ_AGENTS_QUESTION_TREES),
615
+ maxAgeDays: Number(env.JQ_AGENTS_MAX_AGE_DAYS) || 3
616
+ };
617
+ const value = (i, flag) => {
618
+ const v = argv[i + 1];
619
+ if (v === void 0 || v.startsWith("--")) throw new Error(`${flag} needs a value`);
620
+ return v;
621
+ };
622
+ for (let i = 0; i < argv.length; i++) {
623
+ const f = argv[i];
624
+ if (f === "--json") a.json = true;
625
+ else if (f === "--watch") a.watch = true;
626
+ else if (f === "--probe") a.probe = true;
627
+ else if (f === "--no-sample") a.sample = false;
628
+ else if (f === "--html") a.html = value(i++, f);
629
+ else if (f === "--exec") a.exec = value(i++, f);
630
+ else if (f === "--interval") a.intervalS = Number(value(i++, f));
631
+ else if (f === "--port") a.port = Number(value(i++, f));
632
+ else if (f === "--questions") a.questionTrees = list(value(i++, f));
633
+ else if (f === "--max-age-days") a.maxAgeDays = Number(value(i++, f));
634
+ else throw new Error(`unknown option: ${f}`);
635
+ }
636
+ if (!Number.isInteger(a.port) || a.port < 1 || a.port > 65535) throw new Error("--port needs a number from 1 to 65535");
637
+ if (!(a.intervalS >= 5)) throw new Error("--interval needs 5 seconds or more");
638
+ if (!(a.maxAgeDays > 0)) throw new Error("--max-age-days needs a number above 0");
639
+ if (a.watch && !a.exec) throw new Error("--watch needs --exec CMD (what should receive each snapshot?)");
640
+ if (a.exec && !a.watch && !a.json) throw new Error("--exec goes with --watch");
641
+ return a;
642
+ }
643
+ var collect = (a) => snapshot({ questionTrees: a.questionTrees, maxAgeDays: a.maxAgeDays, probe: a.probe, sample: a.sample });
644
+ function hand(cmd, snap) {
645
+ return new Promise((resolve) => {
646
+ const child = spawn(cmd, { shell: true, stdio: ["pipe", "inherit", "inherit"] });
647
+ child.on("error", () => resolve(127));
648
+ child.on("close", (code) => resolve(code ?? 1));
649
+ child.stdin.on("error", () => {
650
+ });
651
+ child.stdin.end(JSON.stringify(snap));
652
+ });
653
+ }
654
+ async function run2(argv) {
655
+ const a = parseArgs(argv, process.env);
656
+ if (a.watch) {
657
+ const tick = async () => {
658
+ try {
659
+ const snap = await collect(a);
660
+ const code = await hand(a.exec, snap);
661
+ const line = `jq-agents: ${snap.sessions.length} sessions handed to your command`;
662
+ if (code === 0) console.log(line);
663
+ else console.error(`${line}, which FAILED (exit ${code})`);
664
+ } catch (e) {
665
+ console.error("jq-agents: snapshot failed:", e?.message || e);
666
+ }
667
+ };
668
+ await tick();
669
+ console.log(`jq-agents: watching every ${a.intervalS}s (Ctrl-C to stop)`);
670
+ setInterval(tick, a.intervalS * 1e3);
671
+ return;
672
+ }
673
+ if (a.json) {
674
+ console.log(JSON.stringify(await collect(a), null, 2));
675
+ return;
676
+ }
677
+ if (a.html) {
678
+ writeFileSync(a.html, renderPage(await collect(a)));
679
+ console.log(`wrote ${a.html}`);
680
+ return;
681
+ }
682
+ createServer(async (_req, res) => {
683
+ try {
684
+ const page = renderPage(await collect(a));
685
+ res.writeHead(200, { "content-type": "text/html; charset=utf-8", "cache-control": "no-store" });
686
+ res.end(page);
687
+ } catch (e) {
688
+ res.writeHead(500, { "content-type": "text/plain; charset=utf-8" });
689
+ res.end(String(e?.message || e));
690
+ }
691
+ }).listen(a.port, "127.0.0.1", () => console.log(`jq-agents: http://127.0.0.1:${a.port} (Ctrl-C to stop)`));
692
+ }
693
+
694
+ // src/main.ts
695
+ var VERSION = true ? "0.1.1" : "dev";
696
+ var HELP = `JQ Agents ${VERSION}: what every Claude Code session on this machine is doing.
697
+
698
+ jq-agents open a board at http://127.0.0.1:${DEFAULT_PORT}
699
+ jq-agents --html FILE write the board to a file
700
+ jq-agents --json print one snapshot
701
+ jq-agents --watch --exec CMD every interval, pipe a snapshot (JSON) to CMD
702
+ --interval SECONDS for --watch (default 60)
703
+ jq-agents --questions DIR,DIR show the question a waiting session asked, for
704
+ sessions under these folders (default: none)
705
+ jq-agents --probe also time a connection to the API host
706
+ jq-agents --no-sample skip CPU, memory and network sampling
707
+ jq-agents --max-age-days N ignore sessions idle longer than this (default 3)
708
+ jq-agents --port NUMBER
709
+
710
+ It reads session transcripts under ~/.claude/projects and the process table. It is
711
+ read-only: it never writes into a session. Nothing leaves this machine unless you
712
+ pass --exec (your command gets the snapshot) or --probe (one timed connection).
713
+
714
+ Unofficial. Not affiliated with or endorsed by Anthropic.`;
715
+ var args = process.argv.slice(2);
716
+ if (args.includes("--help") || args.includes("-h")) console.log(HELP);
717
+ else if (args.includes("--version") || args.includes("-v")) console.log(VERSION);
718
+ else
719
+ run2(args).catch((error) => {
720
+ console.error(error.message || error);
721
+ process.exit(1);
722
+ });