marmonitor 0.2.4 → 0.2.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/README.ko.md +52 -1
  2. package/README.md +76 -1
  3. package/dist/alerts/desktop.d.ts +3 -0
  4. package/dist/alerts/desktop.js +23 -0
  5. package/dist/alerts/index.d.ts +7 -0
  6. package/dist/alerts/index.js +5 -0
  7. package/dist/alerts/log.d.ts +3 -0
  8. package/dist/alerts/log.js +14 -0
  9. package/dist/alerts/snapshot.d.ts +4 -0
  10. package/dist/alerts/snapshot.js +25 -0
  11. package/dist/alerts/store.d.ts +23 -0
  12. package/dist/alerts/store.js +61 -0
  13. package/dist/alerts/token.d.ts +18 -0
  14. package/dist/alerts/token.js +73 -0
  15. package/dist/alerts/types.d.ts +23 -0
  16. package/dist/alerts/types.js +2 -0
  17. package/dist/cli.js +341 -23
  18. package/dist/clipboard.d.ts +12 -0
  19. package/dist/clipboard.js +56 -0
  20. package/dist/config/index.d.ts +14 -0
  21. package/dist/config/index.js +8 -0
  22. package/dist/guard/index.js +51 -5
  23. package/dist/output/badge-themes.d.ts +3 -0
  24. package/dist/output/badge-themes.js +12 -0
  25. package/dist/output/index.d.ts +1 -1
  26. package/dist/output/index.js +2 -2
  27. package/dist/output/utils.d.ts +2 -1
  28. package/dist/output/utils.js +9 -4
  29. package/dist/scanner/claude.js +212 -90
  30. package/dist/scanner/codex.d.ts +2 -0
  31. package/dist/scanner/codex.js +40 -9
  32. package/dist/scanner/daemon-entry.js +2 -0
  33. package/dist/scanner/daemon-loop.d.ts +4 -0
  34. package/dist/scanner/daemon-loop.js +25 -1
  35. package/dist/scanner/gemini.d.ts +10 -0
  36. package/dist/scanner/gemini.js +82 -0
  37. package/dist/scanner/process.js +11 -1
  38. package/dist/tmux/index.d.ts +26 -0
  39. package/dist/tmux/index.js +102 -0
  40. package/dist/turns.d.ts +68 -0
  41. package/dist/turns.js +430 -0
  42. package/dist/types.d.ts +2 -0
  43. package/package.json +3 -1
@@ -10,6 +10,33 @@ 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
12
  const CODEX_SQLITE_RECENT_DAYS = 7;
