marmonitor 0.1.6 → 0.2.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/README.ko.md +248 -0
  2. package/README.md +41 -5
  3. package/bin/daemon.js +2 -0
  4. package/bin/postinstall.cjs +75 -0
  5. package/bin/preuninstall.cjs +14 -0
  6. package/dist/banner/index.js +15 -7
  7. package/dist/cli.js +297 -110
  8. package/dist/config/index.d.ts +2 -0
  9. package/dist/config/index.js +5 -3
  10. package/dist/output/badge-themes.d.ts +19 -0
  11. package/dist/output/badge-themes.js +52 -0
  12. package/dist/output/index.d.ts +5 -2
  13. package/dist/output/index.js +69 -22
  14. package/dist/output/utils.d.ts +23 -9
  15. package/dist/output/utils.js +85 -48
  16. package/dist/scanner/claude.d.ts +8 -1
  17. package/dist/scanner/claude.js +156 -19
  18. package/dist/scanner/codex-sqlite.d.ts +11 -0
  19. package/dist/scanner/codex-sqlite.js +50 -0
  20. package/dist/scanner/codex.d.ts +1 -1
  21. package/dist/scanner/codex.js +42 -2
  22. package/dist/scanner/concurrency.d.ts +5 -0
  23. package/dist/scanner/concurrency.js +22 -0
  24. package/dist/scanner/daemon-entry.d.ts +5 -0
  25. package/dist/scanner/daemon-entry.js +27 -0
  26. package/dist/scanner/daemon-loop.d.ts +13 -0
  27. package/dist/scanner/daemon-loop.js +77 -0
  28. package/dist/scanner/daemon-utils.d.ts +9 -0
  29. package/dist/scanner/daemon-utils.js +56 -0
  30. package/dist/scanner/gemini.js +3 -1
  31. package/dist/scanner/index.js +51 -10
  32. package/dist/scanner/perf.d.ts +8 -0
  33. package/dist/scanner/perf.js +26 -0
  34. package/dist/scanner/session-registry.d.ts +31 -0
  35. package/dist/scanner/session-registry.js +99 -0
  36. package/dist/scanner/session-tier.d.ts +6 -0
  37. package/dist/scanner/session-tier.js +22 -0
  38. package/dist/tmux/index.js +11 -0
  39. package/dist/tmux/jump-anchor.d.ts +25 -0
  40. package/dist/tmux/jump-anchor.js +100 -0
  41. package/dist/tmux/setup.d.ts +4 -0
  42. package/dist/tmux/setup.js +41 -1
  43. package/dist/tmux/status-click.d.ts +9 -0
  44. package/dist/tmux/status-click.js +19 -0
  45. package/package.json +2 -2
  46. package/bin/postinstall.js +0 -20
@@ -6,7 +6,7 @@
6
6
  * and determines activity status.
7
7
  */
8
8
  import { existsSync } from "node:fs";
9
- import { readFile, readdir } from "node:fs/promises";
9
+ import { readFile, readdir, stat } from "node:fs/promises";
10
10
  import { join } from "node:path";
11
11
  import pidusage from "pidusage";
12
12
  import psList from "ps-list";
@@ -14,12 +14,15 @@ export { detectAgentFromProcessSignature } from "./process.js";
14
14
  export { propagateWorkerStateToParent } from "./group.js";
15
15
  export { parseGeminiSessionContent } from "./gemini.js";
16
16
  // ─── Internal imports ─────────────────────────────────────────────
17
- import { sessionEnrichmentCache } from "./cache.js";
17
+ import { claudeSessionRegistry, sessionEnrichmentCache } from "./cache.js";
18
18
  import { detectClaudePhase, getClaudeSessionRoots, parseClaudeSession, parseClaudeTokens, } from "./claude.js";
19
19
  import { detectCodexPhase, indexCodexSessions, matchCodexSession } from "./codex.js";
20
+ import { promiseAllLimited } from "./concurrency.js";
20
21
  import { parseGeminiSession } from "./gemini.js";
21
22
  import { groupByParent } from "./group.js";
