marmonitor 0.2.6 → 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.
@@ -5,6 +5,34 @@ import { execFile } from "node:child_process";
5
5
  import { promisify } from "node:util";
6
6
  import { PROCESS_CWD_TTL_MS, PROCESS_START_TTL_MS, processCwdCache, processStartCache, } from "./cache.js";
7
7
  export const execFileAsync = promisify(execFile);
8
+ /**
9
+ * Environment for external commands whose output we parse.
10
+ *
11
+ * `ps -o lstart=` renders through LC_TIME, so a Korean or German locale emits
12
+ * "2026년 8월 17일 월요일 16시 27분 49초" / "Mo. 17 Aug. 16:27:49 2026" — neither
13
+ * of which `new Date()` can parse. Pinning the locale keeps the output in the
14
+ * one format our parsers were written against.
15
+ */
16
+ function parseableOutputEnv() {
17
+ return { ...process.env, LC_ALL: "C" };
18
+ }
19
+ /**
20
+ * Parse a `ps -o lstart=` line into epoch seconds.
21
+ *
22
+ * Exported for tests: the locale that produced a given line cannot be recreated
23
+ * on an arbitrary CI runner, so the parser is exercised with captured output
24
+ * instead of a live `ps` call.
25
+ */
26
+ export function parsePsLstart(raw) {
27
+ const trimmed = raw.trim();
28
+ if (!trimmed)
29
+ return undefined;
30
+ const parsed = new Date(trimmed).getTime();
31
+ // A non-C locale (or any unexpected format) yields NaN here. Returning it
32
+ // would poison every downstream comparison — NaN passes `>` thresholds and
33
+ // silently disables mtime prefilters — and the value is cached for minutes.
34
+ return Number.isFinite(parsed) ? parsed / 1000 : undefined;
35
+ }
8
36
  /** Get process cwd via lsof (fallback for non-Claude agents) */
