marmonitor 0.2.5 → 0.2.7
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 +39 -3
- package/README.md +41 -4
- package/dist/alerts/token.js +10 -2
- package/dist/cli.js +201 -28
- package/dist/clipboard.d.ts +12 -0
- package/dist/clipboard.js +56 -0
- package/dist/config/index.d.ts +3 -0
- package/dist/config/index.js +10 -4
- package/dist/output/index.d.ts +6 -3
- package/dist/output/index.js +43 -32
- package/dist/output/utils.d.ts +9 -2
- package/dist/output/utils.js +58 -2
- package/dist/scanner/cache.d.ts +10 -0
- package/dist/scanner/cache.js +14 -0
- package/dist/scanner/claude.d.ts +70 -3
- package/dist/scanner/claude.js +350 -26
- package/dist/scanner/codex.d.ts +39 -0
- package/dist/scanner/codex.js +171 -9
- package/dist/scanner/daemon-loop.d.ts +2 -0
- package/dist/scanner/daemon-loop.js +9 -2
- package/dist/scanner/daemon-utils.d.ts +11 -0
- package/dist/scanner/daemon-utils.js +42 -11
- package/dist/scanner/gemini.d.ts +10 -0
- package/dist/scanner/gemini.js +82 -0
- package/dist/scanner/group.d.ts +1 -1
- package/dist/scanner/group.js +9 -0
- package/dist/scanner/index.d.ts +18 -0
- package/dist/scanner/index.js +247 -28
- package/dist/scanner/process.d.ts +12 -0
- package/dist/scanner/process.js +242 -16
- package/dist/scanner/session-registry.d.ts +21 -0
- package/dist/scanner/session-registry.js +85 -4
- package/dist/scanner/status.d.ts +36 -1
- package/dist/scanner/status.js +49 -5
- package/dist/sessions.d.ts +9 -0
- package/dist/sessions.js +11 -0
- package/dist/tmux/index.d.ts +29 -5
- package/dist/tmux/index.js +131 -16
- package/dist/turns.d.ts +68 -0
- package/dist/turns.js +430 -0
- package/dist/types.d.ts +8 -0
- package/package.json +3 -1
package/dist/scanner/codex.js
CHANGED
|
@@ -6,10 +6,38 @@ import { open, readFile, readdir, stat } from "node:fs/promises";
|
|
|
6
6
|
import { homedir } from "node:os";
|
|
7
7
|
import { join } from "node:path";
|
|
8
8
|
import { indexCodexSessionsFromSqlite } from "./codex-sqlite.js";
|
|
9
|
+
import { CODEX_VALUE_OPTIONS, getCodexProcessArguments } from "./process.js";
|
|
9
10
|
import { resolveRuntimeDataPaths } from "../config/index.js";
|
|
10
11
|
import { advanceJsonlCursor, resolvePhaseFromHistory, resolvePhaseWithDecay, selectCodexSession, updatePhaseHistory, upsertSessionRegistryEntry, } from "../output/utils.js";
|
|
11
12
|
import { CODEX_INDEX_TTL_MS, CODEX_PHASE_RECENT_LINES, HOME, codexIndexCache, codexPhaseCache, codexSessionFileCache, codexSessionRegistry, setCodexIndexCache, } from "./cache.js";
|
|
12
13
|
const CODEX_SQLITE_RECENT_DAYS = 7;
|
|
14
|
+
function mergeCodexIndexedSessions(baseSessions, incomingSessions) {
|
|
15
|
+
const merged = new Map();
|
|
16
|
+
for (const session of baseSessions) {
|
|
17
|
+
merged.set(session.id, session);
|
|
18
|
+
}
|
|
19
|
+
for (const session of incomingSessions) {
|
|
20
|
+
const existing = merged.get(session.id);
|
|
21
|
+
if (!existing) {
|
|
22
|
+
merged.set(session.id, session);
|
|
23
|
+
continue;
|
|
24
|
+
}
|
|
25
|
+
merged.set(session.id, {
|
|
26
|
+
...existing,
|
|
27
|
+
...session,
|
|
28
|
+
filePath: session.filePath || existing.filePath,
|
|
29
|
+
cwd: session.cwd || existing.cwd,
|
|
30
|
+
timestamp: Math.min(existing.timestamp || session.timestamp, session.timestamp || existing.timestamp),
|
|
31
|
+
lastActivityAt: Math.max(existing.lastActivityAt ?? 0, session.lastActivityAt ?? 0) || undefined,
|
|
32
|
+
totalTokenUsage: session.totalTokenUsage?.total_tokens !== undefined
|
|
33
|
+
? session.totalTokenUsage
|
|
34
|
+
: existing.totalTokenUsage,
|
|
35
|
+
model: session.model ?? existing.model,
|
|
36
|
+
});
|
|
37
|
+
}
|
|
38
|
+
return [...merged.values()].sort((a, b) => (b.lastActivityAt ?? b.timestamp) - (a.lastActivityAt ?? a.timestamp));
|
|
39
|
+
}
|
|
40
|
+
export { mergeCodexIndexedSessions };
|
|
13
41
|
export function getCodexSessionRoots(config) {
|
|
14
42
|
return config
|
|
15
43
|
? resolveRuntimeDataPaths(config).codexSessions
|
|
@@ -113,16 +141,17 @@ export async function indexCodexSessions(config, options) {
|
|
|
113
141
|
return codexIndexCache.sessions;
|
|
114
142
|
}
|
|
115
143
|
const hasExplicitSessionRoots = Boolean(config?.paths.codexSessions?.length);
|
|
144
|
+
const sqliteSessions = [];
|
|
116
145
|
// Primary: SQLite threads table
|
|
117
146
|
const dbPath = hasExplicitSessionRoots ? undefined : findCodexStateDb();
|
|
118
147
|
if (dbPath) {
|
|
119
|
-
const
|
|
148
|
+
const indexed = await indexCodexSessionsFromSqlite(dbPath, {
|
|
120
149
|
recentUpdatedAfter: Math.floor(Date.now() / 1000) - CODEX_SQLITE_RECENT_DAYS * 86400,
|
|
121
150
|
includeCwds: activeCwds,
|
|
122
151
|
});
|
|
123
|
-
if (
|
|
152
|
+
if (indexed.length > 0) {
|
|
124
153
|
// Register sessions for phase detection and cwd lookup
|
|
125
|
-
for (const s of
|
|
154
|
+
for (const s of indexed) {
|
|
126
155
|
codexSessionFileCache.set(s.filePath, { ...s, mtimeMs: undefined, size: undefined });
|
|
127
156
|
upsertSessionRegistryEntry(codexSessionRegistry, {
|
|
128
157
|
filePath: s.filePath,
|
|
@@ -135,10 +164,7 @@ export async function indexCodexSessions(config, options) {
|
|
|
135
164
|
binding: "direct",
|
|
136
165
|
});
|
|
137
166
|
}
|
|
138
|
-
|
|
139
|
-
setCodexIndexCache({ builtAt: Date.now(), sessions: sqliteSessions });
|
|
140
|
-
}
|
|
141
|
-
return sqliteSessions;
|
|
167
|
+
sqliteSessions.push(...indexed);
|
|
142
168
|
}
|
|
143
169
|
}
|
|
144
170
|
// Fallback: JSONL directory scan (last 7 days)
|
|
@@ -200,6 +226,9 @@ export async function indexCodexSessions(config, options) {
|
|
|
200
226
|
}
|
|
201
227
|
}
|
|
202
228
|
if (meta.id && meta.cwd && meta.timestamp) {
|
|
229
|
+
if (hasTargetedFilter && !activeCwds.includes(meta.cwd)) {
|
|
230
|
+
continue;
|
|
231
|
+
}
|
|
203
232
|
const parsed = {
|
|
204
233
|
filePath,
|
|
205
234
|
id: meta.id,
|
|
@@ -235,11 +264,144 @@ export async function indexCodexSessions(config, options) {
|
|
|
235
264
|
catch {
|
|
236
265
|
// sessions dir error
|
|
237
266
|
}
|
|
267
|
+
const sessions = mergeCodexIndexedSessions(sqliteSessions, metas);
|
|
238
268
|
setCodexIndexCache({
|
|
239
269
|
builtAt: Date.now(),
|
|
240
|
-
sessions
|
|
270
|
+
sessions,
|
|
241
271
|
});
|
|
242
|
-
return
|
|
272
|
+
return sessions;
|
|
273
|
+
}
|
|
274
|
+
const CODEX_UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
275
|
+
const CODEX_SESSION_ID_RE = /^(?:[0-9a-f]{32}|[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$/i;
|
|
276
|
+
const CODEX_BOOLEAN_OPTIONS = new Set([
|
|
277
|
+
"--all",
|
|
278
|
+
"--include-non-interactive",
|
|
279
|
+
"--strict-config",
|
|
280
|
+
"--oss",
|
|
281
|
+
"--approve-for-me",
|
|
282
|
+
"--dangerously-bypass-approvals-and-sandbox",
|
|
283
|
+
"--dangerously-bypass-hook-trust",
|
|
284
|
+
"--worktree",
|
|
285
|
+
"--search",
|
|
286
|
+
"--no-alt-screen",
|
|
287
|
+
"--no-daemon",
|
|
288
|
+
"--full-auto",
|
|
289
|
+
"--yolo",
|
|
290
|
+
]);
|
|
291
|
+
/**
|
|
292
|
+
* Session id a Codex process names in its own command line.
|
|
293
|
+
*
|
|
294
|
+
* This is an identity, not a guess, and it outranks every heuristic. Matching
|
|
295
|
+
* by cwd and nearest start time gets this wrong in the ordinary case of a
|
|
296
|
+
* resumed thread: the process starts today while its session file is dated
|
|
297
|
+
* whenever the thread began, so a newer unrelated session in the same cwd wins
|
|
298
|
+
* the proximity sort and two processes end up on one session (#114).
|
|
299
|
+
*/
|
|
300
|
+
export function parseCodexSessionIdFromCmd(cmd) {
|
|
301
|
+
if (!cmd)
|
|
302
|
+
return undefined;
|
|
303
|
+
const args = getCodexProcessArguments(cmd);
|
|
304
|
+
if (!args)
|
|
305
|
+
return undefined;
|
|
306
|
+
let resume = false;
|
|
307
|
+
let declared;
|
|
308
|
+
for (let i = 0; i < args.length; i++) {
|
|
309
|
+
const arg = args[i];
|
|
310
|
+
const option = arg.split("=", 1)[0];
|
|
311
|
+
if (arg === "--")
|
|
312
|
+
return declared;
|
|
313
|
+
if (["--last", "--help", "-h", "--version", "-V"].includes(arg))
|
|
314
|
+
return undefined;
|
|
315
|
+
// Image options are variadic; a display string cannot prove where their values end.
|
|
316
|
+
if (option === "--image" || option === "-i")
|
|
317
|
+
return undefined;
|
|
318
|
+
if (option === "--session-id" || option === "--session_id") {
|
|
319
|
+
const value = arg.includes("=") ? arg.slice(arg.indexOf("=") + 1) : args[++i];
|
|
320
|
+
if (!value || !CODEX_SESSION_ID_RE.test(value))
|
|
321
|
+
return undefined;
|
|
322
|
+
if (declared && declared !== value.toLowerCase())
|
|
323
|
+
return undefined;
|
|
324
|
+
declared = value.toLowerCase();
|
|
325
|
+
}
|
|
326
|
+
else if (CODEX_VALUE_OPTIONS.has(option)) {
|
|
327
|
+
if (!arg.includes("=")) {
|
|
328
|
+
if (args[i + 1] === undefined)
|
|
329
|
+
return undefined;
|
|
330
|
+
i++;
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
else if (CODEX_BOOLEAN_OPTIONS.has(arg)) {
|
|
334
|
+
// Options may appear before or after the resume subcommand.
|
|
335
|
+
}
|
|
336
|
+
else if (arg.startsWith("-")) {
|
|
337
|
+
// Unknown options may consume a value. Do not guess a positional boundary.
|
|
338
|
+
return undefined;
|
|
339
|
+
}
|
|
340
|
+
else if (!resume) {
|
|
341
|
+
if (arg.toLowerCase() !== "resume")
|
|
342
|
+
return declared;
|
|
343
|
+
resume = true;
|
|
344
|
+
}
|
|
345
|
+
else {
|
|
346
|
+
const resumed = arg.toLowerCase();
|
|
347
|
+
return CODEX_UUID_RE.test(arg) && (!declared || declared === resumed) ? resumed : undefined;
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
return declared;
|
|
351
|
+
}
|
|
352
|
+
/**
|
|
353
|
+
* Which session a Codex process owns, in order of how much the answer is
|
|
354
|
+
* actually known (#114).
|
|
355
|
+
*
|
|
356
|
+
* Binding to the wrong session is worse than not binding at all: a misbound
|
|
357
|
+
* process reports another session's tokens and jumps to its pane. So each step
|
|
358
|
+
* refuses instead of falling through to a weaker guess once the strong answer
|
|
359
|
+
* is unavailable.
|
|
360
|
+
*
|
|
361
|
+
* declared the id in the process's own command line — an identity
|
|
362
|
+
* binding what this exact PID resolved to before, from the registry
|
|
363
|
+
* heuristic cwd + nearest start time, the only option left
|
|
364
|
+
*
|
|
365
|
+
* Sessions already claimed this cycle, and sessions another process declared,
|
|
366
|
+
* are removed from the pool before the two weaker steps run — otherwise a guess
|
|
367
|
+
* can steal a session that someone else names outright.
|
|
368
|
+
*/
|
|
369
|
+
export function selectCodexSessionForProcess(pick) {
|
|
370
|
+
const { declaredSessionId, sessions, claimedSessionIds } = pick;
|
|
371
|
+
if (declaredSessionId) {
|
|
372
|
+
if (claimedSessionIds.has(declaredSessionId))
|
|
373
|
+
return undefined;
|
|
374
|
+
return sessions.find((session) => session.id === declaredSessionId);
|
|
375
|
+
}
|
|
376
|
+
const available = sessions.filter((session) => !claimedSessionIds.has(session.id) && !pick.argvReservedSessionIds.has(session.id));
|
|
377
|
+
const bound = pick.resolveBinding?.(available);
|
|
378
|
+
if (bound) {
|
|
379
|
+
const bornWith = sessionBornWithProcess(available, pick.cwd, pick.processStartedAt);
|
|
380
|
+
// A persisted binding can be an old heuristic guess. If this process never
|
|
381
|
+
// wrote the bound file but did create a rollout at startup, the rollout wins
|
|
382
|
+
// and the caller's upsert repairs the registry record.
|
|
383
|
+
if (bornWith &&
|
|
384
|
+
bornWith.id !== bound.id &&
|
|
385
|
+
pick.processStartedAt !== undefined &&
|
|
386
|
+
(bound.lastActivityAt ?? bound.timestamp) < pick.processStartedAt - CODEX_START_SLACK_SEC) {
|
|
387
|
+
return bornWith;
|
|
388
|
+
}
|
|
389
|
+
return bound;
|
|
390
|
+
}
|
|
391
|
+
return matchCodexSession(pick.cwd, pick.processStartedAt, available);
|
|
392
|
+
}
|
|
393
|
+
const CODEX_START_SLACK_SEC = 5;
|
|
394
|
+
/** Codex creates its rollout within seconds of process start. */
|
|
395
|
+
const CODEX_ROLLOUT_BIRTH_WINDOW_SEC = 60;
|
|
396
|
+
/** The one rollout in this cwd created right after the process started, if
|
|
397
|
+
* exactly one exists. Two processes starting together make it ambiguous. */
|
|
398
|
+
function sessionBornWithProcess(sessions, cwd, processStartedAt) {
|
|
399
|
+
if (processStartedAt === undefined)
|
|
400
|
+
return undefined;
|
|
401
|
+
const born = sessions.filter((session) => session.cwd === cwd &&
|
|
402
|
+
session.timestamp >= processStartedAt - CODEX_START_SLACK_SEC &&
|
|
403
|
+
session.timestamp <= processStartedAt + CODEX_ROLLOUT_BIRTH_WINDOW_SEC);
|
|
404
|
+
return born.length === 1 ? born[0] : undefined;
|
|
243
405
|
}
|
|
244
406
|
/** Match a Codex process to a session by cwd + closest timestamp */
|
|
245
407
|
export function matchCodexSession(processCwd, processStartTime, sessions) {
|
|
@@ -15,4 +15,6 @@ export interface DaemonOptions {
|
|
|
15
15
|
activityLogDir: string;
|
|
16
16
|
activityRetentionDays: number;
|
|
17
17
|
}
|
|
18
|
+
/** Token/context threshold alerts fire only when both master and category toggles are on. */
|
|
19
|
+
export declare function shouldRunTokenAlerts(config: MarmonitorConfig): boolean;
|
|
18
20
|
export declare function runDaemonLoop(config: MarmonitorConfig, options: DaemonOptions): Promise<void>;
|
|
@@ -13,6 +13,10 @@ import { loadRegistryFromFile, pruneRegistry, saveRegistryToFile, updateRegistry
|
|
|
13
13
|
function sleep(ms) {
|
|
14
14
|
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
15
15
|
}
|
|
16
|
+
/** Token/context threshold alerts fire only when both master and category toggles are on. */
|
|
17
|
+
export function shouldRunTokenAlerts(config) {
|
|
18
|
+
return Boolean(config.alerts.enabled && config.alerts.tokens);
|
|
19
|
+
}
|
|
16
20
|
export async function runDaemonLoop(config, options) {
|
|
17
21
|
const { intervalMs, detailIntervalMs, snapshotPath, alertsSnapshotPath, alertsLogPath, pidPath, registryPath, codexBindingRegistryPath, activityLogDir, activityRetentionDays, } = options;
|
|
18
22
|
// Activity log: per-session JSONL cursor offsets (in-memory only)
|
|
@@ -69,8 +73,8 @@ export async function runDaemonLoop(config, options) {
|
|
|
69
73
|
updateRegistry(registry, agents);
|
|
70
74
|
// Write snapshot for statusline consumers
|
|
71
75
|
await writeDaemonSnapshot(snapshotPath, agents);
|
|
72
|
-
// Check token thresholds and fire alerts (alerts.enabled 확인)
|
|
73
|
-
if (config
|
|
76
|
+
// Check token thresholds and fire alerts (alerts.enabled + alerts.tokens 확인)
|
|
77
|
+
if (shouldRunTokenAlerts(config)) {
|
|
74
78
|
const thresholds = {
|
|
75
79
|
warnAt: config.alerts.contextWarnThreshold,
|
|
76
80
|
critAt: config.alerts.contextCritThreshold,
|
|
@@ -123,6 +127,9 @@ export async function runDaemonLoop(config, options) {
|
|
|
123
127
|
startedAt: agent.startedAt,
|
|
124
128
|
tokenUsage: agent.tokenUsage,
|
|
125
129
|
lastActivityAt: agent.lastActivityAt,
|
|
130
|
+
// #113: without this, updateRegistry() falls back to the merged
|
|
131
|
+
// lastActivityAt and writes the busy inference to disk.
|
|
132
|
+
observedActivityAt: agent.observedActivityAt,
|
|
126
133
|
model: agent.model,
|
|
127
134
|
jsonlPath: sessionFile,
|
|
128
135
|
});
|
|
@@ -6,4 +6,15 @@ export declare function writeDaemonPid(pidPath: string, pid: number): Promise<vo
|
|
|
6
6
|
export declare function readDaemonPid(pidPath: string): Promise<number | undefined>;
|
|
7
7
|
export declare function isDaemonRunning(pidPath: string): Promise<boolean>;
|
|
8
8
|
export declare function writeDaemonSnapshot(snapshotPath: string, data: unknown[]): Promise<void>;
|
|
9
|
+
export type SnapshotReadResult = {
|
|
10
|
+
health: "fresh" | "stale";
|
|
11
|
+
agents: unknown[];
|
|
12
|
+
ageMs: number;
|
|
13
|
+
} | {
|
|
14
|
+
health: "missing" | "unreadable" | "invalid";
|
|
15
|
+
};
|
|
16
|
+
/** Read data and age from the same file generation, including during atomic replacement.
|
|
17
|
+
* Stale data is diagnostic evidence; callers must explicitly require fresh data for actions. */
|
|
18
|
+
export declare function readDaemonSnapshotResult(snapshotPath: string, ttlMs: number): Promise<SnapshotReadResult>;
|
|
19
|
+
/** Compatibility helper for consumers that accept only fresh data. */
|
|
9
20
|
export declare function readDaemonSnapshot(snapshotPath: string, ttlMs: number): Promise<unknown[]>;
|
|
@@ -2,7 +2,8 @@
|
|
|
2
2
|
* Daemon utility functions for PID management and snapshot I/O.
|
|
3
3
|
* Used by both the daemon loop and CLI commands.
|
|
4
4
|
*/
|
|
5
|
-
import {
|
|
5
|
+
import { randomUUID } from "node:crypto";
|
|
6
|
+
import { mkdir, open, readFile, rename, unlink, writeFile } from "node:fs/promises";
|
|
6
7
|
import { dirname } from "node:path";
|
|
7
8
|
export async function writeDaemonPid(pidPath, pid) {
|
|
8
9
|
await mkdir(dirname(pidPath), { recursive: true });
|
|
@@ -33,24 +34,54 @@ export async function isDaemonRunning(pidPath) {
|
|
|
33
34
|
}
|
|
34
35
|
}
|
|
35
36
|
export async function writeDaemonSnapshot(snapshotPath, data) {
|
|
37
|
+
const temporaryPath = `${snapshotPath}.${process.pid}.${randomUUID()}.tmp`;
|
|
36
38
|
try {
|
|
37
39
|
await mkdir(dirname(snapshotPath), { recursive: true });
|
|
38
|
-
await writeFile(
|
|
40
|
+
await writeFile(temporaryPath, JSON.stringify(data), {
|
|
41
|
+
encoding: "utf-8",
|
|
42
|
+
mode: 0o600,
|
|
43
|
+
flag: "wx",
|
|
44
|
+
});
|
|
45
|
+
await rename(temporaryPath, snapshotPath);
|
|
39
46
|
}
|
|
40
47
|
catch {
|
|
41
48
|
// snapshot write failures must never crash the daemon
|
|
42
49
|
}
|
|
50
|
+
finally {
|
|
51
|
+
await unlink(temporaryPath).catch(() => { });
|
|
52
|
+
}
|
|
43
53
|
}
|
|
44
|
-
|
|
54
|
+
/** Read data and age from the same file generation, including during atomic replacement.
|
|
55
|
+
* Stale data is diagnostic evidence; callers must explicitly require fresh data for actions. */
|
|
56
|
+
export async function readDaemonSnapshotResult(snapshotPath, ttlMs) {
|
|
45
57
|
try {
|
|
46
|
-
const
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
58
|
+
const file = await open(snapshotPath, "r");
|
|
59
|
+
try {
|
|
60
|
+
const [fileStat, raw] = await Promise.all([file.stat(), file.readFile("utf-8")]);
|
|
61
|
+
let parsed;
|
|
62
|
+
try {
|
|
63
|
+
parsed = JSON.parse(raw);
|
|
64
|
+
}
|
|
65
|
+
catch {
|
|
66
|
+
return { health: "invalid" };
|
|
67
|
+
}
|
|
68
|
+
if (!Array.isArray(parsed))
|
|
69
|
+
return { health: "invalid" };
|
|
70
|
+
const ageMs = Math.max(0, Date.now() - fileStat.mtimeMs);
|
|
71
|
+
return { health: ageMs > ttlMs ? "stale" : "fresh", agents: parsed, ageMs };
|
|
72
|
+
}
|
|
73
|
+
finally {
|
|
74
|
+
await file.close();
|
|
75
|
+
}
|
|
52
76
|
}
|
|
53
|
-
catch {
|
|
54
|
-
return
|
|
77
|
+
catch (error) {
|
|
78
|
+
return {
|
|
79
|
+
health: error.code === "ENOENT" ? "missing" : "unreadable",
|
|
80
|
+
};
|
|
55
81
|
}
|
|
56
82
|
}
|
|
83
|
+
/** Compatibility helper for consumers that accept only fresh data. */
|
|
84
|
+
export async function readDaemonSnapshot(snapshotPath, ttlMs) {
|
|
85
|
+
const result = await readDaemonSnapshotResult(snapshotPath, ttlMs);
|
|
86
|
+
return result.health === "fresh" ? result.agents : [];
|
|
87
|
+
}
|
package/dist/scanner/gemini.d.ts
CHANGED
|
@@ -16,6 +16,16 @@ export interface GeminiSessionMeta {
|
|
|
16
16
|
export declare function toEpochSec(value: string | undefined): number | undefined;
|
|
17
17
|
export declare function parseGeminiSessionContent(raw: string): Partial<GeminiSessionMeta>;
|
|
18
18
|
export declare function resolveGeminiProjectDir(cwd: string): Promise<string | undefined>;
|
|
19
|
+
/**
|
|
20
|
+
* Resolve a Gemini chats file by sessionId match first, then by latest mtime.
|
|
21
|
+
*
|
|
22
|
+
* Same-cwd multi-session safety: when `sessionId` is provided we scan each
|
|
23
|
+
* chats/*.json's `sessionId` field and return the matching path. Without a
|
|
24
|
+
* match we fall back to the most recently modified file (the legacy
|
|
25
|
+
* behaviour of parseGeminiSession). Returns undefined if no chats dir or
|
|
26
|
+
* no files exist.
|
|
27
|
+
*/
|
|
28
|
+
export declare function resolveGeminiChatFile(cwd: string, sessionId?: string): Promise<string | undefined>;
|
|
19
29
|
export declare function parseGeminiSession(cwd: string): Promise<Partial<AgentSession> & {
|
|
20
30
|
sessionFile?: string;
|
|
21
31
|
}>;
|
package/dist/scanner/gemini.js
CHANGED
|
@@ -84,6 +84,88 @@ export async function resolveGeminiProjectDir(cwd) {
|
|
|
84
84
|
}
|
|
85
85
|
return undefined;
|
|
86
86
|
}
|
|
87
|
+
/**
|
|
88
|
+
* Resolve a Gemini chats file by sessionId match first, then by latest mtime.
|
|
89
|
+
*
|
|
90
|
+
* Same-cwd multi-session safety: when `sessionId` is provided we scan each
|
|
91
|
+
* chats/*.json's `sessionId` field and return the matching path. Without a
|
|
92
|
+
* match we fall back to the most recently modified file (the legacy
|
|
93
|
+
* behaviour of parseGeminiSession). Returns undefined if no chats dir or
|
|
94
|
+
* no files exist.
|
|
95
|
+
*/
|
|
96
|
+
export async function resolveGeminiChatFile(cwd, sessionId) {
|
|
97
|
+
const projectDir = await resolveGeminiProjectDir(cwd);
|
|
98
|
+
if (!projectDir)
|
|
99
|
+
return undefined;
|
|
100
|
+
const chatsDir = join(projectDir, "chats");
|
|
101
|
+
if (!existsSync(chatsDir))
|
|
102
|
+
return undefined;
|
|
103
|
+
let files;
|
|
104
|
+
try {
|
|
105
|
+
files = (await readdir(chatsDir))
|
|
106
|
+
.filter((name) => name.startsWith("session-") && name.endsWith(".json"))
|
|
107
|
+
.map((name) => join(chatsDir, name));
|
|
108
|
+
}
|
|
109
|
+
catch {
|
|
110
|
+
return undefined;
|
|
111
|
+
}
|
|
112
|
+
if (files.length === 0)
|
|
113
|
+
return undefined;
|
|
114
|
+
// Tier 0: filename fast-path. Gemini chats are written as
|
|
115
|
+
// session-<YYYY-MM-DDTHH-MM>-<sessionId first 8 chars>.json
|
|
116
|
+
// so checking the basename against the sessionId prefix avoids reading
|
|
117
|
+
// every file. Verified against ~/.gemini/tmp/*/chats/session-*.json.
|
|
118
|
+
if (sessionId && sessionId.length >= 8) {
|
|
119
|
+
const prefix = sessionId.slice(0, 8);
|
|
120
|
+
const namedHit = files.find((filePath) => filePath.includes(`-${prefix}.json`));
|
|
121
|
+
if (namedHit) {
|
|
122
|
+
// Confirm by reading the sessionId field — filenames could collide on a
|
|
123
|
+
// short prefix, and a false positive here would route to the wrong chat.
|
|
124
|
+
try {
|
|
125
|
+
const raw = await readFile(namedHit, "utf-8");
|
|
126
|
+
const data = JSON.parse(raw);
|
|
127
|
+
if (typeof data.sessionId === "string" && data.sessionId === sessionId) {
|
|
128
|
+
return namedHit;
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
catch {
|
|
132
|
+
// fall through to the content-scan tier
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
// Tier 1: sessionId match — open each file, return on first hit. Reached
|
|
137
|
+
// only when the filename fast-path missed (e.g. format drift or collision).
|
|
138
|
+
if (sessionId) {
|
|
139
|
+
for (const filePath of files) {
|
|
140
|
+
try {
|
|
141
|
+
const raw = await readFile(filePath, "utf-8");
|
|
142
|
+
const data = JSON.parse(raw);
|
|
143
|
+
if (typeof data.sessionId === "string" && data.sessionId === sessionId) {
|
|
144
|
+
return filePath;
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
catch {
|
|
148
|
+
// skip unreadable / malformed file
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
// Tier 2: fallback — latest mtime.
|
|
153
|
+
let latestFile;
|
|
154
|
+
let latestMtimeMs = -1;
|
|
155
|
+
for (const filePath of files) {
|
|
156
|
+
try {
|
|
157
|
+
const fileStat = await stat(filePath);
|
|
158
|
+
if (fileStat.mtimeMs > latestMtimeMs) {
|
|
159
|
+
latestMtimeMs = fileStat.mtimeMs;
|
|
160
|
+
latestFile = filePath;
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
catch {
|
|
164
|
+
// skip
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
return latestFile;
|
|
168
|
+
}
|
|
87
169
|
export async function parseGeminiSession(cwd) {
|
|
88
170
|
const projectDir = await resolveGeminiProjectDir(cwd);
|
|
89
171
|
if (!projectDir)
|
package/dist/scanner/group.d.ts
CHANGED
|
@@ -2,6 +2,6 @@
|
|
|
2
2
|
* Process tree grouping and worker state propagation.
|
|
3
3
|
*/
|
|
4
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;
|
|
5
|
+
export declare function propagateWorkerStateToParent(parent: AgentSession, child: Pick<AgentSession, "status" | "phase" | "lastActivityAt" | "observedActivityAt" | "lastResponseAt" | "startedAt" | "cpuPercent" | "memoryMb" | "resourceUsageAvailable">): AgentSession;
|
|
6
6
|
/** Group child agent processes under their parent */
|
|
7
7
|
export declare function groupByParent(sessions: AgentSession[]): AgentSession[];
|
package/dist/scanner/group.js
CHANGED
|
@@ -15,10 +15,17 @@ export function propagateWorkerStateToParent(parent, child) {
|
|
|
15
15
|
phase: inheritedPhase,
|
|
16
16
|
cpuPercent: parent.cpuPercent + (("cpuPercent" in child && child.cpuPercent) || 0),
|
|
17
17
|
memoryMb: parent.memoryMb + (("memoryMb" in child && child.memoryMb) || 0),
|
|
18
|
+
resourceUsageAvailable: parent.resourceUsageAvailable !== false && child.resourceUsageAvailable !== false,
|
|
18
19
|
startedAt: parent.startedAt && child.startedAt
|
|
19
20
|
? Math.min(parent.startedAt, child.startedAt)
|
|
20
21
|
: (parent.startedAt ?? child.startedAt),
|
|
21
22
|
lastActivityAt: Math.max(parent.lastActivityAt ?? 0, child.lastActivityAt ?? 0, child.lastResponseAt ?? 0, child.startedAt ?? 0),
|
|
23
|
+
// #113: raise the observed component alongside the merged one. Only
|
|
24
|
+
// observed times are persisted now, so leaving this behind would drop a
|
|
25
|
+
// worker's genuinely observed activity from the parent's registry record
|
|
26
|
+
// and break the `lastActivityAt = max(observed, fresh inference)`
|
|
27
|
+
// invariant. The child's own observed field is used, never its merged one.
|
|
28
|
+
observedActivityAt: Math.max(parent.observedActivityAt ?? 0, child.observedActivityAt ?? 0, child.lastResponseAt ?? 0, child.startedAt ?? 0) || undefined,
|
|
22
29
|
lastResponseAt: Math.max(parent.lastResponseAt ?? 0, child.lastResponseAt ?? 0) || undefined,
|
|
23
30
|
};
|
|
24
31
|
}
|
|
@@ -36,11 +43,13 @@ export function groupByParent(sessions) {
|
|
|
36
43
|
pid: session.pid,
|
|
37
44
|
cpuPercent: session.cpuPercent,
|
|
38
45
|
memoryMb: session.memoryMb,
|
|
46
|
+
resourceUsageAvailable: session.resourceUsageAvailable,
|
|
39
47
|
status: session.status,
|
|
40
48
|
});
|
|
41
49
|
const propagated = propagateWorkerStateToParent(parent, session);
|
|
42
50
|
parent.cpuPercent = propagated.cpuPercent;
|
|
43
51
|
parent.memoryMb = propagated.memoryMb;
|
|
52
|
+
parent.resourceUsageAvailable = propagated.resourceUsageAvailable;
|
|
44
53
|
parent.status = propagated.status;
|
|
45
54
|
parent.phase = propagated.phase;
|
|
46
55
|
parent.startedAt = propagated.startedAt;
|
package/dist/scanner/index.d.ts
CHANGED
|
@@ -12,5 +12,23 @@ export { detectAgentFromProcessSignature } from "./process.js";
|
|
|
12
12
|
export { propagateWorkerStateToParent } from "./group.js";
|
|
13
13
|
export { parseGeminiSessionContent } from "./gemini.js";
|
|
14
14
|
import type { ScanOptions } from "./types.js";
|
|
15
|
+
/**
|
|
16
|
+
* Whether a Claude PID belongs in the batch mtime resolution pass (#108).
|
|
17
|
+
*
|
|
18
|
+
* The batch scores candidates against `processStartedAt` inside a known cwd,
|
|
19
|
+
* so a PID missing either is unscorable there. Such a PID must fall through to
|
|
20
|
+
* the per-PID matcher, which still has an mtime-dominance fallback — keeping it
|
|
21
|
+
* in the batch would mark it "resolved to nothing" instead. `ps -o lstart=`
|
|
22
|
+
* failures are cached for PROCESS_START_TTL_MS, so one transient failure would
|
|
23
|
+
* otherwise leave the session unbound for that entire window.
|
|
24
|
+
*
|
|
25
|
+
* NaN must be rejected as firmly as undefined: getProcessStartTime derives the
|
|
26
|
+
* value with `new Date(...).getTime()`, so an unparseable `ps` line yields NaN,
|
|
27
|
+
* and a NaN deltaSec silently passes every `>` threshold comparison.
|
|
28
|
+
*/
|
|
29
|
+
export declare function isBatchableClaudeMtimeRequest<T extends {
|
|
30
|
+
cwd?: string;
|
|
31
|
+
processStartedAt?: number;
|
|
32
|
+
}>(request: T | null | undefined): request is T;
|
|
15
33
|
/** Scan for all running AI agent sessions */
|
|
16
34
|
export declare function scanAgents(config: MarmonitorConfig, options?: ScanOptions): Promise<AgentSession[]>;
|