marmonitor 0.2.3 → 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.
- package/README.ko.md +109 -17
- package/README.md +73 -0
- package/dist/alerts/desktop.d.ts +3 -0
- package/dist/alerts/desktop.js +23 -0
- package/dist/alerts/index.d.ts +7 -0
- package/dist/alerts/index.js +5 -0
- package/dist/alerts/log.d.ts +3 -0
- package/dist/alerts/log.js +14 -0
- package/dist/alerts/snapshot.d.ts +4 -0
- package/dist/alerts/snapshot.js +25 -0
- package/dist/alerts/store.d.ts +23 -0
- package/dist/alerts/store.js +61 -0
- package/dist/alerts/token.d.ts +18 -0
- package/dist/alerts/token.js +65 -0
- package/dist/alerts/types.d.ts +23 -0
- package/dist/alerts/types.js +2 -0
- package/dist/cli.js +318 -124
- package/dist/config/index.d.ts +13 -1
- package/dist/config/index.js +7 -0
- package/dist/guard/index.js +51 -5
- package/dist/output/badge-themes.d.ts +3 -0
- package/dist/output/badge-themes.js +26 -0
- package/dist/output/index.d.ts +2 -1
- package/dist/output/index.js +156 -34
- package/dist/output/utils.d.ts +4 -2
- package/dist/output/utils.js +10 -4
- package/dist/scanner/claude.js +174 -90
- package/dist/scanner/codex.js +2 -0
- package/dist/scanner/daemon-entry.js +2 -0
- package/dist/scanner/daemon-loop.d.ts +2 -0
- package/dist/scanner/daemon-loop.js +25 -27
- package/dist/scanner/index.js +14 -0
- package/dist/scanner/process.js +6 -0
- package/dist/tmux/index.d.ts +6 -0
- package/dist/tmux/index.js +28 -0
- package/dist/types.d.ts +3 -0
- package/package.json +3 -1
package/dist/scanner/claude.js
CHANGED
|
@@ -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,
|
|
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
|
|
97
|
-
|
|
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
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
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
|
|
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
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
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
|
|
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:
|
|
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
|
-
|
|
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
|
-
|
|
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
|
|
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:
|
|
539
|
-
sessionId:
|
|
540
|
-
startedAt:
|
|
622
|
+
cwd: resolvedCwd,
|
|
623
|
+
sessionId: resolvedSessionId,
|
|
624
|
+
startedAt: resolvedStartedAt,
|
|
541
625
|
lastActivityAt: fileStat.mtimeMs / 1000,
|
|
542
626
|
sessionMatched: true,
|
|
543
627
|
};
|
|
544
|
-
if (
|
|
545
|
-
const tokenData = await parseClaudeTokens(
|
|
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
|
}
|
package/dist/scanner/codex.js
CHANGED
|
@@ -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"),
|
|
@@ -2,8 +2,8 @@
|
|
|
2
2
|
* Daemon scan loop — runs in background, writes snapshots and registry to files.
|
|
3
3
|
* Reuses watch/dock pattern: light scan every intervalMs, full every detailIntervalMs.
|
|
4
4
|
*/
|
|
5
|
-
import { open,
|
|
6
|
-
import {
|
|
5
|
+
import { open, stat, unlink } from "node:fs/promises";
|
|
6
|
+
import { AlertStore, appendAlertLog, checkTokenAlert, sendDesktopNotification, writeAlertsSnapshot, } from "../alerts/index.js";
|
|
7
7
|
import { appendActivityEntries, cleanupOldActivityLogs, extractClaudeToolUses, extractCodexToolUses, formatDateKey, } from "./activity-log.js";
|
|
8
8
|
import { loadCodexBindingRegistryFromFile, pruneCodexBindingRegistry, saveCodexBindingRegistryToFile, } from "./codex-binding-registry.js";
|
|
9
9
|
import { writeDaemonPid, writeDaemonSnapshot } from "./daemon-utils.js";
|
|
@@ -14,10 +14,11 @@ function sleep(ms) {
|
|
|
14
14
|
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
15
15
|
}
|
|
16
16
|
export async function runDaemonLoop(config, options) {
|
|
17
|
-
const { intervalMs, detailIntervalMs, snapshotPath, pidPath, registryPath, codexBindingRegistryPath, activityLogDir, activityRetentionDays, } = options;
|
|
17
|
+
const { intervalMs, detailIntervalMs, snapshotPath, alertsSnapshotPath, alertsLogPath, pidPath, registryPath, codexBindingRegistryPath, activityLogDir, activityRetentionDays, } = options;
|
|
18
18
|
// Activity log: per-session JSONL cursor offsets (in-memory only)
|
|
19
19
|
const activityCursors = new Map();
|
|
20
20
|
let lastActivityCleanupAt = 0;
|
|
21
|
+
const alertStore = new AlertStore();
|
|
21
22
|
await writeDaemonPid(pidPath, process.pid);
|
|
22
23
|
const registry = new Map();
|
|
23
24
|
const codexBindingRegistry = new Map();
|
|
@@ -68,6 +69,24 @@ export async function runDaemonLoop(config, options) {
|
|
|
68
69
|
updateRegistry(registry, agents);
|
|
69
70
|
// Write snapshot for statusline consumers
|
|
70
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());
|
|
71
90
|
// Save registry periodically (on heavy scan) + prune old entries
|
|
72
91
|
if (needsHeavy) {
|
|
73
92
|
pruneRegistry(registry, 30);
|
|
@@ -85,32 +104,11 @@ export async function runDaemonLoop(config, options) {
|
|
|
85
104
|
const jsonlPath = agent.agentName === "Codex"
|
|
86
105
|
? codexBindingRegistry.get(`${agent.pid}:${agent.processStartedAt ?? 0}`)?.rolloutPath
|
|
87
106
|
: undefined;
|
|
88
|
-
// Claude:
|
|
107
|
+
// Claude: resolve JSONL path via resolveClaudeSessionFile (projects dir)
|
|
89
108
|
let sessionFile;
|
|
90
109
|
if (agent.agentName === "Claude Code" && agent.sessionId && agent.cwd) {
|
|
91
|
-
const {
|
|
92
|
-
|
|
93
|
-
for (const root of roots) {
|
|
94
|
-
try {
|
|
95
|
-
const dirs = await readdir(root);
|
|
96
|
-
for (const dir of dirs) {
|
|
97
|
-
const candidate = join(root, dir, `${agent.sessionId}.jsonl`);
|
|
98
|
-
try {
|
|
99
|
-
await stat(candidate);
|
|
100
|
-
sessionFile = candidate;
|
|
101
|
-
break;
|
|
102
|
-
}
|
|
103
|
-
catch {
|
|
104
|
-
// not here
|
|
105
|
-
}
|
|
106
|
-
}
|
|
107
|
-
if (sessionFile)
|
|
108
|
-
break;
|
|
109
|
-
}
|
|
110
|
-
catch {
|
|
111
|
-
// root doesn't exist
|
|
112
|
-
}
|
|
113
|
-
}
|
|
110
|
+
const { resolveClaudeSessionFile } = await import("./claude.js");
|
|
111
|
+
sessionFile = await resolveClaudeSessionFile(agent.sessionId, agent.cwd, agent.startedAt, config);
|
|
114
112
|
}
|
|
115
113
|
else if (agent.agentName === "Codex" && jsonlPath) {
|
|
116
114
|
sessionFile = jsonlPath;
|
package/dist/scanner/index.js
CHANGED
|
@@ -233,6 +233,18 @@ export async function scanAgents(config, options = {}) {
|
|
|
233
233
|
const elapsed = statusBaseAt ? Date.now() / 1000 - statusBaseAt : undefined;
|
|
234
234
|
const rawStatus = determineStatus(cpuPercent, elapsed, sessionMatched, phase, config, agentName);
|
|
235
235
|
const status = applyStatusHysteresis(rawStatus, cachedEnrichment?.status, elapsed, phase, agentName);
|
|
236
|
+
// Read git branch from .git/HEAD (full enrichment only, ~0.1ms per session)
|
|
237
|
+
let branch = cachedEnrichment?.branch;
|
|
238
|
+
if (isFullEnrichment && cwd !== "unknown") {
|
|
239
|
+
try {
|
|
240
|
+
const headContent = await readFile(join(cwd, ".git", "HEAD"), "utf-8");
|
|
241
|
+
const trimmed = headContent.trim();
|
|
242
|
+
branch = trimmed.startsWith("ref: refs/heads/") ? trimmed.slice(16) : undefined;
|
|
243
|
+
}
|
|
244
|
+
catch {
|
|
245
|
+
branch = undefined;
|
|
246
|
+
}
|
|
247
|
+
}
|
|
236
248
|
const session = {
|
|
237
249
|
agentName,
|
|
238
250
|
pid: proc.pid,
|
|
@@ -251,6 +263,7 @@ export async function scanAgents(config, options = {}) {
|
|
|
251
263
|
lastResponseAt,
|
|
252
264
|
lastActivityAt,
|
|
253
265
|
runtimeSource,
|
|
266
|
+
branch,
|
|
254
267
|
};
|
|
255
268
|
if (isFullEnrichment) {
|
|
256
269
|
sessionEnrichmentCache.set(cacheKey, {
|
|
@@ -266,6 +279,7 @@ export async function scanAgents(config, options = {}) {
|
|
|
266
279
|
lastResponseAt: session.lastResponseAt,
|
|
267
280
|
lastActivityAt: session.lastActivityAt,
|
|
268
281
|
runtimeSource: session.runtimeSource,
|
|
282
|
+
branch: session.branch,
|
|
269
283
|
});
|
|
270
284
|
}
|
|
271
285
|
return session;
|
package/dist/scanner/process.js
CHANGED
|
@@ -75,8 +75,14 @@ export function matchesProcessCommand(command, processName) {
|
|
|
75
75
|
const escaped = processName.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
76
76
|
return new RegExp(`(?:^|[/\\\\])${escaped}(?:\\s|$)`, "i").test(command);
|
|
77
77
|
}
|
|
78
|
+
/** Electron sub-process flags that indicate a desktop GUI helper, not a CLI agent. */
|
|
79
|
+
const ELECTRON_TYPE_RE = /--type=(utility|renderer|gpu-process|zygote|broker)/;
|
|
78
80
|
/** Match a process against agent signatures using process name first, then cmd fallback. */
|
|
79
81
|
export function detectAgentFromProcessSignature(proc, config) {
|
|
82
|
+
// Skip Electron sub-processes (renderer, utility, gpu, zygote) to avoid
|
|
83
|
+
// false-positive detection of desktop apps (e.g. Claude Desktop) as CLI agents.
|
|
84
|
+
if (proc.cmd && ELECTRON_TYPE_RE.test(proc.cmd))
|
|
85
|
+
return null;
|
|
80
86
|
const name = proc.name.toLowerCase();
|
|
81
87
|
const command = (proc.cmd ?? "").toLowerCase();
|
|
82
88
|
for (const [agentName, agentConfig] of Object.entries(config.agents)) {
|
package/dist/tmux/index.d.ts
CHANGED
|
@@ -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>;
|
package/dist/tmux/index.js
CHANGED
|
@@ -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";
|
|
@@ -40,6 +42,7 @@ export interface AgentSession {
|
|
|
40
42
|
lastResponseAt?: number;
|
|
41
43
|
lastActivityAt?: number;
|
|
42
44
|
runtimeSource?: RuntimeSource;
|
|
45
|
+
branch?: string;
|
|
43
46
|
}
|
|
44
47
|
/** Agent detection signature */
|
|
45
48
|
export interface AgentSignature {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "marmonitor",
|
|
3
|
-
"version": "0.2.
|
|
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
|
},
|