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