marmonitor 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +219 -0
  3. package/bin/marmonitor.js +2 -0
  4. package/dist/banner/index.d.ts +7 -0
  5. package/dist/banner/index.js +212 -0
  6. package/dist/cli.d.ts +1 -0
  7. package/dist/cli.js +855 -0
  8. package/dist/config/index.d.ts +105 -0
  9. package/dist/config/index.js +218 -0
  10. package/dist/guard/index.d.ts +23 -0
  11. package/dist/guard/index.js +128 -0
  12. package/dist/output/index.d.ts +28 -0
  13. package/dist/output/index.js +457 -0
  14. package/dist/output/utils.d.ts +138 -0
  15. package/dist/output/utils.js +588 -0
  16. package/dist/process-safety.d.ts +2 -0
  17. package/dist/process-safety.js +7 -0
  18. package/dist/scanner/bounded-map.d.ts +10 -0
  19. package/dist/scanner/bounded-map.js +25 -0
  20. package/dist/scanner/cache.d.ts +88 -0
  21. package/dist/scanner/cache.js +32 -0
  22. package/dist/scanner/claude.d.ts +25 -0
  23. package/dist/scanner/claude.js +425 -0
  24. package/dist/scanner/codex.d.ts +14 -0
  25. package/dist/scanner/codex.js +195 -0
  26. package/dist/scanner/gemini.d.ts +21 -0
  27. package/dist/scanner/gemini.js +131 -0
  28. package/dist/scanner/group.d.ts +7 -0
  29. package/dist/scanner/group.js +54 -0
  30. package/dist/scanner/index.d.ts +16 -0
  31. package/dist/scanner/index.js +256 -0
  32. package/dist/scanner/process.d.ts +17 -0
  33. package/dist/scanner/process.js +91 -0
  34. package/dist/scanner/status.d.ts +8 -0
  35. package/dist/scanner/status.js +45 -0
  36. package/dist/scanner/types.d.ts +6 -0
  37. package/dist/scanner/types.js +4 -0
  38. package/dist/tmux/index.d.ts +34 -0
  39. package/dist/tmux/index.js +166 -0
  40. package/dist/types.d.ts +55 -0
  41. package/dist/types.js +1 -0
  42. package/dist/version.d.ts +1 -0
  43. package/dist/version.js +1 -0
  44. package/docs/banner-ansi.png +0 -0
  45. package/docs/marmot-small.png +0 -0
  46. package/package.json +70 -0