23
+ import { perfEnd, perfStart } from "./perf.js";
22
24
  import { detectAgentFromProcessSignature as _detectAgent, detectRuntimeSource, getProcessCwd, getProcessStartTime, } from "./process.js";
25
+ import { classifySessionTier } from "./session-tier.js";
23
26
  import { detectCliStdoutPhase, determineStatus } from "./status.js";
24
27
  // ─── Main Scanner ──────────────────────────────────────────────────
25
28
  /** Scan for all running AI agent sessions */
@@ -27,8 +30,11 @@ export async function scanAgents(config, options = {}) {
27
30
  const enrichmentMode = options.enrichmentMode ?? "full";
28
31
  const isFullEnrichment = enrichmentMode === "full";
29
32
  const seenPids = new Set();
33
+ perfStart("scanAgents");
30
34
  // 1. Find running processes
35
+ perfStart("ps-list");
31
36
  const processes = await psList();
37
+ perfEnd("ps-list");
32
38
  // Filter to agent processes
33
39
  const agentProcesses = [];
34
40
  for (const proc of processes) {
@@ -41,6 +47,7 @@ export async function scanAgents(config, options = {}) {
41
47
  agentProcesses.push({ proc, agentName });
42
48
  }
43
49
  // 2. Batch pidusage
50
+ perfStart("pidusage");
44
51
  const pids = agentProcesses.map((a) => a.proc.pid);
45
52
  let usageMap = {};
46
53
  try {
@@ -49,10 +56,13 @@ export async function scanAgents(config, options = {}) {
49
56
  catch {
50
57
  // some PIDs may have exited
51
58
  }
59
+ perfEnd("pidusage");
52
60
  // 3. Pre-index Codex sessions (once, shared across all Codex processes)
61
+ perfStart("codex-index");
53
62
  const codexSessions = isFullEnrichment ? await indexCodexSessions(config) : [];
54
- // 4. Build sessions with enrichment (parallel)
55
- const sessionPromises = agentProcesses.map(async ({ proc, agentName }) => {
63
+ perfEnd("codex-index");
64
+ // 4. Build sessions with enrichment (concurrency limited)
65
+ const sessionPromises = agentProcesses.map(({ proc, agentName }) => async () => {
56
66
  const usage = usageMap[proc.pid];
57
67
  const cpuPercent = usage ? Math.round(usage.cpu * 10) / 10 : 0;
58
68
  const memoryMb = usage ? Math.round((usage.memory / (1024 * 1024)) * 10) / 10 : 0;
@@ -72,7 +82,29 @@ export async function scanAgents(config, options = {}) {
72
82
  const runtimeSource = detectRuntimeSource(agentName, proc.cmd);
73
83
  const cacheKey = `${agentName}:${proc.pid}`;
74
84
  const cachedEnrichment = sessionEnrichmentCache.get(cacheKey);
75
- if (!isFullEnrichment && cachedEnrichment) {
85
+ // Determine session tier for differential enrichment
86
+ const tier = cachedEnrichment
87
+ ? classifySessionTier(cachedEnrichment.lastActivityAt, Date.now() / 1000, cpuPercent, cachedEnrichment.phase)
88
+ : "hot"; // no cache = first time seeing this session, treat as hot
89
+ // Cold session JSONL mtime check: detect activity without full enrichment
90
+ let coldPromoted = false;
91
+ if (tier === "cold" && cachedEnrichment?.sessionId && agentName === "Claude Code") {
92
+ const regEntry = claudeSessionRegistry.get(cachedEnrichment.sessionId);
93
+ if (regEntry?.filePath) {
94
+ try {
95
+ const fileStat = await stat(regEntry.filePath);
96
+ const cachedActivity = (cachedEnrichment.lastActivityAt ?? 0) * 1000;
97
+ if (fileStat.mtimeMs > cachedActivity + 1000) {
98
+ coldPromoted = true; // JSONL changed → force enrichment
99
+ }
100
+ }
101
+ catch {
102
+ // file gone or inaccessible — keep cold
103
+ }
104
+ }
105
+ }
106
+ const useCachedEnrichment = cachedEnrichment && !coldPromoted && (!isFullEnrichment || tier === "cold");
107
+ if (useCachedEnrichment) {
76
108
  if (cachedEnrichment.cwd)
77
109
  cwd = cachedEnrichment.cwd;
78
110
  sessionId = cachedEnrichment.sessionId;
@@ -84,14 +116,21 @@ export async function scanAgents(config, options = {}) {
84
116
  lastResponseAt = cachedEnrichment.lastResponseAt;
85
117
  lastActivityAt = cachedEnrichment.lastActivityAt;
86
118
  }
119
+ else if (!isFullEnrichment && !cachedEnrichment) {
120
+ // Light mode with no cache: skip expensive enrichment (lsof, JSONL, tmux)
121
+ sessionMatched = true;
122
+ }
87
123
  else if (agentName === "Claude Code") {
88
- const claudeData = await parseClaudeSession(proc.pid, config);
124
+ // Get cwd and start time early so mtime-based matching can use them
125
+ const processCwd = (await getProcessCwd(proc.pid)) ?? undefined;
126
+ const processStartTime = await getProcessStartTime(proc.pid);
127
+ const claudeData = await parseClaudeSession(proc.pid, processCwd, processStartTime, config);
89
128
  if (claudeData.cwd)
90
129
  cwd = claudeData.cwd;
91
130
  if (cwd === "unknown")
92
- cwd = (await getProcessCwd(proc.pid)) ?? "unknown";
131
+ cwd = processCwd ?? "unknown";
93
132
  sessionId = claudeData.sessionId;
94
- startedAt = claudeData.startedAt;
133
+ startedAt = claudeData.startedAt ?? processStartTime;
95
134
  tokenUsage = claudeData.tokenUsage;
96
135
  model = claudeData.model;
97
136
  sessionMatched = claudeData.sessionMatched ?? false;
@@ -145,7 +184,7 @@ export async function scanAgents(config, options = {}) {
145
184
  phase = (await detectCliStdoutPhase({ pid: proc.pid, cwd }, config)) ?? phase;
146
185
  }
147
186
  }
148
- if (cwd === "unknown") {
187
+ if (cwd === "unknown" && isFullEnrichment) {
149
188
  cwd = cachedEnrichment?.cwd ?? (await getProcessCwd(proc.pid)) ?? "unknown";
150
189
  }
151
190
  const statusBaseAt = lastActivityAt ?? lastResponseAt ?? startedAt;
@@ -185,7 +224,8 @@ export async function scanAgents(config, options = {}) {
185
224
  }
186
225
  return session;
187
226
  });
188
- const results = await Promise.all(sessionPromises);
227
+ const concurrencyLimit = isFullEnrichment ? 8 : 4;
228
+ const results = await promiseAllLimited(sessionPromises, concurrencyLimit);
189
229
  const sessions = results.filter((s) => s !== null);
190
230
  // 5. Check for dead sessions (Claude: session file exists but process gone)
191
231
  if (config.display.showDead) {
@@ -252,5 +292,6 @@ export async function scanAgents(config, options = {}) {
252
292
  return a.cwd.localeCompare(b.cwd);
253
293
  }
254
294
  });
295
+ perfEnd("scanAgents");
255
296
  return grouped;
256
297
  }
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Performance instrumentation for marmonitor.
3
+ * Enable with MARMONITOR_PERF=1 environment variable.
4
+ * Outputs timing to stderr so it doesn't interfere with statusline output.
5
+ */
6
+ export declare function perfStart(label: string): void;
7
+ export declare function perfEnd(label: string): number;
8
+ export declare function perfEnabled(): boolean;
@@ -0,0 +1,26 @@
1
+ /**
2
+ * Performance instrumentation for marmonitor.
3
+ * Enable with MARMONITOR_PERF=1 environment variable.
4
+ * Outputs timing to stderr so it doesn't interfere with statusline output.
5
+ */
6
+ const enabled = process.env.MARMONITOR_PERF === "1";
7
+ const timers = new Map();
8
+ export function perfStart(label) {
9
+ if (!enabled)
10
+ return;
11
+ timers.set(label, performance.now());
12
+ }
13
+ export function perfEnd(label) {
14
+ if (!enabled)
15
+ return 0;
16
+ const start = timers.get(label);
17
+ if (start === undefined)
18
+ return 0;
19
+ const elapsed = performance.now() - start;
20
+ timers.delete(label);
21
+ process.stderr.write(`[perf] ${label}: ${elapsed.toFixed(1)}ms\n`);
22
+ return elapsed;
23
+ }
24
+ export function perfEnabled() {
25
+ return enabled;
26
+ }
@@ -0,0 +1,31 @@
1
+ /**
2
+ * Session registry — tracks session lifecycle across PID/JSONL changes.
3
+ * Maps sessionId → session history with PID changes and token accumulation.
4
+ */
5
+ import type { AgentSession } from "../types.js";
6
+ export interface SessionRegistryRecord {
7
+ sessionId: string;
8
+ agent: string;
9
+ cwd: string;
10
+ history: Array<{
11
+ pid: number;
12
+ jsonlPath?: string;
13
+ startedAt: number;
14
+ endedAt?: number;
15
+ }>;
16
+ totalTokens: {
17
+ input: number;
18
+ output: number;
19
+ cache: number;
20
+ };
21
+ lastActivityAt?: number;
22
+ model?: string;
23
+ }
24
+ export declare function updateRegistry(registry: Map<string, SessionRegistryRecord>, agents: Partial<AgentSession>[]): void;
25
+ /**
26
+ * Remove sessions whose lastActivityAt is older than maxAgeDays.
27
+ * Returns the number of pruned entries.
28
+ */
29
+ export declare function pruneRegistry(registry: Map<string, SessionRegistryRecord>, maxAgeDays: number): number;
30
+ export declare function saveRegistryToFile(filePath: string, registry: Map<string, SessionRegistryRecord>): Promise<void>;
31
+ export declare function loadRegistryFromFile(filePath: string, registry: Map<string, SessionRegistryRecord>): Promise<void>;
@@ -0,0 +1,99 @@
1
+ /**
2
+ * Session registry — tracks session lifecycle across PID/JSONL changes.
3
+ * Maps sessionId → session history with PID changes and token accumulation.
4
+ */
5
+ import { mkdir, readFile, writeFile } from "node:fs/promises";
6
+ import { dirname } from "node:path";
7
+ export function updateRegistry(registry, agents) {
8
+ for (const agent of agents) {
9
+ if (!agent.sessionId)
10
+ continue;
11
+ const existing = registry.get(agent.sessionId);
12
+ if (existing) {
13
+ // Check if PID changed (resume)
14
+ const lastEntry = existing.history[existing.history.length - 1];
15
+ if (lastEntry && lastEntry.pid !== agent.pid) {
16
+ // Mark previous as ended
17
+ if (!lastEntry.endedAt)
18
+ lastEntry.endedAt = Math.floor(Date.now() / 1000);
19
+ // Add new PID to history
20
+ existing.history.push({
21
+ pid: agent.pid ?? 0,
22
+ startedAt: agent.startedAt ?? Math.floor(Date.now() / 1000),
23
+ });
24
+ }
25
+ // Update token totals
26
+ if (agent.tokenUsage) {
27
+ existing.totalTokens.input = agent.tokenUsage.inputTokens ?? 0;
28
+ existing.totalTokens.output = agent.tokenUsage.outputTokens ?? 0;
29
+ existing.totalTokens.cache = agent.tokenUsage.cacheReadTokens ?? 0;
30
+ }
31
+ if (agent.lastActivityAt)
32
+ existing.lastActivityAt = agent.lastActivityAt;
33
+ if (agent.model)
34
+ existing.model = agent.model;
35
+ if (agent.cwd)
36
+ existing.cwd = agent.cwd;
37
+ }
38
+ else {
39
+ // New session
40
+ registry.set(agent.sessionId, {
41
+ sessionId: agent.sessionId,
42
+ agent: agent.agentName ?? "unknown",
43
+ cwd: agent.cwd ?? "unknown",
44
+ history: [
45
+ {
46
+ pid: agent.pid ?? 0,
47
+ startedAt: agent.startedAt ?? Math.floor(Date.now() / 1000),
48
+ },
49
+ ],
50
+ totalTokens: {
51
+ input: agent.tokenUsage?.inputTokens ?? 0,
52
+ output: agent.tokenUsage?.outputTokens ?? 0,
53
+ cache: agent.tokenUsage?.cacheReadTokens ?? 0,
54
+ },
55
+ lastActivityAt: agent.lastActivityAt,
56
+ model: agent.model,
57
+ });
58
+ }
59
+ }
60
+ }
61
+ /**
62
+ * Remove sessions whose lastActivityAt is older than maxAgeDays.
63
+ * Returns the number of pruned entries.
64
+ */
65
+ export function pruneRegistry(registry, maxAgeDays) {
66
+ const cutoff = Math.floor(Date.now() / 1000) - maxAgeDays * 86400;
67
+ let pruned = 0;
68
+ for (const [key, record] of registry) {
69
+ if (record.lastActivityAt !== undefined && record.lastActivityAt < cutoff) {
70
+ registry.delete(key);
71
+ pruned++;
72
+ }
73
+ }
74
+ return pruned;
75
+ }
76
+ export async function saveRegistryToFile(filePath, registry) {
77
+ try {
78
+ await mkdir(dirname(filePath), { recursive: true });
79
+ const data = Object.fromEntries(registry.entries());
80
+ await writeFile(filePath, JSON.stringify(data, null, 2), "utf-8");
81
+ }
82
+ catch {
83
+ // registry save failures must never crash
84
+ }
85
+ }
86
+ export async function loadRegistryFromFile(filePath, registry) {
87
+ try {
88
+ const raw = await readFile(filePath, "utf-8");
89
+ const data = JSON.parse(raw);
90
+ if (typeof data === "object" && data !== null && !Array.isArray(data)) {
91
+ for (const [key, value] of Object.entries(data)) {
92
+ registry.set(key, value);
93
+ }
94
+ }
95
+ }
96
+ catch {
97
+ // missing or malformed file — start with empty registry
98
+ }
99
+ }
@@ -0,0 +1,6 @@
1
+ /**
2
+ * Session activity tier classification.
3
+ * Determines enrichment frequency based on how recently a session was active.
4
+ */
5
+ export type SessionTier = "hot" | "warm" | "cold";
6
+ export declare function classifySessionTier(lastActivityAt: number | undefined, nowSec: number, cpuPercent?: number, phase?: string): SessionTier;
@@ -0,0 +1,22 @@
1
+ /**
2
+ * Session activity tier classification.
3
+ * Determines enrichment frequency based on how recently a session was active.
4
+ */
5
+ const HOT_THRESHOLD_SEC = 120; // 2 minutes
6
+ const WARM_THRESHOLD_SEC = 600; // 10 minutes
7
+ const CPU_HOT_THRESHOLD = 1.0; // CPU% above this = always hot
8
+ const HOT_PHASES = new Set(["permission", "thinking", "tool"]);
9
+ export function classifySessionTier(lastActivityAt, nowSec, cpuPercent = 0, phase) {
10
+ if (cpuPercent >= CPU_HOT_THRESHOLD)
11
+ return "hot";
12
+ if (phase && HOT_PHASES.has(phase))
13
+ return "hot";
14
+ if (lastActivityAt === undefined)
15
+ return "cold";
16
+ const elapsed = nowSec - lastActivityAt;
17
+ if (elapsed <= HOT_THRESHOLD_SEC)
18
+ return "hot";
19
+ if (elapsed <= WARM_THRESHOLD_SEC)
20
+ return "warm";
21
+ return "cold";
22
+ }
@@ -1,5 +1,8 @@
1
1
  import { execFile } from "node:child_process";
2
+ import { tmpdir } from "node:os";
3
+ import { join } from "node:path";
2
4
  import { promisify } from "node:util";
5
+ import { getClientTty, getCurrentTmuxLocation, saveJumpAnchorIfMissing } from "./jump-anchor.js";
3
6
  const execFileAsync = promisify(execFile);
4
7
  export function parseTmuxPanes(raw) {
5
8
  return raw
@@ -137,7 +140,15 @@ export async function jumpToTmuxPane(target) {
137
140
  return false;
138
141
  }
139
142
  }
143
+ const ANCHOR_PATH = join(tmpdir(), "marmonitor", "jump-anchors.json");
140
144
  export async function jumpToAgent(agent) {
145
+ // Save current location as jump-back anchor before jumping
146
+ if (process.env.TMUX) {
147
+ const [tty, location] = await Promise.all([getClientTty(), getCurrentTmuxLocation()]);
148
+ if (tty && location) {
149
+ await saveJumpAnchorIfMissing(ANCHOR_PATH, tty, location).catch(() => { });
150
+ }
151
+ }
141
152
  const target = await resolveTmuxJumpTarget(agent);
142
153
  if (!target) {
143
154
  return {
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Jump-back anchor management.
3
+ * Saves the current tmux pane location before jumping, so the user can return.
4
+ */
5
+ export interface JumpAnchorLocation {
6
+ session: string;
7
+ window: string;
8
+ pane: string;
9
+ }
10
+ export interface JumpAnchor extends JumpAnchorLocation {
11
+ savedAt: number;
12
+ }
13
+ export declare function saveJumpAnchor(anchorPath: string, clientTty: string, location: JumpAnchorLocation): Promise<void>;
14
+ export declare function saveJumpAnchorIfMissing(anchorPath: string, clientTty: string, location: JumpAnchorLocation): Promise<boolean>;
15
+ export declare function loadJumpAnchor(anchorPath: string, clientTty: string): Promise<JumpAnchor | undefined>;
16
+ export declare function clearJumpAnchor(anchorPath: string, clientTty: string): Promise<boolean>;
17
+ /** Get the current tmux pane location for the active client */
18
+ export declare function getCurrentTmuxLocation(): Promise<JumpAnchorLocation | undefined>;
19
+ /** Get the client tty of the current tmux client */
20
+ export declare function getClientTty(): Promise<string | undefined>;
21
+ /** Jump back to a saved anchor location */
22
+ export declare function jumpBack(anchorPath: string, clientTty: string): Promise<{
23
+ success: boolean;
24
+ message: string;
25
+ }>;
@@ -0,0 +1,100 @@
1
+ /**
2
+ * Jump-back anchor management.
3
+ * Saves the current tmux pane location before jumping, so the user can return.
4
+ */
5
+ import { execFile } from "node:child_process";
6
+ import { mkdir, readFile, writeFile } from "node:fs/promises";
7
+ import { dirname } from "node:path";
8
+ import { promisify } from "node:util";
9
+ const execFileAsync = promisify(execFile);
10
+ async function readAnchors(anchorPath) {
11
+ try {
12
+ const raw = await readFile(anchorPath, "utf-8");
13
+ return JSON.parse(raw);
14
+ }
15
+ catch {
16
+ return {};
17
+ }
18
+ }
19
+ async function writeAnchors(anchorPath, anchors) {
20
+ await mkdir(dirname(anchorPath), { recursive: true });
21
+ await writeFile(anchorPath, JSON.stringify(anchors, null, 2), "utf-8");
22
+ }
23
+ export async function saveJumpAnchor(anchorPath, clientTty, location) {
24
+ const anchors = await readAnchors(anchorPath);
25
+ anchors[clientTty] = { ...location, savedAt: Date.now() };
26
+ await writeAnchors(anchorPath, anchors);
27
+ }
28
+ export async function saveJumpAnchorIfMissing(anchorPath, clientTty, location) {
29
+ const anchors = await readAnchors(anchorPath);
30
+ if (anchors[clientTty])
31
+ return false;
32
+ anchors[clientTty] = { ...location, savedAt: Date.now() };
33
+ await writeAnchors(anchorPath, anchors);
34
+ return true;
35
+ }
36
+ export async function loadJumpAnchor(anchorPath, clientTty) {
37
+ try {
38
+ const anchors = await readAnchors(anchorPath);
39
+ return anchors[clientTty] ?? undefined;
40
+ }
41
+ catch {
42
+ return undefined;
43
+ }
44
+ }
45
+ export async function clearJumpAnchor(anchorPath, clientTty) {
46
+ const anchors = await readAnchors(anchorPath);
47
+ if (!anchors[clientTty])
48
+ return false;
49
+ delete anchors[clientTty];
50
+ await writeAnchors(anchorPath, anchors);
51
+ return true;
52
+ }
53
+ /** Get the current tmux pane location for the active client */
54
+ export async function getCurrentTmuxLocation() {
55
+ try {
56
+ const { stdout } = await execFileAsync("tmux", [
57
+ "display-message",
58
+ "-p",
59
+ "#{session_name}\t#{window_index}\t#{session_name}:#{window_index}.#{pane_index}",
60
+ ]);
61
+ const [session, window, pane] = stdout.trim().split("\t");
62
+ if (session && window && pane)
63
+ return { session, window, pane };
64
+ return undefined;
65
+ }
66
+ catch {
67
+ return undefined;
68
+ }
69
+ }
70
+ /** Get the client tty of the current tmux client */
71
+ export async function getClientTty() {
72
+ try {
73
+ const { stdout } = await execFileAsync("tmux", ["display-message", "-p", "#{client_tty}"]);
74
+ const tty = stdout.trim();
75
+ return tty || undefined;
76
+ }
77
+ catch {
78
+ return undefined;
79
+ }
80
+ }
81
+ /** Jump back to a saved anchor location */
82
+ export async function jumpBack(anchorPath, clientTty) {
83
+ const anchor = await loadJumpAnchor(anchorPath, clientTty);
84
+ if (!anchor) {
85
+ return { success: false, message: "No jump-back anchor found." };
86
+ }
87
+ try {
88
+ const windowTarget = `${anchor.session}:${anchor.window}`;
89
+ if (process.env.TMUX) {
90
+ await execFileAsync("tmux", ["switch-client", "-t", windowTarget]);
91
+ }
92
+ await execFileAsync("tmux", ["select-window", "-t", windowTarget]);
93
+ await execFileAsync("tmux", ["select-pane", "-t", anchor.pane]);
94
+ await clearJumpAnchor(anchorPath, clientTty).catch(() => { });
95
+ return { success: true, message: `Jumped back to ${anchor.pane}.` };
96
+ }
97
+ catch {
98
+ return { success: false, message: `Failed to jump back to ${anchor.pane}.` };
99
+ }
100
+ }
@@ -2,6 +2,10 @@
2
2
  * tmux.conf plugin line management.
3
3
  * Adds/removes the marmonitor-tmux tpm plugin line.
4
4
  */
5
+ export type TmuxIntegrationMode = "local" | "tpm" | "missing" | "not_git";
6
+ export declare function getMarmonitorPluginDir(home?: string): string;
7
+ export declare function hasInstalledMarmonitorPlugin(pluginDir: string): Promise<boolean>;
8
+ export declare function detectTmuxIntegrationMode(confPath: string, pluginDir: string): Promise<TmuxIntegrationMode | undefined>;
5
9
  export declare function hasMarmonitorPlugin(confPath: string): Promise<boolean>;
6
10
  export declare function addMarmonitorPlugin(confPath: string): Promise<boolean>;
7
11
  export declare function removeMarmonitorPlugin(confPath: string): Promise<boolean>;
@@ -2,11 +2,51 @@
2
2
  * tmux.conf plugin line management.
3
3
  * Adds/removes the marmonitor-tmux tpm plugin line.
4
4
  */
5
- import { readFile, writeFile } from "node:fs/promises";
5
+ import { constants } from "node:fs";
6
+ import { access, readFile, writeFile } from "node:fs/promises";
7
+ import { homedir } from "node:os";
8
+ import { join } from "node:path";
6
9
  const PLUGIN_LINE = "set -g @plugin 'mjjo16/marmonitor-tmux'";
7
10
  function matchesPluginLine(line) {
8
11
  return line.trim() === PLUGIN_LINE;
9
12
  }
13
+ export function getMarmonitorPluginDir(home = homedir()) {
14
+ return join(home, ".tmux", "plugins", "marmonitor-tmux");
15
+ }
16
+ export async function hasInstalledMarmonitorPlugin(pluginDir) {
17
+ try {
18
+ await access(join(pluginDir, "marmonitor.tmux"), constants.F_OK);
19
+ return true;
20
+ }
21
+ catch {
22
+ return false;
23
+ }
24
+ }
25
+ export async function detectTmuxIntegrationMode(confPath, pluginDir) {
26
+ let content = "";
27
+ if (!(await hasInstalledMarmonitorPlugin(pluginDir))) {
28
+ try {
29
+ content = await readFile(confPath, "utf-8");
30
+ }
31
+ catch {
32
+ return undefined;
33
+ }
34
+ if (content.includes("marmonitor-tmux/marmonitor.tmux")) {
35
+ return "local";
36
+ }
37
+ if (content.split("\n").some(matchesPluginLine)) {
38
+ return "missing";
39
+ }
40
+ return undefined;
41
+ }
42
+ try {
43
+ await access(join(pluginDir, ".git"), constants.F_OK);
44
+ return "tpm";
45
+ }
46
+ catch {
47
+ return "not_git";
48
+ }
49
+ }
10
50
  export async function hasMarmonitorPlugin(confPath) {
11
51
  try {
12
52
  const content = await readFile(confPath, "utf-8");
@@ -0,0 +1,9 @@
1
+ import type { AgentSession } from "../types.js";
2
+ export type StatusClickAction = {
3
+ kind: "jump";
4
+ pid: number;
5
+ } | {
6
+ kind: "jump-back";
7
+ };
8
+ export declare function parseStatusClickToken(token?: string): StatusClickAction | undefined;
9
+ export declare function findClickedAgent(sessions: AgentSession[], action: StatusClickAction): AgentSession | undefined;
@@ -0,0 +1,19 @@
1
+ export function parseStatusClickToken(token) {
2
+ if (!token)
3
+ return undefined;
4
+ const trimmed = token.trim();
5
+ if (trimmed === "jump-back")
6
+ return { kind: "jump-back" };
7
+ const pidMatch = /^pid:(\d+)$/.exec(trimmed);
8
+ if (!pidMatch)
9
+ return undefined;
10
+ const pid = Number.parseInt(pidMatch[1] ?? "", 10);
11
+ if (!Number.isFinite(pid))
12
+ return undefined;
13
+ return { kind: "jump", pid };
14
+ }
15
+ export function findClickedAgent(sessions, action) {
16
+ if (action.kind !== "jump")
17
+ return undefined;
18
+ return sessions.find((session) => session.pid === action.pid);
19
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "marmonitor",
3
- "version": "0.1.6",
3
+ "version": "0.2.0",
4
4
  "author": "MJ JO <mjjo16@gmail.com>",
5
5
  "description": "tmux status bar monitor for AI coding agents — track Claude Code, Codex, Gemini sessions, tokens, and phases in real time",
6
6
  "type": "module",
@@ -48,7 +48,7 @@
48
48
  "start": "node bin/marmonitor.js",
49
49
  "lint": "biome check src tests",
50
50
  "test": "node --test tests/*.test.mjs",
51
- "postinstall": "node bin/postinstall.js",
51
+ "postinstall": "node bin/postinstall.cjs",
52
52
  "preuninstall": "node bin/preuninstall.cjs",
53
53
  "prepublishOnly": "npm run build && npm test"
54
54
  },
@@ -1,20 +0,0 @@
1
- #!/usr/bin/env node
2
-
3
- /**
4
- * postinstall script — show install banner + setup guide.
5
- * Runs after `npm install -g marmonitor`.
6
- *
7
- * npm postinstall runs with stdin as pipe (non-TTY),
8
- * so interactive prompts are not possible here.
9
- * Actual tmux setup is done via `marmonitor setup tmux`.
10
- */
11
-
12
- console.log("");
13
- console.log(" ✓ marmonitor installed");
14
- console.log(" Standing guard over your AI coding sessions");
15
- console.log("");
16
- console.log(" Quick start:");
17
- console.log(" $ marmonitor setup tmux — auto-configure tmux integration");
18
- console.log(" $ marmonitor status — show active AI sessions");
19
- console.log(" $ marmonitor help — all commands and shortcuts");
20
- console.log("");