marmonitor 0.1.7 → 0.2.2
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 +262 -0
- package/README.md +49 -5
- package/bin/daemon.js +2 -0
- package/bin/postinstall.cjs +47 -1
- package/bin/preuninstall.cjs +14 -0
- package/dist/banner/index.js +15 -7
- package/dist/cli.js +282 -107
- package/dist/config/index.d.ts +2 -0
- package/dist/config/index.js +2 -0
- package/dist/output/badge-themes.d.ts +19 -0
- package/dist/output/badge-themes.js +52 -0
- package/dist/output/index.d.ts +5 -2
- package/dist/output/index.js +69 -22
- package/dist/output/utils.d.ts +22 -8
- package/dist/output/utils.js +83 -48
- package/dist/scanner/claude.d.ts +8 -1
- package/dist/scanner/claude.js +156 -19
- package/dist/scanner/codex-sqlite.d.ts +11 -0
- package/dist/scanner/codex-sqlite.js +50 -0
- package/dist/scanner/codex.d.ts +1 -1
- package/dist/scanner/codex.js +42 -2
- package/dist/scanner/concurrency.d.ts +5 -0
- package/dist/scanner/concurrency.js +22 -0
- package/dist/scanner/daemon-entry.d.ts +5 -0
- package/dist/scanner/daemon-entry.js +27 -0
- package/dist/scanner/daemon-loop.d.ts +13 -0
- package/dist/scanner/daemon-loop.js +77 -0
- package/dist/scanner/daemon-utils.d.ts +9 -0
- package/dist/scanner/daemon-utils.js +56 -0
- package/dist/scanner/index.js +51 -10
- package/dist/scanner/perf.d.ts +8 -0
- package/dist/scanner/perf.js +26 -0
- package/dist/scanner/session-registry.d.ts +31 -0
- package/dist/scanner/session-registry.js +99 -0
- package/dist/scanner/session-tier.d.ts +6 -0
- package/dist/scanner/session-tier.js +22 -0
- package/dist/tmux/index.js +11 -0
- package/dist/tmux/jump-anchor.d.ts +25 -0
- package/dist/tmux/jump-anchor.js +100 -0
- package/dist/tmux/setup.d.ts +4 -0
- package/dist/tmux/setup.js +41 -1
- package/dist/tmux/status-click.d.ts +9 -0
- package/dist/tmux/status-click.js +19 -0
- package/package.json +1 -1
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Codex session indexing via SQLite threads table.
|
|
3
|
+
* Uses sqlite3 CLI (pre-installed on macOS/Linux) — no npm dependency.
|
|
4
|
+
* Falls back gracefully if sqlite3 is unavailable or DB is missing.
|
|
5
|
+
*/
|
|
6
|
+
import { execFile } from "node:child_process";
|
|
7
|
+
import { promisify } from "node:util";
|
|
8
|
+
const execFileAsync = promisify(execFile);
|
|
9
|
+
/**
|
|
10
|
+
* Query Codex state SQLite for active (non-archived) threads.
|
|
11
|
+
* Returns CodexSessionMeta[] compatible with existing matchCodexSession().
|
|
12
|
+
*/
|
|
13
|
+
export async function indexCodexSessionsFromSqlite(dbPath) {
|
|
14
|
+
try {
|
|
15
|
+
const { stdout } = await execFileAsync("sqlite3", [
|
|
16
|
+
dbPath,
|
|
17
|
+
"-separator",
|
|
18
|
+
"\t",
|
|
19
|
+
"SELECT id, cwd, rollout_path, tokens_used, model, updated_at, created_at FROM threads WHERE archived = 0 ORDER BY updated_at DESC;",
|
|
20
|
+
]);
|
|
21
|
+
const lines = stdout.trim().split("\n").filter(Boolean);
|
|
22
|
+
const sessions = [];
|
|
23
|
+
for (const line of lines) {
|
|
24
|
+
const [id, cwd, rolloutPath, tokensUsed, model, updatedAt, createdAt] = line.split("\t");
|
|
25
|
+
if (!id || !cwd)
|
|
26
|
+
continue;
|
|
27
|
+
sessions.push({
|
|
28
|
+
filePath: rolloutPath ?? "",
|
|
29
|
+
id,
|
|
30
|
+
cwd,
|
|
31
|
+
timestamp: Number(createdAt) || 0,
|
|
32
|
+
lastActivityAt: Number(updatedAt) || undefined,
|
|
33
|
+
totalTokenUsage: tokensUsed
|
|
34
|
+
? {
|
|
35
|
+
input_tokens: 0,
|
|
36
|
+
cached_input_tokens: 0,
|
|
37
|
+
output_tokens: 0,
|
|
38
|
+
total_tokens: Number(tokensUsed) || 0,
|
|
39
|
+
}
|
|
40
|
+
: undefined,
|
|
41
|
+
model: model || undefined,
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
return sessions;
|
|
45
|
+
}
|
|
46
|
+
catch {
|
|
47
|
+
// sqlite3 not available, DB missing, or query failed — return empty
|
|
48
|
+
return [];
|
|
49
|
+
}
|
|
50
|
+
}
|
package/dist/scanner/codex.d.ts
CHANGED
|
@@ -8,7 +8,7 @@ export type { CodexSessionMeta } from "./cache.js";
|
|
|
8
8
|
export declare function getCodexSessionRoots(config?: MarmonitorConfig): string[];
|
|
9
9
|
/** Detect Codex session phase from session JSONL */
|
|
10
10
|
export declare function detectCodexPhase(sessionFilePath: string | undefined, config?: MarmonitorConfig): Promise<SessionPhase>;
|
|
11
|
-
/** Build index of
|
|
11
|
+
/** Build index of Codex sessions (SQLite primary, JSONL fallback) */
|
|
12
12
|
export declare function indexCodexSessions(config?: MarmonitorConfig): Promise<CodexSessionMeta[]>;
|
|
13
13
|
/** Match a Codex process to a session by cwd + closest timestamp */
|
|
14
14
|
export declare function matchCodexSession(processCwd: string, processStartTime: number | undefined, sessions: CodexSessionMeta[]): CodexSessionMeta | undefined;
|
package/dist/scanner/codex.js
CHANGED
|
@@ -1,9 +1,11 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Codex session parsing, indexing, and phase detection.
|
|
3
3
|
*/
|
|
4
|
-
import { existsSync } from "node:fs";
|
|
4
|
+
import { existsSync, readdirSync } from "node:fs";
|
|
5
5
|
import { open, readFile, readdir, stat } from "node:fs/promises";
|
|
6
|
+
import { homedir } from "node:os";
|
|
6
7
|
import { join } from "node:path";
|
|
8
|
+
import { indexCodexSessionsFromSqlite } from "./codex-sqlite.js";
|
|
7
9
|
import { resolveRuntimeDataPaths } from "../config/index.js";
|
|
8
10
|
import { advanceJsonlCursor, resolvePhaseFromHistory, resolvePhaseWithDecay, selectCodexSession, updatePhaseHistory, upsertSessionRegistryEntry, } from "../output/utils.js";
|
|
9
11
|
import { CODEX_INDEX_TTL_MS, CODEX_PHASE_RECENT_LINES, HOME, codexIndexCache, codexPhaseCache, codexSessionFileCache, codexSessionRegistry, setCodexIndexCache, } from "./cache.js";
|
|
@@ -86,11 +88,49 @@ export async function detectCodexPhase(sessionFilePath, config) {
|
|
|
86
88
|
return undefined;
|
|
87
89
|
}
|
|
88
90
|
}
|
|
89
|
-
/**
|
|
91
|
+
/** Find the latest Codex state SQLite DB path */
|
|
92
|
+
function findCodexStateDb() {
|
|
93
|
+
const codexDir = join(homedir(), ".codex");
|
|
94
|
+
try {
|
|
95
|
+
const files = readdirSync(codexDir)
|
|
96
|
+
.filter((f) => f.startsWith("state_") && f.endsWith(".sqlite"))
|
|
97
|
+
.sort()
|
|
98
|
+
.reverse();
|
|
99
|
+
return files.length > 0 ? join(codexDir, files[0]) : undefined;
|
|
100
|
+
}
|
|
101
|
+
catch {
|
|
102
|
+
return undefined;
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
/** Build index of Codex sessions (SQLite primary, JSONL fallback) */
|
|
90
106
|
export async function indexCodexSessions(config) {
|
|
91
107
|
if (codexIndexCache && Date.now() - codexIndexCache.builtAt < CODEX_INDEX_TTL_MS) {
|
|
92
108
|
return codexIndexCache.sessions;
|
|
93
109
|
}
|
|
110
|
+
const hasExplicitSessionRoots = Boolean(config?.paths.codexSessions?.length);
|
|
111
|
+
// Primary: SQLite threads table
|
|
112
|
+
const dbPath = hasExplicitSessionRoots ? undefined : findCodexStateDb();
|
|
113
|
+
if (dbPath) {
|
|
114
|
+
const sqliteSessions = await indexCodexSessionsFromSqlite(dbPath);
|
|
115
|
+
if (sqliteSessions.length > 0) {
|
|
116
|
+
// Register sessions for phase detection and cwd lookup
|
|
117
|
+
for (const s of sqliteSessions) {
|
|
118
|
+
codexSessionFileCache.set(s.filePath, { ...s, mtimeMs: undefined, size: undefined });
|
|
119
|
+
upsertSessionRegistryEntry(codexSessionRegistry, {
|
|
120
|
+
filePath: s.filePath,
|
|
121
|
+
sessionId: s.id,
|
|
122
|
+
cwd: s.cwd,
|
|
123
|
+
firstSeenOffset: 0,
|
|
124
|
+
startedAt: s.timestamp,
|
|
125
|
+
model: s.model,
|
|
126
|
+
source: "codex",
|
|
127
|
+
});
|
|
128
|
+
}
|
|
129
|
+
setCodexIndexCache({ builtAt: Date.now(), sessions: sqliteSessions });
|
|
130
|
+
return sqliteSessions;
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
// Fallback: JSONL directory scan (last 7 days)
|
|
94
134
|
const sessionRoots = getCodexSessionRoots(config);
|
|
95
135
|
if (!sessionRoots.some((sessionsDir) => existsSync(sessionsDir)))
|
|
96
136
|
return [];
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Simple concurrency limiter for Promise.all replacement.
|
|
3
|
+
* Limits how many tasks run in parallel to reduce CPU/IO spikes.
|
|
4
|
+
*/
|
|
5
|
+
export async function promiseAllLimited(tasks, limit) {
|
|
6
|
+
const results = new Array(tasks.length).fill(null);
|
|
7
|
+
let index = 0;
|
|
8
|
+
async function worker() {
|
|
9
|
+
while (index < tasks.length) {
|
|
10
|
+
const i = index++;
|
|
11
|
+
try {
|
|
12
|
+
results[i] = await tasks[i]();
|
|
13
|
+
}
|
|
14
|
+
catch {
|
|
15
|
+
results[i] = null;
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
const workers = Array.from({ length: Math.min(limit, tasks.length) }, () => worker());
|
|
20
|
+
await Promise.all(workers);
|
|
21
|
+
return results;
|
|
22
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Daemon entry point — loaded by bin/daemon.js.
|
|
3
|
+
* Starts the background scan loop with default paths.
|
|
4
|
+
*/
|
|
5
|
+
import { tmpdir } from "node:os";
|
|
6
|
+
import { join } from "node:path";
|
|
7
|
+
import { loadConfig } from "../config/index.js";
|
|
8
|
+
import { getConfigDir } from "../config/index.js";
|
|
9
|
+
import { runDaemonLoop } from "./daemon-loop.js";
|
|
10
|
+
const DAEMON_DIR = join(tmpdir(), "marmonitor");
|
|
11
|
+
const CONFIG_DIR = getConfigDir();
|
|
12
|
+
async function main() {
|
|
13
|
+
process.title = "marmonitor";
|
|
14
|
+
const config = await loadConfig();
|
|
15
|
+
const intervalSec = Math.max(1, Math.min(30, Math.floor(config.performance.daemonIntervalSec)));
|
|
16
|
+
await runDaemonLoop(config, {
|
|
17
|
+
intervalMs: intervalSec * 1000,
|
|
18
|
+
detailIntervalMs: 30_000,
|
|
19
|
+
snapshotPath: join(DAEMON_DIR, "daemon-snapshot.json"),
|
|
20
|
+
pidPath: join(DAEMON_DIR, "daemon.pid"),
|
|
21
|
+
registryPath: join(CONFIG_DIR, "session-registry.json"),
|
|
22
|
+
});
|
|
23
|
+
}
|
|
24
|
+
main().catch((err) => {
|
|
25
|
+
process.stderr.write(`[marmonitor daemon] Fatal: ${err}\n`);
|
|
26
|
+
process.exit(1);
|
|
27
|
+
});
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Daemon scan loop — runs in background, writes snapshots and registry to files.
|
|
3
|
+
* Reuses watch/dock pattern: light scan every intervalMs, full every detailIntervalMs.
|
|
4
|
+
*/
|
|
5
|
+
import type { MarmonitorConfig } from "../config/index.js";
|
|
6
|
+
export interface DaemonOptions {
|
|
7
|
+
intervalMs: number;
|
|
8
|
+
detailIntervalMs: number;
|
|
9
|
+
snapshotPath: string;
|
|
10
|
+
pidPath: string;
|
|
11
|
+
registryPath: string;
|
|
12
|
+
}
|
|
13
|
+
export declare function runDaemonLoop(config: MarmonitorConfig, options: DaemonOptions): Promise<void>;
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Daemon scan loop — runs in background, writes snapshots and registry to files.
|
|
3
|
+
* Reuses watch/dock pattern: light scan every intervalMs, full every detailIntervalMs.
|
|
4
|
+
*/
|
|
5
|
+
import { unlink } from "node:fs/promises";
|
|
6
|
+
import { writeDaemonPid, writeDaemonSnapshot } from "./daemon-utils.js";
|
|
7
|
+
import { scanAgents } from "./index.js";
|
|
8
|
+
import { perfEnd, perfStart } from "./perf.js";
|
|
9
|
+
import { loadRegistryFromFile, pruneRegistry, saveRegistryToFile, updateRegistry, } from "./session-registry.js";
|
|
10
|
+
function sleep(ms) {
|
|
11
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
12
|
+
}
|
|
13
|
+
export async function runDaemonLoop(config, options) {
|
|
14
|
+
const { intervalMs, detailIntervalMs, snapshotPath, pidPath, registryPath } = options;
|
|
15
|
+
await writeDaemonPid(pidPath, process.pid);
|
|
16
|
+
const registry = new Map();
|
|
17
|
+
// Restore registry if saved recently (within 10 minutes)
|
|
18
|
+
try {
|
|
19
|
+
const { stat: fsStat } = await import("node:fs/promises");
|
|
20
|
+
const fileStat = await fsStat(registryPath);
|
|
21
|
+
const ageMs = Date.now() - fileStat.mtimeMs;
|
|
22
|
+
if (ageMs < 10 * 60 * 1000) {
|
|
23
|
+
await loadRegistryFromFile(registryPath, registry);
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
catch {
|
|
27
|
+
// file missing or inaccessible — start fresh
|
|
28
|
+
}
|
|
29
|
+
let lastHeavyAt = 0;
|
|
30
|
+
let running = true;
|
|
31
|
+
const shutdown = async () => {
|
|
32
|
+
if (!running)
|
|
33
|
+
return;
|
|
34
|
+
running = false;
|
|
35
|
+
// Save registry before exit
|
|
36
|
+
await saveRegistryToFile(registryPath, registry);
|
|
37
|
+
await unlink(pidPath).catch(() => { });
|
|
38
|
+
process.exit(0);
|
|
39
|
+
};
|
|
40
|
+
process.on("SIGTERM", shutdown);
|
|
41
|
+
process.on("SIGINT", shutdown);
|
|
42
|
+
// Memory monitor: warn if RSS exceeds 200MB
|
|
43
|
+
const RSS_WARN_MB = 200;
|
|
44
|
+
let lastMemWarnAt = 0;
|
|
45
|
+
while (running) {
|
|
46
|
+
const now = Date.now();
|
|
47
|
+
const needsHeavy = lastHeavyAt === 0 || now - lastHeavyAt >= detailIntervalMs;
|
|
48
|
+
const enrichmentMode = needsHeavy ? "full" : "light";
|
|
49
|
+
perfStart("daemon-scan");
|
|
50
|
+
try {
|
|
51
|
+
const agents = await scanAgents(config, { enrichmentMode });
|
|
52
|
+
if (needsHeavy)
|
|
53
|
+
lastHeavyAt = now;
|
|
54
|
+
// Update session registry
|
|
55
|
+
updateRegistry(registry, agents);
|
|
56
|
+
// Write snapshot for statusline consumers
|
|
57
|
+
await writeDaemonSnapshot(snapshotPath, agents);
|
|
58
|
+
// Save registry periodically (on heavy scan) + prune old entries
|
|
59
|
+
if (needsHeavy) {
|
|
60
|
+
pruneRegistry(registry, 30);
|
|
61
|
+
await saveRegistryToFile(registryPath, registry);
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
catch (err) {
|
|
65
|
+
// scan failures must never crash the daemon
|
|
66
|
+
process.stderr.write(`[marmonitor daemon] scan error: ${err}\n`);
|
|
67
|
+
}
|
|
68
|
+
perfEnd("daemon-scan");
|
|
69
|
+
// Memory check
|
|
70
|
+
const rssMb = process.memoryUsage.rss() / (1024 * 1024);
|
|
71
|
+
if (rssMb > RSS_WARN_MB && now - lastMemWarnAt > 60_000) {
|
|
72
|
+
process.stderr.write(`[marmonitor daemon] Warning: RSS ${Math.round(rssMb)}MB exceeds ${RSS_WARN_MB}MB\n`);
|
|
73
|
+
lastMemWarnAt = now;
|
|
74
|
+
}
|
|
75
|
+
await sleep(intervalMs);
|
|
76
|
+
}
|
|
77
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Daemon utility functions for PID management and snapshot I/O.
|
|
3
|
+
* Used by both the daemon loop and CLI commands.
|
|
4
|
+
*/
|
|
5
|
+
export declare function writeDaemonPid(pidPath: string, pid: number): Promise<void>;
|
|
6
|
+
export declare function readDaemonPid(pidPath: string): Promise<number | undefined>;
|
|
7
|
+
export declare function isDaemonRunning(pidPath: string): Promise<boolean>;
|
|
8
|
+
export declare function writeDaemonSnapshot(snapshotPath: string, data: unknown[]): Promise<void>;
|
|
9
|
+
export declare function readDaemonSnapshot(snapshotPath: string, ttlMs: number): Promise<unknown[]>;
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Daemon utility functions for PID management and snapshot I/O.
|
|
3
|
+
* Used by both the daemon loop and CLI commands.
|
|
4
|
+
*/
|
|
5
|
+
import { mkdir, readFile, stat, unlink, writeFile } from "node:fs/promises";
|
|
6
|
+
import { dirname } from "node:path";
|
|
7
|
+
export async function writeDaemonPid(pidPath, pid) {
|
|
8
|
+
await mkdir(dirname(pidPath), { recursive: true });
|
|
9
|
+
await writeFile(pidPath, String(pid), "utf-8");
|
|
10
|
+
}
|
|
11
|
+
export async function readDaemonPid(pidPath) {
|
|
12
|
+
try {
|
|
13
|
+
const content = await readFile(pidPath, "utf-8");
|
|
14
|
+
const pid = Number.parseInt(content.trim(), 10);
|
|
15
|
+
return Number.isNaN(pid) ? undefined : pid;
|
|
16
|
+
}
|
|
17
|
+
catch {
|
|
18
|
+
return undefined;
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
export async function isDaemonRunning(pidPath) {
|
|
22
|
+
const pid = await readDaemonPid(pidPath);
|
|
23
|
+
if (pid === undefined)
|
|
24
|
+
return false;
|
|
25
|
+
try {
|
|
26
|
+
process.kill(pid, 0); // signal 0 = check if process exists
|
|
27
|
+
return true;
|
|
28
|
+
}
|
|
29
|
+
catch {
|
|
30
|
+
// process doesn't exist — stale PID file
|
|
31
|
+
await unlink(pidPath).catch(() => { });
|
|
32
|
+
return false;
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
export async function writeDaemonSnapshot(snapshotPath, data) {
|
|
36
|
+
try {
|
|
37
|
+
await mkdir(dirname(snapshotPath), { recursive: true });
|
|
38
|
+
await writeFile(snapshotPath, JSON.stringify(data), "utf-8");
|
|
39
|
+
}
|
|
40
|
+
catch {
|
|
41
|
+
// snapshot write failures must never crash the daemon
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
export async function readDaemonSnapshot(snapshotPath, ttlMs) {
|
|
45
|
+
try {
|
|
46
|
+
const fileStat = await stat(snapshotPath);
|
|
47
|
+
if (Date.now() - fileStat.mtimeMs > ttlMs)
|
|
48
|
+
return [];
|
|
49
|
+
const raw = await readFile(snapshotPath, "utf-8");
|
|
50
|
+
const parsed = JSON.parse(raw);
|
|
51
|
+
return Array.isArray(parsed) ? parsed : [];
|
|
52
|
+
}
|
|
53
|
+
catch {
|
|
54
|
+
return [];
|
|
55
|
+
}
|
|
56
|
+
}
|
package/dist/scanner/index.js
CHANGED
|
@@ -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
|
-
|
|
55
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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 =
|
|
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
|
|
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;
|