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,88 @@
1
+ /**
2
+ * Cache instances and internal cache types for the scanner modules.
3
+ */
4
+ import type { SessionRegistryEntry } from "../output/utils.js";
5
+ import type { AgentSession, SessionPhase, TokenUsage } from "../types.js";
6
+ import { BoundedMap } from "./bounded-map.js";
7
+ export declare const HOME: string;
8
+ export declare const PROCESS_CWD_TTL_MS = 60000;
9
+ export declare const PROCESS_START_TTL_MS = 300000;
10
+ export declare const CODEX_INDEX_TTL_MS = 30000;
11
+ export declare const CLAUDE_SESSION_MTIME_MATCH_SEC = 120;
12
+ export declare const CLAUDE_SESSION_AMBIGUITY_GAP_SEC = 300;
13
+ export declare const CLAUDE_PHASE_RECENT_LINES = 50;
14
+ export declare const CODEX_PHASE_RECENT_LINES = 30;
15
+ export declare const RECENT_ACTIVITY_ACTIVE_SEC = 180;
16
+ export interface FileTokenCacheEntry {
17
+ mtimeMs: number;
18
+ size: number;
19
+ result: {
20
+ tokenUsage?: TokenUsage;
21
+ model?: string;
22
+ };
23
+ }
24
+ export interface PhaseResult {
25
+ phase?: SessionPhase;
26
+ lastResponseAt?: number;
27
+ lastActivityAt?: number;
28
+ }
29
+ export interface PhaseCacheEntry {
30
+ mtimeMs: number;
31
+ size: number;
32
+ phaseDetectedAtMs?: number;
33
+ offset: number;
34
+ remainder: string;
35
+ recentLines: string[];
36
+ previousPhase?: SessionPhase;
37
+ history: Array<{
38
+ phase: Exclude<SessionPhase, undefined>;
39
+ at: number;
40
+ }>;
41
+ result: PhaseResult;
42
+ }
43
+ export interface ProcessCwdCacheEntry {
44
+ checkedAt: number;
45
+ cwd?: string;
46
+ }
47
+ export interface ProcessStartCacheEntry {
48
+ checkedAt: number;
49
+ startedAt?: number;
50
+ }
51
+ export interface StdoutHeuristicCacheEntry {
52
+ checkedAt: number;
53
+ phase?: SessionPhase;
54
+ }
55
+ /** Codex session metadata (parsed from JSONL first lines) */
56
+ export interface CodexSessionMeta {
57
+ filePath: string;
58
+ id: string;
59
+ cwd: string;
60
+ timestamp: number;
61
+ lastActivityAt?: number;
62
+ totalTokenUsage?: {
63
+ input_tokens: number;
64
+ cached_input_tokens: number;
65
+ output_tokens: number;
66
+ total_tokens: number;
67
+ };
68
+ model?: string;
69
+ }
70
+ export declare const claudeProjectDirCache: BoundedMap<string, string>;
71
+ export declare const claudeTokenCache: BoundedMap<string, FileTokenCacheEntry>;
72
+ export declare const claudePhaseCache: BoundedMap<string, PhaseCacheEntry>;
73
+ export declare const codexPhaseCache: BoundedMap<string, PhaseCacheEntry>;
74
+ export declare const codexSessionFileCache: BoundedMap<string, CodexSessionMeta & {
75
+ mtimeMs?: number;
76
+ size?: number;
77
+ }>;
78
+ export declare const claudeSessionRegistry: BoundedMap<string, SessionRegistryEntry>;
79
+ export declare const codexSessionRegistry: BoundedMap<string, SessionRegistryEntry>;
80
+ export declare const processCwdCache: BoundedMap<number, ProcessCwdCacheEntry>;
81
+ export declare const processStartCache: BoundedMap<number, ProcessStartCacheEntry>;
82
+ export declare const stdoutHeuristicCache: BoundedMap<number, StdoutHeuristicCacheEntry>;
83
+ export declare const sessionEnrichmentCache: BoundedMap<string, Partial<AgentSession>>;
84
+ export declare let codexIndexCache: {
85
+ builtAt: number;
86
+ sessions: CodexSessionMeta[];
87
+ } | undefined;
88
+ export declare function setCodexIndexCache(value: typeof codexIndexCache): void;
@@ -0,0 +1,32 @@
1
+ /**
2
+ * Cache instances and internal cache types for the scanner modules.
3
+ */
4
+ import { homedir } from "node:os";
5
+ import { BoundedMap } from "./bounded-map.js";
6
+ // ─── Shared Constants ──────────────────────────────────────────────
7
+ export const HOME = homedir();
8
+ export const PROCESS_CWD_TTL_MS = 60_000;
9
+ export const PROCESS_START_TTL_MS = 300_000;
10
+ export const CODEX_INDEX_TTL_MS = 30_000;
11
+ export const CLAUDE_SESSION_MTIME_MATCH_SEC = 120;
12
+ export const CLAUDE_SESSION_AMBIGUITY_GAP_SEC = 300;
13
+ export const CLAUDE_PHASE_RECENT_LINES = 50;
14
+ export const CODEX_PHASE_RECENT_LINES = 30;
15
+ export const RECENT_ACTIVITY_ACTIVE_SEC = 180;
16
+ // ─── Cache Instances ───────────────────────────────────────────────
17
+ export const claudeProjectDirCache = new BoundedMap(64);
18
+ export const claudeTokenCache = new BoundedMap(64);
19
+ export const claudePhaseCache = new BoundedMap(64);
20
+ export const codexPhaseCache = new BoundedMap(64);
21
+ export const codexSessionFileCache = new BoundedMap(256);
22
+ export const claudeSessionRegistry = new BoundedMap(128);
23
+ export const codexSessionRegistry = new BoundedMap(128);
24
+ export const processCwdCache = new BoundedMap(128);
25
+ export const processStartCache = new BoundedMap(128);
26
+ export const stdoutHeuristicCache = new BoundedMap(64);
27
+ export const sessionEnrichmentCache = new BoundedMap(64);
28
+ // ─── Codex Index Cache ─────────────────────────────────────────────
29
+ export let codexIndexCache;
30
+ export function setCodexIndexCache(value) {
31
+ codexIndexCache = value;
32
+ }
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Claude Code session parsing, token extraction, and phase detection.
3
+ */
4
+ import type { MarmonitorConfig } from "../config/index.js";
5
+ import type { AgentSession, TokenUsage } from "../types.js";
6
+ import type { PhaseResult } from "./cache.js";
7
+ export declare function getClaudeProjectRoots(config?: MarmonitorConfig): string[];
8
+ export declare function getClaudeSessionRoots(config?: MarmonitorConfig): string[];
9
+ /**
10
+ * Find the Claude projects/ subdirectory matching a given cwd.
11
+ * Strategy: (1) realpath + encode, (2) fallback scan by sessionId.
12
+ */
13
+ export declare function findClaudeProjectDir(cwd: string, sessionId?: string, config?: MarmonitorConfig): Promise<string | undefined>;
14
+ export declare function resolveClaudeSessionFile(sessionId: string, cwd: string, startedAt?: number, config?: MarmonitorConfig): Promise<string | undefined>;
15
+ /** Parse Claude session JSONL for token usage (streaming, stops early for large files) */
16
+ export declare function parseClaudeTokens(sessionId: string, cwd: string, startedAt?: number, config?: MarmonitorConfig): Promise<{
17
+ tokenUsage?: TokenUsage;
18
+ model?: string;
19
+ }>;
20
+ /**
21
+ * Detect current Claude session phase by reading the last few lines of JSONL.
22
+ */
23
+ export declare function detectClaudePhase(sessionId: string, cwd: string, startedAt?: number, config?: MarmonitorConfig): Promise<PhaseResult>;
24
+ /** Parse Claude Code session file for enriched data */
25
+ export declare function parseClaudeSession(pid: number, config?: MarmonitorConfig): Promise<Partial<AgentSession>>;
@@ -0,0 +1,425 @@
1
+ /**
2
+ * Claude Code session parsing, token extraction, and phase detection.
3
+ */
4
+ import { existsSync } from "node:fs";
5
+ import { realpath as fsRealpath, 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, 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";
10
+ export function getClaudeProjectRoots(config) {
11
+ return config
12
+ ? resolveRuntimeDataPaths(config).claudeProjects
13
+ : [join(HOME, ".claude", "projects")];
14
+ }
15
+ export function getClaudeSessionRoots(config) {
16
+ return config
17
+ ? resolveRuntimeDataPaths(config).claudeSessions
18
+ : [join(HOME, ".claude", "sessions")];
19
+ }
20
+ /**
21
+ * Find the Claude projects/ subdirectory matching a given cwd.
22
+ * Strategy: (1) realpath + encode, (2) fallback scan by sessionId.
23
+ */
24
+ export async function findClaudeProjectDir(cwd, sessionId, config) {
25
+ const projectRoots = getClaudeProjectRoots(config);
26
+ if (!projectRoots.some((projectsDir) => existsSync(projectsDir)))
27
+ return undefined;
28
+ const cacheKey = `${cwd}::${sessionId ?? ""}`;
29
+ const cached = claudeProjectDirCache.get(cacheKey);
30
+ if (cached && projectRoots.some((projectsDir) => existsSync(join(projectsDir, cached)))) {
31
+ return cached;
32
+ }
33
+ // Claude Code encodes cwd by replacing both "/" and "." with "-"
34
+ const encodeCwd = (p) => p.replace(/[/.]/g, "-");
35
+ // 1st: realpath → encode → direct check
36
+ try {
37
+ const canonical = await fsRealpath(cwd).catch(() => cwd);
38
+ const encoded = encodeCwd(canonical);
39
+ for (const projectsDir of projectRoots) {
40
+ if (existsSync(join(projectsDir, encoded))) {
41
+ claudeProjectDirCache.set(cacheKey, encoded);
42
+ return encoded;
43
+ }
44
+ }
45
+ }
46
+ catch {
47
+ // continue to fallback
48
+ }
49
+ // 2nd: raw cwd encode (without realpath)
50
+ const rawEncoded = encodeCwd(cwd);
51
+ for (const projectsDir of projectRoots) {
52
+ if (existsSync(join(projectsDir, rawEncoded))) {
53
+ claudeProjectDirCache.set(cacheKey, rawEncoded);
54
+ return rawEncoded;
55
+ }
56
+ }
57
+ // 3rd: fallback scan — find dir containing sessionId.jsonl
58
+ if (sessionId) {
59
+ const registeredPath = resolveSessionRegistryPath(claudeSessionRegistry, sessionId);
60
+ if (registeredPath && existsSync(registeredPath)) {
61
+ const parts = registeredPath.split("/");
62
+ const dir = parts.at(-2);
63
+ if (dir) {
64
+ claudeProjectDirCache.set(cacheKey, dir);
65
+ return dir;
66
+ }
67
+ }
68
+ try {
69
+ for (const projectsDir of projectRoots) {
70
+ if (!existsSync(projectsDir))
71
+ continue;
72
+ const dirs = await readdir(projectsDir);
73
+ for (const dir of dirs) {
74
+ const sessionFile = join(projectsDir, dir, `${sessionId}.jsonl`);
75
+ if (existsSync(sessionFile)) {
76
+ upsertSessionRegistryEntry(claudeSessionRegistry, {
77
+ filePath: sessionFile,
78
+ sessionId,
79
+ cwd,
80
+ firstSeenOffset: 0,
81
+ source: "claude",
82
+ });
83
+ claudeProjectDirCache.set(cacheKey, dir);
84
+ return dir;
85
+ }
86
+ }
87
+ }
88
+ }
89
+ catch {
90
+ // scan failed
91
+ }
92
+ }
93
+ return undefined;
94
+ }
95
+ export async function resolveClaudeSessionFile(sessionId, cwd, startedAt, config) {
96
+ const registeredPath = resolveSessionRegistryPath(claudeSessionRegistry, sessionId);
97
+ if (registeredPath && existsSync(registeredPath))
98
+ return registeredPath;
99
+ const projectDirName = await findClaudeProjectDir(cwd, sessionId, config);
100
+ if (!projectDirName)
101
+ return undefined;
102
+ const projectRoots = getClaudeProjectRoots(config);
103
+ for (const projectsDir of projectRoots) {
104
+ const directPath = join(projectsDir, projectDirName, `${sessionId}.jsonl`);
105
+ if (existsSync(directPath)) {
106
+ upsertSessionRegistryEntry(claudeSessionRegistry, {
107
+ filePath: directPath,
108
+ sessionId,
109
+ cwd,
110
+ firstSeenOffset: 0,
111
+ startedAt,
112
+ source: "claude",
113
+ });
114
+ return directPath;
115
+ }
116
+ }
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;
186
+ }
187
+ }
188
+ /** Parse Claude session JSONL for token usage (streaming, stops early for large files) */
189
+ export async function parseClaudeTokens(sessionId, cwd, startedAt, config) {
190
+ const sessionFile = await resolveClaudeSessionFile(sessionId, cwd, startedAt, config);
191
+ if (!sessionFile || !existsSync(sessionFile))
192
+ return {};
193
+ try {
194
+ const fileStat = await stat(sessionFile);
195
+ const cached = claudeTokenCache.get(sessionFile);
196
+ if (cached && cached.mtimeMs === fileStat.mtimeMs && cached.size === fileStat.size) {
197
+ return cached.result;
198
+ }
199
+ let inputTokens = cached?.result.tokenUsage?.inputTokens ?? 0;
200
+ let outputTokens = cached?.result.tokenUsage?.outputTokens ?? 0;
201
+ let cacheCreationTokens = cached?.result.tokenUsage?.cacheCreationTokens ?? 0;
202
+ let cacheReadTokens = cached?.result.tokenUsage?.cacheReadTokens ?? 0;
203
+ let model = cached?.result.model;
204
+ let raw;
205
+ if (cached && fileStat.size > cached.size) {
206
+ const appendSize = fileStat.size - cached.size;
207
+ const fd = await open(sessionFile, "r");
208
+ const buf = Buffer.alloc(appendSize);
209
+ await fd.read(buf, 0, appendSize, cached.size);
210
+ await fd.close();
211
+ raw = buf.toString("utf-8");
212
+ }
213
+ else {
214
+ raw = await readFile(sessionFile, "utf-8");
215
+ inputTokens = 0;
216
+ outputTokens = 0;
217
+ cacheCreationTokens = 0;
218
+ cacheReadTokens = 0;
219
+ model = undefined;
220
+ }
221
+ const lines = raw.split("\n").filter((line) => line.trim());
222
+ for (const line of lines) {
223
+ try {
224
+ const entry = JSON.parse(line);
225
+ const usage = entry?.message?.usage;
226
+ if (!usage)
227
+ continue;
228
+ inputTokens += usage.input_tokens ?? 0;
229
+ outputTokens += usage.output_tokens ?? 0;
230
+ cacheCreationTokens += usage.cache_creation_input_tokens ?? 0;
231
+ cacheReadTokens += usage.cache_read_input_tokens ?? 0;
232
+ if (entry?.message?.model)
233
+ model = entry.message.model;
234
+ }
235
+ catch {
236
+ // skip malformed lines
237
+ }
238
+ }
239
+ const result = {
240
+ tokenUsage: inputTokens === 0 && outputTokens === 0
241
+ ? undefined
242
+ : {
243
+ inputTokens,
244
+ outputTokens,
245
+ cacheCreationTokens,
246
+ cacheReadTokens,
247
+ totalTokens: inputTokens + outputTokens,
248
+ },
249
+ model,
250
+ };
251
+ claudeTokenCache.set(sessionFile, {
252
+ mtimeMs: fileStat.mtimeMs,
253
+ size: fileStat.size,
254
+ result,
255
+ });
256
+ return result;
257
+ }
258
+ catch {
259
+ return {};
260
+ }
261
+ }
262
+ /**
263
+ * Detect current Claude session phase by reading the last few lines of JSONL.
264
+ */
265
+ export async function detectClaudePhase(sessionId, cwd, startedAt, config) {
266
+ const sessionFile = await resolveClaudeSessionFile(sessionId, cwd, startedAt, config);
267
+ if (!sessionFile || !existsSync(sessionFile))
268
+ return {};
269
+ try {
270
+ const fileStat = await stat(sessionFile);
271
+ const cached = claudePhaseCache.get(sessionFile);
272
+ if (cached && cached.mtimeMs === fileStat.mtimeMs && cached.size === fileStat.size) {
273
+ return {
274
+ ...cached.result,
275
+ phase: config
276
+ ? resolvePhaseWithDecay(cached.result.phase, cached.result.phase, cached.phaseDetectedAtMs, config.status.phaseDecay)
277
+ : cached.result.phase,
278
+ };
279
+ }
280
+ const { size } = fileStat;
281
+ const shouldAppend = Boolean(cached) && size >= (cached?.offset ?? 0);
282
+ const readFrom = shouldAppend ? (cached?.offset ?? 0) : 0;
283
+ const previousRemainder = shouldAppend ? (cached?.remainder ?? "") : "";
284
+ const previousLines = shouldAppend ? (cached?.recentLines ?? []) : [];
285
+ const readSize = Math.max(0, size - readFrom);
286
+ const fd = await open(sessionFile, "r");
287
+ const buf = Buffer.alloc(readSize);
288
+ await fd.read(buf, 0, readSize, readFrom);
289
+ await fd.close();
290
+ const chunk = buf.toString("utf-8");
291
+ const cursor = advanceJsonlCursor({
292
+ offset: readFrom,
293
+ remainder: previousRemainder,
294
+ recentLines: previousLines,
295
+ }, chunk, CLAUDE_PHASE_RECENT_LINES);
296
+ const lines = cursor.recentLines;
297
+ let lastResponseAt;
298
+ let lastActivityAt;
299
+ let phase;
300
+ const getContentTypes = (content) => {
301
+ if (!Array.isArray(content))
302
+ return [];
303
+ return content
304
+ .map((item) => {
305
+ if (item && typeof item === "object" && "type" in item) {
306
+ const type = item.type;
307
+ return typeof type === "string" ? type : undefined;
308
+ }
309
+ return undefined;
310
+ })
311
+ .filter((value) => Boolean(value));
312
+ };
313
+ // Walk backwards through the last events
314
+ for (let i = lines.length - 1; i >= Math.max(0, lines.length - 20); i--) {
315
+ try {
316
+ const entry = JSON.parse(lines[i]);
317
+ const type = entry.type;
318
+ const ts = entry.timestamp ? new Date(entry.timestamp).getTime() / 1000 : undefined;
319
+ // Track latest timestamps
320
+ if (ts && !lastActivityAt)
321
+ lastActivityAt = ts;
322
+ if (ts && type === "assistant" && !lastResponseAt)
323
+ lastResponseAt = ts;
324
+ // Phase detection (only set once — first match wins)
325
+ if (!phase) {
326
+ if (type === "progress") {
327
+ const data = entry.data;
328
+ if (data?.type === "hook_progress") {
329
+ phase = "tool";
330
+ }
331
+ continue;
332
+ }
333
+ if (type === "assistant") {
334
+ const stopReason = entry.message?.stop_reason;
335
+ const contentTypes = getContentTypes(entry.message?.content);
336
+ if (stopReason === "tool_use") {
337
+ const hasResult = lines.slice(i + 1).some((l) => {
338
+ try {
339
+ const e = JSON.parse(l);
340
+ return (e.type === "user" && getContentTypes(e.message?.content).includes("tool_result"));
341
+ }
342
+ catch {
343
+ return false;
344
+ }
345
+ });
346
+ if (!hasResult)
347
+ phase = "permission";
348
+ continue;
349
+ }
350
+ if (stopReason === null || stopReason === undefined) {
351
+ if (contentTypes.includes("text") || contentTypes.includes("tool_use")) {
352
+ phase = "thinking";
353
+ }
354
+ }
355
+ if (stopReason === "end_turn") {
356
+ phase = "done";
357
+ }
358
+ }
359
+ if (type === "user") {
360
+ phase = "thinking";
361
+ }
362
+ }
363
+ // Stop early if we have everything
364
+ if (phase && lastResponseAt && lastActivityAt)
365
+ break;
366
+ }
367
+ catch { }
368
+ }
369
+ // If event timestamps were not parseable, fall back to the project JSONL mtime.
370
+ if (!lastActivityAt) {
371
+ lastActivityAt = fileStat.mtimeMs / 1000;
372
+ }
373
+ const decayedPhase = config
374
+ ? resolvePhaseWithDecay(phase, cached?.result.phase, cached?.phaseDetectedAtMs, config.status.phaseDecay)
375
+ : phase;
376
+ const resolvedPhase = resolvePhaseFromHistory(decayedPhase, cached?.history ?? [], Date.now());
377
+ const nowMs = Date.now();
378
+ const transition = updatePhaseHistory(cached?.result.phase, cached?.history ?? [], resolvedPhase, nowMs);
379
+ const result = { phase: resolvedPhase, lastResponseAt, lastActivityAt };
380
+ claudePhaseCache.set(sessionFile, {
381
+ mtimeMs: fileStat.mtimeMs,
382
+ size: fileStat.size,
383
+ phaseDetectedAtMs: resolvedPhase ? nowMs : cached?.phaseDetectedAtMs,
384
+ offset: cursor.offset,
385
+ remainder: cursor.remainder,
386
+ recentLines: cursor.recentLines,
387
+ previousPhase: transition.previousPhase,
388
+ history: transition.history,
389
+ result,
390
+ });
391
+ return result;
392
+ }
393
+ catch {
394
+ return {};
395
+ }
396
+ }
397
+ /** Parse Claude Code session file for enriched data */
398
+ export async function parseClaudeSession(pid, config) {
399
+ const sessionFile = getClaudeSessionRoots(config)
400
+ .map((root) => join(root, `${pid}.json`))
401
+ .find((candidate) => existsSync(candidate));
402
+ if (!sessionFile)
403
+ return {};
404
+ try {
405
+ const fileStat = await stat(sessionFile);
406
+ const raw = await readFile(sessionFile, "utf-8");
407
+ const data = JSON.parse(raw);
408
+ const result = {
409
+ cwd: data.cwd,
410
+ sessionId: data.sessionId,
411
+ startedAt: data.startedAt ? data.startedAt / 1000 : undefined,
412
+ lastActivityAt: fileStat.mtimeMs / 1000,
413
+ sessionMatched: true,
414
+ };
415
+ if (data.sessionId && data.cwd) {
416
+ const tokenData = await parseClaudeTokens(data.sessionId, data.cwd, data.startedAt ? data.startedAt / 1000 : undefined, config);
417
+ result.tokenUsage = tokenData.tokenUsage;
418
+ result.model = tokenData.model;
419
+ }
420
+ return result;
421
+ }
422
+ catch {
423
+ return {};
424
+ }
425
+ }
@@ -0,0 +1,14 @@
1
+ /**
2
+ * Codex session parsing, indexing, and phase detection.
3
+ */
4
+ import type { MarmonitorConfig } from "../config/index.js";
5
+ import type { SessionPhase } from "../types.js";
6
+ import type { CodexSessionMeta } from "./cache.js";
7
+ export type { CodexSessionMeta } from "./cache.js";
8
+ export declare function getCodexSessionRoots(config?: MarmonitorConfig): string[];
9
+ /** Detect Codex session phase from session JSONL */
10
+ export declare function detectCodexPhase(sessionFilePath: string | undefined, config?: MarmonitorConfig): Promise<SessionPhase>;
11
+ /** Build index of recent Codex sessions (last 7 days) */
12
+ export declare function indexCodexSessions(config?: MarmonitorConfig): Promise<CodexSessionMeta[]>;
13
+ /** Match a Codex process to a session by cwd + closest timestamp */
14
+ export declare function matchCodexSession(processCwd: string, processStartTime: number | undefined, sessions: CodexSessionMeta[]): CodexSessionMeta | undefined;