13
+ function mergeCodexIndexedSessions(baseSessions, incomingSessions) {
14
+ const merged = new Map();
15
+ for (const session of baseSessions) {
16
+ merged.set(session.id, session);
17
+ }
18
+ for (const session of incomingSessions) {
19
+ const existing = merged.get(session.id);
20
+ if (!existing) {
21
+ merged.set(session.id, session);
22
+ continue;
23
+ }
24
+ merged.set(session.id, {
25
+ ...existing,
26
+ ...session,
27
+ filePath: session.filePath || existing.filePath,
28
+ cwd: session.cwd || existing.cwd,
29
+ timestamp: Math.min(existing.timestamp || session.timestamp, session.timestamp || existing.timestamp),
30
+ lastActivityAt: Math.max(existing.lastActivityAt ?? 0, session.lastActivityAt ?? 0) || undefined,
31
+ totalTokenUsage: session.totalTokenUsage?.total_tokens !== undefined
32
+ ? session.totalTokenUsage
33
+ : existing.totalTokenUsage,
34
+ model: session.model ?? existing.model,
35
+ });
36
+ }
37
+ return [...merged.values()].sort((a, b) => (b.lastActivityAt ?? b.timestamp) - (a.lastActivityAt ?? a.timestamp));
38
+ }
39
+ export { mergeCodexIndexedSessions };
13
40
  export function getCodexSessionRoots(config) {
14
41
  return config
15
42
  ? resolveRuntimeDataPaths(config).codexSessions
@@ -113,16 +140,17 @@ export async function indexCodexSessions(config, options) {
113
140
  return codexIndexCache.sessions;
114
141
  }
115
142
  const hasExplicitSessionRoots = Boolean(config?.paths.codexSessions?.length);
143
+ const sqliteSessions = [];
116
144
  // Primary: SQLite threads table
117
145
  const dbPath = hasExplicitSessionRoots ? undefined : findCodexStateDb();
118
146
  if (dbPath) {
119
- const sqliteSessions = await indexCodexSessionsFromSqlite(dbPath, {
147
+ const indexed = await indexCodexSessionsFromSqlite(dbPath, {
120
148
  recentUpdatedAfter: Math.floor(Date.now() / 1000) - CODEX_SQLITE_RECENT_DAYS * 86400,
121
149
  includeCwds: activeCwds,
122
150
  });
123
- if (sqliteSessions.length > 0) {
151
+ if (indexed.length > 0) {
124
152
  // Register sessions for phase detection and cwd lookup
125
- for (const s of sqliteSessions) {
153
+ for (const s of indexed) {
126
154
  codexSessionFileCache.set(s.filePath, { ...s, mtimeMs: undefined, size: undefined });
127
155
  upsertSessionRegistryEntry(codexSessionRegistry, {
128
156
  filePath: s.filePath,
@@ -132,12 +160,10 @@ export async function indexCodexSessions(config, options) {
132
160
  startedAt: s.timestamp,
133
161
  model: s.model,
134
162
  source: "codex",
163
+ binding: "direct",
135
164
  });
136
165
  }
137
- if (!hasTargetedFilter) {
138
- setCodexIndexCache({ builtAt: Date.now(), sessions: sqliteSessions });
139
- }
140
- return sqliteSessions;
166
+ sqliteSessions.push(...indexed);
141
167
  }
142
168
  }
143
169
  // Fallback: JSONL directory scan (last 7 days)
@@ -199,6 +225,9 @@ export async function indexCodexSessions(config, options) {
199
225
  }
200
226
  }
201
227
  if (meta.id && meta.cwd && meta.timestamp) {
228
+ if (hasTargetedFilter && !activeCwds.includes(meta.cwd)) {
229
+ continue;
230
+ }
202
231
  const parsed = {
203
232
  filePath,
204
233
  id: meta.id,
@@ -219,6 +248,7 @@ export async function indexCodexSessions(config, options) {
219
248
  startedAt: meta.timestamp,
220
249
  model: meta.model,
221
250
  source: "codex",
251
+ binding: "direct",
222
252
  });
223
253
  metas.push(parsed);
224
254
  }
@@ -233,11 +263,12 @@ export async function indexCodexSessions(config, options) {
233
263
  catch {
234
264
  // sessions dir error
235
265
  }
266
+ const sessions = mergeCodexIndexedSessions(sqliteSessions, metas);
236
267
  setCodexIndexCache({
237
268
  builtAt: Date.now(),
238
- sessions: metas,
269
+ sessions,
239
270
  });
240
- return metas;
271
+ return sessions;
241
272
  }
242
273
  /** Match a Codex process to a session by cwd + closest timestamp */
243
274
  export function matchCodexSession(processCwd, processStartTime, sessions) {
@@ -17,6 +17,8 @@ async function main() {
17
17
  intervalMs: intervalSec * 1000,
18
18
  detailIntervalMs: 30_000,
19
19
  snapshotPath: join(DAEMON_DIR, "daemon-snapshot.json"),
20
+ alertsSnapshotPath: join(DAEMON_DIR, "alerts-snapshot.json"),
21
+ alertsLogPath: join(CONFIG_DIR, "alerts.log"),
20
22
  pidPath: join(DAEMON_DIR, "daemon.pid"),
21
23
  registryPath: join(CONFIG_DIR, "session-registry.json"),
22
24
  codexBindingRegistryPath: join(CONFIG_DIR, "codex-binding-registry.json"),
@@ -7,10 +7,14 @@ export interface DaemonOptions {
7
7
  intervalMs: number;
8
8
  detailIntervalMs: number;
9
9
  snapshotPath: string;
10
+ alertsSnapshotPath: string;
11
+ alertsLogPath: string;
10
12
  pidPath: string;
11
13
  registryPath: string;
12
14
  codexBindingRegistryPath: string;
13
15
  activityLogDir: string;
14
16
  activityRetentionDays: number;
15
17
  }
18
+ /** Token/context threshold alerts fire only when both master and category toggles are on. */
19
+ export declare function shouldRunTokenAlerts(config: MarmonitorConfig): boolean;
16
20
  export declare function runDaemonLoop(config: MarmonitorConfig, options: DaemonOptions): Promise<void>;
@@ -3,6 +3,7 @@
3
3
  * Reuses watch/dock pattern: light scan every intervalMs, full every detailIntervalMs.
4
4
  */
5
5
  import { open, stat, unlink } from "node:fs/promises";
6
+ import { AlertStore, appendAlertLog, checkTokenAlert, sendDesktopNotification, writeAlertsSnapshot, } from "../alerts/index.js";
6
7
  import { appendActivityEntries, cleanupOldActivityLogs, extractClaudeToolUses, extractCodexToolUses, formatDateKey, } from "./activity-log.js";
7
8
  import { loadCodexBindingRegistryFromFile, pruneCodexBindingRegistry, saveCodexBindingRegistryToFile, } from "./codex-binding-registry.js";
8
9
  import { writeDaemonPid, writeDaemonSnapshot } from "./daemon-utils.js";
@@ -12,11 +13,16 @@ import { loadRegistryFromFile, pruneRegistry, saveRegistryToFile, updateRegistry
12
13
  function sleep(ms) {
13
14
  return new Promise((resolve) => setTimeout(resolve, ms));
14
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
+ }
15
20
  export async function runDaemonLoop(config, options) {
16
- const { intervalMs, detailIntervalMs, snapshotPath, pidPath, registryPath, codexBindingRegistryPath, activityLogDir, activityRetentionDays, } = options;
21
+ const { intervalMs, detailIntervalMs, snapshotPath, alertsSnapshotPath, alertsLogPath, pidPath, registryPath, codexBindingRegistryPath, activityLogDir, activityRetentionDays, } = options;
17
22
  // Activity log: per-session JSONL cursor offsets (in-memory only)
18
23
  const activityCursors = new Map();
19
24
  let lastActivityCleanupAt = 0;
25
+ const alertStore = new AlertStore();
20
26
  await writeDaemonPid(pidPath, process.pid);
21
27
  const registry = new Map();
22
28
  const codexBindingRegistry = new Map();
@@ -67,6 +73,24 @@ export async function runDaemonLoop(config, options) {
67
73
  updateRegistry(registry, agents);
68
74
  // Write snapshot for statusline consumers
69
75
  await writeDaemonSnapshot(snapshotPath, agents);
76
+ // Check token thresholds and fire alerts (alerts.enabled + alerts.tokens 확인)
77
+ if (shouldRunTokenAlerts(config)) {
78
+ const thresholds = {
79
+ warnAt: config.alerts.contextWarnThreshold,
80
+ critAt: config.alerts.contextCritThreshold,
81
+ };
82
+ for (const agent of agents) {
83
+ const alert = checkTokenAlert(alertStore, agent, thresholds);
84
+ if (alert) {
85
+ if (config.alerts.log)
86
+ await appendAlertLog(alertsLogPath, alert);
87
+ if (config.alerts.desktop && alert.severity === "critical") {
88
+ void sendDesktopNotification(alert); // fire-and-forget
89
+ }
90
+ }
91
+ }
92
+ }
93
+ await writeAlertsSnapshot(alertsSnapshotPath, alertStore.active());
70
94
  // Save registry periodically (on heavy scan) + prune old entries
71
95
  if (needsHeavy) {
72
96
  pruneRegistry(registry, 30);
@@ -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
  }>;
@@ -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)
@@ -66,7 +66,7 @@ export function detectRuntimeSource(agentName, cmd) {
66
66
  const normalized = (cmd ?? "").toLowerCase();
67
67
  if (!normalized)
68
68
  return "unknown";
69
- if (normalized.includes(".vscode/extensions") || normalized.includes("app-server")) {
69
+ if (normalized.includes(".vscode/extensions")) {
70
70
  return "vscode";
71
71
  }
72
72
  return "cli";
@@ -77,14 +77,24 @@ export function matchesProcessCommand(command, processName) {
77
77
  }
78
78
  /** Electron sub-process flags that indicate a desktop GUI helper, not a CLI agent. */
79
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;
80
83
  /** Match a process against agent signatures using process name first, then cmd fallback. */
81
84
  export function detectAgentFromProcessSignature(proc, config) {
82
85
  // Skip Electron sub-processes (renderer, utility, gpu, zygote) to avoid
83
86
  // false-positive detection of desktop apps (e.g. Claude Desktop) as CLI agents.
84
87
  if (proc.cmd && ELECTRON_TYPE_RE.test(proc.cmd))
85
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;
86
93
  const name = proc.name.toLowerCase();
87
94
  const command = (proc.cmd ?? "").toLowerCase();
95
+ if (command.includes(".vscode/extensions") && CODEX_VSCODE_APP_SERVER_RE.test(proc.cmd ?? "")) {
96
+ return null;
97
+ }
88
98
  for (const [agentName, agentConfig] of Object.entries(config.agents)) {
89
99
  for (const pname of agentConfig.processNames) {
90
100
  if (name === pname)
@@ -28,6 +28,32 @@ export declare function isPidInTree(rootPid: number, targetPid: number, childMap
28
28
  export declare function selectTmuxPaneForAgent(agent: Pick<AgentSession, "pid" | "cwd">, panes: TmuxPane[], childMap: Map<number, number[]>): TmuxJumpTarget | undefined;
29
29
  export declare function listTmuxPanes(): Promise<TmuxPane[]>;
30
30
  export declare function getProcessTree(): Promise<Map<number, number[]>>;
31
+ /** Get the PID of the currently active tmux pane */
32
+ export declare function getActiveTmuxPanePid(): Promise<number | undefined>;
33
+ /** Get the controlling tty of a PID via lsof (`-d 0` reads stdin fd → tty).
34
+ * Uses lsof instead of `ps -o tty=` because the latter returns EPERM on
35
+ * macOS for processes the caller does not own in the same session. */
36
+ export declare function getProcessTty(pid: number): Promise<string | undefined>;
37
+ /** Batched variant of `getProcessTty` — one `lsof -p pid1,pid2,...` call
38
+ * returns the controlling tty for every PID at once. Returns a Map keyed
39
+ * by PID; PIDs with no tty (or lsof errors) are simply absent. lsof's `-F`
40
+ * output is one field per line, with `p<pid>` markers preceding each
41
+ * process's records, so we walk the lines with a running `currentPid` and
42
+ * pair the next `n<path>` we see with it. */
43
+ export declare function getProcessTtys(pids: number[]): Promise<Map<number, string>>;
44
+ /** Find the agent PID that runs inside the currently active tmux pane.
45
+ *
46
+ * Two-tier match:
47
+ * 1. pid-tree — `panePid` is the pane's shell PID; walk its descendants
48
+ * and find one matching `agentPids`. Works in most cases.
49
+ * 2. tty fallback — when the pid-tree walk misses (e.g. macOS denies
50
+ * ps walks for some processes), compare the pane's controlling tty
51
+ * with each agent process's controlling tty. The agent and the
52
+ * pane's shell share a tty when they run in the same pane.
53
+ *
54
+ * When `panePid` is provided, skips the tmux query (useful when the
55
+ * caller already resolved the active pane PID for cache-key purposes). */
56
+ export declare function findActiveAgentPid(agentPids: number[], panePid?: number): Promise<number | undefined>;
31
57
  export declare function resolveTmuxJumpTarget(agent: Pick<AgentSession, "pid" | "cwd">): Promise<TmuxJumpTarget | undefined>;
32
58
  export declare function captureTmuxPaneOutput(target: TmuxJumpTarget, lines?: number): Promise<string | undefined>;
33
59
  export declare function jumpToTmuxPane(target: TmuxJumpTarget): Promise<boolean>;
@@ -98,6 +98,108 @@ export async function getProcessTree() {
98
98
  return new Map();
99
99
  }
100
100
  }
101
+ /** Get the PID of the currently active tmux pane */
102
+ export async function getActiveTmuxPanePid() {
103
+ try {
104
+ const { stdout } = await execFileAsync("tmux", ["display-message", "-p", "#{pane_pid}"]);
105
+ const pid = Number.parseInt(stdout.trim(), 10);
106
+ return Number.isFinite(pid) ? pid : undefined;
107
+ }
108
+ catch {
109
+ return undefined;
110
+ }
111
+ }
112
+ /** Get the controlling tty of a PID via lsof (`-d 0` reads stdin fd → tty).
113
+ * Uses lsof instead of `ps -o tty=` because the latter returns EPERM on
114
+ * macOS for processes the caller does not own in the same session. */
115
+ export async function getProcessTty(pid) {
116
+ try {
117
+ const { stdout } = await execFileAsync("lsof", ["-a", "-p", String(pid), "-d", "0", "-Fn"], {
118
+ timeout: 2000,
119
+ });
120
+ const line = stdout
121
+ .split("\n")
122
+ .map((l) => l.trim())
123
+ .find((l) => l.startsWith("n/"));
124
+ return line ? line.slice(1) : undefined;
125
+ }
126
+ catch {
127
+ return undefined;
128
+ }
129
+ }
130
+ /** Batched variant of `getProcessTty` — one `lsof -p pid1,pid2,...` call
131
+ * returns the controlling tty for every PID at once. Returns a Map keyed
132
+ * by PID; PIDs with no tty (or lsof errors) are simply absent. lsof's `-F`
133
+ * output is one field per line, with `p<pid>` markers preceding each
134
+ * process's records, so we walk the lines with a running `currentPid` and
135
+ * pair the next `n<path>` we see with it. */
136
+ export async function getProcessTtys(pids) {
137
+ const result = new Map();
138
+ if (pids.length === 0)
139
+ return result;
140
+ try {
141
+ const { stdout } = await execFileAsync("lsof", ["-a", "-p", pids.join(","), "-d", "0", "-Fn"], {
142
+ timeout: 2000,
143
+ });
144
+ let currentPid;
145
+ for (const raw of stdout.split("\n")) {
146
+ const line = raw.trim();
147
+ if (line.startsWith("p")) {
148
+ const parsed = Number.parseInt(line.slice(1), 10);
149
+ currentPid = Number.isFinite(parsed) ? parsed : undefined;
150
+ }
151
+ else if (currentPid !== undefined && line.startsWith("n/")) {
152
+ // Keep the first `n` field per pid (stdin's tty); ignore any extras.
153
+ if (!result.has(currentPid))
154
+ result.set(currentPid, line.slice(1));
155
+ }
156
+ }
157
+ }
158
+ catch {
159
+ // partial output may still be useful if returned; otherwise empty map.
160
+ }
161
+ return result;
162
+ }
163
+ /** Find the agent PID that runs inside the currently active tmux pane.
164
+ *
165
+ * Two-tier match:
166
+ * 1. pid-tree — `panePid` is the pane's shell PID; walk its descendants
167
+ * and find one matching `agentPids`. Works in most cases.
168
+ * 2. tty fallback — when the pid-tree walk misses (e.g. macOS denies
169
+ * ps walks for some processes), compare the pane's controlling tty
170
+ * with each agent process's controlling tty. The agent and the
171
+ * pane's shell share a tty when they run in the same pane.
172
+ *
173
+ * When `panePid` is provided, skips the tmux query (useful when the
174
+ * caller already resolved the active pane PID for cache-key purposes). */
175
+ export async function findActiveAgentPid(agentPids, panePid) {
176
+ if (agentPids.length === 0)
177
+ return undefined;
178
+ try {
179
+ const activePanePid = panePid ?? (await getActiveTmuxPanePid());
180
+ if (!activePanePid)
181
+ return undefined;
182
+ // Tier 1: pid-tree
183
+ const childMap = await getProcessTree();
184
+ const treeMatch = agentPids.find((pid) => isPidInTree(activePanePid, pid, childMap));
185
+ if (treeMatch !== undefined)
186
+ return treeMatch;
187
+ // Tier 2: tty fallback — one batched lsof for the pane shell + all
188
+ // agent PIDs, instead of N+1 separate calls.
189
+ const ttys = await getProcessTtys([activePanePid, ...agentPids]);
190
+ const paneTty = ttys.get(activePanePid);
191
+ if (!paneTty)
192
+ return undefined;
193
+ for (const agentPid of agentPids) {
194
+ if (ttys.get(agentPid) === paneTty)
195
+ return agentPid;
196
+ }
197
+ return undefined;
198
+ }
199
+ catch {
200
+ return undefined;
201
+ }
202
+ }
101
203
  export async function resolveTmuxJumpTarget(agent) {
102
204
  try {
103
205
  const [panes, childMap] = await Promise.all([listTmuxPanes(), getProcessTree()]);
@@ -0,0 +1,68 @@
1
+ /**
2
+ * AI session turn parsing.
3
+ *
4
+ * Reads agent-local turn data (Claude jsonl for v1) and groups it into
5
+ * user / assistant turns. A single assistant turn bundles all `text` /
6
+ * `tool_use` / `tool_result` lines that follow a user prompt until the
7
+ * next user prompt or `stop_reason === "end_turn"`.
8
+ *
9
+ * Two extraction modes are exposed via `TurnTextMode`:
10
+ * - "text" (default): assistant text blocks only. What the user saw
11
+ * Claude "say" — ideal for sharing to Slack / issue / note.
12
+ * - "bundle": text + tool_use input + tool_result content (thinking
13
+ * excluded). Closer to the full Claude UI rendering — for handing
14
+ * context to another AI or debug PRs.
15
+ */
16
+ export type TurnRole = "user" | "assistant";
17
+ export type TurnTextMode = "text" | "bundle";
18
+ export interface SessionTurn {
19
+ role: TurnRole;
20
+ startedAt?: number;
21
+ completedAt?: number;
22
+ /** Assistant text-only extraction. user turns reuse this field. */
23
+ text: string;
24
+ /** Full bundle (text + tool_use + tool_result) — assistant turns only. */
25
+ bundle?: string;
26
+ }
27
+ /**
28
+ * Parse a Claude session JSONL into ordered user/assistant turns.
29
+ * Lines without role information (file-history-snapshot, last-prompt, etc.)
30
+ * are ignored.
31
+ */
32
+ export declare function parseClaudeConversationTurns(raw: string): SessionTurn[];
33
+ /**
34
+ * Parse a Codex rollout JSONL into ordered user/assistant turns.
35
+ *
36
+ * Rollout structure:
37
+ * - `type: "session_meta"` / `"event_msg"` / `"turn_context"` — meta, ignored
38
+ * - `type: "response_item"` payload:
39
+ * - `type: "message"` + `role: "user"|"assistant"|"developer"`
40
+ * — content is an array of `{type: "input_text"|"output_text", text}`.
41
+ * `developer` is system-side, skipped.
42
+ * - `type: "reasoning"` — Codex's thinking, excluded (matches option B).
43
+ * - `type: "function_call"` — tool invocation (bundle-only).
44
+ * - `type: "function_call_output"` — tool result (bundle-only).
45
+ * - `type: "web_search_call"` — surfaced as a marker in bundle.
46
+ *
47
+ * Turn boundary: a new `user` message flushes the in-progress assistant.
48
+ */
49
+ export declare function parseCodexConversationTurns(raw: string): SessionTurn[];
50
+ /**
51
+ * Parse a Gemini chats JSON (`messages: [{type, content, timestamp, ...}]`)
52
+ * into ordered user/assistant turns.
53
+ *
54
+ * Recognised message types:
55
+ * - `"user"` — user prompt → user turn
56
+ * - `"gemini"` — assistant response → flushed as assistant turn
57
+ * - everything else (`"info"`, `"error"`, etc.) — ignored as scaffolding
58
+ *
59
+ * NOTE: live verification is currently unavailable (the user does not run the
60
+ * Gemini CLI). Behaviour is covered by unit tests with fixture data and is
61
+ * expected to be conservative — unknown shapes degrade to no-turn rather than
62
+ * raising.
63
+ */
64
+ export declare function parseGeminiConversationTurns(raw: string): SessionTurn[];
65
+ /** Pick the latest turn for a given role. */
66
+ export declare function selectLatestTurn(turns: SessionTurn[], role?: TurnRole): SessionTurn | undefined;
67
+ /** Extract the copyable text from a turn for the chosen mode. */
68
+ export declare function turnTextForMode(turn: SessionTurn, mode?: TurnTextMode): string;