marmonitor 0.1.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.
Files changed (46) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +219 -0
  3. package/bin/marmonitor.js +2 -0
  4. package/dist/banner/index.d.ts +7 -0
  5. package/dist/banner/index.js +212 -0
  6. package/dist/cli.d.ts +1 -0
  7. package/dist/cli.js +855 -0
  8. package/dist/config/index.d.ts +105 -0
  9. package/dist/config/index.js +218 -0
  10. package/dist/guard/index.d.ts +23 -0
  11. package/dist/guard/index.js +128 -0
  12. package/dist/output/index.d.ts +28 -0
  13. package/dist/output/index.js +457 -0
  14. package/dist/output/utils.d.ts +138 -0
  15. package/dist/output/utils.js +588 -0
  16. package/dist/process-safety.d.ts +2 -0
  17. package/dist/process-safety.js +7 -0
  18. package/dist/scanner/bounded-map.d.ts +10 -0
  19. package/dist/scanner/bounded-map.js +25 -0
  20. package/dist/scanner/cache.d.ts +88 -0
  21. package/dist/scanner/cache.js +32 -0
  22. package/dist/scanner/claude.d.ts +25 -0
  23. package/dist/scanner/claude.js +425 -0
  24. package/dist/scanner/codex.d.ts +14 -0
  25. package/dist/scanner/codex.js +195 -0
  26. package/dist/scanner/gemini.d.ts +21 -0
  27. package/dist/scanner/gemini.js +131 -0
  28. package/dist/scanner/group.d.ts +7 -0
  29. package/dist/scanner/group.js +54 -0
  30. package/dist/scanner/index.d.ts +16 -0
  31. package/dist/scanner/index.js +256 -0
  32. package/dist/scanner/process.d.ts +17 -0
  33. package/dist/scanner/process.js +91 -0
  34. package/dist/scanner/status.d.ts +8 -0
  35. package/dist/scanner/status.js +45 -0
  36. package/dist/scanner/types.d.ts +6 -0
  37. package/dist/scanner/types.js +4 -0
  38. package/dist/tmux/index.d.ts +34 -0
  39. package/dist/tmux/index.js +166 -0
  40. package/dist/types.d.ts +55 -0
  41. package/dist/types.js +1 -0
  42. package/dist/version.d.ts +1 -0
  43. package/dist/version.js +1 -0
  44. package/docs/banner-ansi.png +0 -0
  45. package/docs/marmot-small.png +0 -0
  46. package/package.json +70 -0
