marmonitor 0.2.4 → 0.2.5

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.
@@ -3,10 +3,35 @@
3
3
  */
4
4
  import { existsSync } from "node:fs";
5
5
  import { realpath as fsRealpath, open, readFile, readdir, stat } from "node:fs/promises";
6
- import { join } from "node:path";
6
+ import { basename, join } from "node:path";
7
7
  import { resolveRuntimeDataPaths } from "../config/index.js";
8
8
  import { advanceJsonlCursor, resolvePhaseFromHistory, resolvePhaseWithDecay, resolveSessionRegistryPath, selectRecentSessionFile, updatePhaseHistory, upsertSessionRegistryEntry, } from "../output/utils.js";
9
- import { CLAUDE_PHASE_RECENT_LINES, CLAUDE_SESSION_AMBIGUITY_GAP_SEC, CLAUDE_SESSION_MTIME_MATCH_SEC, HOME, claudePhaseCache, claudeProjectDirCache, claudeSessionRegistry, claudeTokenCache, } from "./cache.js";
9
+ import { CLAUDE_PHASE_RECENT_LINES, CLAUDE_SESSION_MTIME_MATCH_SEC, HOME, claudePhaseCache, claudeProjectDirCache, claudeSessionRegistry, claudeTokenCache, } from "./cache.js";
10
+ async function listClaudeSessionCandidates(projectDirName, projectRoots) {
11
+ const candidates = [];
12
+ for (const projectsDir of projectRoots) {
13
+ const projectDir = join(projectsDir, projectDirName);
14
+ if (!existsSync(projectDir))
15
+ continue;
16
+ const files = await readdir(projectDir);
17
+ for (const file of files) {
18
+ if (!file.endsWith(".jsonl"))
19
+ continue;
20
+ const candidatePath = join(projectDir, file);
21
+ try {
22
+ const fileStat = await stat(candidatePath);
23
+ candidates.push({ path: candidatePath, mtimeMs: fileStat.mtimeMs });
24
+ }
25
+ catch {
26
+ // skip candidate
27
+ }
28
+ }
29
+ }
30
+ return candidates;
31
+ }
32
+ function isDirectSessionFile(path, sessionId) {
33
+ return Boolean(path && basename(path) === `${sessionId}.jsonl`);
34
+ }
10
35
  export function getClaudeProjectRoots(config) {
11
36
  return config
12
37
  ? resolveRuntimeDataPaths(config).claudeProjects
@@ -79,6 +104,7 @@ export async function findClaudeProjectDir(cwd, sessionId, config) {
79
104
  cwd,
80
105
  firstSeenOffset: 0,
81
106
  source: "claude",
107
+ binding: "direct",
82
108
  });
83
109
  claudeProjectDirCache.set(cacheKey, dir);
84
110
  return dir;
@@ -93,12 +119,18 @@ export async function findClaudeProjectDir(cwd, sessionId, config) {
93
119
  return undefined;
94
120
  }
95
121
  export async function resolveClaudeSessionFile(sessionId, cwd, startedAt, config) {
96
- const registeredPath = resolveSessionRegistryPath(claudeSessionRegistry, sessionId);
97
- if (registeredPath && existsSync(registeredPath))
122
+ const registeredEntry = claudeSessionRegistry.get(sessionId);
123
+ const registeredPath = registeredEntry?.filePath;
124
+ if (registeredEntry?.binding === "direct" && registeredPath && existsSync(registeredPath)) {
98
125
  return registeredPath;
126
+ }
99
127
  const projectDirName = await findClaudeProjectDir(cwd, sessionId, config);
100
- if (!projectDirName)
128
+ if (!projectDirName) {
129
+ // No project dir found; fall back to mtime-matched registry entry if available
130
+ if (registeredPath && existsSync(registeredPath))
131
+ return registeredPath;
101
132
  return undefined;
133
+ }
102
134
  const projectRoots = getClaudeProjectRoots(config);
103
135
  for (const projectsDir of projectRoots) {
104
136
  const directPath = join(projectsDir, projectDirName, `${sessionId}.jsonl`);
@@ -110,80 +142,19 @@ export async function resolveClaudeSessionFile(sessionId, cwd, startedAt, config
110
142
  firstSeenOffset: 0,
111
143
  startedAt,
112
144
  source: "claude",
145
+ binding: "direct",
113
146
  });
114
147
  return directPath;
115
148
  }
