marmonitor 0.2.4 → 0.2.6
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 +52 -1
- package/README.md +76 -1
- 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 +73 -0
- package/dist/alerts/types.d.ts +23 -0
- package/dist/alerts/types.js +2 -0
- package/dist/cli.js +341 -23
- package/dist/clipboard.d.ts +12 -0
- package/dist/clipboard.js +56 -0
- package/dist/config/index.d.ts +14 -0
- package/dist/config/index.js +8 -0
- package/dist/guard/index.js +51 -5
- package/dist/output/badge-themes.d.ts +3 -0
- package/dist/output/badge-themes.js +12 -0
- package/dist/output/index.d.ts +1 -1
- package/dist/output/index.js +2 -2
- package/dist/output/utils.d.ts +2 -1
- package/dist/output/utils.js +9 -4
- package/dist/scanner/claude.js +212 -90
- package/dist/scanner/codex.d.ts +2 -0
- package/dist/scanner/codex.js +40 -9
- package/dist/scanner/daemon-entry.js +2 -0
- package/dist/scanner/daemon-loop.d.ts +4 -0
- package/dist/scanner/daemon-loop.js +25 -1
- package/dist/scanner/gemini.d.ts +10 -0
- package/dist/scanner/gemini.js +82 -0
- package/dist/scanner/process.js +11 -1
- package/dist/tmux/index.d.ts +26 -0
- package/dist/tmux/index.js +102 -0
- package/dist/turns.d.ts +68 -0
- package/dist/turns.js +430 -0
- package/dist/types.d.ts +2 -0
- package/package.json +3 -1
|
@@ -9,6 +9,7 @@ export const BADGE_THEMES = {
|
|
|
9
9
|
basic: {
|
|
10
10
|
badge: "#[fg={bg},bg=#1e1e2e]#[bold,fg={fg},bg={bg}] {label} #[fg={bg},bg=#1e1e2e]#[default]",
|
|
11
11
|
attention: "#[fg={bg},bg=#1e1e2e]#[bold,fg=#11111b,bg={bg}] {index} #[fg=#313244,bg={bg}]#[fg=#cdd6f4,bg=#313244] {label} #[fg=#313244,bg=#1e1e2e]#[default]",
|
|
12
|
+
attentionActive: "#[fg={bg},bg=#1e1e2e]#[bold,underscore,fg=#11111b,bg={bg}] {index} #[fg=#45475a,bg={bg}]#[underscore,fg=#cdd6f4,bg=#45475a] {label} #[fg=#45475a,bg=#1e1e2e]#[default]",
|
|
12
13
|
focus: "#[fg=#bac2de,bg=#181825] {text} #[default]",
|
|
13
14
|
empty: "#[fg=#cdd6f4,bg=#313244] no active #[fg=#313244,bg=#1e1e2e]#[default]",
|
|
14
15
|
jumpBack: "#[fg=#45475a,bg=#1e1e2e]#[fg=#bac2de,bg=#45475a] ↩ #[fg=#45475a,bg=#1e1e2e]#[default]",
|
|
@@ -16,6 +17,7 @@ export const BADGE_THEMES = {
|
|
|
16
17
|
"basic-mono": {
|
|
17
18
|
badge: "#[fg=#313244,bg=#1e1e2e]#[bold,fg=#cdd6f4,bg=#313244] {label} #[fg=#313244,bg=#1e1e2e]#[default]",
|
|
18
19
|
attention: "#[fg=#313244,bg=#1e1e2e]#[bold,fg=#cdd6f4,bg=#313244] {index} #[fg=#1e1e2e,bg=#313244]#[fg=#6c7086,bg=#1e1e2e] {label} #[fg=#1e1e2e]#[default]",
|
|
20
|
+
attentionActive: "#[fg=#45475a,bg=#1e1e2e]#[bold,underscore,fg=#cdd6f4,bg=#45475a] {index} #[fg=#1e1e2e,bg=#45475a]#[underscore,fg=#cdd6f4,bg=#1e1e2e] {label} #[fg=#1e1e2e]#[default]",
|
|
19
21
|
focus: "#[fg=#6c7086,bg=#181825] {text} #[default]",
|
|
20
22
|
empty: "#[fg=#313244,bg=#1e1e2e]#[fg=#6c7086,bg=#313244] no active #[fg=#313244,bg=#1e1e2e]#[default]",
|
|
21
23
|
jumpBack: "#[fg=#313244,bg=#1e1e2e]#[fg=#6c7086,bg=#313244] ↩ #[fg=#313244,bg=#1e1e2e]#[default]",
|
|
@@ -23,6 +25,7 @@ export const BADGE_THEMES = {
|
|
|
23
25
|
block: {
|
|
24
26
|
badge: "#[bold,fg={fg},bg={bg}] {label} #[default]",
|
|
25
27
|
attention: "#[bold,fg=#11111b,bg={bg}] {index} #[fg=#cdd6f4,bg=#313244] {label} #[default]",
|
|
28
|
+
attentionActive: "#[bold,underscore,fg=#11111b,bg={bg}] {index} #[underscore,fg=#cdd6f4,bg=#45475a] {label} #[default]",
|
|
26
29
|
focus: "#[fg=#bac2de,bg=#181825] {text} #[default]",
|
|
27
30
|
empty: "#[fg=#cdd6f4,bg=#313244] no active #[default]",
|
|
28
31
|
jumpBack: "#[fg=#bac2de,bg=#45475a] ↩ #[default]",
|
|
@@ -30,6 +33,7 @@ export const BADGE_THEMES = {
|
|
|
30
33
|
"block-mono": {
|
|
31
34
|
badge: "#[bold,fg=#cdd6f4,bg=#313244] {label} #[default]",
|
|
32
35
|
attention: "#[bold,fg=#cdd6f4,bg=#313244] {index} #[fg=#6c7086,bg=#1e1e2e] {label} #[default]",
|
|
36
|
+
attentionActive: "#[bold,underscore,fg=#cdd6f4,bg=#45475a] {index} #[underscore,fg=#cdd6f4,bg=#1e1e2e] {label} #[default]",
|
|
33
37
|
focus: "#[fg=#6c7086,bg=#181825] {text} #[default]",
|
|
34
38
|
empty: "#[fg=#6c7086,bg=#313244] no active #[default]",
|
|
35
39
|
jumpBack: "#[fg=#6c7086,bg=#313244] ↩ #[default]",
|
|
@@ -37,6 +41,7 @@ export const BADGE_THEMES = {
|
|
|
37
41
|
text: {
|
|
38
42
|
badge: "#[fg={bg}]{label}#[default]",
|
|
39
43
|
attention: "#[fg={bg}]{index} {label}#[default]",
|
|
44
|
+
attentionActive: "#[underscore,fg={bg}]{index} {label}#[default]",
|
|
40
45
|
focus: "{text}",
|
|
41
46
|
empty: "no active",
|
|
42
47
|
jumpBack: "#[fg=#89b4fa]↩#[default]",
|
|
@@ -44,6 +49,7 @@ export const BADGE_THEMES = {
|
|
|
44
49
|
"text-mono": {
|
|
45
50
|
badge: "#[fg=#cdd6f4]{label}#[default]",
|
|
46
51
|
attention: "#[bold,fg=#cdd6f4]{index}#[default] #[fg=#6c7086]{label}#[default]",
|
|
52
|
+
attentionActive: "#[bold,underscore,fg=#cdd6f4]{index}#[default] #[underscore,fg=#6c7086]{label}#[default]",
|
|
47
53
|
focus: "#[fg=#6c7086]{text}#[default]",
|
|
48
54
|
empty: "#[fg=#6c7086]no active#[default]",
|
|
49
55
|
jumpBack: "#[fg=#6c7086]↩#[default]",
|
|
@@ -58,6 +64,12 @@ export function renderAttention(theme, index, label, bg) {
|
|
|
58
64
|
.replaceAll("{label}", label)
|
|
59
65
|
.replaceAll("{bg}", bg);
|
|
60
66
|
}
|
|
67
|
+
export function renderAttentionActive(theme, index, label, bg) {
|
|
68
|
+
return theme.attentionActive
|
|
69
|
+
.replaceAll("{index}", String(index))
|
|
70
|
+
.replaceAll("{label}", label)
|
|
71
|
+
.replaceAll("{bg}", bg);
|
|
72
|
+
}
|
|
61
73
|
export function renderFocus(theme, text) {
|
|
62
74
|
return theme.focus.replaceAll("{text}", text);
|
|
63
75
|
}
|
package/dist/output/index.d.ts
CHANGED
|
@@ -27,6 +27,6 @@ export declare function printDock(agents: AgentSession[], maxLines?: number): Pr
|
|
|
27
27
|
/** Print one-line summary for tmux/terminal status bar */
|
|
28
28
|
export declare function renderUnavailableStatusline(format?: StatuslineFormat): string;
|
|
29
29
|
/** Print one-line summary for tmux/terminal status bar */
|
|
30
|
-
export declare function renderStatusline(agents: AgentSession[], format?: StatuslineFormat, attentionLimit?: number, width?: number, badgeStyle?: BadgeStyle, hasJumpAnchor?: boolean): Promise<string>;
|
|
30
|
+
export declare function renderStatusline(agents: AgentSession[], format?: StatuslineFormat, attentionLimit?: number, width?: number, badgeStyle?: BadgeStyle, hasJumpAnchor?: boolean, activeAgentPid?: number): Promise<string>;
|
|
31
31
|
/** Print one-line summary for tmux/terminal status bar */
|
|
32
32
|
export declare function printStatusline(agents: AgentSession[], format?: StatuslineFormat, attentionLimit?: number, width?: number): Promise<void>;
|
package/dist/output/index.js
CHANGED
|
@@ -578,7 +578,7 @@ export function renderUnavailableStatusline(format = "compact") {
|
|
|
578
578
|
return "marmonitor unavailable";
|
|
579
579
|
}
|
|
580
580
|
/** Print one-line summary for tmux/terminal status bar */
|
|
581
|
-
export async function renderStatusline(agents, format = "compact", attentionLimit = 5, width, badgeStyle = "basic", hasJumpAnchor = false) {
|
|
581
|
+
export async function renderStatusline(agents, format = "compact", attentionLimit = 5, width, badgeStyle = "basic", hasJumpAnchor = false, activeAgentPid) {
|
|
582
582
|
const alive = agents.filter((a) => a.status !== "Dead" && a.status !== "Unmatched");
|
|
583
583
|
const unmatched = agents.filter((a) => a.status === "Unmatched");
|
|
584
584
|
if (alive.length === 0) {
|
|
@@ -611,7 +611,7 @@ export async function renderStatusline(agents, format = "compact", attentionLimi
|
|
|
611
611
|
memoryUsedGb: sys.memoryUsedGb,
|
|
612
612
|
};
|
|
613
613
|
if (format === "tmux-badges") {
|
|
614
|
-
const focusText = buildTmuxAttentionPills(buildJumpAttentionItems(agents), attentionLimit, width, badgeStyle);
|
|
614
|
+
const focusText = buildTmuxAttentionPills(buildJumpAttentionItems(agents), attentionLimit, width, badgeStyle, activeAgentPid);
|
|
615
615
|
return buildTmuxBadgeBar(snapshot, focusText, badgeStyle, hasJumpAnchor);
|
|
616
616
|
}
|
|
617
617
|
if (format === "wezterm-pills") {
|
package/dist/output/utils.d.ts
CHANGED
|
@@ -103,6 +103,7 @@ export interface SessionRegistryEntry {
|
|
|
103
103
|
startedAt?: number;
|
|
104
104
|
model?: string;
|
|
105
105
|
source: "claude" | "codex";
|
|
106
|
+
binding: "direct" | "provisional";
|
|
106
107
|
}
|
|
107
108
|
export interface SessionFileCandidate {
|
|
108
109
|
path: string;
|
|
@@ -149,5 +150,5 @@ export declare function buildStatusPills(snapshot: StatuslineSnapshot): {
|
|
|
149
150
|
export declare function buildStatuslineSummary(snapshot: StatuslineSnapshot, format?: StatuslineFormat): string;
|
|
150
151
|
export type BadgeStyle = "basic" | "basic-mono" | "block" | "block-mono" | "text" | "text-mono";
|
|
151
152
|
export declare function buildTmuxBadgeBar(snapshot: StatuslineSnapshot, focusText?: string, badgeStyle?: BadgeStyle, hasJumpAnchor?: boolean): string;
|
|
152
|
-
export declare function buildTmuxAttentionPills(items: AttentionItem[], maxCount?: number, width?: number, badgeStyle?: BadgeStyle): string | undefined;
|
|
153
|
+
export declare function buildTmuxAttentionPills(items: AttentionItem[], maxCount?: number, width?: number, badgeStyle?: BadgeStyle, activeAgentPid?: number): string | undefined;
|
|
153
154
|
export declare function serializeWeztermPills(snapshot: StatuslineSnapshot, focusText?: string): string;
|
package/dist/output/utils.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { renderAttention, renderBadge, renderFocus, resolveTheme } from "./badge-themes.js";
|
|
1
|
+
import { renderAttention, renderAttentionActive, renderBadge, renderFocus, resolveTheme, } from "./badge-themes.js";
|
|
2
2
|
/**
|
|
3
3
|
* Pure utility functions for marmonitor.
|
|
4
4
|
* Extracted for testability — no side effects, no I/O.
|
|
@@ -257,7 +257,10 @@ export function resolveSessionRegistryPath(registry, sessionId) {
|
|
|
257
257
|
return registry.get(sessionId)?.filePath;
|
|
258
258
|
}
|
|
259
259
|
export function upsertSessionRegistryEntry(registry, entry) {
|
|
260
|
-
registry.set(entry.sessionId,
|
|
260
|
+
registry.set(entry.sessionId, {
|
|
261
|
+
...entry,
|
|
262
|
+
binding: entry.binding ?? "provisional",
|
|
263
|
+
});
|
|
261
264
|
}
|
|
262
265
|
export function selectRecentSessionFile(candidates, nowMs = Date.now(), maxAgeMs = 72 * 60 * 60 * 1000, minLeadMs = 5 * 60 * 1000) {
|
|
263
266
|
if (candidates.length === 0)
|
|
@@ -583,7 +586,7 @@ export function buildTmuxBadgeBar(snapshot, focusText, badgeStyle = "basic", has
|
|
|
583
586
|
const focus = focusText ? renderFocus(theme, focusText) : "";
|
|
584
587
|
return [agentPills.join(" "), alertPills.join(" "), jumpBack, focus].filter(Boolean).join(" ");
|
|
585
588
|
}
|
|
586
|
-
export function buildTmuxAttentionPills(items, maxCount = 5, width, badgeStyle = "basic") {
|
|
589
|
+
export function buildTmuxAttentionPills(items, maxCount = 5, width, badgeStyle = "basic", activeAgentPid) {
|
|
587
590
|
if (maxCount <= 0)
|
|
588
591
|
return undefined;
|
|
589
592
|
const layout = resolveStatuslineDetailLayout(width, maxCount);
|
|
@@ -615,7 +618,9 @@ export function buildTmuxAttentionPills(items, maxCount = 5, width, badgeStyle =
|
|
|
615
618
|
: time
|
|
616
619
|
? `⚠${agent} ${path} ${time}`
|
|
617
620
|
: `⚠${agent} ${path}`;
|
|
618
|
-
|
|
621
|
+
const isActive = activeAgentPid !== undefined && item.pid === activeAgentPid;
|
|
622
|
+
const render = isActive ? renderAttentionActive : renderAttention;
|
|
623
|
+
return tmuxUserRange(`pid:${item.pid}`, render(theme, index + 1, label, attentionBg(item.kind)));
|
|
619
624
|
});
|
|
620
625
|
return segments.join(" ");
|
|
621
626
|
}
|
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,89 @@ async function readJsonlFirstLine(filePath) {
|
|
|
416
418
|
await fd?.close().catch(() => { });
|
|
417
419
|
}
|
|
418
420
|
}
|
|
421
|
+
/**
|
|
422
|
+
* Stale-session override resolver.
|
|
423
|
+
*
|
|
424
|
+
* Picks a non-current jsonl when the current sessionId's metadata is stale
|
|
425
|
+
* (e.g. just after /clear), but refuses to do so when the current jsonl
|
|
426
|
+
* clearly belongs to this process or when the candidate jsonl is already
|
|
427
|
+
* claimed in the registry. See local issue #103 / GH #56 for the misrouting
|
|
428
|
+
* case this guards.
|
|
429
|
+
*
|
|
430
|
+
* Conservative guards layered on top of the legacy mtime-lead check:
|
|
431
|
+
* - F1: if currentDirectPath exists and its first-line timestamp is on or
|
|
432
|
+
* after processStartedAt, the current jsonl was authored by this
|
|
433
|
+
* process — keep it, do not override.
|
|
434
|
+
* - F2: if the override-candidate sessionId is already direct-bound in
|
|
435
|
+
* claudeSessionRegistry, refuse the override. Keeps the
|
|
436
|
+
* one-jsonl-per-sessionId invariant intact.
|
|
437
|
+
* - F3: anything ambiguous falls through to `undefined` (unresolved) —
|
|
438
|
+
* a missed match is safer than a misrouted one.
|
|
439
|
+
*/
|
|
440
|
+
async function chooseStaleSessionOverride(processCwd, currentSessionId, processStartedAt, config) {
|
|
441
|
+
const projectDirName = await findClaudeProjectDir(processCwd, currentSessionId, config);
|
|
442
|
+
if (!projectDirName)
|
|
443
|
+
return undefined;
|
|
444
|
+
const candidates = await listClaudeSessionCandidates(projectDirName, getClaudeProjectRoots(config));
|
|
445
|
+
const recentPath = selectRecentSessionFile(candidates);
|
|
446
|
+
if (!recentPath)
|
|
447
|
+
return undefined;
|
|
448
|
+
if (currentSessionId && isDirectSessionFile(recentPath, currentSessionId)) {
|
|
449
|
+
return undefined;
|
|
450
|
+
}
|
|
451
|
+
const currentDirectPath = currentSessionId != null
|
|
452
|
+
? getClaudeProjectRoots(config)
|
|
453
|
+
.map((projectsDir) => join(projectsDir, projectDirName, `${currentSessionId}.jsonl`))
|
|
454
|
+
.find((candidate) => existsSync(candidate))
|
|
455
|
+
: undefined;
|
|
456
|
+
if (currentDirectPath) {
|
|
457
|
+
let currentStat;
|
|
458
|
+
let recentStat;
|
|
459
|
+
try {
|
|
460
|
+
[recentStat, currentStat] = await Promise.all([stat(recentPath), stat(currentDirectPath)]);
|
|
461
|
+
}
|
|
462
|
+
catch {
|
|
463
|
+
return undefined;
|
|
464
|
+
}
|
|
465
|
+
// F1: a non-empty current jsonl whose first event is on or after the
|
|
466
|
+
// process start belongs to this process. Same-cwd sibling sessions land
|
|
467
|
+
// here and must not be routed onto another session's active jsonl.
|
|
468
|
+
if (currentStat.size > 0 && processStartedAt !== undefined) {
|
|
469
|
+
const currentMeta = await readJsonlSessionMeta(currentDirectPath);
|
|
470
|
+
if (currentMeta?.timestamp) {
|
|
471
|
+
const jsonlCreatedAtSec = new Date(currentMeta.timestamp).getTime() / 1000;
|
|
472
|
+
if (Number.isFinite(jsonlCreatedAtSec)) {
|
|
473
|
+
const CLOCK_SKEW_SEC = 60;
|
|
474
|
+
if (jsonlCreatedAtSec >= processStartedAt - CLOCK_SKEW_SEC)
|
|
475
|
+
return undefined;
|
|
476
|
+
}
|
|
477
|
+
}
|
|
478
|
+
}
|
|
479
|
+
const minLeadMs = 5 * 60 * 1000;
|
|
480
|
+
const staleGapMs = 30 * 60 * 1000;
|
|
481
|
+
if (recentStat.mtimeMs - currentStat.mtimeMs < minLeadMs)
|
|
482
|
+
return undefined;
|
|
483
|
+
if (Date.now() - currentStat.mtimeMs < staleGapMs)
|
|
484
|
+
return undefined;
|
|
485
|
+
}
|
|
486
|
+
const recentMeta = await readJsonlSessionMeta(recentPath);
|
|
487
|
+
if (!recentMeta?.sessionId)
|
|
488
|
+
return undefined;
|
|
489
|
+
if (recentMeta.sessionId === currentSessionId)
|
|
490
|
+
return undefined;
|
|
491
|
+
// F2: the candidate sessionId is already direct-bound in the registry.
|
|
492
|
+
// Overriding would let two sessionIds share one jsonl — the exact bug
|
|
493
|
+
// in #103. Keeps the one-jsonl-per-sessionId invariant.
|
|
494
|
+
const recentBinding = claudeSessionRegistry.get(recentMeta.sessionId);
|
|
495
|
+
if (recentBinding?.binding === "direct")
|
|
496
|
+
return undefined;
|
|
497
|
+
return {
|
|
498
|
+
sessionId: recentMeta.sessionId,
|
|
499
|
+
cwd: recentMeta.cwd ?? processCwd,
|
|
500
|
+
timestamp: recentMeta.timestamp,
|
|
501
|
+
filePath: recentPath,
|
|
502
|
+
};
|
|
503
|
+
}
|
|
419
504
|
/**
|
|
420
505
|
* Match a Claude session by scanning JSONL files in the project directory.
|
|
421
506
|
* When processStartedAt is available, matches by JSONL creation timestamp
|
|
@@ -462,7 +547,7 @@ export async function matchClaudeSessionByMtime(cwd, processStartedAt, config) {
|
|
|
462
547
|
// Read first lines to get creation timestamps and match by proximity
|
|
463
548
|
const scored = [];
|
|
464
549
|
for (const c of pool) {
|
|
465
|
-
const firstLine = await
|
|
550
|
+
const firstLine = await readJsonlSessionMeta(c.path);
|
|
466
551
|
if (!firstLine?.timestamp)
|
|
467
552
|
continue;
|
|
468
553
|
const createdAt = new Date(firstLine.timestamp).getTime() / 1000;
|
|
@@ -480,19 +565,31 @@ export async function matchClaudeSessionByMtime(cwd, processStartedAt, config) {
|
|
|
480
565
|
bestPath = scored[0].path;
|
|
481
566
|
}
|
|
482
567
|
}
|
|
483
|
-
// Fallback:
|
|
568
|
+
// Fallback: no timestamp-scored match — only commit if one file clearly leads
|
|
569
|
+
// to avoid mismatching when multiple sessions share the same cwd.
|
|
484
570
|
if (!bestPath) {
|
|
485
571
|
pool.sort((a, b) => b.mtimeMs - a.mtimeMs);
|
|
486
|
-
|
|
572
|
+
const latest = pool[0];
|
|
573
|
+
const second = pool[1];
|
|
574
|
+
if (!second || latest.mtimeMs - second.mtimeMs >= 5 * 60 * 1000) {
|
|
575
|
+
bestPath = latest.path;
|
|
576
|
+
}
|
|
577
|
+
// Ambiguous (two recent files within 5 min of each other) → bestPath stays undefined
|
|
487
578
|
}
|
|
488
579
|
}
|
|
489
580
|
else {
|
|
490
|
-
// No process start time — pick most recently modified
|
|
581
|
+
// No process start time — pick most recently modified, but only if unambiguous
|
|
491
582
|
candidates.sort((a, b) => b.mtimeMs - a.mtimeMs);
|
|
492
|
-
|
|
583
|
+
const latest = candidates[0];
|
|
584
|
+
const second = candidates[1];
|
|
585
|
+
if (!second || latest.mtimeMs - second.mtimeMs >= 5 * 60 * 1000) {
|
|
586
|
+
bestPath = candidates[0].path;
|
|
587
|
+
}
|
|
493
588
|
}
|
|
589
|
+
if (!bestPath)
|
|
590
|
+
return undefined;
|
|
494
591
|
// Read first line for session metadata
|
|
495
|
-
const entry = await
|
|
592
|
+
const entry = await readJsonlSessionMeta(bestPath);
|
|
496
593
|
if (!entry?.sessionId)
|
|
497
594
|
return undefined;
|
|
498
595
|
try {
|
|
@@ -513,6 +610,7 @@ export async function matchClaudeSessionByMtime(cwd, processStartedAt, config) {
|
|
|
513
610
|
firstSeenOffset: 0,
|
|
514
611
|
startedAt: result.startedAt,
|
|
515
612
|
source: "claude",
|
|
613
|
+
binding: basename(bestPath).includes(entry.sessionId) ? "direct" : "provisional",
|
|
516
614
|
});
|
|
517
615
|
const tokenData = await parseClaudeTokens(entry.sessionId, sessionCwd, result.startedAt, config);
|
|
518
616
|
result.tokenUsage = tokenData.tokenUsage;
|
|
@@ -534,15 +632,39 @@ export async function parseClaudeSession(pid, cwd, processStartedAt, config) {
|
|
|
534
632
|
const fileStat = await stat(sessionFile);
|
|
535
633
|
const raw = await readFile(sessionFile, "utf-8");
|
|
536
634
|
const data = JSON.parse(raw);
|
|
635
|
+
const processCwd = cwd ?? data.cwd;
|
|
636
|
+
const sessionStartedAt = data.startedAt ? data.startedAt / 1000 : undefined;
|
|
637
|
+
let resolvedSessionId = data.sessionId;
|
|
638
|
+
let resolvedCwd = data.cwd;
|
|
639
|
+
let resolvedStartedAt = sessionStartedAt;
|
|
640
|
+
if (processCwd && processCwd !== "unknown") {
|
|
641
|
+
const override = await chooseStaleSessionOverride(processCwd, data.sessionId, processStartedAt, config);
|
|
642
|
+
if (override) {
|
|
643
|
+
resolvedSessionId = override.sessionId;
|
|
644
|
+
resolvedCwd = override.cwd ?? processCwd;
|
|
645
|
+
resolvedStartedAt = override.timestamp
|
|
646
|
+
? new Date(override.timestamp).getTime() / 1000
|
|
647
|
+
: sessionStartedAt;
|
|
648
|
+
upsertSessionRegistryEntry(claudeSessionRegistry, {
|
|
649
|
+
filePath: override.filePath,
|
|
650
|
+
sessionId: override.sessionId,
|
|
651
|
+
cwd: resolvedCwd ?? processCwd,
|
|
652
|
+
firstSeenOffset: 0,
|
|
653
|
+
startedAt: resolvedStartedAt,
|
|
654
|
+
source: "claude",
|
|
655
|
+
binding: "provisional",
|
|
656
|
+
});
|
|
657
|
+
}
|
|
658
|
+
}
|
|
537
659
|
const result = {
|
|
538
|
-
cwd:
|
|
539
|
-
sessionId:
|
|
540
|
-
startedAt:
|
|
660
|
+
cwd: resolvedCwd,
|
|
661
|
+
sessionId: resolvedSessionId,
|
|
662
|
+
startedAt: resolvedStartedAt,
|
|
541
663
|
lastActivityAt: fileStat.mtimeMs / 1000,
|
|
542
664
|
sessionMatched: true,
|
|
543
665
|
};
|
|
544
|
-
if (
|
|
545
|
-
const tokenData = await parseClaudeTokens(
|
|
666
|
+
if (resolvedSessionId && resolvedCwd) {
|
|
667
|
+
const tokenData = await parseClaudeTokens(resolvedSessionId, resolvedCwd, resolvedStartedAt, config);
|
|
546
668
|
result.tokenUsage = tokenData.tokenUsage;
|
|
547
669
|
result.model = tokenData.model;
|
|
548
670
|
}
|
package/dist/scanner/codex.d.ts
CHANGED
|
@@ -5,6 +5,8 @@ import type { MarmonitorConfig } from "../config/index.js";
|
|
|
5
5
|
import type { SessionPhase } from "../types.js";
|
|
6
6
|
import type { CodexSessionMeta } from "./cache.js";
|
|
7
7
|
export type { CodexSessionMeta } from "./cache.js";
|
|
8
|
+
declare function mergeCodexIndexedSessions(baseSessions: CodexSessionMeta[], incomingSessions: CodexSessionMeta[]): CodexSessionMeta[];
|
|
9
|
+
export { mergeCodexIndexedSessions };
|
|
8
10
|
export declare function getCodexSessionRoots(config?: MarmonitorConfig): string[];
|
|
9
11
|
/** Detect Codex session phase from session JSONL */
|
|
10
12
|
export declare function detectCodexPhase(sessionFilePath: string | undefined, config?: MarmonitorConfig): Promise<SessionPhase>;
|