marmonitor 0.2.5 → 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.
@@ -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)
@@ -30,9 +30,29 @@ export declare function listTmuxPanes(): Promise<TmuxPane[]>;
30
30
  export declare function getProcessTree(): Promise<Map<number, number[]>>;
31
31
  /** Get the PID of the currently active tmux pane */
32
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>>;
33
44
  /** Find the agent PID that runs inside the currently active tmux pane.
34
- * When panePid is provided, skips the tmux query (useful when the caller
35
- * already resolved the active pane PID for cache-key purposes). */
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). */
36
56
  export declare function findActiveAgentPid(agentPids: number[], panePid?: number): Promise<number | undefined>;
37
57
  export declare function resolveTmuxJumpTarget(agent: Pick<AgentSession, "pid" | "cwd">): Promise<TmuxJumpTarget | undefined>;
38
58
  export declare function captureTmuxPaneOutput(target: TmuxJumpTarget, lines?: number): Promise<string | undefined>;
@@ -109,9 +109,69 @@ export async function getActiveTmuxPanePid() {
109
109
  return undefined;
110
110
  }
111
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
+ }
112
163
  /** Find the agent PID that runs inside the currently active tmux pane.
113
- * When panePid is provided, skips the tmux query (useful when the caller
114
- * already resolved the active pane PID for cache-key purposes). */
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). */
115
175
  export async function findActiveAgentPid(agentPids, panePid) {
116
176
  if (agentPids.length === 0)
117
177
  return undefined;
@@ -119,8 +179,22 @@ export async function findActiveAgentPid(agentPids, panePid) {
119
179
  const activePanePid = panePid ?? (await getActiveTmuxPanePid());
120
180
  if (!activePanePid)
121
181
  return undefined;
182
+ // Tier 1: pid-tree
122
183
  const childMap = await getProcessTree();
123
- return agentPids.find((pid) => isPidInTree(activePanePid, pid, childMap));
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;
124
198
  }
125
199
  catch {
126
200
  return undefined;
@@ -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;