@@ -0,0 +1,588 @@
1
+ /**
2
+ * Pure utility functions for marmonitor.
3
+ * Extracted for testability — no side effects, no I/O.
4
+ */
5
+ /** Shorten home directory path with ~ */
6
+ export function shortenPath(path, home) {
7
+ const h = home ?? process.env.HOME ?? "";
8
+ return path.startsWith(h) ? `~${path.slice(h.length)}` : path;
9
+ }
10
+ /** Format elapsed time from epoch seconds to human-readable */
11
+ export function formatElapsed(epochSec, now) {
12
+ if (!epochSec)
13
+ return "?";
14
+ const current = now ?? Date.now() / 1000;
15
+ const elapsed = current - epochSec;
16
+ if (elapsed < 0)
17
+ return "?";
18
+ if (elapsed < 60)
19
+ return `${Math.floor(elapsed)}s ago`;
20
+ if (elapsed < 3600)
21
+ return `${Math.floor(elapsed / 60)}m ago`;
22
+ if (elapsed < 86400)
23
+ return `${Math.floor(elapsed / 3600)}h ago`;
24
+ return `${Math.floor(elapsed / 86400)}d ago`;
25
+ }
26
+ /** Compact elapsed label for status bars/popups.
27
+ * e.g. 26s, 3m, 2h, 1d */
28
+ export function formatElapsedCompact(epochSec, now) {
29
+ if (!epochSec)
30
+ return undefined;
31
+ const current = now ?? Date.now() / 1000;
32
+ const elapsed = current - epochSec;
33
+ if (elapsed < 0)
34
+ return undefined;
35
+ if (elapsed < 60)
36
+ return `${Math.floor(elapsed)}s`;
37
+ if (elapsed < 3600)
38
+ return `${Math.floor(elapsed / 60)}m`;
39
+ if (elapsed < 86400)
40
+ return `${Math.floor(elapsed / 3600)}h`;
41
+ return `${Math.floor(elapsed / 86400)}d`;
42
+ }
43
+ /** Format token count (e.g. 1234 -> "1.2K", 1234567 -> "1.2M") */
44
+ export function formatTokens(n) {
45
+ if (n >= 1_000_000)
46
+ return `${(n / 1_000_000).toFixed(1)}M`;
47
+ if (n >= 1_000)
48
+ return `${(n / 1_000).toFixed(1)}K`;
49
+ return String(n);
50
+ }
51
+ /** Compact directory label for dock/focus display.
52
+ * Shows last 2 path segments to avoid basename collisions.
53
+ * e.g. "/Users/macrent/.ai/projects/mjjo" → "projects/mjjo"
54
+ * "/Users/macrent/Documents/valueofspace/vos-data-service" → "valueofspace/vos-data-service"
55
+ * "/Users/macrent/.ai/projects/vos" → "projects/vos" */
56
+ export function compactDirLabel(cwd) {
57
+ const parts = cwd.split("/").filter(Boolean);
58
+ if (parts.length <= 1)
59
+ return parts[0] || cwd;
60
+ return parts.slice(-2).join("/");
61
+ }
62
+ function truncateMiddle(value, maxLength) {
63
+ if (value.length <= maxLength)
64
+ return value;
65
+ if (maxLength <= 1)
66
+ return value.slice(0, maxLength);
67
+ if (maxLength <= 3)
68
+ return `${value.slice(0, maxLength - 1)}…`;
69
+ const head = Math.ceil((maxLength - 1) / 2);
70
+ const tail = Math.floor((maxLength - 1) / 2);
71
+ return `${value.slice(0, head)}…${value.slice(-tail)}`;
72
+ }
73
+ /** Compact directory label for narrow statusline surfaces.
74
+ * Preserves the last repo segment most aggressively and shortens parent first. */
75
+ export function compactStatuslineDirLabel(cwd, maxLength = 26) {
76
+ const label = compactDirLabel(cwd);
77
+ if (label.length <= maxLength)
78
+ return label;
79
+ const [parent, base] = label.split("/", 2);
80
+ if (!base)
81
+ return truncateMiddle(label, maxLength);
82
+ const parentLabel = parent.slice(0, 1);
83
+ const baseBudget = maxLength - parentLabel.length - 1;
84
+ return `${parentLabel}/${truncateMiddle(base, baseBudget)}`;
85
+ }
86
+ export function resolveStatuslineDetailLayout(width, maxCount) {
87
+ if (!width || width <= 0) {
88
+ return { itemCount: maxCount, pathMaxLength: 26 };
89
+ }
90
+ if (width < 70) {
91
+ return { itemCount: Math.min(maxCount, 1), pathMaxLength: 12 };
92
+ }
93
+ if (width < 90) {
94
+ return { itemCount: Math.min(maxCount, 2), pathMaxLength: 14 };
95
+ }
96
+ if (width < 120) {
97
+ return { itemCount: Math.min(maxCount, 3), pathMaxLength: 16 };
98
+ }
99
+ if (width < 150) {
100
+ return { itemCount: Math.min(maxCount, 4), pathMaxLength: 20 };
101
+ }
102
+ return { itemCount: maxCount, pathMaxLength: 26 };
103
+ }
104
+ /** Encode cwd to Claude project directory name.
105
+ * Claude Code replaces both "/" and "." with "-". */
106
+ export function cwdToProjectDirName(cwd) {
107
+ return cwd.replace(/[/.]/g, "-");
108
+ }
109
+ /** Determine agent status from CPU, elapsed time, and session match state */
110
+ export function determineStatus(cpuPercent, elapsedSec, sessionMatched, activeCpuThreshold, stalledAfterMin, phase, recentActivityActiveSec = 180) {
111
+ if (!sessionMatched)
112
+ return "Unmatched";
113
+ if (cpuPercent > activeCpuThreshold)
114
+ return "Active";
115
+ if ((phase === "thinking" || phase === "tool" || phase === "permission") &&
116
+ (elapsedSec === undefined || elapsedSec <= recentActivityActiveSec)) {
117
+ return "Active";
118
+ }
119
+ const stalledSec = stalledAfterMin * 60;
120
+ if (elapsedSec !== undefined && elapsedSec > stalledSec && cpuPercent < 0.1) {
121
+ return "Stalled";
122
+ }
123
+ return "Idle";
124
+ }
125
+ /** Select the most plausible Codex session for a process.
126
+ * Prefer exact cwd match, then nearest timestamp; otherwise most recent. */
127
+ export function selectCodexSession(processCwd, processStartTime, sessions) {
128
+ const cwdMatches = sessions.filter((session) => session.cwd === processCwd);
129
+ if (cwdMatches.length === 0)
130
+ return undefined;
131
+ if (cwdMatches.length === 1)
132
+ return cwdMatches[0];
133
+ const sorted = [...cwdMatches];
134
+ if (processStartTime !== undefined) {
135
+ sorted.sort((a, b) => Math.abs(a.timestamp - processStartTime) - Math.abs(b.timestamp - processStartTime));
136
+ }
137
+ else {
138
+ sorted.sort((a, b) => b.timestamp - a.timestamp);
139
+ }
140
+ return sorted[0];
141
+ }
142
+ /** Select unmatched processes that are eligible for cleanup. */
143
+ export function selectUnmatchedTargets(agents, selectedPids) {
144
+ const unmatched = agents.filter((agent) => agent.status === "Unmatched");
145
+ if (!selectedPids || selectedPids.length === 0) {
146
+ return unmatched.sort((a, b) => a.pid - b.pid);
147
+ }
148
+ const selected = new Set(selectedPids);
149
+ return unmatched.filter((agent) => selected.has(agent.pid)).sort((a, b) => a.pid - b.pid);
150
+ }
151
+ export function resolvePhaseWithDecay(currentPhase, cachedPhase, cachedDetectedAtMs, decay, nowMs = Date.now()) {
152
+ if (currentPhase)
153
+ return currentPhase;
154
+ if (!cachedPhase || cachedDetectedAtMs === undefined)
155
+ return undefined;
156
+ const decaySec = decay[cachedPhase];
157
+ if (decaySec === 0)
158
+ return cachedPhase;
159
+ if (nowMs - cachedDetectedAtMs <= decaySec * 1000)
160
+ return cachedPhase;
161
+ return undefined;
162
+ }
163
+ export function advanceJsonlCursor(previous, chunk, maxLines) {
164
+ const merged = previous.remainder + chunk;
165
+ const parts = merged.split("\n");
166
+ const remainder = parts.pop() ?? "";
167
+ const completeLines = parts.filter((line) => line.trim());
168
+ const recentLines = [...previous.recentLines, ...completeLines].slice(-maxLines);
169
+ return {
170
+ offset: previous.offset + Buffer.byteLength(chunk),
171
+ remainder,
172
+ recentLines,
173
+ };
174
+ }
175
+ export function detectApprovalPromptPhase(output, patterns = [
176
+ "would you like to",
177
+ "approve this",
178
+ "approve the following",
179
+ "confirm",
180
+ "confirmation required",
181
+ ], clearPatterns = [
182
+ "reading files",
183
+ "applying patch",
184
+ "running tests",
185
+ "running command",
186
+ "edited",
187
+ "changes applied",
188
+ ]) {
189
+ const recentLines = output
190
+ .split("\n")
191
+ .map((line) => line.trim())
192
+ .filter(Boolean)
193
+ .slice(-8);
194
+ if (recentLines.length === 0)
195
+ return undefined;
196
+ const recentMatchIndex = recentLines.findIndex((line) => {
197
+ const normalized = line.toLowerCase();
198
+ return patterns.some((pattern) => normalized.includes(pattern.toLowerCase()));
199
+ });
200
+ if (recentMatchIndex === -1)
201
+ return undefined;
202
+ const hasClearSignalAfterPrompt = recentLines.slice(recentMatchIndex + 1).some((line) => {
203
+ const normalized = line.toLowerCase();
204
+ return clearPatterns.some((pattern) => normalized.includes(pattern.toLowerCase()));
205
+ });
206
+ if (hasClearSignalAfterPrompt)
207
+ return undefined;
208
+ const hasApprovalChoices = recentLines.slice(recentMatchIndex + 1).some((line) => {
209
+ const normalized = line.toLowerCase();
210
+ return (normalized.includes("allow once") ||
211
+ normalized.includes("allow for this session") ||
212
+ normalized.includes("no, suggest changes") ||
213
+ normalized.includes("press 1") ||
214
+ normalized.includes("press 1-9") ||
215
+ /^\W*1\./.test(normalized));
216
+ });
217
+ if (hasApprovalChoices)
218
+ return "permission";
219
+ return recentMatchIndex >= recentLines.length - 3 ? "permission" : undefined;
220
+ }
221
+ export function updatePhaseHistory(previousPhase, previousHistory, nextPhase, at, maxEntries = 5) {
222
+ if (!nextPhase || nextPhase === previousPhase) {
223
+ return {
224
+ previousPhase,
225
+ history: previousHistory,
226
+ };
227
+ }
228
+ return {
229
+ previousPhase,
230
+ history: [...previousHistory, { phase: nextPhase, at }].slice(-maxEntries),
231
+ };
232
+ }
233
+ export function resolvePhaseFromHistory(currentPhase, history, nowMs = Date.now(), maxAgeMs = 10_000) {
234
+ if (currentPhase)
235
+ return currentPhase;
236
+ const last = history.at(-1);
237
+ if (!last)
238
+ return undefined;
239
+ if (nowMs - last.at > maxAgeMs)
240
+ return undefined;
241
+ return last.phase;
242
+ }
243
+ export function resolveSessionRegistryPath(registry, sessionId) {
244
+ return registry.get(sessionId)?.filePath;
245
+ }
246
+ export function upsertSessionRegistryEntry(registry, entry) {
247
+ registry.set(entry.sessionId, entry);
248
+ }
249
+ export function selectRecentSessionFile(candidates, nowMs = Date.now(), maxAgeMs = 72 * 60 * 60 * 1000, minLeadMs = 5 * 60 * 1000) {
250
+ if (candidates.length === 0)
251
+ return undefined;
252
+ const sorted = [...candidates].sort((a, b) => b.mtimeMs - a.mtimeMs);
253
+ const latest = sorted[0];
254
+ const second = sorted[1];
255
+ if (nowMs - latest.mtimeMs > maxAgeMs)
256
+ return undefined;
257
+ if (second && latest.mtimeMs - second.mtimeMs < minLeadMs)
258
+ return undefined;
259
+ return latest.path;
260
+ }
261
+ function agentShortName(agentName) {
262
+ if (agentName === "Claude Code")
263
+ return "Cl";
264
+ if (agentName === "Codex")
265
+ return "Cx";
266
+ if (agentName === "Gemini")
267
+ return "Gm";
268
+ return agentName;
269
+ }
270
+ function attentionPriority(agent) {
271
+ if (agent.phase === "permission")
272
+ return 0;
273
+ if (agent.phase === "thinking")
274
+ return 1;
275
+ return undefined;
276
+ }
277
+ function attentionKind(agent) {
278
+ if (agent.phase === "permission")
279
+ return "permission";
280
+ if (agent.phase === "thinking")
281
+ return "thinking";
282
+ if (agent.phase === "tool")
283
+ return "tool";
284
+ if (agent.status === "Dead" || agent.status === "Unmatched" || agent.status === "Stalled") {
285
+ return undefined;
286
+ }
287
+ return "active";
288
+ }
289
+ function attentionActivityTime(agent) {
290
+ return agent.lastActivityAt ?? agent.lastResponseAt ?? agent.startedAt ?? 0;
291
+ }
292
+ function orderedAttentionItems(items) {
293
+ const tier1Order = {
294
+ permission: 0,
295
+ thinking: 1,
296
+ };
297
+ return [...items].sort((a, b) => {
298
+ const aTier1 = tier1Order[a.kind];
299
+ const bTier1 = tier1Order[b.kind];
300
+ if (aTier1 !== undefined || bTier1 !== undefined) {
301
+ if (aTier1 === undefined)
302
+ return 1;
303
+ if (bTier1 === undefined)
304
+ return -1;
305
+ if (aTier1 !== bTier1)
306
+ return aTier1 - bTier1;
307
+ return attentionActivityTime(b) - attentionActivityTime(a);
308
+ }
309
+ return attentionActivityTime(b) - attentionActivityTime(a);
310
+ });
311
+ }
312
+ /** Build prioritized attention list for popup/jump UX.
313
+ * Order: permission -> thinking -> recently active alive sessions. */
314
+ export function buildAttentionItems(agents) {
315
+ const alive = agents.filter((agent) => agent.status !== "Dead" && agent.status !== "Unmatched" && agent.status !== "Stalled");
316
+ const toAttentionItem = (agent, priority, kind) => ({
317
+ kind,
318
+ priority,
319
+ pid: agent.pid,
320
+ agentName: agent.agentName,
321
+ cwd: agent.cwd,
322
+ cpuPercent: agent.cpuPercent,
323
+ memoryMb: agent.memoryMb,
324
+ startedAt: agent.startedAt,
325
+ runtimeSource: agent.runtimeSource,
326
+ status: agent.status,
327
+ phase: agent.phase,
328
+ lastResponseAt: agent.lastResponseAt,
329
+ lastActivityAt: agent.lastActivityAt,
330
+ });
331
+ const tier1 = alive
332
+ .filter((agent) => attentionPriority(agent) !== undefined)
333
+ .sort((a, b) => {
334
+ const aPriority = attentionPriority(a) ?? Number.MAX_SAFE_INTEGER;
335
+ const bPriority = attentionPriority(b) ?? Number.MAX_SAFE_INTEGER;
336
+ if (aPriority !== bPriority)
337
+ return aPriority - bPriority;
338
+ return attentionActivityTime(b) - attentionActivityTime(a);
339
+ })
340
+ .map((agent) => toAttentionItem(agent, attentionPriority(agent) ?? 0, attentionKind(agent) ?? "active"));
341
+ const tier1Pids = new Set(tier1.map((item) => item.pid));
342
+ const tier2 = alive
343
+ .filter((agent) => !tier1Pids.has(agent.pid))
344
+ .sort((a, b) => attentionActivityTime(b) - attentionActivityTime(a))
345
+ .map((agent) => toAttentionItem(agent, 2, attentionKind(agent) ?? "active"));
346
+ return [...tier1, ...tier2];
347
+ }
348
+ export function selectAttentionItem(agents, selection) {
349
+ if (!Number.isInteger(selection) || selection < 1)
350
+ return undefined;
351
+ return buildAttentionItems(agents)[selection - 1];
352
+ }
353
+ /** Build jumpable attention items for interactive navigation.
354
+ * Statusline/jump share the same top-of-mind ordering. */
355
+ export function buildJumpAttentionItems(agents) {
356
+ return orderedAttentionItems(buildAttentionItems(agents));
357
+ }
358
+ export function selectJumpAttentionItem(agents, selection) {
359
+ if (!Number.isInteger(selection) || selection < 1)
360
+ return undefined;
361
+ return buildJumpAttentionItems(agents)[selection - 1];
362
+ }
363
+ export function buildAttentionFocusText(items, maxCount = 3, width) {
364
+ if (maxCount <= 0 || items.length === 0)
365
+ return undefined;
366
+ const layout = resolveStatuslineDetailLayout(width, maxCount);
367
+ const detailItems = orderedAttentionItems(items)
368
+ .filter((item) => item.kind !== "unmatched" && item.kind !== "stalled")
369
+ .slice(0, layout.itemCount);
370
+ const segments = [];
371
+ for (const item of detailItems) {
372
+ const agent = agentShortName(item.agentName);
373
+ const path = compactStatuslineDirLabel(item.cwd, layout.pathMaxLength);
374
+ const time = formatElapsedCompact(item.lastActivityAt ?? item.lastResponseAt);
375
+ if (item.kind === "permission") {
376
+ segments.push(`⏳${agent} ${path} allow`);
377
+ }
378
+ else if (item.kind === "stalled") {
379
+ segments.push(time ? `⚠${agent} ${path} ${time}` : `⚠${agent} ${path}`);
380
+ }
381
+ else if (item.kind === "thinking") {
382
+ segments.push(time ? `🤔${agent} ${path} ${time}` : `🤔${agent} ${path}`);
383
+ }
384
+ else if (item.kind === "tool") {
385
+ segments.push(time ? `🔧${agent} ${path} ${time}` : `🔧${agent} ${path}`);
386
+ }
387
+ else if (item.kind === "active") {
388
+ segments.push(time ? `•${agent} ${path} ${time}` : `•${agent} ${path}`);
389
+ }
390
+ }
391
+ return segments.length > 0 ? segments.join(" │ ") : undefined;
392
+ }
393
+ export function buildTmuxBadgeSummary(snapshot) {
394
+ const agentBadges = [];
395
+ if ((snapshot.claudeCount ?? 0) > 0)
396
+ agentBadges.push(`Cl ${snapshot.claudeCount}`);
397
+ if ((snapshot.codexCount ?? 0) > 0)
398
+ agentBadges.push(`Cx ${snapshot.codexCount}`);
399
+ if ((snapshot.geminiCount ?? 0) > 0)
400
+ agentBadges.push(`Gm ${snapshot.geminiCount}`);
401
+ if (agentBadges.length === 0)
402
+ agentBadges.push(`AI ${snapshot.aliveCount}`);
403
+ const attentionBadges = [];
404
+ if (snapshot.waitingCount > 0)
405
+ attentionBadges.push(`⏳ ${snapshot.waitingCount}`);
406
+ if (snapshot.stalledCount + snapshot.unmatchedCount + snapshot.riskCount > 0) {
407
+ attentionBadges.push(`⚠ ${snapshot.stalledCount + snapshot.unmatchedCount + snapshot.riskCount}`);
408
+ }
409
+ if ((snapshot.thinkingCount ?? 0) > 0)
410
+ attentionBadges.push(`🤔 ${snapshot.thinkingCount}`);
411
+ if ((snapshot.toolCount ?? 0) > 0)
412
+ attentionBadges.push(`🔧 ${snapshot.toolCount}`);
413
+ if (attentionBadges.length === 0) {
414
+ attentionBadges.push(`✅ ${snapshot.activeCount}`);
415
+ }
416
+ return `${agentBadges.join(" ")} ${attentionBadges.join(" ")}`;
417
+ }
418
+ export function buildStatusPills(snapshot) {
419
+ const agents = [];
420
+ if ((snapshot.claudeCount ?? 0) > 0) {
421
+ agents.push({ label: `Cl ${snapshot.claudeCount}`, fg: "#1e1e2e", bg: "#fab387" });
422
+ }
423
+ if ((snapshot.codexCount ?? 0) > 0) {
424
+ agents.push({ label: `Cx ${snapshot.codexCount}`, fg: "#1e1e2e", bg: "#94e2d5" });
425
+ }
426
+ if ((snapshot.geminiCount ?? 0) > 0) {
427
+ agents.push({ label: `Gm ${snapshot.geminiCount}`, fg: "#1e1e2e", bg: "#89b4fa" });
428
+ }
429
+ if (agents.length === 0) {
430
+ agents.push({ label: `AI ${snapshot.aliveCount}`, fg: "#1e1e2e", bg: "#cba6f7" });
431
+ }
432
+ const alerts = [];
433
+ if (snapshot.waitingCount > 0) {
434
+ alerts.push({ label: `⏳ ${snapshot.waitingCount}`, fg: "#11111b", bg: "#f38ba8" });
435
+ }
436
+ if (snapshot.stalledCount + snapshot.unmatchedCount + snapshot.riskCount > 0) {
437
+ alerts.push({
438
+ label: `⚠ ${snapshot.stalledCount + snapshot.unmatchedCount + snapshot.riskCount}`,
439
+ fg: "#11111b",
440
+ bg: "#f9e2af",
441
+ });
442
+ }
443
+ if ((snapshot.thinkingCount ?? 0) > 0) {
444
+ alerts.push({ label: `🤔 ${snapshot.thinkingCount}`, fg: "#11111b", bg: "#cba6f7" });
445
+ }
446
+ if ((snapshot.toolCount ?? 0) > 0) {
447
+ alerts.push({ label: `🔧 ${snapshot.toolCount}`, fg: "#11111b", bg: "#a6e3a1" });
448
+ }
449
+ if (alerts.length === 0) {
450
+ alerts.push({ label: `✅ ${snapshot.activeCount}`, fg: "#11111b", bg: "#a6e3a1" });
451
+ }
452
+ return { agents, alerts };
453
+ }
454
+ /** Build one-line persistent-bar summary string. */
455
+ export function buildStatuslineSummary(snapshot, format = "compact") {
456
+ if (format === "tmux-badges" || format === "wezterm-pills") {
457
+ return buildTmuxBadgeSummary(snapshot);
458
+ }
459
+ const compactParts = [`AI${snapshot.aliveCount}`];
460
+ const standardParts = [`AI ${snapshot.aliveCount}`];
461
+ if (snapshot.waitingCount > 0) {
462
+ compactParts.push(`!${snapshot.waitingCount}`);
463
+ standardParts.push(`wait ${snapshot.waitingCount}`);
464
+ }
465
+ if (snapshot.riskCount > 0) {
466
+ compactParts.push(`R${snapshot.riskCount}`);
467
+ standardParts.push(`risk ${snapshot.riskCount}`);
468
+ }
469
+ if (snapshot.stalledCount > 0) {
470
+ compactParts.push(`S${snapshot.stalledCount}`);
471
+ standardParts.push(`stalled ${snapshot.stalledCount}`);
472
+ }
473
+ if (snapshot.unmatchedCount > 0) {
474
+ compactParts.push(`O${snapshot.unmatchedCount}`);
475
+ standardParts.push(`orphan ${snapshot.unmatchedCount}`);
476
+ }
477
+ if (format === "extended") {
478
+ if (snapshot.activeCount > 0)
479
+ standardParts.push(`active ${snapshot.activeCount}`);
480
+ if (snapshot.highCpuCount > 0)
481
+ standardParts.push(`hot ${snapshot.highCpuCount}`);
482
+ }
483
+ if (snapshot.waitingCount === 0 &&
484
+ snapshot.riskCount === 0 &&
485
+ snapshot.stalledCount === 0 &&
486
+ snapshot.unmatchedCount === 0) {
487
+ compactParts.push("ok");
488
+ standardParts.push("ok");
489
+ }
490
+ if (format === "compact") {
491
+ const metrics = [];
492
+ if (snapshot.cpuPercent !== undefined)
493
+ metrics.push(`${snapshot.cpuPercent.toFixed(0)}%`);
494
+ if (snapshot.memoryUsedGb !== undefined)
495
+ metrics.push(`${snapshot.memoryUsedGb}G`);
496
+ return metrics.length > 0
497
+ ? `${compactParts.join(" ")} | ${metrics.join(" ")}`
498
+ : compactParts.join(" ");
499
+ }
500
+ const metrics = [];
501
+ if (snapshot.cpuPercent !== undefined)
502
+ metrics.push(`CPU ${snapshot.cpuPercent.toFixed(0)}%`);
503
+ if (format === "extended" && snapshot.memoryUsedGb !== undefined) {
504
+ metrics.push(`MEM ${snapshot.memoryUsedGb}G`);
505
+ }
506
+ if (metrics.length > 0)
507
+ standardParts.push(...metrics);
508
+ return standardParts.join(" | ");
509
+ }
510
+ function tmuxPill(label, fg, bg) {
511
+ return `#[fg=${bg},bg=#1e1e2e]#[bold,fg=${fg},bg=${bg}] ${label} #[fg=${bg},bg=#1e1e2e]#[default]`;
512
+ }
513
+ function tmuxDetailBlock(label) {
514
+ return `#[fg=#cdd6f4,bg=#313244] ${label} #[fg=#313244,bg=#1e1e2e]#[default]`;
515
+ }
516
+ function attentionBg(kind) {
517
+ if (kind === "permission")
518
+ return "#f38ba8";
519
+ if (kind === "thinking")
520
+ return "#cba6f7";
521
+ if (kind === "tool")
522
+ return "#a6e3a1";
523
+ if (kind === "active")
524
+ return "#6ee7b7";
525
+ return "#f9e2af";
526
+ }
527
+ function tmuxAttentionSegment(index, kind, label) {
528
+ const bg = attentionBg(kind);
529
+ return `#[fg=${bg},bg=#1e1e2e]#[bold,fg=#11111b,bg=${bg}] ${index} #[fg=#313244,bg=${bg}]#[fg=#cdd6f4,bg=#313244] ${label} #[fg=#313244,bg=#1e1e2e]#[default]`;
530
+ }
531
+ export function buildTmuxBadgeBar(snapshot, focusText) {
532
+ const { agents, alerts } = buildStatusPills(snapshot);
533
+ const agentPills = agents.map((pill) => tmuxPill(pill.label, pill.fg, pill.bg));
534
+ const alertPills = alerts.map((pill) => tmuxPill(pill.label, pill.fg, pill.bg));
535
+ const focus = focusText ? `#[fg=#bac2de,bg=#181825] ${focusText} #[default]` : "";
536
+ return [agentPills.join(" "), alertPills.join(" "), focus].filter(Boolean).join(" ");
537
+ }
538
+ export function buildTmuxAttentionPills(items, maxCount = 5, width) {
539
+ if (maxCount <= 0)
540
+ return undefined;
541
+ const layout = resolveStatuslineDetailLayout(width, maxCount);
542
+ const jumpItems = orderedAttentionItems(items)
543
+ .filter((item) => item.kind !== "unmatched" && item.kind !== "stalled")
544
+ .slice(0, layout.itemCount);
545
+ if (jumpItems.length === 0) {
546
+ return tmuxDetailBlock("✅ all ok");
547
+ }
548
+ const segments = jumpItems.map((item, index) => {
549
+ const agent = agentShortName(item.agentName);
550
+ const path = compactStatuslineDirLabel(item.cwd, layout.pathMaxLength);
551
+ const time = formatElapsedCompact(item.lastActivityAt ?? item.lastResponseAt);
552
+ const label = item.kind === "permission"
553
+ ? `⏳${agent} ${path} allow`
554
+ : item.kind === "thinking"
555
+ ? time
556
+ ? `🤔${agent} ${path} ${time}`
557
+ : `🤔${agent} ${path}`
558
+ : item.kind === "tool"
559
+ ? time
560
+ ? `🔧${agent} ${path} ${time}`
561
+ : `🔧${agent} ${path}`
562
+ : item.kind === "active"
563
+ ? time
564
+ ? `•${agent} ${path} ${time}`
565
+ : `•${agent} ${path}`
566
+ : time
567
+ ? `⚠${agent} ${path} ${time}`
568
+ : `⚠${agent} ${path}`;
569
+ return tmuxAttentionSegment(index + 1, item.kind, label);
570
+ });
571
+ return segments.join(" ");
572
+ }
573
+ export function serializeWeztermPills(snapshot, focusText) {
574
+ const { agents, alerts } = buildStatusPills(snapshot);
575
+ const lines = [
576
+ ...agents.map((pill) => `agent\t${pill.label}\t${pill.fg}\t${pill.bg}`),
577
+ ...alerts.map((pill) => `alert\t${pill.label}\t${pill.fg}\t${pill.bg}`),
578
+ ];
579
+ if (focusText) {
580
+ for (const segment of focusText.split(" │ ")) {
581
+ const trimmed = segment.trim();
582
+ if (trimmed !== "") {
583
+ lines.push(`focus\t${trimmed}\t#bac2de\t#181825`);
584
+ }
585
+ }
586
+ }
587
+ return lines.join("\n");
588
+ }
@@ -0,0 +1,2 @@
1
+ export declare const TERMINAL_RESTORE_SEQUENCE = "\u001B[0m\u001B[?25h\u001B[?1049l";
2
+ export declare function formatProcessFailure(reason: unknown): string;
@@ -0,0 +1,7 @@
1
+ export const TERMINAL_RESTORE_SEQUENCE = "\x1b[0m\x1b[?25h\x1b[?1049l";
2
+ export function formatProcessFailure(reason) {
3
+ if (reason instanceof Error) {
4
+ return reason.stack ?? reason.message;
5
+ }
6
+ return String(reason);
7
+ }
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Size-limited Map with LRU-like eviction.
3
+ * When the map exceeds maxSize, the oldest (least recently set) entry is removed.
4
+ * Re-setting an existing key refreshes its position (moves to newest).
5
+ */
6
+ export declare class BoundedMap<K, V> extends Map<K, V> {
7
+ private readonly maxSize;
8
+ constructor(maxSize: number);
9
+ set(key: K, value: V): this;
10
+ }
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Size-limited Map with LRU-like eviction.
3
+ * When the map exceeds maxSize, the oldest (least recently set) entry is removed.
4
+ * Re-setting an existing key refreshes its position (moves to newest).
5
+ */
6
+ export class BoundedMap extends Map {
7
+ maxSize;
8
+ constructor(maxSize) {
9
+ super();
10
+ this.maxSize = maxSize;
11
+ }
12
+ set(key, value) {
13
+ // Re-set: delete first to refresh insertion order
14
+ if (this.has(key)) {
15
+ this.delete(key);
16
+ }
17
+ else if (this.size >= this.maxSize) {
18
+ // Evict oldest (first inserted) entry
19
+ const oldest = this.keys().next().value;
20
+ if (oldest !== undefined)
21
+ this.delete(oldest);
22
+ }
23
+ return super.set(key, value);
24
+ }
25
+ }