116
149
  }
117
- if (!startedAt)
118
- return undefined;
119
- try {
120
- const candidates = [];
121
- for (const projectsDir of projectRoots) {
122
- const projectDir = join(projectsDir, projectDirName);
123
- if (!existsSync(projectDir))
124
- continue;
125
- const files = await readdir(projectDir);
126
- for (const file of files) {
127
- if (!file.endsWith(".jsonl"))
128
- continue;
129
- const candidatePath = join(projectDir, file);
130
- try {
131
- const fileStat = await stat(candidatePath);
132
- candidates.push({
133
- path: candidatePath,
134
- deltaSec: Math.abs(fileStat.mtimeMs / 1000 - startedAt),
135
- mtimeMs: fileStat.mtimeMs,
136
- });
137
- }
138
- catch {
139
- // skip candidate
140
- }
141
- }
142
- }
143
- candidates.sort((a, b) => a.deltaSec - b.deltaSec);
144
- const best = candidates[0];
145
- const second = candidates[1];
146
- if (!best || best.deltaSec > CLAUDE_SESSION_MTIME_MATCH_SEC) {
147
- const fallbackPath = selectRecentSessionFile(candidates);
148
- if (!fallbackPath)
149
- return undefined;
150
- upsertSessionRegistryEntry(claudeSessionRegistry, {
151
- filePath: fallbackPath,
152
- sessionId,
153
- cwd,
154
- firstSeenOffset: 0,
155
- startedAt,
156
- source: "claude",
157
- });
158
- return fallbackPath;
159
- }
160
- if (second && second.deltaSec - best.deltaSec < CLAUDE_SESSION_AMBIGUITY_GAP_SEC) {
161
- const fallbackPath = selectRecentSessionFile(candidates);
162
- if (!fallbackPath)
163
- return undefined;
164
- upsertSessionRegistryEntry(claudeSessionRegistry, {
165
- filePath: fallbackPath,
166
- sessionId,
167
- cwd,
168
- firstSeenOffset: 0,
169
- startedAt,
170
- source: "claude",
171
- });
172
- return fallbackPath;
173
- }
174
- upsertSessionRegistryEntry(claudeSessionRegistry, {
175
- filePath: best.path,
176
- sessionId,
177
- cwd,
178
- firstSeenOffset: 0,
179
- startedAt,
180
- source: "claude",
181
- });
182
- return best.path;
183
- }
184
- catch {
185
- return undefined;
150
+ // For a known sessionId, never guess another file by recency alone.
151
+ // Provisional registry entries are allowed only when they were already
152
+ // associated with this same session during an earlier match step.
153
+ if (registeredEntry?.binding === "provisional" && registeredPath && existsSync(registeredPath)) {
154
+ return registeredPath;
186
155
  }
156
+ void startedAt;
157
+ return undefined;
187
158
  }
188
159
  /** Parse Claude session JSONL for token usage (streaming, stops early for large files) */