@@ -0,0 +1,195 @@
1
+ /**
2
+ * Codex session parsing, indexing, and phase detection.
3
+ */
4
+ import { existsSync } from "node:fs";
5
+ import { open, readFile, readdir, stat } from "node:fs/promises";
6
+ import { join } from "node:path";
7
+ import { resolveRuntimeDataPaths } from "../config/index.js";
8
+ import { advanceJsonlCursor, resolvePhaseFromHistory, resolvePhaseWithDecay, selectCodexSession, updatePhaseHistory, upsertSessionRegistryEntry, } from "../output/utils.js";
9
+ import { CODEX_INDEX_TTL_MS, CODEX_PHASE_RECENT_LINES, HOME, codexIndexCache, codexPhaseCache, codexSessionFileCache, codexSessionRegistry, setCodexIndexCache, } from "./cache.js";
10
+ export function getCodexSessionRoots(config) {
11
+ return config
12
+ ? resolveRuntimeDataPaths(config).codexSessions
13
+ : [join(HOME, ".codex", "sessions")];
14
+ }
15
+ /** Detect Codex session phase from session JSONL */
16
+ export async function detectCodexPhase(sessionFilePath, config) {
17
+ if (!sessionFilePath || !existsSync(sessionFilePath))
18
+ return undefined;
19
+ try {
20
+ const fileStat = await stat(sessionFilePath);
21
+ const cached = codexPhaseCache.get(sessionFilePath);
22
+ if (cached && cached.mtimeMs === fileStat.mtimeMs && cached.size === fileStat.size) {
23
+ return config
24
+ ? resolvePhaseWithDecay(cached.result.phase, cached.result.phase, cached.phaseDetectedAtMs, config.status.phaseDecay)
25
+ : cached.result.phase;
26
+ }
27
+ const { size } = fileStat;
28
+ const shouldAppend = Boolean(cached) && size >= (cached?.offset ?? 0);
29
+ const readFrom = shouldAppend ? (cached?.offset ?? 0) : 0;
30
+ const previousRemainder = shouldAppend ? (cached?.remainder ?? "") : "";
31
+ const previousLines = shouldAppend ? (cached?.recentLines ?? []) : [];
32
+ const readSize = Math.max(0, size - readFrom);
33
+ const fd = await open(sessionFilePath, "r");
34
+ const buf = Buffer.alloc(readSize);
35
+ await fd.read(buf, 0, readSize, readFrom);
36
+ await fd.close();
37
+ const chunk = buf.toString("utf-8");
38
+ const cursor = advanceJsonlCursor({
39
+ offset: readFrom,
40
+ remainder: previousRemainder,
41
+ recentLines: previousLines,
42
+ }, chunk, CODEX_PHASE_RECENT_LINES);
43
+ const lines = cursor.recentLines;
44
+ let phase;
45
+ for (let i = lines.length - 1; i >= Math.max(0, lines.length - 10); i--) {
46
+ try {
47
+ const entry = JSON.parse(lines[i]);
48
+ if (entry.type === "event_msg") {
49
+ const payloadType = entry.payload?.type;
50
+ if (payloadType === "exec_command" || payloadType === "tool_call") {
51
+ phase = "tool";
52
+ break;
53
+ }
54
+ if (payloadType === "token_count") {
55
+ phase = "done";
56
+ break;
57
+ }
58
+ }
59
+ if (entry.type === "response_item") {
60
+ phase = "thinking";
61
+ break;
62
+ }
63
+ }
64
+ catch { }
65
+ }
66
+ const decayedPhase = config
67
+ ? resolvePhaseWithDecay(phase, cached?.result.phase, cached?.phaseDetectedAtMs, config.status.phaseDecay)
68
+ : phase;
69
+ const resolvedPhase = resolvePhaseFromHistory(decayedPhase, cached?.history ?? [], Date.now());
70
+ const nowMs = Date.now();
71
+ const transition = updatePhaseHistory(cached?.result.phase, cached?.history ?? [], resolvedPhase, nowMs);
72
+ codexPhaseCache.set(sessionFilePath, {
73
+ mtimeMs: fileStat.mtimeMs,
74
+ size: fileStat.size,
75
+ phaseDetectedAtMs: resolvedPhase ? nowMs : cached?.phaseDetectedAtMs,
76
+ offset: cursor.offset,
77
+ remainder: cursor.remainder,
78
+ recentLines: cursor.recentLines,
79
+ previousPhase: transition.previousPhase,
80
+ history: transition.history,
81
+ result: { phase: resolvedPhase },
82
+ });
83
+ return resolvedPhase;
84
+ }
85
+ catch {
86
+ return undefined;
87
+ }
88
+ }
89
+ /** Build index of recent Codex sessions (last 7 days) */
90
+ export async function indexCodexSessions(config) {
91
+ if (codexIndexCache && Date.now() - codexIndexCache.builtAt < CODEX_INDEX_TTL_MS) {
92
+ return codexIndexCache.sessions;
93
+ }
94
+ const sessionRoots = getCodexSessionRoots(config);
95
+ if (!sessionRoots.some((sessionsDir) => existsSync(sessionsDir)))
96
+ return [];
97
+ const metas = [];
98
+ const now = new Date();
99
+ try {
100
+ for (const sessionsDir of sessionRoots) {
101
+ for (let daysBack = 0; daysBack < 7; daysBack++) {
102
+ const d = new Date(now.getTime() - daysBack * 86400000);
103
+ const yyyy = d.getFullYear().toString();
104
+ const mm = String(d.getMonth() + 1).padStart(2, "0");
105
+ const dd = String(d.getDate()).padStart(2, "0");
106
+ const dayDir = join(sessionsDir, yyyy, mm, dd);
107
+ if (!existsSync(dayDir))
108
+ continue;
109
+ const files = await readdir(dayDir);
110
+ for (const f of files) {
111
+ if (!f.endsWith(".jsonl"))
112
+ continue;
113
+ const filePath = join(dayDir, f);
114
+ try {
115
+ const fileStat = await stat(filePath);
116
+ const cachedMeta = codexSessionFileCache.get(filePath);
117
+ if (cachedMeta?.timestamp &&
118
+ cachedMeta.mtimeMs ===
119
+ fileStat.mtimeMs &&
120
+ cachedMeta.size ===
121
+ fileStat.size) {
122
+ metas.push(cachedMeta);
123
+ continue;
124
+ }
125
+ const raw = await readFile(filePath, "utf-8");
126
+ const lines = raw.trim().split("\n");
127
+ const meta = { filePath };
128
+ let lastTokenCount;
129
+ for (const line of lines) {
130
+ try {
131
+ const entry = JSON.parse(line);
132
+ if (entry.type === "session_meta") {
133
+ meta.id = entry.payload?.id;
134
+ meta.cwd = entry.payload?.cwd;
135
+ meta.model = entry.payload?.model_provider;
136
+ if (entry.payload?.timestamp) {
137
+ meta.timestamp = new Date(entry.payload.timestamp).getTime() / 1000;
138
+ }
139
+ }
140
+ if (entry.type === "turn_context" && entry.payload?.model) {
141
+ meta.model = entry.payload.model;
142
+ }
143
+ if (entry.type === "event_msg" && entry.payload?.type === "token_count") {
144
+ lastTokenCount = entry.payload.info.total_token_usage;
145
+ }
146
+ }
147
+ catch {
148
+ // skip
149
+ }
150
+ }
151
+ if (meta.id && meta.cwd && meta.timestamp) {
152
+ const parsed = {
153
+ filePath,
154
+ id: meta.id,
155
+ cwd: meta.cwd,
156
+ timestamp: meta.timestamp,
157
+ lastActivityAt: fileStat.mtimeMs / 1000,
158
+ totalTokenUsage: lastTokenCount,
159
+ model: meta.model,
160
+ mtimeMs: fileStat.mtimeMs,
161
+ size: fileStat.size,
162
+ };
163
+ codexSessionFileCache.set(filePath, parsed);
164
+ upsertSessionRegistryEntry(codexSessionRegistry, {
165
+ filePath,
166
+ sessionId: meta.id,
167
+ cwd: meta.cwd,
168
+ firstSeenOffset: 0,
169
+ startedAt: meta.timestamp,
170
+ model: meta.model,
171
+ source: "codex",
172
+ });
173
+ metas.push(parsed);
174
+ }
175
+ }
176
+ catch {
177
+ // skip file
178
+ }
179
+ }
180
+ }
181
+ }
182
+ }
183
+ catch {
184
+ // sessions dir error
185
+ }
186
+ setCodexIndexCache({
187
+ builtAt: Date.now(),
188
+ sessions: metas,
189
+ });
190
+ return metas;
191
+ }
192
+ /** Match a Codex process to a session by cwd + closest timestamp */
193
+ export function matchCodexSession(processCwd, processStartTime, sessions) {
194
+ return selectCodexSession(processCwd, processStartTime, sessions);
195
+ }
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Gemini session parsing and phase detection.
3
+ */
4
+ import type { AgentSession, SessionPhase, TokenUsage } from "../types.js";
5
+ export interface GeminiSessionMeta {
6
+ filePath: string;
7
+ sessionId: string;
8
+ cwd: string;
9
+ startedAt?: number;
10
+ lastActivityAt?: number;
11
+ lastResponseAt?: number;
12
+ tokenUsage?: TokenUsage;
13
+ model?: string;
14
+ phase?: SessionPhase;
15
+ }
16
+ export declare function toEpochSec(value: string | undefined): number | undefined;
17
+ export declare function parseGeminiSessionContent(raw: string): Partial<GeminiSessionMeta>;
18
+ export declare function resolveGeminiProjectDir(cwd: string): Promise<string | undefined>;
19
+ export declare function parseGeminiSession(cwd: string): Promise<Partial<AgentSession> & {
20
+ sessionFile?: string;
21
+ }>;
@@ -0,0 +1,131 @@
1
+ /**
2
+ * Gemini session parsing and phase detection.
3
+ */
4
+ import { existsSync } from "node:fs";
5
+ import { readFile, readdir, stat } from "node:fs/promises";
6
+ import { join } from "node:path";
7
+ import { HOME } from "./cache.js";
8
+ export function toEpochSec(value) {
9
+ if (!value)
10
+ return undefined;
11
+ const parsed = new Date(value).getTime();
12
+ return Number.isNaN(parsed) ? undefined : parsed / 1000;
13
+ }
14
+ export function parseGeminiSessionContent(raw) {
15
+ try {
16
+ const data = JSON.parse(raw);
17
+ const messages = Array.isArray(data.messages) ? data.messages : [];
18
+ const latestMessage = messages.at(-1);
19
+ const latestGeminiMessage = [...messages].reverse().find((msg) => msg.type === "gemini");
20
+ const lastActivityAt = toEpochSec(data.lastUpdated) ??
21
+ [...messages]
22
+ .map((msg) => toEpochSec(msg.timestamp))
23
+ .filter((value) => value !== undefined)
24
+ .at(-1);
25
+ const lastResponseAt = toEpochSec(latestGeminiMessage?.timestamp);
26
+ // Phase priority: done (last message is gemini response) > thinking > tool
27
+ // A gemini response with toolCalls means the tool already ran and gemini answered.
28
+ const phase = latestMessage?.type === "user"
29
+ ? "thinking"
30
+ : latestMessage?.type === "gemini" || latestMessage?.type === "error"
31
+ ? "done"
32
+ : latestGeminiMessage?.toolCalls && latestGeminiMessage.toolCalls.length > 0
33
+ ? "tool"
34
+ : undefined;
35
+ return {
36
+ sessionId: typeof data.sessionId === "string" ? data.sessionId : undefined,
37
+ startedAt: toEpochSec(data.startTime),
38
+ lastActivityAt,
39
+ lastResponseAt,
40
+ model: latestGeminiMessage?.model,
41
+ tokenUsage: latestGeminiMessage?.tokens
42
+ ? {
43
+ inputTokens: latestGeminiMessage.tokens.input ?? 0,
44
+ outputTokens: latestGeminiMessage.tokens.output ?? 0,
45
+ cacheCreationTokens: 0,
46
+ cacheReadTokens: latestGeminiMessage.tokens.cached ?? 0,
47
+ totalTokens: latestGeminiMessage.tokens.total ?? 0,
48
+ }
49
+ : undefined,
50
+ phase,
51
+ };
52
+ }
53
+ catch {
54
+ return {};
55
+ }
56
+ }
57
+ export async function resolveGeminiProjectDir(cwd) {
58
+ const geminiTmpRoot = join(HOME, ".gemini", "tmp");
59
+ if (!existsSync(geminiTmpRoot))
60
+ return undefined;
61
+ try {
62
+ const entries = await readdir(geminiTmpRoot, { withFileTypes: true });
63
+ for (const entry of entries) {
64
+ if (!entry.isDirectory())
65
+ continue;
66
+ const projectDir = join(geminiTmpRoot, entry.name);
67
+ const projectRootFile = join(projectDir, ".project_root");
68
+ if (!existsSync(projectRootFile))
69
+ continue;
70
+ try {
71
+ const projectRoot = (await readFile(projectRootFile, "utf-8")).trim();
72
+ if (projectRoot === cwd)
73
+ return projectDir;
74
+ }
75
+ catch {
76
+ // skip unreadable project_root file
77
+ }
78
+ }
79
+ }
80
+ catch {
81
+ return undefined;
82
+ }
83
+ return undefined;
84
+ }
85
+ export async function parseGeminiSession(cwd) {
86
+ const projectDir = await resolveGeminiProjectDir(cwd);
87
+ if (!projectDir)
88
+ return {};
89
+ const chatsDir = join(projectDir, "chats");
90
+ if (!existsSync(chatsDir))
91
+ return {};
92
+ try {
93
+ const files = (await readdir(chatsDir))
94
+ .filter((name) => name.startsWith("session-") && name.endsWith(".json"))
95
+ .map((name) => join(chatsDir, name));
96
+ if (files.length === 0)
97
+ return {};
98
+ let latestFile;
99
+ let latestMtimeMs = -1;
100
+ for (const filePath of files) {
101
+ try {
102
+ const fileStat = await stat(filePath);
103
+ if (fileStat.mtimeMs > latestMtimeMs) {
104
+ latestMtimeMs = fileStat.mtimeMs;
105
+ latestFile = filePath;
106
+ }
107
+ }
108
+ catch {
109
+ // skip unreadable file
110
+ }
111
+ }
112
+ if (!latestFile)
113
+ return {};
114
+ const parsed = parseGeminiSessionContent(await readFile(latestFile, "utf-8"));
115
+ return {
116
+ cwd,
117
+ sessionId: parsed.sessionId,
118
+ startedAt: parsed.startedAt,
119
+ lastActivityAt: parsed.lastActivityAt,
120
+ lastResponseAt: parsed.lastResponseAt,
121
+ tokenUsage: parsed.tokenUsage,
122
+ model: parsed.model,
123
+ phase: parsed.phase,
124
+ sessionMatched: true,
125
+ sessionFile: latestFile,
126
+ };
127
+ }
128
+ catch {
129
+ return {};
130
+ }
131
+ }
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Process tree grouping and worker state propagation.
3
+ */
4
+ import type { AgentSession } from "../types.js";
5
+ export declare function propagateWorkerStateToParent(parent: AgentSession, child: Pick<AgentSession, "status" | "phase" | "lastActivityAt" | "lastResponseAt" | "startedAt" | "cpuPercent" | "memoryMb">): AgentSession;
6
+ /** Group child agent processes under their parent */
7
+ export declare function groupByParent(sessions: AgentSession[]): AgentSession[];
@@ -0,0 +1,54 @@
1
+ /**
2
+ * Process tree grouping and worker state propagation.
3
+ */
4
+ export function propagateWorkerStateToParent(parent, child) {
5
+ if (child.status !== "Active")
6
+ return parent;
7
+ const inheritedPhase = child.phase && child.phase !== "done"
8
+ ? child.phase
9
+ : parent.phase === "permission" || parent.phase === "done" || parent.phase === undefined
10
+ ? "tool"
11
+ : parent.phase;
12
+ return {
13
+ ...parent,
14
+ status: "Active",
15
+ phase: inheritedPhase,
16
+ cpuPercent: parent.cpuPercent + (("cpuPercent" in child && child.cpuPercent) || 0),
17
+ memoryMb: parent.memoryMb + (("memoryMb" in child && child.memoryMb) || 0),
18
+ startedAt: parent.startedAt && child.startedAt
19
+ ? Math.min(parent.startedAt, child.startedAt)
20
+ : (parent.startedAt ?? child.startedAt),
21
+ lastActivityAt: Math.max(parent.lastActivityAt ?? 0, child.lastActivityAt ?? 0, child.lastResponseAt ?? 0, child.startedAt ?? 0),
22
+ lastResponseAt: Math.max(parent.lastResponseAt ?? 0, child.lastResponseAt ?? 0) || undefined,
23
+ };
24
+ }
25
+ /** Group child agent processes under their parent */
26
+ export function groupByParent(sessions) {
27
+ const pidSet = new Set(sessions.map((s) => s.pid));
28
+ const childPids = new Set();
29
+ for (const session of sessions) {
30
+ if (session.ppid && pidSet.has(session.ppid)) {
31
+ const parent = sessions.find((s) => s.pid === session.ppid && s.agentName === session.agentName);
32
+ if (parent) {
33
+ if (!parent.workers)
34
+ parent.workers = [];
35
+ parent.workers.push({
36
+ pid: session.pid,
37
+ cpuPercent: session.cpuPercent,
38
+ memoryMb: session.memoryMb,
39
+ status: session.status,
40
+ });
41
+ const propagated = propagateWorkerStateToParent(parent, session);
42
+ parent.cpuPercent = propagated.cpuPercent;
43
+ parent.memoryMb = propagated.memoryMb;
44
+ parent.status = propagated.status;
45
+ parent.phase = propagated.phase;
46
+ parent.startedAt = propagated.startedAt;
47
+ parent.lastActivityAt = propagated.lastActivityAt;
48
+ parent.lastResponseAt = propagated.lastResponseAt;
49
+ childPids.add(session.pid);
50
+ }
51
+ }
52
+ }
53
+ return sessions.filter((s) => !childPids.has(s.pid));
54
+ }
@@ -0,0 +1,16 @@
1
+ /**
2
+ * AI agent process scanner.
3
+ *
4
+ * Detects running AI coding agents (Claude Code, Codex, Gemini),
5
+ * enriches with session data (tokens, cwd, start time),
6
+ * and determines activity status.
7
+ */
8
+ import type { MarmonitorConfig } from "../config/index.js";
9
+ import type { AgentSession } from "../types.js";
10
+ export type { ScanOptions } from "./types.js";
11
+ export { detectAgentFromProcessSignature } from "./process.js";
12
+ export { propagateWorkerStateToParent } from "./group.js";
13
+ export { parseGeminiSessionContent } from "./gemini.js";
14
+ import type { ScanOptions } from "./types.js";
15
+ /** Scan for all running AI agent sessions */
16
+ export declare function scanAgents(config: MarmonitorConfig, options?: ScanOptions): Promise<AgentSession[]>;
@@ -0,0 +1,256 @@
1
+ /**
2
+ * AI agent process scanner.
3
+ *
4
+ * Detects running AI coding agents (Claude Code, Codex, Gemini),
5
+ * enriches with session data (tokens, cwd, start time),
6
+ * and determines activity status.
7
+ */
8
+ import { existsSync } from "node:fs";
9
+ import { readFile, readdir } from "node:fs/promises";
10
+ import { join } from "node:path";
11
+ import pidusage from "pidusage";
12
+ import psList from "ps-list";
13
+ export { detectAgentFromProcessSignature } from "./process.js";
14
+ export { propagateWorkerStateToParent } from "./group.js";
15
+ export { parseGeminiSessionContent } from "./gemini.js";
16
+ // ─── Internal imports ─────────────────────────────────────────────
17
+ import { sessionEnrichmentCache } from "./cache.js";
18
+ import { detectClaudePhase, getClaudeSessionRoots, parseClaudeSession, parseClaudeTokens, } from "./claude.js";
19
+ import { detectCodexPhase, indexCodexSessions, matchCodexSession } from "./codex.js";
20
+ import { parseGeminiSession } from "./gemini.js";
21
+ import { groupByParent } from "./group.js";
22
+ import { detectAgentFromProcessSignature as _detectAgent, detectRuntimeSource, getProcessCwd, getProcessStartTime, } from "./process.js";
23
+ import { detectCliStdoutPhase, determineStatus } from "./status.js";
24
+ // ─── Main Scanner ──────────────────────────────────────────────────
25
+ /** Scan for all running AI agent sessions */
26
+ export async function scanAgents(config, options = {}) {
27
+ const enrichmentMode = options.enrichmentMode ?? "full";
28
+ const isFullEnrichment = enrichmentMode === "full";
29
+ const seenPids = new Set();
30
+ // 1. Find running processes
31
+ const processes = await psList();
32
+ // Filter to agent processes
33
+ const agentProcesses = [];
34
+ for (const proc of processes) {
35
+ const agentName = _detectAgent(proc, config);
36
+ if (!agentName)
37
+ continue;
38
+ if (seenPids.has(proc.pid))
39
+ continue;
40
+ seenPids.add(proc.pid);
41
+ agentProcesses.push({ proc, agentName });
42
+ }
43
+ // 2. Batch pidusage
44
+ const pids = agentProcesses.map((a) => a.proc.pid);
45
+ let usageMap = {};
46
+ try {
47
+ usageMap = await pidusage(pids);
48
+ }
49
+ catch {
50
+ // some PIDs may have exited
51
+ }
52
+ // 3. Pre-index Codex sessions (once, shared across all Codex processes)
53
+ const codexSessions = isFullEnrichment ? await indexCodexSessions(config) : [];
54
+ // 4. Build sessions with enrichment (parallel)
55
+ const sessionPromises = agentProcesses.map(async ({ proc, agentName }) => {
56
+ const usage = usageMap[proc.pid];
57
+ const cpuPercent = usage ? Math.round(usage.cpu * 10) / 10 : 0;
58
+ const memoryMb = usage ? Math.round((usage.memory / (1024 * 1024)) * 10) / 10 : 0;
59
+ // Skip tiny processes (spawners/wrappers)
60
+ if (memoryMb < config.status.minMemoryMb)
61
+ return null;
62
+ let cwd = "unknown";
63
+ let sessionId;
64
+ let startedAt;
65
+ let tokenUsage;
66
+ let model;
67
+ let sessionMatched = false;
68
+ let phase;
69
+ let lastResponseAt;
70
+ let lastActivityAt;
71
+ let codexSessionFile;
72
+ const runtimeSource = detectRuntimeSource(agentName, proc.cmd);
73
+ const cacheKey = `${agentName}:${proc.pid}`;
74
+ const cachedEnrichment = sessionEnrichmentCache.get(cacheKey);
75
+ if (!isFullEnrichment && cachedEnrichment) {
76
+ if (cachedEnrichment.cwd)
77
+ cwd = cachedEnrichment.cwd;
78
+ sessionId = cachedEnrichment.sessionId;
79
+ startedAt = cachedEnrichment.startedAt;
80
+ tokenUsage = cachedEnrichment.tokenUsage;
81
+ model = cachedEnrichment.model;
82
+ sessionMatched = cachedEnrichment.sessionMatched ?? false;
83
+ phase = cachedEnrichment.phase;
84
+ lastResponseAt = cachedEnrichment.lastResponseAt;
85
+ lastActivityAt = cachedEnrichment.lastActivityAt;
86
+ }
87
+ else if (agentName === "Claude Code") {
88
+ const claudeData = await parseClaudeSession(proc.pid, config);
89
+ if (claudeData.cwd)
90
+ cwd = claudeData.cwd;
91
+ if (cwd === "unknown")
92
+ cwd = (await getProcessCwd(proc.pid)) ?? "unknown";
93
+ sessionId = claudeData.sessionId;
94
+ startedAt = claudeData.startedAt;
95
+ tokenUsage = claudeData.tokenUsage;
96
+ model = claudeData.model;
97
+ sessionMatched = claudeData.sessionMatched ?? false;
98
+ lastActivityAt = claudeData.lastActivityAt;
99
+ if (sessionId && cwd) {
100
+ const phaseResult = await detectClaudePhase(sessionId, cwd, startedAt, config);
101
+ phase = phaseResult.phase;
102
+ lastResponseAt = phaseResult.lastResponseAt;
103
+ lastActivityAt = phaseResult.lastActivityAt ?? lastActivityAt;
104
+ }
105
+ }
106
+ else if (agentName === "Codex") {
107
+ cwd = cachedEnrichment?.cwd ?? (await getProcessCwd(proc.pid)) ?? "unknown";
108
+ const processStartTime = await getProcessStartTime(proc.pid);
109
+ const matched = matchCodexSession(cwd, processStartTime, codexSessions);
110
+ if (matched) {
111
+ sessionMatched = true;
112
+ sessionId = matched.id;
113
+ startedAt = matched.timestamp;
114
+ lastActivityAt = matched.lastActivityAt;
115
+ model = matched.model;
116
+ codexSessionFile = matched.filePath;
117
+ if (matched.totalTokenUsage) {
118
+ tokenUsage = {
119
+ inputTokens: matched.totalTokenUsage.input_tokens,
120
+ outputTokens: matched.totalTokenUsage.output_tokens,
121
+ cacheCreationTokens: 0,
122
+ cacheReadTokens: matched.totalTokenUsage.cached_input_tokens ?? 0,
123
+ totalTokens: matched.totalTokenUsage.total_tokens,
124
+ };
125
+ }
126
+ }
127
+ // Detect phase from session JSONL
128
+ phase = await detectCodexPhase(codexSessionFile, config);
129
+ if (phase !== "permission" && runtimeSource === "cli") {
130
+ phase = (await detectCliStdoutPhase({ pid: proc.pid, cwd }, config)) ?? phase;
131
+ }
132
+ }
133
+ else if (agentName === "Gemini") {
134
+ cwd = cachedEnrichment?.cwd ?? (await getProcessCwd(proc.pid)) ?? "unknown";
135
+ const geminiData = await parseGeminiSession(cwd);
136
+ startedAt = geminiData.startedAt ?? (await getProcessStartTime(proc.pid));
137
+ sessionId = geminiData.sessionId;
138
+ tokenUsage = geminiData.tokenUsage;
139
+ model = geminiData.model;
140
+ phase = geminiData.phase;
141
+ lastResponseAt = geminiData.lastResponseAt;
142
+ lastActivityAt = geminiData.lastActivityAt;
143
+ sessionMatched = geminiData.sessionMatched ?? true;
144
+ if (phase !== "permission") {
145
+ phase = (await detectCliStdoutPhase({ pid: proc.pid, cwd }, config)) ?? phase;
146
+ }
147
+ }
148
+ if (cwd === "unknown") {
149
+ cwd = cachedEnrichment?.cwd ?? (await getProcessCwd(proc.pid)) ?? "unknown";
150
+ }
151
+ const statusBaseAt = lastActivityAt ?? lastResponseAt ?? startedAt;
152
+ const elapsed = statusBaseAt ? Date.now() / 1000 - statusBaseAt : undefined;
153
+ const status = determineStatus(cpuPercent, elapsed, sessionMatched, phase, config);
154
+ const session = {
155
+ agentName,
156
+ pid: proc.pid,
157
+ ppid: proc.ppid,
158
+ cwd,
159
+ cpuPercent,
160
+ memoryMb,
161
+ status,
162
+ startedAt,
163
+ sessionId,
164
+ tokenUsage,
165
+ model,
166
+ sessionMatched,
167
+ phase,
168
+ lastResponseAt,
169
+ lastActivityAt,
170
+ runtimeSource,
171
+ };
172
+ if (isFullEnrichment) {
173
+ sessionEnrichmentCache.set(cacheKey, {
174
+ cwd: session.cwd,
175
+ sessionId: session.sessionId,
176
+ startedAt: session.startedAt,
177
+ tokenUsage: session.tokenUsage,
178
+ model: session.model,
179
+ sessionMatched: session.sessionMatched,
180
+ phase: session.phase,
181
+ lastResponseAt: session.lastResponseAt,
182
+ lastActivityAt: session.lastActivityAt,
183
+ runtimeSource: session.runtimeSource,
184
+ });
185
+ }
186
+ return session;
187
+ });
188
+ const results = await Promise.all(sessionPromises);
189
+ const sessions = results.filter((s) => s !== null);
190
+ // 5. Check for dead sessions (Claude: session file exists but process gone)
191
+ if (config.display.showDead) {
192
+ for (const claudeSessionDir of getClaudeSessionRoots(config)) {
193
+ if (!existsSync(claudeSessionDir))
194
+ continue;
195
+ try {
196
+ const files = await readdir(claudeSessionDir);
197
+ for (const file of files) {
198
+ if (!file.endsWith(".json"))
199
+ continue;
200
+ const pid = Number.parseInt(file.replace(".json", ""), 10);
201
+ if (Number.isNaN(pid) || seenPids.has(pid))
202
+ continue;
203
+ const isRunning = processes.some((p) => p.pid === pid);
204
+ if (isRunning)
205
+ continue;
206
+ try {
207
+ const raw = await readFile(join(claudeSessionDir, file), "utf-8");
208
+ const data = JSON.parse(raw);
209
+ let tokenUsage;
210
+ let model;
211
+ if (data.sessionId && data.cwd) {
212
+ const tokenData = await parseClaudeTokens(data.sessionId, data.cwd, undefined, config);
213
+ tokenUsage = tokenData.tokenUsage;
214
+ model = tokenData.model;
215
+ }
216
+ sessions.push({
217
+ agentName: "Claude Code",
218
+ pid,
219
+ cwd: data.cwd ?? "unknown",
220
+ cpuPercent: 0,
221
+ memoryMb: 0,
222
+ status: "Dead",
223
+ sessionId: data.sessionId,
224
+ startedAt: data.startedAt ? data.startedAt / 1000 : undefined,
225
+ tokenUsage,
226
+ model,
227
+ sessionMatched: true,
228
+ });
229
+ }
230
+ catch {
231
+ // skip
232
+ }
233
+ }
234
+ }
235
+ catch {
236
+ // session dir read error
237
+ }
238
+ }
239
+ }
240
+ // 6. Group by parent, then sort by config
241
+ const grouped = groupByParent(sessions);
242
+ const sortKey = config.display.sortBy;
243
+ grouped.sort((a, b) => {
244
+ switch (sortKey) {
245
+ case "agent":
246
+ return a.agentName.localeCompare(b.agentName) || a.cwd.localeCompare(b.cwd);
247
+ case "status":
248
+ return a.status.localeCompare(b.status) || a.cwd.localeCompare(b.cwd);
249
+ case "pid":
250
+ return a.pid - b.pid;
251
+ default:
252
+ return a.cwd.localeCompare(b.cwd);
253
+ }
254
+ });
255
+ return grouped;
256
+ }