9
37
  export async function getProcessCwd(pid) {
10
38
  const cached = processCwdCache.get(pid);
@@ -41,9 +69,9 @@ export async function getProcessStartTime(pid) {
41
69
  const { stdout } = await execFileAsync("ps", ["-o", "lstart=", "-p", String(pid)], {
42
70
  encoding: "utf-8",
43
71
  timeout: 2000,
72
+ env: parseableOutputEnv(),
44
73
  });
45
- const trimmed = stdout.trim();
46
- const startedAt = trimmed ? new Date(trimmed).getTime() / 1000 : undefined;
74
+ const startedAt = parsePsLstart(stdout);
47
75
  processStartCache.set(pid, {
48
76
  checkedAt: Date.now(),
49
77
  startedAt,
@@ -72,35 +100,223 @@ export function detectRuntimeSource(agentName, cmd) {
72
100
  return "cli";
73
101
  }
74
102
  export function matchesProcessCommand(command, processName) {
75
- const escaped = processName.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
76
- return new RegExp(`(?:^|[/\\\\])${escaped}(?:\\s|$)`, "i").test(command);
103
+ return commandExecutable(command, processName) !== undefined;
104
+ }
105
+ /** Match only the command's executable, never a path or prompt in its arguments.
106
+ * Native process names come from ps comm, so unquoted spaces in parent paths
107
+ * are safe here. Interpreted entry points are handled separately below. */
108
+ function commandExecutable(command, name) {
109
+ const escaped = name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
110
+ const match = command
111
+ .trim()
112
+ .match(new RegExp(`^(?:"((?:.*?[/\\\\])?${escaped})"|'((?:.*?[/\\\\])?${escaped})'|((?:.*?[/\\\\])?${escaped}))(?=\\s|$)`, "i"));
113
+ if (!match)
114
+ return undefined;
115
+ const executable = match[1] ?? match[2] ?? match[3];
116
+ // Do not extend an unquoted executable into subsequent command arguments.
117
+ if (!match[1] && !match[2] && /\s[-/]|\s[^\s]*=/.test(executable))
118
+ return undefined;
119
+ return {
120
+ executable,
121
+ args: commandWords(command.trim().slice(match[0].length)),
122
+ };
123
+ }
124
+ // ps args is a display string, not lossless argv. Respect quotes when present;
125
+ // never search later words for an entry point if the first one is ambiguous.
126
+ function commandWords(command) {
127
+ const words = [];
128
+ let word = "";
129
+ let started = false;
130
+ let quote;
131
+ for (let i = 0; i < command.length; i++) {
132
+ const char = command[i];
133
+ if (char === quote) {
134
+ quote = undefined;
135
+ }
136
+ else if (char === "\\" && quote !== "'") {
137
+ if (i + 1 >= command.length)
138
+ return [];
139
+ word += command[++i];
140
+ started = true;
141
+ }
142
+ else if (!quote && (char === "'" || char === '"')) {
143
+ quote = char;
144
+ started = true;
145
+ }
146
+ else if (!quote && /\s/.test(char)) {
147
+ if (started)
148
+ words.push(word);
149
+ word = "";
150
+ started = false;
151
+ }
152
+ else {
153
+ word += char;
154
+ started = true;
155
+ }
156
+ }
157
+ // A display string with incomplete quoting is not enough identity evidence.
158
+ if (quote)
159
+ return [];
160
+ if (started)
161
+ words.push(word);
162
+ return words;
163
+ }
164
+ const NODE_VALUE_OPTIONS = new Set([
165
+ "-r",
166
+ "--require",
167
+ "--import",
168
+ "--loader",
169
+ "--experimental-loader",
170
+ "--conditions",
171
+ "-C",
172
+ ]);
173
+ export const CODEX_VALUE_OPTIONS = new Set([
174
+ "-c",
175
+ "--config",
176
+ "-m",
177
+ "--model",
178
+ "-p",
179
+ "--profile",
180
+ "-C",
181
+ "--cd",
182
+ "-s",
183
+ "--sandbox",
184
+ "-a",
185
+ "--ask-for-approval",
186
+ "--approval-mode",
187
+ "--enable",
188
+ "--disable",
189
+ "--add-dir",
190
+ "--local-provider",
191
+ "--remote",
192
+ "--remote-auth-token-env",
193
+ "-i",
194
+ "--image",
195
+ ]);
196
+ /** Only the first positional CLI argument is a subcommand. Option values,
197
+ * prompt text and arguments after `--` cannot turn a CLI into a server. */
198
+ function codexMode(args) {
199
+ for (let i = 0; i < args.length; i++) {
200
+ const arg = args[i];
201
+ if (arg === "--")
202
+ return undefined;
203
+ if (["-h", "--help", "-V", "--version"].includes(arg))
204
+ return "help";
205
+ if (CODEX_VALUE_OPTIONS.has(arg)) {
206
+ i++;
207
+ }
208
+ else if (!arg.startsWith("-")) {
209
+ return arg;
210
+ }
211
+ }
212
+ return undefined;
213
+ }
214
+ // A Codex binary is also a launcher for non-agent runtimes and management
215
+ // commands. Only session-bearing invocations belong in the CLI inventory.
216
+ // Keep mode interpretation separate from executable identity and file binding.
217
+ const CODEX_NON_SESSION_MODES = {
218
+ "app-server": "server",
219
+ "exec-server": "server",
220
+ "mcp-server": "server",
221
+ sandbox: "sandbox",
222
+ agents: "utility",
223
+ login: "utility",
224
+ logout: "utility",
225
+ mcp: "utility",
226
+ plugin: "utility",
227
+ "remote-control": "utility",
228
+ app: "utility",
229
+ completion: "utility",
230
+ update: "utility",
231
+ doctor: "utility",
232
+ debug: "utility",
233
+ apply: "utility",
234
+ a: "utility",
235
+ queue: "utility",
236
+ archive: "utility",
237
+ delete: "utility",
238
+ "migrate-rollouts": "utility",
239
+ "migrate-nfs-db": "utility",
240
+ unarchive: "utility",
241
+ cloud: "utility",
242
+ features: "utility",
243
+ help: "utility",
244
+ };
245
+ function codexProcessRole(args) {
246
+ const mode = codexMode(args);
247
+ return mode && Object.hasOwn(CODEX_NON_SESSION_MODES, mode)
248
+ ? CODEX_NON_SESSION_MODES[mode]
249
+ : "session";
250
+ }
251
+ const NODE_ENTRY_POINTS = {
252
+ "Claude Code": /[/\\]@anthropic-ai[/\\]claude-code[/\\]cli\.js$/i,
253
+ Codex: /[/\\]@openai[/\\]codex[/\\]bin[/\\]codex\.js$/i,
254
+ Gemini: /[/\\]@google[/\\]gemini-cli[/\\](?:dist[/\\])?(?:src[/\\])?index\.js$/i,
255
+ };
256
+ function nodeEntryPoint(command) {
257
+ const node = commandExecutable(command, "node") ?? commandExecutable(command, "nodejs");
258
+ if (!node)
259
+ return undefined;
260
+ for (let i = 0; i < node.args.length; i++) {
261
+ const arg = node.args[i];
262
+ // Eval/print input is code, not an agent entry script.
263
+ if (["-e", "--eval", "-p", "--print"].includes(arg) || /^(--eval|--print)=/.test(arg))
264
+ return undefined;
265
+ if (NODE_VALUE_OPTIONS.has(arg)) {
266
+ i++;
267
+ }
268
+ else if (arg === "--") {
269
+ return { executable: node.args[i + 1] ?? "", args: node.args.slice(i + 2) };
270
+ }
271
+ else if (!arg.startsWith("-")) {
272
+ return { executable: arg, args: node.args.slice(i + 1) };
273
+ }
274
+ }
275
+ return undefined;
276
+ }
277
+ /** Arguments belonging to a native Codex executable or supported Node entry point.
278
+ * Prompt text and other programs mentioning Codex do not establish executable identity. */
279
+ export function getCodexProcessArguments(command) {
280
+ const native = commandExecutable(command, "codex");
281
+ if (native)
282
+ return native.args;
283
+ const script = nodeEntryPoint(command);
284
+ if (script &&
285
+ (script.executable.split(/[/\\]/).pop()?.toLowerCase() === "codex" ||
286
+ NODE_ENTRY_POINTS.Codex.test(script.executable)))
287
+ return script.args;
288
+ return undefined;
77
289
  }
78
- /** Electron sub-process flags that indicate a desktop GUI helper, not a CLI agent. */
79
- const ELECTRON_TYPE_RE = /--type=(utility|renderer|gpu-process|zygote|broker)/;
80
- const CODEX_VSCODE_APP_SERVER_RE = /[/\\]codex\s+app-server(?:\s|$)/i;
81
- /** Codex `app-server` mode is an IDE/Desktop embedded RPC backend, not an interactive CLI session. */
82
- const CODEX_APP_SERVER_RE = /\bcodex\b[\s\S]*\bapp-server\b/i;
83
290
  /** Match a process against agent signatures using process name first, then cmd fallback. */
84
291
  export function detectAgentFromProcessSignature(proc, config) {
85
- // Skip Electron sub-processes (renderer, utility, gpu, zygote) to avoid
86
- // false-positive detection of desktop apps (e.g. Claude Desktop) as CLI agents.
87
- if (proc.cmd && ELECTRON_TYPE_RE.test(proc.cmd))
88
- return null;
89
- // Skip `codex app-server` backends spawned by Codex Desktop or the VS Code
90
- // Codex extension — these are RPC backends, not interactive CLI sessions.
91
- if (proc.cmd && CODEX_APP_SERVER_RE.test(proc.cmd))
92
- return null;
93
292
  const name = proc.name.toLowerCase();
94
- const command = (proc.cmd ?? "").toLowerCase();
95
- if (command.includes(".vscode/extensions") && CODEX_VSCODE_APP_SERVER_RE.test(proc.cmd ?? "")) {
96
- return null;
97
- }
293
+ const command = proc.cmd ?? "";
294
+ const script = name === "node" || name === "nodejs" ? nodeEntryPoint(command) : undefined;
98
295
  for (const [agentName, agentConfig] of Object.entries(config.agents)) {
99
296
  for (const pname of agentConfig.processNames) {
100
- if (name === pname)
101
- return agentName;
102
- if (command && matchesProcessCommand(command, pname))
103
- return agentName;
297
+ const native = name === pname.toLowerCase();
298
+ const entry = native || ((name === "node" || name === "nodejs") && !script)
299
+ ? commandExecutable(command, pname)
300
+ : script &&
301
+ (script.executable.split(/[/\\]/).pop()?.toLowerCase() === pname.toLowerCase() ||
302
+ NODE_ENTRY_POINTS[agentName]?.test(script.executable))
303
+ ? script
304
+ : undefined;
305
+ // An unavailable command retains the native-name fallback. A present
306
+ // but contradictory command is not evidence of an agent CLI.
307
+ if (!entry && !(native && !command))
308
+ continue;
309
+ if (entry &&
310
+ /[/\\](?:claude|codex)\.app[/\\]contents[/\\]macos[/\\](?:claude|codex)$/i.test(entry.executable))
311
+ return null;
312
+ if (entry?.args.some((arg) => /^--type=(utility|renderer|gpu-process|zygote|broker)$/.test(arg)))
313
+ return null;
314
+ // Linux Electron may advertise /proc/self/exe instead of its app path.
315
+ if (agentName === "Codex" && entry) {
316
+ if (codexProcessRole(entry.args) !== "session")
317
+ return null;
318
+ }
319
+ return agentName;
104
320
  }
105
321
  }
106
322
  return null;
@@ -30,5 +30,26 @@ export declare function updateRegistry(registry: Map<string, SessionRegistryReco
30
30
  * Returns the number of pruned entries.
31
31
  */
32
32
  export declare function pruneRegistry(registry: Map<string, SessionRegistryRecord>, maxAgeDays: number): number;
33
+ /**
34
+ * Repair activity times that exceed what the session files can justify (#113).
35
+ *
36
+ * A record's `lastActivityAt` can never legitimately be newer than the mtime of
37
+ * the jsonl it was derived from: the file is written when the event happens, so
38
+ * the timestamp inside it is always at or before the write. Anything later came
39
+ * from an inference that used to be persisted without an expiry, which left
40
+ * long-quiet sessions reporting "recent" indefinitely — for ten days in the
41
+ * case that surfaced this.
42
+ *
43
+ * Two things keep this from firing on legitimate drift. Times are compared
44
+ * against the mtime rounded *up*, because stored stamps are fractional
45
+ * (`mtimeMs / 1000`) and a floor comparison would clamp nearly every record by
46
+ * under a second on every load. And a tolerance is allowed on top, because a
47
+ * Codex time can come from the SQLite `updated_at` that `mergeCodexIndexedSessions`
48
+ * maxes with the rollout mtime, so it may legitimately lead the file by a little.
49
+ * The drift this repairs is hours to days, so the tolerance costs nothing.
50
+ *
51
+ * Records whose file is gone are left alone; there is nothing to check against.
52
+ */
53
+ export declare function clampRegistryActivityToObserved(registry: Map<string, SessionRegistryRecord>): Promise<number>;
33
54
  export declare function saveRegistryToFile(filePath: string, registry: Map<string, SessionRegistryRecord>): Promise<void>;
34
55
  export declare function loadRegistryFromFile(filePath: string, registry: Map<string, SessionRegistryRecord>): Promise<void>;
@@ -2,8 +2,19 @@
2
2
  * Session registry — tracks session lifecycle across PID/JSONL changes.
3
3
  * Maps sessionId → session history with PID changes and token accumulation.
4
4
  */
5
- import { mkdir, readFile, writeFile } from "node:fs/promises";
5
+ import { mkdir, readFile, stat, writeFile } from "node:fs/promises";
6
6
  import { dirname } from "node:path";
7
+ import { CODEX_INFERRED_BUSY_TTL_SEC } from "./cache.js";
8
+ /**
9
+ * The activity time safe to write to disk: the observed one when the caller
10
+ * tracks it at all, otherwise whatever it reported. Callers that split the two
11
+ * always set `observedActivityAt`, even when it is undefined, so its presence —
12
+ * not its value — is what says "this caller separates observation from
13
+ * inference" (#113).
14
+ */
15
+ function resolveObservedForPersist(agent) {
16
+ return "observedActivityAt" in agent ? agent.observedActivityAt : agent.lastActivityAt;
17
+ }
7
18
  export function updateRegistry(registry, agents) {
8
19
  for (const agent of agents) {
9
20
  if (!agent.sessionId)
@@ -33,8 +44,15 @@ export function updateRegistry(registry, agents) {
33
44
  existing.totalTokens.output = agent.tokenUsage.outputTokens ?? 0;
34
45
  existing.totalTokens.cache = agent.tokenUsage.cacheReadTokens ?? 0;
35
46
  }
36
- if (agent.lastActivityAt) {
37
- existing.lastActivityAt = Math.max(existing.lastActivityAt ?? 0, agent.lastActivityAt);
47
+ // #113: persist observed activity only. lastActivityAt may carry a
48
+ // fresh CPU/phase inference, and this Math.max is monotonic with no
49
+ // expiry — one inferred stamp on disk would outlive the session forever.
50
+ // The fallback keys on the field being absent, not on it being unset: a
51
+ // session with an inference but no observation reports the field as
52
+ // undefined, and `??` would have written the inference instead.
53
+ const observedAt = resolveObservedForPersist(agent);
54
+ if (observedAt) {
55
+ existing.lastActivityAt = Math.max(existing.lastActivityAt ?? 0, observedAt);
38
56
  }
39
57
  if (agent.model)
40
58
  existing.model = agent.model;
@@ -59,7 +77,7 @@ export function updateRegistry(registry, agents) {
59
77
  output: agent.tokenUsage?.outputTokens ?? 0,
60
78
  cache: agent.tokenUsage?.cacheReadTokens ?? 0,
61
79
  },
62
- lastActivityAt: agent.lastActivityAt,
80
+ lastActivityAt: resolveObservedForPersist(agent),
63
81
  model: agent.model,
64
82
  });
65
83
  }
@@ -80,6 +98,68 @@ export function pruneRegistry(registry, maxAgeDays) {
80
98
  }
81
99
  return pruned;
82
100
  }
101
+ /**
102
+ * Newest `jsonlPath` recorded for a session, ignoring path-less history entries.
103
+ */
104
+ function findLatestJsonlPath(record) {
105
+ const history = record.history;
106
+ if (!history)
107
+ return undefined;
108
+ for (let i = history.length - 1; i >= 0; i--) {
109
+ const jsonlPath = history[i]?.jsonlPath;
110
+ if (jsonlPath)
111
+ return jsonlPath;
112
+ }
113
+ return undefined;
114
+ }
115
+ /** Slack allowed before a record counts as drifted from its file. */
116
+ const CLAMP_TOLERANCE_SEC = CODEX_INFERRED_BUSY_TTL_SEC;
117
+ /**
118
+ * Repair activity times that exceed what the session files can justify (#113).
119
+ *
120
+ * A record's `lastActivityAt` can never legitimately be newer than the mtime of
121
+ * the jsonl it was derived from: the file is written when the event happens, so
122
+ * the timestamp inside it is always at or before the write. Anything later came
123
+ * from an inference that used to be persisted without an expiry, which left
124
+ * long-quiet sessions reporting "recent" indefinitely — for ten days in the
125
+ * case that surfaced this.
126
+ *
127
+ * Two things keep this from firing on legitimate drift. Times are compared
128
+ * against the mtime rounded *up*, because stored stamps are fractional
129
+ * (`mtimeMs / 1000`) and a floor comparison would clamp nearly every record by
130
+ * under a second on every load. And a tolerance is allowed on top, because a
131
+ * Codex time can come from the SQLite `updated_at` that `mergeCodexIndexedSessions`
132
+ * maxes with the rollout mtime, so it may legitimately lead the file by a little.
133
+ * The drift this repairs is hours to days, so the tolerance costs nothing.
134
+ *
135
+ * Records whose file is gone are left alone; there is nothing to check against.
136
+ */
137
+ export async function clampRegistryActivityToObserved(registry) {
138
+ let repaired = 0;
139
+ for (const record of registry.values()) {
140
+ if (record.lastActivityAt === undefined)
141
+ continue;
142
+ // Walk back to the newest entry that actually carries a path. Only the
143
+ // heavy-scan writer records one, so the final entry is routinely a
144
+ // path-less light-scan append — anchoring on `at(-1)` alone skipped
145
+ // exactly the long-lived records that drift furthest from their files.
146
+ const jsonlPath = findLatestJsonlPath(record);
147
+ if (!jsonlPath)
148
+ continue;
149
+ try {
150
+ const fileStat = await stat(jsonlPath);
151
+ const observedAt = Math.ceil(fileStat.mtimeMs / 1000);
152
+ if (record.lastActivityAt > observedAt + CLAMP_TOLERANCE_SEC) {
153
+ record.lastActivityAt = observedAt;
154
+ repaired++;
155
+ }
156
+ }
157
+ catch {
158
+ // file moved or removed — nothing to validate against
159
+ }
160
+ }
161
+ return repaired;
162
+ }
83
163
  export async function saveRegistryToFile(filePath, registry) {
84
164
  try {
85
165
  await mkdir(dirname(filePath), { recursive: true });
@@ -98,6 +178,7 @@ export async function loadRegistryFromFile(filePath, registry) {
98
178
  for (const [key, value] of Object.entries(data)) {
99
179
  registry.set(key, value);
100
180
  }
181
+ await clampRegistryActivityToObserved(registry);
101
182
  }
102
183
  }
103
184
  catch {
@@ -3,7 +3,42 @@
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
+ * When a Codex process looks busy right now, independent of what its session
8
+ * files say.
9
+ *
10
+ * Codex drops to ~0% CPU the instant a burst ends and its rollout file lags,
11
+ * so #090 introduced this inference to stop `last activity` from snapping back
12
+ * to the old mtime mid-turn. It is an inference, not an observation: it must be
13
+ * kept apart from observed activity and given a lifetime, which is what #113
14
+ * was about — the stamp used to be merged into `lastActivityAt` and persisted,
15
+ * so one CPU blip made a long-dead session look recent forever.
16
+ */
17
+ export declare function resolveCodexInferredBusyAt(cpuPercent: number, phase: SessionPhase | undefined, activeCpuThreshold: number, agentName: string | undefined, nowSec?: number): number | undefined;
18
+ /**
19
+ * Newest observed activity among the candidates.
20
+ *
21
+ * Every argument must be observation-only. Passing the merged `lastActivityAt`
22
+ * here is precisely how an inference got laundered into an observation: the
23
+ * merged value is stored in the enrichment cache for tiering, so reading that
24
+ * field back on the next scan re-promoted a CPU stamp to "observed", and from
25
+ * there the monotonic registry merge made it permanent.
26
+ */
27
+ export declare function mergeObservedActivityAt(...candidates: Array<number | undefined>): number | undefined;
28
+ /**
29
+ * Whether a busy inference may still stand in for observed activity.
30
+ *
31
+ * A process doing real work keeps re-stamping well inside this window, so a
32
+ * stamp older than the TTL means it has been quiet since — and the reported
33
+ * time must fall back to what the session files actually show.
34
+ */
35
+ export declare function isInferredBusyFresh(inferredBusyAt: number | undefined, nowSec?: number, ttlSec?: number): boolean;
36
+ /**
37
+ * Activity time to report: observed activity, or a still-fresh inference when
38
+ * that is more recent. An expired inference is dropped so the reported time
39
+ * falls back to what the session files actually show.
40
+ */
41
+ export declare function resolveEffectiveActivityAt(observedActivityAt: number | undefined, inferredBusyAt: number | undefined, nowSec?: number, ttlSec?: number): number | undefined;
7
42
  /** Determine agent activity status */
8
43
  export declare function determineStatus(cpuPercent: number, elapsedSec: number | undefined, sessionMatched: boolean, phase: SessionPhase | undefined, config: MarmonitorConfig, agentName?: string): SessionStatus;
9
44
  export declare function applyStatusHysteresis(nextStatus: SessionStatus, previousStatus: SessionStatus | undefined, elapsedSec: number | undefined, phase: SessionPhase | undefined, agentName: string | undefined): SessionStatus;
@@ -3,17 +3,61 @@
3
3
  */
4
4
  import { detectApprovalPromptPhase } from "../output/utils.js";
5
5
  import { captureTmuxPaneOutput, resolveTmuxJumpTarget } from "../tmux/index.js";
6
- import { RECENT_ACTIVITY_ACTIVE_SEC, STATUS_HYSTERESIS_SEC, stdoutHeuristicCache, } from "./cache.js";
7
- export function refreshLastActivityAt(lastActivityAt, cpuPercent, phase, activeCpuThreshold, agentName, nowSec = Math.floor(Date.now() / 1000)) {
6
+ import { CODEX_INFERRED_BUSY_TTL_SEC, RECENT_ACTIVITY_ACTIVE_SEC, STATUS_HYSTERESIS_SEC, stdoutHeuristicCache, } from "./cache.js";
7
+ /**
8
+ * When a Codex process looks busy right now, independent of what its session
9
+ * files say.
10
+ *
11
+ * Codex drops to ~0% CPU the instant a burst ends and its rollout file lags,
12
+ * so #090 introduced this inference to stop `last activity` from snapping back
13
+ * to the old mtime mid-turn. It is an inference, not an observation: it must be
14
+ * kept apart from observed activity and given a lifetime, which is what #113
15
+ * was about — the stamp used to be merged into `lastActivityAt` and persisted,
16
+ * so one CPU blip made a long-dead session look recent forever.
17
+ */
18
+ export function resolveCodexInferredBusyAt(cpuPercent, phase, activeCpuThreshold, agentName, nowSec = Math.floor(Date.now() / 1000)) {
8
19
  if (agentName !== "Codex")
9
- return lastActivityAt;
20
+ return undefined;
10
21
  if (cpuPercent > activeCpuThreshold ||
11
22
  phase === "permission" ||
12
23
  phase === "thinking" ||
13
24
  phase === "tool") {
14
- return Math.max(lastActivityAt ?? 0, nowSec);
25
+ return nowSec;
15
26
  }
16
- return lastActivityAt;
27
+ return undefined;
28
+ }
29
+ /**
30
+ * Newest observed activity among the candidates.
31
+ *
32
+ * Every argument must be observation-only. Passing the merged `lastActivityAt`
33
+ * here is precisely how an inference got laundered into an observation: the
34
+ * merged value is stored in the enrichment cache for tiering, so reading that
35
+ * field back on the next scan re-promoted a CPU stamp to "observed", and from
36
+ * there the monotonic registry merge made it permanent.
37
+ */
38
+ export function mergeObservedActivityAt(...candidates) {
39
+ return Math.max(0, ...candidates.map((candidate) => candidate ?? 0)) || undefined;
40
+ }
41
+ /**
42
+ * Whether a busy inference may still stand in for observed activity.
43
+ *
44
+ * A process doing real work keeps re-stamping well inside this window, so a
45
+ * stamp older than the TTL means it has been quiet since — and the reported
46
+ * time must fall back to what the session files actually show.
47
+ */
48
+ export function isInferredBusyFresh(inferredBusyAt, nowSec = Math.floor(Date.now() / 1000), ttlSec = CODEX_INFERRED_BUSY_TTL_SEC) {
49
+ return inferredBusyAt !== undefined && nowSec - inferredBusyAt <= ttlSec;
50
+ }
51
+ /**
52
+ * Activity time to report: observed activity, or a still-fresh inference when
53
+ * that is more recent. An expired inference is dropped so the reported time
54
+ * falls back to what the session files actually show.
55
+ */
56
+ export function resolveEffectiveActivityAt(observedActivityAt, inferredBusyAt, nowSec = Math.floor(Date.now() / 1000), ttlSec = CODEX_INFERRED_BUSY_TTL_SEC) {
57
+ const usableInference = isInferredBusyFresh(inferredBusyAt, nowSec, ttlSec)
58
+ ? inferredBusyAt
59
+ : undefined;
60
+ return Math.max(observedActivityAt ?? 0, usableInference ?? 0) || undefined;
17
61
  }
18
62
  /** Determine agent activity status */
19
63
  export function determineStatus(cpuPercent, elapsedSec, sessionMatched, phase, config, agentName) {
@@ -0,0 +1,9 @@
1
+ import type { AgentSession } from "./types.js";
2
+ /** A CLI's existence is independent of whether its metadata has been bound.
3
+ * Unmatched CLIs still count as running; historical dead sessions never do. */
4
+ export declare function partitionSessions(agents: AgentSession[]): {
5
+ running: AgentSession[];
6
+ matched: AgentSession[];
7
+ unmatched: AgentSession[];
8
+ dead: AgentSession[];
9
+ };
@@ -0,0 +1,11 @@
1
+ /** A CLI's existence is independent of whether its metadata has been bound.
2
+ * Unmatched CLIs still count as running; historical dead sessions never do. */
3
+ export function partitionSessions(agents) {
4
+ const running = agents.filter((agent) => agent.status !== "Dead");
5
+ return {
6
+ running,
7
+ matched: running.filter((agent) => agent.status !== "Unmatched"),
8
+ unmatched: running.filter((agent) => agent.status === "Unmatched"),
9
+ dead: agents.filter((agent) => agent.status === "Dead"),
10
+ };
11
+ }
@@ -6,17 +6,18 @@ export interface TmuxPane {
6
6
  paneIndex: number;
7
7
  panePid: number;
8
8
  cwd: string;
9
+ paneId?: string;
9
10
  }
10
11
  export interface TmuxJumpTarget {
11
12
  pane: TmuxPane;
12
- match: "pid-tree" | "cwd";
13
+ match: "pid-tree" | "tty" | "cwd";
13
14
  }
14
15
  export interface TmuxJumpResult {
15
16
  found: boolean;
16
17
  executed: boolean;
17
18
  insideTmux: boolean;
18
19
  pid: number;
19
- match?: "pid-tree" | "cwd";
20
+ match?: "pid-tree" | "tty" | "cwd";
20
21
  target?: string;
21
22
  sessionName?: string;
22
23
  cwd?: string;
@@ -25,7 +26,7 @@ export interface TmuxJumpResult {
25
26
  export declare function parseTmuxPanes(raw: string): TmuxPane[];
26
27
  export declare function parseProcessTree(raw: string): Map<number, number[]>;
27
28
  export declare function isPidInTree(rootPid: number, targetPid: number, childMap: Map<number, number[]>): boolean;
28
- export declare function selectTmuxPaneForAgent(agent: Pick<AgentSession, "pid" | "cwd">, panes: TmuxPane[], childMap: Map<number, number[]>): TmuxJumpTarget | undefined;
29
+ export declare function selectTmuxPaneForAgent(agent: Pick<AgentSession, "pid" | "cwd">, panes: TmuxPane[], childMap: Map<number, number[]>, ttys?: ReadonlyMap<number, string>, allowCwdFallback?: boolean): TmuxJumpTarget | undefined;
29
30
  export declare function listTmuxPanes(): Promise<TmuxPane[]>;
30
31
  export declare function getProcessTree(): Promise<Map<number, number[]>>;
31
32
  /** Get the PID of the currently active tmux pane */
@@ -55,6 +56,9 @@ export declare function getProcessTtys(pids: number[]): Promise<Map<number, stri
55
56
  * caller already resolved the active pane PID for cache-key purposes). */
56
57
  export declare function findActiveAgentPid(agentPids: number[], panePid?: number): Promise<number | undefined>;
57
58
  export declare function resolveTmuxJumpTarget(agent: Pick<AgentSession, "pid" | "cwd">): Promise<TmuxJumpTarget | undefined>;
59
+ /** Resolve labels, jumps and stdout capture using process/TTY ownership.
60
+ * Cwd matching is available only to callers that explicitly request an estimate. */
61
+ export declare function resolveAgentTmuxTargets(agents: Array<Pick<AgentSession, "pid" | "cwd">>, allowCwdFallback?: boolean): Promise<Map<number, TmuxJumpTarget>>;
58
62
  export declare function captureTmuxPaneOutput(target: TmuxJumpTarget, lines?: number): Promise<string | undefined>;
59
63
  export declare function jumpToTmuxPane(target: TmuxJumpTarget): Promise<boolean>;
60
64
  export declare function jumpToAgent(agent: Pick<AgentSession, "pid" | "cwd">): Promise<TmuxJumpResult>;