189
160
  export async function parseClaudeTokens(sessionId, cwd, startedAt, config) {
@@ -200,6 +171,7 @@ export async function parseClaudeTokens(sessionId, cwd, startedAt, config) {
200
171
  let outputTokens = cached?.result.tokenUsage?.outputTokens ?? 0;
201
172
  let cacheCreationTokens = cached?.result.tokenUsage?.cacheCreationTokens ?? 0;
202
173
  let cacheReadTokens = cached?.result.tokenUsage?.cacheReadTokens ?? 0;
174
+ let lastInputTokens = cached?.result.tokenUsage?.lastInputTokens;
203
175
  let model = cached?.result.model;
204
176
  let raw;
205
177
  if (cached && fileStat.size > cached.size) {
@@ -216,6 +188,7 @@ export async function parseClaudeTokens(sessionId, cwd, startedAt, config) {
216
188
  outputTokens = 0;
217
189
  cacheCreationTokens = 0;
218
190
  cacheReadTokens = 0;
191
+ lastInputTokens = undefined;
219
192
  model = undefined;
220
193
  }
221
194
  const lines = raw.split("\n").filter((line) => line.trim());
@@ -229,6 +202,10 @@ export async function parseClaudeTokens(sessionId, cwd, startedAt, config) {
229
202
  outputTokens += usage.output_tokens ?? 0;
230
203
  cacheCreationTokens += usage.cache_creation_input_tokens ?? 0;
231
204
  cacheReadTokens += usage.cache_read_input_tokens ?? 0;
205
+ // Track most recent call's input_tokens for context % calculation
206
+ if (usage.input_tokens != null) {
207
+ lastInputTokens = usage.input_tokens;
208
+ }
232
209
  if (entry?.message?.model)
233
210
  model = entry.message.model;
234
211
  }
@@ -245,6 +222,7 @@ export async function parseClaudeTokens(sessionId, cwd, startedAt, config) {
245
222
  cacheCreationTokens,
246
223
  cacheReadTokens,
247
224
  totalTokens: inputTokens + outputTokens,
225
+ lastInputTokens,
248
226
  },
249
227
  model,
250
228
  };
@@ -398,16 +376,40 @@ export async function detectClaudePhase(sessionId, cwd, startedAt, config) {
398
376
  * Read the first line of a JSONL file to extract session metadata.
399
377
  * Returns undefined if the file can't be read or parsed.
400
378
  */
401
- async function readJsonlFirstLine(filePath) {
379
+ async function readJsonlSessionMeta(filePath) {
402
380
  let fd;
403
381
  try {
404
382
  fd = await open(filePath, "r");
405
383
  const buf = Buffer.alloc(4096);
406
384
  await fd.read(buf, 0, 4096, 0);
407
- const firstLine = buf.toString("utf-8").split("\n")[0];
408
- if (!firstLine)
409
- return undefined;
410
- return JSON.parse(firstLine);
385
+ const lines = buf
386
+ .toString("utf-8")
387
+ .split("\n")
388
+ .map((line) => line.trim())
389
+ .filter(Boolean)
390
+ .slice(0, 8);
391
+ const meta = {};
392
+ for (const line of lines) {
393
+ try {
394
+ const entry = JSON.parse(line);
395
+ if (!meta.sessionId && typeof entry?.sessionId === "string")
396
+ meta.sessionId = entry.sessionId;
397
+ if (!meta.cwd && typeof entry?.cwd === "string")
398
+ meta.cwd = entry.cwd;
399
+ if (!meta.timestamp) {
400
+ if (typeof entry?.timestamp === "string")
401
+ meta.timestamp = entry.timestamp;
402
+ else if (typeof entry?.snapshot?.timestamp === "string")
403
+ meta.timestamp = entry.snapshot.timestamp;
404
+ }
405
+ if (meta.sessionId && meta.cwd && meta.timestamp)
406
+ return meta;
407
+ }
408
+ catch {
409
+ // ignore malformed line
410
+ }
411
+ }
412
+ return meta.sessionId || meta.cwd || meta.timestamp ? meta : undefined;
411
413
  }
412
414
  catch {
413
415
  return undefined;
@@ -416,6 +418,51 @@ async function readJsonlFirstLine(filePath) {
416
418
  await fd?.close().catch(() => { });
417
419
  }
418
420
  }
421
+ async function chooseStaleSessionOverride(processCwd, currentSessionId, config) {
422
+ const projectDirName = await findClaudeProjectDir(processCwd, currentSessionId, config);
423
+ if (!projectDirName)
424
+ return undefined;
425
+ const candidates = await listClaudeSessionCandidates(projectDirName, getClaudeProjectRoots(config));
426
+ const recentPath = selectRecentSessionFile(candidates);
427
+ if (!recentPath)
428
+ return undefined;
429
+ if (currentSessionId && isDirectSessionFile(recentPath, currentSessionId)) {
430
+ return undefined;
431
+ }
432
+ const currentDirectPath = currentSessionId != null
433
+ ? getClaudeProjectRoots(config)
434
+ .map((projectsDir) => join(projectsDir, projectDirName, `${currentSessionId}.jsonl`))
435
+ .find((candidate) => existsSync(candidate))
436
+ : undefined;
437
+ if (currentDirectPath) {
438
+ try {
439
+ const [recentStat, currentStat] = await Promise.all([
440
+ stat(recentPath),
441
+ stat(currentDirectPath),
442
+ ]);
443
+ const minLeadMs = 5 * 60 * 1000;
444
+ const staleGapMs = 30 * 60 * 1000;
445
+ if (recentStat.mtimeMs - currentStat.mtimeMs < minLeadMs)
446
+ return undefined;
447
+ if (Date.now() - currentStat.mtimeMs < staleGapMs)
448
+ return undefined;
449
+ }
450
+ catch {
451
+ return undefined;
452
+ }
453
+ }
454
+ const recentMeta = await readJsonlSessionMeta(recentPath);
455
+ if (!recentMeta?.sessionId)
456
+ return undefined;
457
+ if (recentMeta.sessionId === currentSessionId)
458
+ return undefined;
459
+ return {
460
+ sessionId: recentMeta.sessionId,
461
+ cwd: recentMeta.cwd ?? processCwd,
462
+ timestamp: recentMeta.timestamp,
463
+ filePath: recentPath,
464
+ };
465
+ }
419
466
  /**
420
467
  * Match a Claude session by scanning JSONL files in the project directory.
421
468
  * When processStartedAt is available, matches by JSONL creation timestamp
@@ -462,7 +509,7 @@ export async function matchClaudeSessionByMtime(cwd, processStartedAt, config) {
462
509
  // Read first lines to get creation timestamps and match by proximity
463
510
  const scored = [];
464
511
  for (const c of pool) {
465
- const firstLine = await readJsonlFirstLine(c.path);
512
+ const firstLine = await readJsonlSessionMeta(c.path);
466
513
  if (!firstLine?.timestamp)
467
514
  continue;
468
515
  const createdAt = new Date(firstLine.timestamp).getTime() / 1000;
@@ -480,19 +527,31 @@ export async function matchClaudeSessionByMtime(cwd, processStartedAt, config) {
480
527
  bestPath = scored[0].path;
481
528
  }
482
529
  }
483
- // Fallback: most recently modified
530
+ // Fallback: no timestamp-scored match — only commit if one file clearly leads
531
+ // to avoid mismatching when multiple sessions share the same cwd.
484
532
  if (!bestPath) {
485
533
  pool.sort((a, b) => b.mtimeMs - a.mtimeMs);
486
- bestPath = pool[0].path;
534
+ const latest = pool[0];
535
+ const second = pool[1];
536
+ if (!second || latest.mtimeMs - second.mtimeMs >= 5 * 60 * 1000) {
537
+ bestPath = latest.path;
538
+ }
539
+ // Ambiguous (two recent files within 5 min of each other) → bestPath stays undefined
487
540
  }
488
541
  }
489
542
  else {
490
- // No process start time — pick most recently modified
543
+ // No process start time — pick most recently modified, but only if unambiguous
491
544
  candidates.sort((a, b) => b.mtimeMs - a.mtimeMs);
492
- bestPath = candidates[0].path;
545
+ const latest = candidates[0];
546
+ const second = candidates[1];
547
+ if (!second || latest.mtimeMs - second.mtimeMs >= 5 * 60 * 1000) {
548
+ bestPath = candidates[0].path;
549
+ }
493
550
  }
551
+ if (!bestPath)
552
+ return undefined;
494
553
  // Read first line for session metadata
495
- const entry = await readJsonlFirstLine(bestPath);
554
+ const entry = await readJsonlSessionMeta(bestPath);
496
555
  if (!entry?.sessionId)
497
556
  return undefined;
498
557
  try {
@@ -513,6 +572,7 @@ export async function matchClaudeSessionByMtime(cwd, processStartedAt, config) {
513
572
  firstSeenOffset: 0,
514
573
  startedAt: result.startedAt,
515
574
  source: "claude",
575
+ binding: basename(bestPath).includes(entry.sessionId) ? "direct" : "provisional",
516
576
  });
517
577
  const tokenData = await parseClaudeTokens(entry.sessionId, sessionCwd, result.startedAt, config);
518
578
  result.tokenUsage = tokenData.tokenUsage;
@@ -534,15 +594,39 @@ export async function parseClaudeSession(pid, cwd, processStartedAt, config) {
534
594
  const fileStat = await stat(sessionFile);
535
595
  const raw = await readFile(sessionFile, "utf-8");
536
596
  const data = JSON.parse(raw);
597
+ const processCwd = cwd ?? data.cwd;
598
+ const sessionStartedAt = data.startedAt ? data.startedAt / 1000 : undefined;
599
+ let resolvedSessionId = data.sessionId;
600
+ let resolvedCwd = data.cwd;
601
+ let resolvedStartedAt = sessionStartedAt;
602
+ if (processCwd && processCwd !== "unknown") {
603
+ const override = await chooseStaleSessionOverride(processCwd, data.sessionId, config);
604
+ if (override) {
605
+ resolvedSessionId = override.sessionId;
606
+ resolvedCwd = override.cwd ?? processCwd;
607
+ resolvedStartedAt = override.timestamp
608
+ ? new Date(override.timestamp).getTime() / 1000
609
+ : sessionStartedAt;
610
+ upsertSessionRegistryEntry(claudeSessionRegistry, {
611
+ filePath: override.filePath,
612
+ sessionId: override.sessionId,
613
+ cwd: resolvedCwd ?? processCwd,
614
+ firstSeenOffset: 0,
615
+ startedAt: resolvedStartedAt,
616
+ source: "claude",
617
+ binding: "provisional",
618
+ });
619
+ }
620
+ }
537
621
  const result = {
538
- cwd: data.cwd,
539
- sessionId: data.sessionId,
540
- startedAt: data.startedAt ? data.startedAt / 1000 : undefined,
622
+ cwd: resolvedCwd,
623
+ sessionId: resolvedSessionId,
624
+ startedAt: resolvedStartedAt,
541
625
  lastActivityAt: fileStat.mtimeMs / 1000,
542
626
  sessionMatched: true,
543
627
  };
544
- if (data.sessionId && data.cwd) {
545
- const tokenData = await parseClaudeTokens(data.sessionId, data.cwd, data.startedAt ? data.startedAt / 1000 : undefined, config);
628
+ if (resolvedSessionId && resolvedCwd) {
629
+ const tokenData = await parseClaudeTokens(resolvedSessionId, resolvedCwd, resolvedStartedAt, config);
546
630
  result.tokenUsage = tokenData.tokenUsage;
547
631
  result.model = tokenData.model;
548
632
  }
@@ -132,6 +132,7 @@ export async function indexCodexSessions(config, options) {
132
132
  startedAt: s.timestamp,
133
133
  model: s.model,
134
134
  source: "codex",
135
+ binding: "direct",
135
136
  });
136
137
  }
137
138
  if (!hasTargetedFilter) {
@@ -219,6 +220,7 @@ export async function indexCodexSessions(config, options) {
219
220
  startedAt: meta.timestamp,
220
221
  model: meta.model,
221
222
  source: "codex",
223
+ binding: "direct",
222
224
  });
223
225
  metas.push(parsed);
224
226
  }
@@ -17,6 +17,8 @@ async function main() {
17
17
  intervalMs: intervalSec * 1000,
18
18
  detailIntervalMs: 30_000,
19
19
  snapshotPath: join(DAEMON_DIR, "daemon-snapshot.json"),
20
+ alertsSnapshotPath: join(DAEMON_DIR, "alerts-snapshot.json"),
21
+ alertsLogPath: join(CONFIG_DIR, "alerts.log"),
20
22
  pidPath: join(DAEMON_DIR, "daemon.pid"),
21
23
  registryPath: join(CONFIG_DIR, "session-registry.json"),
22
24
  codexBindingRegistryPath: join(CONFIG_DIR, "codex-binding-registry.json"),
@@ -7,6 +7,8 @@ export interface DaemonOptions {
7
7
  intervalMs: number;
8
8
  detailIntervalMs: number;
9
9
  snapshotPath: string;
10
+ alertsSnapshotPath: string;
11
+ alertsLogPath: string;
10
12
  pidPath: string;
11
13
  registryPath: string;
12
14
  codexBindingRegistryPath: string;
@@ -3,6 +3,7 @@
3
3
  * Reuses watch/dock pattern: light scan every intervalMs, full every detailIntervalMs.
4
4
  */
5
5
  import { open, stat, unlink } from "node:fs/promises";
6
+ import { AlertStore, appendAlertLog, checkTokenAlert, sendDesktopNotification, writeAlertsSnapshot, } from "../alerts/index.js";
6
7
  import { appendActivityEntries, cleanupOldActivityLogs, extractClaudeToolUses, extractCodexToolUses, formatDateKey, } from "./activity-log.js";
7
8
  import { loadCodexBindingRegistryFromFile, pruneCodexBindingRegistry, saveCodexBindingRegistryToFile, } from "./codex-binding-registry.js";
8
9
  import { writeDaemonPid, writeDaemonSnapshot } from "./daemon-utils.js";
@@ -13,10 +14,11 @@ function sleep(ms) {
13
14
  return new Promise((resolve) => setTimeout(resolve, ms));
14
15
  }
15
16
  export async function runDaemonLoop(config, options) {
16
- const { intervalMs, detailIntervalMs, snapshotPath, pidPath, registryPath, codexBindingRegistryPath, activityLogDir, activityRetentionDays, } = options;
17
+ const { intervalMs, detailIntervalMs, snapshotPath, alertsSnapshotPath, alertsLogPath, pidPath, registryPath, codexBindingRegistryPath, activityLogDir, activityRetentionDays, } = options;
17
18
  // Activity log: per-session JSONL cursor offsets (in-memory only)
18
19
  const activityCursors = new Map();
19
20
  let lastActivityCleanupAt = 0;
21
+ const alertStore = new AlertStore();
20
22
  await writeDaemonPid(pidPath, process.pid);
21
23
  const registry = new Map();
22
24
  const codexBindingRegistry = new Map();
@@ -67,6 +69,24 @@ export async function runDaemonLoop(config, options) {
67
69
  updateRegistry(registry, agents);
68
70
  // Write snapshot for statusline consumers
69
71
  await writeDaemonSnapshot(snapshotPath, agents);
72
+ // Check token thresholds and fire alerts (alerts.enabled 확인)
73
+ if (config.alerts.enabled) {
74
+ const thresholds = {
75
+ warnAt: config.alerts.contextWarnThreshold,
76
+ critAt: config.alerts.contextCritThreshold,
77
+ };
78
+ for (const agent of agents) {
79
+ const alert = checkTokenAlert(alertStore, agent, thresholds);
80
+ if (alert) {
81
+ if (config.alerts.log)
82
+ await appendAlertLog(alertsLogPath, alert);
83
+ if (config.alerts.desktop && alert.severity === "critical") {
84
+ void sendDesktopNotification(alert); // fire-and-forget
85
+ }
86
+ }
87
+ }
88
+ }
89
+ await writeAlertsSnapshot(alertsSnapshotPath, alertStore.active());
70
90
  // Save registry periodically (on heavy scan) + prune old entries
71
91
  if (needsHeavy) {
72
92
  pruneRegistry(registry, 30);
@@ -28,6 +28,12 @@ export declare function isPidInTree(rootPid: number, targetPid: number, childMap
28
28
  export declare function selectTmuxPaneForAgent(agent: Pick<AgentSession, "pid" | "cwd">, panes: TmuxPane[], childMap: Map<number, number[]>): TmuxJumpTarget | undefined;
29
29
  export declare function listTmuxPanes(): Promise<TmuxPane[]>;
30
30
  export declare function getProcessTree(): Promise<Map<number, number[]>>;
31
+ /** Get the PID of the currently active tmux pane */
32
+ export declare function getActiveTmuxPanePid(): Promise<number | undefined>;
33
+ /** Find the agent PID that runs inside the currently active tmux pane.
34
+ * When panePid is provided, skips the tmux query (useful when the caller
35
+ * already resolved the active pane PID for cache-key purposes). */
36
+ export declare function findActiveAgentPid(agentPids: number[], panePid?: number): Promise<number | undefined>;
31
37
  export declare function resolveTmuxJumpTarget(agent: Pick<AgentSession, "pid" | "cwd">): Promise<TmuxJumpTarget | undefined>;
32
38
  export declare function captureTmuxPaneOutput(target: TmuxJumpTarget, lines?: number): Promise<string | undefined>;
33
39
  export declare function jumpToTmuxPane(target: TmuxJumpTarget): Promise<boolean>;
@@ -98,6 +98,34 @@ export async function getProcessTree() {
98
98
  return new Map();
99
99
  }
100
100
  }
101
+ /** Get the PID of the currently active tmux pane */
102
+ export async function getActiveTmuxPanePid() {
103
+ try {
104
+ const { stdout } = await execFileAsync("tmux", ["display-message", "-p", "#{pane_pid}"]);
105
+ const pid = Number.parseInt(stdout.trim(), 10);
106
+ return Number.isFinite(pid) ? pid : undefined;
107
+ }
108
+ catch {
109
+ return undefined;
110
+ }
111
+ }
112
+ /** Find the agent PID that runs inside the currently active tmux pane.
113
+ * When panePid is provided, skips the tmux query (useful when the caller
114
+ * already resolved the active pane PID for cache-key purposes). */
115
+ export async function findActiveAgentPid(agentPids, panePid) {
116
+ if (agentPids.length === 0)
117
+ return undefined;
118
+ try {
119
+ const activePanePid = panePid ?? (await getActiveTmuxPanePid());
120
+ if (!activePanePid)
121
+ return undefined;
122
+ const childMap = await getProcessTree();
123
+ return agentPids.find((pid) => isPidInTree(activePanePid, pid, childMap));
124
+ }
125
+ catch {
126
+ return undefined;
127
+ }
128
+ }
101
129
  export async function resolveTmuxJumpTarget(agent) {
102
130
  try {
103
131
  const [panes, childMap] = await Promise.all([listTmuxPanes(), getProcessTree()]);
package/dist/types.d.ts CHANGED
@@ -5,6 +5,8 @@ export interface TokenUsage {
5
5
  cacheCreationTokens: number;
6
6
  cacheReadTokens: number;
7
7
  totalTokens: number;
8
+ /** input_tokens from the most recent API response (= current context window size) */
9
+ lastInputTokens?: number;
8
10
  }
9
11
  /** Agent session status */
10
12
  export type SessionStatus = "Active" | "Idle" | "Stalled" | "Unmatched" | "Dead";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "marmonitor",
3
- "version": "0.2.4",
3
+ "version": "0.2.5",
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",
@@ -55,6 +55,7 @@
55
55
  "dependencies": {
56
56
  "chalk": "^5.3",
57
57
  "commander": "^12.1",
58
+ "node-notifier": "^10.0.1",
58
59
  "pidusage": "^3.0",
59
60
  "ps-list": "^8.1",
60
61
  "systeminformation": "^5.22"
@@ -62,6 +63,7 @@
62
63
  "devDependencies": {
63
64
  "@biomejs/biome": "^1.9.4",
64
65
  "@types/node": "^20.14",
66
+ "@types/node-notifier": "^8.0.5",
65
67
  "@types/pidusage": "^2.0.5",
66
68
  "typescript": "^5.5"
67
69
  },