marmonitor 0.2.2 → 0.2.3
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.md +35 -2
- package/bin/postinstall.cjs +1 -0
- package/dist/cli.js +152 -4
- package/dist/config/index.d.ts +1 -0
- package/dist/config/index.js +1 -0
- package/dist/output/utils.d.ts +1 -1
- package/dist/output/utils.js +13 -2
- package/dist/scanner/activity-log.d.ts +29 -0
- package/dist/scanner/activity-log.js +225 -0
- package/dist/scanner/cache.d.ts +1 -0
- package/dist/scanner/cache.js +1 -0
- package/dist/scanner/codex-binding-registry.d.ts +30 -0
- package/dist/scanner/codex-binding-registry.js +87 -0
- package/dist/scanner/codex-sqlite.d.ts +6 -1
- package/dist/scanner/codex-sqlite.js +27 -7
- package/dist/scanner/codex.d.ts +3 -1
- package/dist/scanner/codex.js +14 -4
- package/dist/scanner/daemon-entry.js +3 -0
- package/dist/scanner/daemon-loop.d.ts +3 -0
- package/dist/scanner/daemon-loop.js +110 -4
- package/dist/scanner/index.js +59 -7
- package/dist/scanner/session-registry.d.ts +4 -1
- package/dist/scanner/session-registry.js +16 -9
- package/dist/scanner/status.d.ts +3 -1
- package/dist/scanner/status.js +53 -8
- package/dist/scanner/types.d.ts +4 -0
- package/dist/types.d.ts +1 -0
- package/package.json +1 -1
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Codex binding registry — persists PID/process bindings to Codex thread/jsonl.
|
|
3
|
+
* 1차는 schema + load/save + prune만 제공한다.
|
|
4
|
+
*/
|
|
5
|
+
import { mkdir, readFile, writeFile } from "node:fs/promises";
|
|
6
|
+
import { dirname } from "node:path";
|
|
7
|
+
export function buildCodexBindingKey(pid, processStartedAt) {
|
|
8
|
+
return `${pid}:${processStartedAt ?? 0}`;
|
|
9
|
+
}
|
|
10
|
+
export function selectCodexBindingSession(registry, pid, processStartedAt, cwd, sessions) {
|
|
11
|
+
const binding = registry.get(buildCodexBindingKey(pid, processStartedAt));
|
|
12
|
+
if (!binding || binding.deadAt !== undefined)
|
|
13
|
+
return undefined;
|
|
14
|
+
if (binding.cwd !== cwd)
|
|
15
|
+
return undefined;
|
|
16
|
+
const matched = sessions.find((session) => session.id === binding.threadId &&
|
|
17
|
+
session.filePath === binding.rolloutPath &&
|
|
18
|
+
session.cwd === cwd);
|
|
19
|
+
return matched;
|
|
20
|
+
}
|
|
21
|
+
export function upsertCodexBindingRecord(registry, params) {
|
|
22
|
+
const { pid, processStartedAt, cwd, matched, confidence = "high" } = params;
|
|
23
|
+
const key = buildCodexBindingKey(pid, processStartedAt);
|
|
24
|
+
const previous = registry.get(key);
|
|
25
|
+
const now = Math.floor(Date.now() / 1000);
|
|
26
|
+
const isChanged = previous !== undefined &&
|
|
27
|
+
(previous.threadId !== matched.id || previous.rolloutPath !== matched.filePath);
|
|
28
|
+
registry.set(key, {
|
|
29
|
+
pid,
|
|
30
|
+
processStartedAt,
|
|
31
|
+
cwd,
|
|
32
|
+
threadId: matched.id,
|
|
33
|
+
rolloutPath: matched.filePath,
|
|
34
|
+
lastVerifiedAt: now,
|
|
35
|
+
confidence,
|
|
36
|
+
unstableCount: isChanged ? (previous?.unstableCount ?? 0) + 1 : (previous?.unstableCount ?? 0),
|
|
37
|
+
deadAt: undefined,
|
|
38
|
+
});
|
|
39
|
+
}
|
|
40
|
+
export function markMissingCodexBindingsDead(registry, aliveKeys) {
|
|
41
|
+
const now = Math.floor(Date.now() / 1000);
|
|
42
|
+
let updated = 0;
|
|
43
|
+
for (const [key, record] of registry) {
|
|
44
|
+
if (aliveKeys.has(key))
|
|
45
|
+
continue;
|
|
46
|
+
if (record.deadAt === undefined) {
|
|
47
|
+
registry.set(key, { ...record, deadAt: now });
|
|
48
|
+
updated++;
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
return updated;
|
|
52
|
+
}
|
|
53
|
+
export function pruneCodexBindingRegistry(registry, maxAgeDays) {
|
|
54
|
+
const cutoff = Math.floor(Date.now() / 1000) - maxAgeDays * 86400;
|
|
55
|
+
let pruned = 0;
|
|
56
|
+
for (const [key, record] of registry) {
|
|
57
|
+
if (record.deadAt !== undefined && record.deadAt < cutoff) {
|
|
58
|
+
registry.delete(key);
|
|
59
|
+
pruned++;
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
return pruned;
|
|
63
|
+
}
|
|
64
|
+
export async function saveCodexBindingRegistryToFile(filePath, registry) {
|
|
65
|
+
try {
|
|
66
|
+
await mkdir(dirname(filePath), { recursive: true });
|
|
67
|
+
const data = Object.fromEntries(registry.entries());
|
|
68
|
+
await writeFile(filePath, JSON.stringify(data, null, 2), "utf-8");
|
|
69
|
+
}
|
|
70
|
+
catch {
|
|
71
|
+
// registry save failures must never crash the daemon
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
export async function loadCodexBindingRegistryFromFile(filePath, registry) {
|
|
75
|
+
try {
|
|
76
|
+
const raw = await readFile(filePath, "utf-8");
|
|
77
|
+
const data = JSON.parse(raw);
|
|
78
|
+
if (typeof data === "object" && data !== null && !Array.isArray(data)) {
|
|
79
|
+
for (const [key, value] of Object.entries(data)) {
|
|
80
|
+
registry.set(key, value);
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
catch {
|
|
85
|
+
// missing or malformed file — start with empty registry
|
|
86
|
+
}
|
|
87
|
+
}
|
|
@@ -4,8 +4,13 @@
|
|
|
4
4
|
* Falls back gracefully if sqlite3 is unavailable or DB is missing.
|
|
5
5
|
*/
|
|
6
6
|
import type { CodexSessionMeta } from "./cache.js";
|
|
7
|
+
export interface CodexSqliteIndexOptions {
|
|
8
|
+
recentUpdatedAfter?: number;
|
|
9
|
+
includeCwds?: string[];
|
|
10
|
+
}
|
|
11
|
+
export declare function buildCodexThreadsQuery(options?: CodexSqliteIndexOptions): string;
|
|
7
12
|
/**
|
|
8
13
|
* Query Codex state SQLite for active (non-archived) threads.
|
|
9
14
|
* Returns CodexSessionMeta[] compatible with existing matchCodexSession().
|
|
10
15
|
*/
|
|
11
|
-
export declare function indexCodexSessionsFromSqlite(dbPath: string): Promise<CodexSessionMeta[]>;
|
|
16
|
+
export declare function indexCodexSessionsFromSqlite(dbPath: string, options?: CodexSqliteIndexOptions): Promise<CodexSessionMeta[]>;
|
|
@@ -6,18 +6,38 @@
|
|
|
6
6
|
import { execFile } from "node:child_process";
|
|
7
7
|
import { promisify } from "node:util";
|
|
8
8
|
const execFileAsync = promisify(execFile);
|
|
9
|
+
function escapeSqlString(value) {
|
|
10
|
+
return value.replaceAll("'", "''");
|
|
11
|
+
}
|
|
12
|
+
export function buildCodexThreadsQuery(options = {}) {
|
|
13
|
+
const filters = ["archived = 0"];
|
|
14
|
+
const includeCwds = [...new Set((options.includeCwds ?? []).filter(Boolean))];
|
|
15
|
+
if (options.recentUpdatedAfter && includeCwds.length > 0) {
|
|
16
|
+
const inClause = includeCwds.map((cwd) => `'${escapeSqlString(cwd)}'`).join(", ");
|
|
17
|
+
filters.push(`(updated_at >= ${Math.floor(options.recentUpdatedAfter)} OR cwd IN (${inClause}))`);
|
|
18
|
+
}
|
|
19
|
+
else if (options.recentUpdatedAfter) {
|
|
20
|
+
filters.push(`updated_at >= ${Math.floor(options.recentUpdatedAfter)}`);
|
|
21
|
+
}
|
|
22
|
+
else if (includeCwds.length > 0) {
|
|
23
|
+
const inClause = includeCwds.map((cwd) => `'${escapeSqlString(cwd)}'`).join(", ");
|
|
24
|
+
filters.push(`cwd IN (${inClause})`);
|
|
25
|
+
}
|
|
26
|
+
return [
|
|
27
|
+
"SELECT id, cwd, rollout_path, tokens_used, model, updated_at, created_at",
|
|
28
|
+
"FROM threads",
|
|
29
|
+
`WHERE ${filters.join(" AND ")}`,
|
|
30
|
+
"ORDER BY updated_at DESC;",
|
|
31
|
+
].join(" ");
|
|
32
|
+
}
|
|
9
33
|
/**
|
|
10
34
|
* Query Codex state SQLite for active (non-archived) threads.
|
|
11
35
|
* Returns CodexSessionMeta[] compatible with existing matchCodexSession().
|
|
12
36
|
*/
|
|
13
|
-
export async function indexCodexSessionsFromSqlite(dbPath) {
|
|
37
|
+
export async function indexCodexSessionsFromSqlite(dbPath, options = {}) {
|
|
14
38
|
try {
|
|
15
|
-
const
|
|
16
|
-
|
|
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
|
-
]);
|
|
39
|
+
const query = buildCodexThreadsQuery(options);
|
|
40
|
+
const { stdout } = await execFileAsync("sqlite3", [dbPath, "-separator", "\t", query]);
|
|
21
41
|
const lines = stdout.trim().split("\n").filter(Boolean);
|
|
22
42
|
const sessions = [];
|
|
23
43
|
for (const line of lines) {
|
package/dist/scanner/codex.d.ts
CHANGED
|
@@ -9,6 +9,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
11
|
/** Build index of Codex sessions (SQLite primary, JSONL fallback) */
|
|
12
|
-
export declare function indexCodexSessions(config?: MarmonitorConfig
|
|
12
|
+
export declare function indexCodexSessions(config?: MarmonitorConfig, options?: {
|
|
13
|
+
activeCwds?: string[];
|
|
14
|
+
}): Promise<CodexSessionMeta[]>;
|
|
13
15
|
/** Match a Codex process to a session by cwd + closest timestamp */
|
|
14
16
|
export declare function matchCodexSession(processCwd: string, processStartTime: number | undefined, sessions: CodexSessionMeta[]): CodexSessionMeta | undefined;
|
package/dist/scanner/codex.js
CHANGED
|
@@ -9,6 +9,7 @@ import { indexCodexSessionsFromSqlite } from "./codex-sqlite.js";
|
|
|
9
9
|
import { resolveRuntimeDataPaths } from "../config/index.js";
|
|
10
10
|
import { advanceJsonlCursor, resolvePhaseFromHistory, resolvePhaseWithDecay, selectCodexSession, updatePhaseHistory, upsertSessionRegistryEntry, } from "../output/utils.js";
|
|
11
11
|
import { CODEX_INDEX_TTL_MS, CODEX_PHASE_RECENT_LINES, HOME, codexIndexCache, codexPhaseCache, codexSessionFileCache, codexSessionRegistry, setCodexIndexCache, } from "./cache.js";
|
|
12
|
+
const CODEX_SQLITE_RECENT_DAYS = 7;
|
|
12
13
|
export function getCodexSessionRoots(config) {
|
|
13
14
|
return config
|
|
14
15
|
? resolveRuntimeDataPaths(config).codexSessions
|
|
@@ -103,15 +104,22 @@ function findCodexStateDb() {
|
|
|
103
104
|
}
|
|
104
105
|
}
|
|
105
106
|
/** Build index of Codex sessions (SQLite primary, JSONL fallback) */
|
|
106
|
-
export async function indexCodexSessions(config) {
|
|
107
|
-
|
|
107
|
+
export async function indexCodexSessions(config, options) {
|
|
108
|
+
const activeCwds = [...new Set((options?.activeCwds ?? []).filter(Boolean))];
|
|
109
|
+
const hasTargetedFilter = activeCwds.length > 0;
|
|
110
|
+
if (!hasTargetedFilter &&
|
|
111
|
+
codexIndexCache &&
|
|
112
|
+
Date.now() - codexIndexCache.builtAt < CODEX_INDEX_TTL_MS) {
|
|
108
113
|
return codexIndexCache.sessions;
|
|
109
114
|
}
|
|
110
115
|
const hasExplicitSessionRoots = Boolean(config?.paths.codexSessions?.length);
|
|
111
116
|
// Primary: SQLite threads table
|
|
112
117
|
const dbPath = hasExplicitSessionRoots ? undefined : findCodexStateDb();
|
|
113
118
|
if (dbPath) {
|
|
114
|
-
const sqliteSessions = await indexCodexSessionsFromSqlite(dbPath
|
|
119
|
+
const sqliteSessions = await indexCodexSessionsFromSqlite(dbPath, {
|
|
120
|
+
recentUpdatedAfter: Math.floor(Date.now() / 1000) - CODEX_SQLITE_RECENT_DAYS * 86400,
|
|
121
|
+
includeCwds: activeCwds,
|
|
122
|
+
});
|
|
115
123
|
if (sqliteSessions.length > 0) {
|
|
116
124
|
// Register sessions for phase detection and cwd lookup
|
|
117
125
|
for (const s of sqliteSessions) {
|
|
@@ -126,7 +134,9 @@ export async function indexCodexSessions(config) {
|
|
|
126
134
|
source: "codex",
|
|
127
135
|
});
|
|
128
136
|
}
|
|
129
|
-
|
|
137
|
+
if (!hasTargetedFilter) {
|
|
138
|
+
setCodexIndexCache({ builtAt: Date.now(), sessions: sqliteSessions });
|
|
139
|
+
}
|
|
130
140
|
return sqliteSessions;
|
|
131
141
|
}
|
|
132
142
|
}
|
|
@@ -19,6 +19,9 @@ async function main() {
|
|
|
19
19
|
snapshotPath: join(DAEMON_DIR, "daemon-snapshot.json"),
|
|
20
20
|
pidPath: join(DAEMON_DIR, "daemon.pid"),
|
|
21
21
|
registryPath: join(CONFIG_DIR, "session-registry.json"),
|
|
22
|
+
codexBindingRegistryPath: join(CONFIG_DIR, "codex-binding-registry.json"),
|
|
23
|
+
activityLogDir: join(CONFIG_DIR, "activity-log"),
|
|
24
|
+
activityRetentionDays: config.performance.activityRetentionDays,
|
|
22
25
|
});
|
|
23
26
|
}
|
|
24
27
|
main().catch((err) => {
|
|
@@ -9,5 +9,8 @@ export interface DaemonOptions {
|
|
|
9
9
|
snapshotPath: string;
|
|
10
10
|
pidPath: string;
|
|
11
11
|
registryPath: string;
|
|
12
|
+
codexBindingRegistryPath: string;
|
|
13
|
+
activityLogDir: string;
|
|
14
|
+
activityRetentionDays: number;
|
|
12
15
|
}
|
|
13
16
|
export declare function runDaemonLoop(config: MarmonitorConfig, options: DaemonOptions): Promise<void>;
|
|
@@ -2,7 +2,10 @@
|
|
|
2
2
|
* Daemon scan loop — runs in background, writes snapshots and registry to files.
|
|
3
3
|
* Reuses watch/dock pattern: light scan every intervalMs, full every detailIntervalMs.
|
|
4
4
|
*/
|
|
5
|
-
import { unlink } from "node:fs/promises";
|
|
5
|
+
import { open, readdir, stat, unlink } from "node:fs/promises";
|
|
6
|
+
import { join } from "node:path";
|
|
7
|
+
import { appendActivityEntries, cleanupOldActivityLogs, extractClaudeToolUses, extractCodexToolUses, formatDateKey, } from "./activity-log.js";
|
|
8
|
+
import { loadCodexBindingRegistryFromFile, pruneCodexBindingRegistry, saveCodexBindingRegistryToFile, } from "./codex-binding-registry.js";
|
|
6
9
|
import { writeDaemonPid, writeDaemonSnapshot } from "./daemon-utils.js";
|
|
7
10
|
import { scanAgents } from "./index.js";
|
|
8
11
|
import { perfEnd, perfStart } from "./perf.js";
|
|
@@ -11,9 +14,13 @@ function sleep(ms) {
|
|
|
11
14
|
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
12
15
|
}
|
|
13
16
|
export async function runDaemonLoop(config, options) {
|
|
14
|
-
const { intervalMs, detailIntervalMs, snapshotPath, pidPath, registryPath } = options;
|
|
17
|
+
const { intervalMs, detailIntervalMs, snapshotPath, pidPath, registryPath, codexBindingRegistryPath, activityLogDir, activityRetentionDays, } = options;
|
|
18
|
+
// Activity log: per-session JSONL cursor offsets (in-memory only)
|
|
19
|
+
const activityCursors = new Map();
|
|
20
|
+
let lastActivityCleanupAt = 0;
|
|
15
21
|
await writeDaemonPid(pidPath, process.pid);
|
|
16
22
|
const registry = new Map();
|
|
23
|
+
const codexBindingRegistry = new Map();
|
|
17
24
|
// Restore registry if saved recently (within 10 minutes)
|
|
18
25
|
try {
|
|
19
26
|
const { stat: fsStat } = await import("node:fs/promises");
|
|
@@ -26,6 +33,7 @@ export async function runDaemonLoop(config, options) {
|
|
|
26
33
|
catch {
|
|
27
34
|
// file missing or inaccessible — start fresh
|
|
28
35
|
}
|
|
36
|
+
await loadCodexBindingRegistryFromFile(codexBindingRegistryPath, codexBindingRegistry);
|
|
29
37
|
let lastHeavyAt = 0;
|
|
30
38
|
let running = true;
|
|
31
39
|
const shutdown = async () => {
|
|
@@ -34,6 +42,7 @@ export async function runDaemonLoop(config, options) {
|
|
|
34
42
|
running = false;
|
|
35
43
|
// Save registry before exit
|
|
36
44
|
await saveRegistryToFile(registryPath, registry);
|
|
45
|
+
await saveCodexBindingRegistryToFile(codexBindingRegistryPath, codexBindingRegistry);
|
|
37
46
|
await unlink(pidPath).catch(() => { });
|
|
38
47
|
process.exit(0);
|
|
39
48
|
};
|
|
@@ -48,10 +57,14 @@ export async function runDaemonLoop(config, options) {
|
|
|
48
57
|
const enrichmentMode = needsHeavy ? "full" : "light";
|
|
49
58
|
perfStart("daemon-scan");
|
|
50
59
|
try {
|
|
51
|
-
const agents = await scanAgents(config, {
|
|
60
|
+
const agents = await scanAgents(config, {
|
|
61
|
+
enrichmentMode,
|
|
62
|
+
codexBindingRegistry,
|
|
63
|
+
sessionRegistry: registry,
|
|
64
|
+
});
|
|
52
65
|
if (needsHeavy)
|
|
53
66
|
lastHeavyAt = now;
|
|
54
|
-
// Update session registry
|
|
67
|
+
// Update session registry with lightweight agent metadata every scan.
|
|
55
68
|
updateRegistry(registry, agents);
|
|
56
69
|
// Write snapshot for statusline consumers
|
|
57
70
|
await writeDaemonSnapshot(snapshotPath, agents);
|
|
@@ -59,6 +72,99 @@ export async function runDaemonLoop(config, options) {
|
|
|
59
72
|
if (needsHeavy) {
|
|
60
73
|
pruneRegistry(registry, 30);
|
|
61
74
|
await saveRegistryToFile(registryPath, registry);
|
|
75
|
+
pruneCodexBindingRegistry(codexBindingRegistry, 7);
|
|
76
|
+
await saveCodexBindingRegistryToFile(codexBindingRegistryPath, codexBindingRegistry);
|
|
77
|
+
// Collect activity from session JSONLs (incremental cursor)
|
|
78
|
+
const today = formatDateKey(new Date(now));
|
|
79
|
+
const allEntries = [];
|
|
80
|
+
const registryUpdates = [];
|
|
81
|
+
for (const agent of agents) {
|
|
82
|
+
if (!agent.sessionId)
|
|
83
|
+
continue;
|
|
84
|
+
// Find JSONL path from enrichment cache or registry
|
|
85
|
+
const jsonlPath = agent.agentName === "Codex"
|
|
86
|
+
? codexBindingRegistry.get(`${agent.pid}:${agent.processStartedAt ?? 0}`)?.rolloutPath
|
|
87
|
+
: undefined;
|
|
88
|
+
// Claude: construct path from sessionId
|
|
89
|
+
let sessionFile;
|
|
90
|
+
if (agent.agentName === "Claude Code" && agent.sessionId && agent.cwd) {
|
|
91
|
+
const { getClaudeSessionRoots } = await import("./claude.js");
|
|
92
|
+
const roots = getClaudeSessionRoots(config);
|
|
93
|
+
for (const root of roots) {
|
|
94
|
+
try {
|
|
95
|
+
const dirs = await readdir(root);
|
|
96
|
+
for (const dir of dirs) {
|
|
97
|
+
const candidate = join(root, dir, `${agent.sessionId}.jsonl`);
|
|
98
|
+
try {
|
|
99
|
+
await stat(candidate);
|
|
100
|
+
sessionFile = candidate;
|
|
101
|
+
break;
|
|
102
|
+
}
|
|
103
|
+
catch {
|
|
104
|
+
// not here
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
if (sessionFile)
|
|
108
|
+
break;
|
|
109
|
+
}
|
|
110
|
+
catch {
|
|
111
|
+
// root doesn't exist
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
else if (agent.agentName === "Codex" && jsonlPath) {
|
|
116
|
+
sessionFile = jsonlPath;
|
|
117
|
+
}
|
|
118
|
+
if (!sessionFile)
|
|
119
|
+
continue;
|
|
120
|
+
registryUpdates.push({
|
|
121
|
+
agentName: agent.agentName,
|
|
122
|
+
pid: agent.pid,
|
|
123
|
+
sessionId: agent.sessionId,
|
|
124
|
+
cwd: agent.cwd,
|
|
125
|
+
startedAt: agent.startedAt,
|
|
126
|
+
tokenUsage: agent.tokenUsage,
|
|
127
|
+
lastActivityAt: agent.lastActivityAt,
|
|
128
|
+
model: agent.model,
|
|
129
|
+
jsonlPath: sessionFile,
|
|
130
|
+
});
|
|
131
|
+
const cursorKey = sessionFile;
|
|
132
|
+
const prevOffset = activityCursors.get(cursorKey) ?? 0;
|
|
133
|
+
try {
|
|
134
|
+
const fileStat = await stat(sessionFile);
|
|
135
|
+
if (fileStat.size <= prevOffset)
|
|
136
|
+
continue;
|
|
137
|
+
const fd = await open(sessionFile, "r");
|
|
138
|
+
try {
|
|
139
|
+
const buf = Buffer.alloc(fileStat.size - prevOffset);
|
|
140
|
+
await fd.read(buf, 0, buf.length, prevOffset);
|
|
141
|
+
const chunk = buf.toString("utf-8");
|
|
142
|
+
const lines = chunk.split("\n").filter(Boolean);
|
|
143
|
+
const entries = agent.agentName === "Codex"
|
|
144
|
+
? extractCodexToolUses(lines, agent.sessionId, agent.agentName, agent.cwd)
|
|
145
|
+
: extractClaudeToolUses(lines, agent.sessionId, agent.agentName, agent.cwd);
|
|
146
|
+
allEntries.push(...entries);
|
|
147
|
+
activityCursors.set(cursorKey, fileStat.size);
|
|
148
|
+
}
|
|
149
|
+
finally {
|
|
150
|
+
await fd.close();
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
catch {
|
|
154
|
+
// JSONL read failure — skip this session
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
if (allEntries.length > 0) {
|
|
158
|
+
await appendActivityEntries(activityLogDir, today, allEntries);
|
|
159
|
+
}
|
|
160
|
+
if (registryUpdates.length > 0) {
|
|
161
|
+
updateRegistry(registry, registryUpdates);
|
|
162
|
+
}
|
|
163
|
+
// Cleanup old activity logs (once per day)
|
|
164
|
+
if (now - lastActivityCleanupAt > 86400000) {
|
|
165
|
+
await cleanupOldActivityLogs(activityLogDir, activityRetentionDays);
|
|
166
|
+
lastActivityCleanupAt = now;
|
|
167
|
+
}
|
|
62
168
|
}
|
|
63
169
|
}
|
|
64
170
|
catch (err) {
|
package/dist/scanner/index.js
CHANGED
|
@@ -16,6 +16,7 @@ export { parseGeminiSessionContent } from "./gemini.js";
|
|
|
16
16
|
// ─── Internal imports ─────────────────────────────────────────────
|
|
17
17
|
import { claudeSessionRegistry, sessionEnrichmentCache } from "./cache.js";
|
|
18
18
|
import { detectClaudePhase, getClaudeSessionRoots, parseClaudeSession, parseClaudeTokens, } from "./claude.js";
|
|
19
|
+
import { buildCodexBindingKey, markMissingCodexBindingsDead, selectCodexBindingSession, upsertCodexBindingRecord, } from "./codex-binding-registry.js";
|
|
19
20
|
import { detectCodexPhase, indexCodexSessions, matchCodexSession } from "./codex.js";
|
|
20
21
|
import { promiseAllLimited } from "./concurrency.js";
|
|
21
22
|
import { parseGeminiSession } from "./gemini.js";
|
|
@@ -23,12 +24,14 @@ import { groupByParent } from "./group.js";
|
|
|
23
24
|
import { perfEnd, perfStart } from "./perf.js";
|
|
24
25
|
import { detectAgentFromProcessSignature as _detectAgent, detectRuntimeSource, getProcessCwd, getProcessStartTime, } from "./process.js";
|
|
25
26
|
import { classifySessionTier } from "./session-tier.js";
|
|
26
|
-
import { detectCliStdoutPhase, determineStatus } from "./status.js";
|
|
27
|
+
import { applyStatusHysteresis, detectCliStdoutPhase, determineStatus, refreshLastActivityAt, } from "./status.js";
|
|
27
28
|
// ─── Main Scanner ──────────────────────────────────────────────────
|
|
28
29
|
/** Scan for all running AI agent sessions */
|
|
29
30
|
export async function scanAgents(config, options = {}) {
|
|
30
31
|
const enrichmentMode = options.enrichmentMode ?? "full";
|
|
31
32
|
const isFullEnrichment = enrichmentMode === "full";
|
|
33
|
+
const codexBindingRegistry = options.codexBindingRegistry;
|
|
34
|
+
const sessionRegistry = options.sessionRegistry;
|
|
32
35
|
const seenPids = new Set();
|
|
33
36
|
perfStart("scanAgents");
|
|
34
37
|
// 1. Find running processes
|
|
@@ -58,8 +61,23 @@ export async function scanAgents(config, options = {}) {
|
|
|
58
61
|
}
|
|
59
62
|
perfEnd("pidusage");
|
|
60
63
|
// 3. Pre-index Codex sessions (once, shared across all Codex processes)
|
|
64
|
+
const codexCwdEntries = isFullEnrichment
|
|
65
|
+
? await promiseAllLimited(agentProcesses
|
|
66
|
+
.filter((item) => item.agentName === "Codex")
|
|
67
|
+
.map((item) => async () => ({
|
|
68
|
+
pid: item.proc.pid,
|
|
69
|
+
cwd: (await getProcessCwd(item.proc.pid)) ?? undefined,
|
|
70
|
+
})), 4)
|
|
71
|
+
: [];
|
|
72
|
+
const resolvedCodexCwds = codexCwdEntries.flatMap((entry) => (entry ? [entry] : []));
|
|
73
|
+
const activeCodexCwds = [
|
|
74
|
+
...new Set(resolvedCodexCwds.map((entry) => entry.cwd).filter((cwd) => Boolean(cwd))),
|
|
75
|
+
];
|
|
76
|
+
const codexCwdByPid = new Map(resolvedCodexCwds.filter((entry) => entry.cwd).map((entry) => [entry.pid, entry.cwd]));
|
|
61
77
|
perfStart("codex-index");
|
|
62
|
-
const codexSessions = isFullEnrichment
|
|
78
|
+
const codexSessions = isFullEnrichment
|
|
79
|
+
? await indexCodexSessions(config, { activeCwds: activeCodexCwds })
|
|
80
|
+
: [];
|
|
63
81
|
perfEnd("codex-index");
|
|
64
82
|
// 4. Build sessions with enrichment (concurrency limited)
|
|
65
83
|
const sessionPromises = agentProcesses.map(({ proc, agentName }) => async () => {
|
|
@@ -72,6 +90,7 @@ export async function scanAgents(config, options = {}) {
|
|
|
72
90
|
let cwd = "unknown";
|
|
73
91
|
let sessionId;
|
|
74
92
|
let startedAt;
|
|
93
|
+
let processStartedAt;
|
|
75
94
|
let tokenUsage;
|
|
76
95
|
let model;
|
|
77
96
|
let sessionMatched = false;
|
|
@@ -109,6 +128,7 @@ export async function scanAgents(config, options = {}) {
|
|
|
109
128
|
cwd = cachedEnrichment.cwd;
|
|
110
129
|
sessionId = cachedEnrichment.sessionId;
|
|
111
130
|
startedAt = cachedEnrichment.startedAt;
|
|
131
|
+
processStartedAt = cachedEnrichment.processStartedAt;
|
|
112
132
|
tokenUsage = cachedEnrichment.tokenUsage;
|
|
113
133
|
model = cachedEnrichment.model;
|
|
114
134
|
sessionMatched = cachedEnrichment.sessionMatched ?? false;
|
|
@@ -143,14 +163,21 @@ export async function scanAgents(config, options = {}) {
|
|
|
143
163
|
}
|
|
144
164
|
}
|
|
145
165
|
else if (agentName === "Codex") {
|
|
146
|
-
cwd =
|
|
147
|
-
|
|
148
|
-
|
|
166
|
+
cwd =
|
|
167
|
+
cachedEnrichment?.cwd ??
|
|
168
|
+
codexCwdByPid.get(proc.pid) ??
|
|
169
|
+
(await getProcessCwd(proc.pid)) ??
|
|
170
|
+
"unknown";
|
|
171
|
+
processStartedAt = await getProcessStartTime(proc.pid);
|
|
172
|
+
const matched = (codexBindingRegistry
|
|
173
|
+
? selectCodexBindingSession(codexBindingRegistry, proc.pid, processStartedAt, cwd, codexSessions)
|
|
174
|
+
: undefined) ?? matchCodexSession(cwd, processStartedAt, codexSessions);
|
|
149
175
|
if (matched) {
|
|
150
176
|
sessionMatched = true;
|
|
151
177
|
sessionId = matched.id;
|
|
152
178
|
startedAt = matched.timestamp;
|
|
153
|
-
lastActivityAt =
|
|
179
|
+
lastActivityAt =
|
|
180
|
+
Math.max(cachedEnrichment?.lastActivityAt ?? 0, matched.lastActivityAt ?? 0) || undefined;
|
|
154
181
|
model = matched.model;
|
|
155
182
|
codexSessionFile = matched.filePath;
|
|
156
183
|
if (matched.totalTokenUsage) {
|
|
@@ -168,6 +195,17 @@ export async function scanAgents(config, options = {}) {
|
|
|
168
195
|
if (phase !== "permission" && runtimeSource === "cli") {
|
|
169
196
|
phase = (await detectCliStdoutPhase({ pid: proc.pid, cwd }, config)) ?? phase;
|
|
170
197
|
}
|
|
198
|
+
if (codexBindingRegistry && matched) {
|
|
199
|
+
upsertCodexBindingRecord(codexBindingRegistry, {
|
|
200
|
+
pid: proc.pid,
|
|
201
|
+
processStartedAt,
|
|
202
|
+
cwd,
|
|
203
|
+
matched,
|
|
204
|
+
});
|
|
205
|
+
}
|
|
206
|
+
lastActivityAt = refreshLastActivityAt(lastActivityAt, cpuPercent, phase, config.status.activeCpuThreshold, agentName);
|
|
207
|
+
lastActivityAt =
|
|
208
|
+
Math.max(cachedEnrichment?.lastActivityAt ?? 0, lastActivityAt ?? 0) || undefined;
|
|
171
209
|
}
|
|
172
210
|
else if (agentName === "Gemini") {
|
|
173
211
|
cwd = cachedEnrichment?.cwd ?? (await getProcessCwd(proc.pid)) ?? "unknown";
|
|
@@ -184,12 +222,17 @@ export async function scanAgents(config, options = {}) {
|
|
|
184
222
|
phase = (await detectCliStdoutPhase({ pid: proc.pid, cwd }, config)) ?? phase;
|
|
185
223
|
}
|
|
186
224
|
}
|
|
225
|
+
if (sessionId && sessionRegistry?.has(sessionId)) {
|
|
226
|
+
const persistedLastActivityAt = sessionRegistry.get(sessionId)?.lastActivityAt;
|
|
227
|
+
lastActivityAt = Math.max(lastActivityAt ?? 0, persistedLastActivityAt ?? 0) || undefined;
|
|
228
|
+
}
|
|
187
229
|
if (cwd === "unknown" && isFullEnrichment) {
|
|
188
230
|
cwd = cachedEnrichment?.cwd ?? (await getProcessCwd(proc.pid)) ?? "unknown";
|
|
189
231
|
}
|
|
190
232
|
const statusBaseAt = lastActivityAt ?? lastResponseAt ?? startedAt;
|
|
191
233
|
const elapsed = statusBaseAt ? Date.now() / 1000 - statusBaseAt : undefined;
|
|
192
|
-
const
|
|
234
|
+
const rawStatus = determineStatus(cpuPercent, elapsed, sessionMatched, phase, config, agentName);
|
|
235
|
+
const status = applyStatusHysteresis(rawStatus, cachedEnrichment?.status, elapsed, phase, agentName);
|
|
193
236
|
const session = {
|
|
194
237
|
agentName,
|
|
195
238
|
pid: proc.pid,
|
|
@@ -199,6 +242,7 @@ export async function scanAgents(config, options = {}) {
|
|
|
199
242
|
memoryMb,
|
|
200
243
|
status,
|
|
201
244
|
startedAt,
|
|
245
|
+
processStartedAt,
|
|
202
246
|
sessionId,
|
|
203
247
|
tokenUsage,
|
|
204
248
|
model,
|
|
@@ -213,9 +257,11 @@ export async function scanAgents(config, options = {}) {
|
|
|
213
257
|
cwd: session.cwd,
|
|
214
258
|
sessionId: session.sessionId,
|
|
215
259
|
startedAt: session.startedAt,
|
|
260
|
+
processStartedAt: session.processStartedAt,
|
|
216
261
|
tokenUsage: session.tokenUsage,
|
|
217
262
|
model: session.model,
|
|
218
263
|
sessionMatched: session.sessionMatched,
|
|
264
|
+
status: session.status,
|
|
219
265
|
phase: session.phase,
|
|
220
266
|
lastResponseAt: session.lastResponseAt,
|
|
221
267
|
lastActivityAt: session.lastActivityAt,
|
|
@@ -227,6 +273,12 @@ export async function scanAgents(config, options = {}) {
|
|
|
227
273
|
const concurrencyLimit = isFullEnrichment ? 8 : 4;
|
|
228
274
|
const results = await promiseAllLimited(sessionPromises, concurrencyLimit);
|
|
229
275
|
const sessions = results.filter((s) => s !== null);
|
|
276
|
+
if (codexBindingRegistry) {
|
|
277
|
+
const aliveCodexKeys = new Set(sessions
|
|
278
|
+
.filter((session) => session.agentName === "Codex")
|
|
279
|
+
.map((session) => buildCodexBindingKey(session.pid, session.processStartedAt)));
|
|
280
|
+
markMissingCodexBindingsDead(codexBindingRegistry, aliveCodexKeys);
|
|
281
|
+
}
|
|
230
282
|
// 5. Check for dead sessions (Claude: session file exists but process gone)
|
|
231
283
|
if (config.display.showDead) {
|
|
232
284
|
for (const claudeSessionDir of getClaudeSessionRoots(config)) {
|
|
@@ -21,7 +21,10 @@ export interface SessionRegistryRecord {
|
|
|
21
21
|
lastActivityAt?: number;
|
|
22
22
|
model?: string;
|
|
23
23
|
}
|
|
24
|
-
export
|
|
24
|
+
export interface SessionRegistryUpdate extends Partial<AgentSession> {
|
|
25
|
+
jsonlPath?: string;
|
|
26
|
+
}
|
|
27
|
+
export declare function updateRegistry(registry: Map<string, SessionRegistryRecord>, agents: SessionRegistryUpdate[]): void;
|
|
25
28
|
/**
|
|
26
29
|
* Remove sessions whose lastActivityAt is older than maxAgeDays.
|
|
27
30
|
* Returns the number of pruned entries.
|
|
@@ -10,26 +10,32 @@ export function updateRegistry(registry, agents) {
|
|
|
10
10
|
continue;
|
|
11
11
|
const existing = registry.get(agent.sessionId);
|
|
12
12
|
if (existing) {
|
|
13
|
-
// Check if PID changed (resume)
|
|
14
13
|
const lastEntry = existing.history[existing.history.length - 1];
|
|
15
|
-
|
|
16
|
-
|
|
14
|
+
const nextPid = agent.pid ?? 0;
|
|
15
|
+
const nextStartedAt = agent.startedAt ?? Math.floor(Date.now() / 1000);
|
|
16
|
+
const nextJsonlPath = agent.jsonlPath;
|
|
17
|
+
const pidChanged = Boolean(lastEntry && lastEntry.pid !== nextPid);
|
|
18
|
+
const jsonlChanged = Boolean(lastEntry && nextJsonlPath && lastEntry.jsonlPath && lastEntry.jsonlPath !== nextJsonlPath);
|
|
19
|
+
if (lastEntry && (pidChanged || jsonlChanged)) {
|
|
17
20
|
if (!lastEntry.endedAt)
|
|
18
21
|
lastEntry.endedAt = Math.floor(Date.now() / 1000);
|
|
19
|
-
// Add new PID to history
|
|
20
22
|
existing.history.push({
|
|
21
|
-
pid:
|
|
22
|
-
|
|
23
|
+
pid: nextPid,
|
|
24
|
+
jsonlPath: nextJsonlPath,
|
|
25
|
+
startedAt: nextStartedAt,
|
|
23
26
|
});
|
|
24
27
|
}
|
|
25
|
-
|
|
28
|
+
else if (lastEntry && nextJsonlPath && !lastEntry.jsonlPath) {
|
|
29
|
+
lastEntry.jsonlPath = nextJsonlPath;
|
|
30
|
+
}
|
|
26
31
|
if (agent.tokenUsage) {
|
|
27
32
|
existing.totalTokens.input = agent.tokenUsage.inputTokens ?? 0;
|
|
28
33
|
existing.totalTokens.output = agent.tokenUsage.outputTokens ?? 0;
|
|
29
34
|
existing.totalTokens.cache = agent.tokenUsage.cacheReadTokens ?? 0;
|
|
30
35
|
}
|
|
31
|
-
if (agent.lastActivityAt)
|
|
32
|
-
existing.lastActivityAt = agent.lastActivityAt;
|
|
36
|
+
if (agent.lastActivityAt) {
|
|
37
|
+
existing.lastActivityAt = Math.max(existing.lastActivityAt ?? 0, agent.lastActivityAt);
|
|
38
|
+
}
|
|
33
39
|
if (agent.model)
|
|
34
40
|
existing.model = agent.model;
|
|
35
41
|
if (agent.cwd)
|
|
@@ -44,6 +50,7 @@ export function updateRegistry(registry, agents) {
|
|
|
44
50
|
history: [
|
|
45
51
|
{
|
|
46
52
|
pid: agent.pid ?? 0,
|
|
53
|
+
jsonlPath: agent.jsonlPath,
|
|
47
54
|
startedAt: agent.startedAt ?? Math.floor(Date.now() / 1000),
|
|
48
55
|
},
|
|
49
56
|
],
|
package/dist/scanner/status.d.ts
CHANGED
|
@@ -3,6 +3,8 @@
|
|
|
3
3
|
*/
|
|
4
4
|
import type { MarmonitorConfig } from "../config/index.js";
|
|
5
5
|
import type { AgentSession, SessionPhase, SessionStatus } from "../types.js";
|
|
6
|
+
export declare function refreshLastActivityAt(lastActivityAt: number | undefined, cpuPercent: number, phase: SessionPhase | undefined, activeCpuThreshold: number, agentName: string | undefined, nowSec?: number): number | undefined;
|
|
6
7
|
/** Determine agent activity status */
|
|
7
|
-
export declare function determineStatus(cpuPercent: number, elapsedSec: number | undefined, sessionMatched: boolean, phase: SessionPhase | undefined, config: MarmonitorConfig): SessionStatus;
|
|
8
|
+
export declare function determineStatus(cpuPercent: number, elapsedSec: number | undefined, sessionMatched: boolean, phase: SessionPhase | undefined, config: MarmonitorConfig, agentName?: string): SessionStatus;
|
|
9
|
+
export declare function applyStatusHysteresis(nextStatus: SessionStatus, previousStatus: SessionStatus | undefined, elapsedSec: number | undefined, phase: SessionPhase | undefined, agentName: string | undefined): SessionStatus;
|
|
8
10
|
export declare function detectCliStdoutPhase(agent: Pick<AgentSession, "pid" | "cwd">, config: MarmonitorConfig): Promise<SessionPhase>;
|