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.
Files changed (42) hide show
  1. package/README.ko.md +39 -3
  2. package/README.md +41 -4
  3. package/dist/alerts/token.js +10 -2
  4. package/dist/cli.js +201 -28
  5. package/dist/clipboard.d.ts +12 -0
  6. package/dist/clipboard.js +56 -0
  7. package/dist/config/index.d.ts +3 -0
  8. package/dist/config/index.js +10 -4
  9. package/dist/output/index.d.ts +6 -3
  10. package/dist/output/index.js +43 -32
  11. package/dist/output/utils.d.ts +9 -2
  12. package/dist/output/utils.js +58 -2
  13. package/dist/scanner/cache.d.ts +10 -0
  14. package/dist/scanner/cache.js +14 -0
  15. package/dist/scanner/claude.d.ts +70 -3
  16. package/dist/scanner/claude.js +350 -26
  17. package/dist/scanner/codex.d.ts +39 -0
  18. package/dist/scanner/codex.js +171 -9
  19. package/dist/scanner/daemon-loop.d.ts +2 -0
  20. package/dist/scanner/daemon-loop.js +9 -2
  21. package/dist/scanner/daemon-utils.d.ts +11 -0
  22. package/dist/scanner/daemon-utils.js +42 -11
  23. package/dist/scanner/gemini.d.ts +10 -0
  24. package/dist/scanner/gemini.js +82 -0
  25. package/dist/scanner/group.d.ts +1 -1
  26. package/dist/scanner/group.js +9 -0
  27. package/dist/scanner/index.d.ts +18 -0
  28. package/dist/scanner/index.js +247 -28
  29. package/dist/scanner/process.d.ts +12 -0
  30. package/dist/scanner/process.js +242 -16
  31. package/dist/scanner/session-registry.d.ts +21 -0
  32. package/dist/scanner/session-registry.js +85 -4
  33. package/dist/scanner/status.d.ts +36 -1
  34. package/dist/scanner/status.js +49 -5
  35. package/dist/sessions.d.ts +9 -0
  36. package/dist/sessions.js +11 -0
  37. package/dist/tmux/index.d.ts +29 -5
  38. package/dist/tmux/index.js +131 -16
  39. package/dist/turns.d.ts +68 -0
  40. package/dist/turns.js +430 -0
  41. package/dist/types.d.ts +8 -0
  42. package/package.json +3 -1
@@ -10,7 +10,7 @@ export function parseTmuxPanes(raw) {
10
10
  .map((line) => line.trim())
11
11
  .filter(Boolean)
12
12
  .flatMap((line) => {
13
- const [target, panePidRaw, cwd] = line.split("\t");
13
+ const [target, panePidRaw, cwd, paneId] = line.split("\t");
14
14
  if (!target || !panePidRaw || !cwd)
15
15
  return [];
16
16
  const [sessionName, coords] = target.split(":");
@@ -26,6 +26,7 @@ export function parseTmuxPanes(raw) {
26
26
  paneIndex: Number.parseInt(paneIndexRaw, 10),
27
27
  panePid: Number.parseInt(panePidRaw, 10),
28
28
  cwd,
29
+ ...(paneId && /^%\d+$/.test(paneId) ? { paneId } : {}),
29
30
  };
30
31
  return Number.isFinite(pane.panePid) ? [pane] : [];
31
32
  })
@@ -64,14 +65,28 @@ export function isPidInTree(rootPid, targetPid, childMap) {
64
65
  }
65
66
  return false;
66
67
  }
67
- export function selectTmuxPaneForAgent(agent, panes, childMap) {
68
- const treeMatch = panes.find((pane) => isPidInTree(pane.panePid, agent.pid, childMap));
69
- if (treeMatch) {
70
- return { pane: treeMatch, match: "pid-tree" };
68
+ export function selectTmuxPaneForAgent(agent, panes, childMap, ttys = new Map(), allowCwdFallback = false) {
69
+ // Linked windows can expose the same physical pane through multiple paths.
70
+ const uniquePanes = [
71
+ ...new Map(panes.map((pane) => [pane.paneId ?? pane.panePid, pane])).values(),
72
+ ];
73
+ const treeMatches = uniquePanes.filter((pane) => isPidInTree(pane.panePid, agent.pid, childMap));
74
+ if (treeMatches.length === 1) {
75
+ return { pane: treeMatches[0], match: "pid-tree" };
71
76
  }
72
- const cwdMatch = panes.find((pane) => pane.cwd === agent.cwd);
73
- if (cwdMatch) {
74
- return { pane: cwdMatch, match: "cwd" };
77
+ if (treeMatches.length > 1)
78
+ return undefined;
79
+ const tty = ttys.get(agent.pid);
80
+ if (tty && /^\/dev\/(?:tty[^/]*|pts\/\d+|pty[^/]*)$/.test(tty)) {
81
+ const ttyMatches = uniquePanes.filter((pane) => ttys.get(pane.panePid) === tty);
82
+ if (ttyMatches.length === 1)
83
+ return { pane: ttyMatches[0], match: "tty" };
84
+ if (ttyMatches.length > 1)
85
+ return undefined;
86
+ }
87
+ const cwdMatches = allowCwdFallback ? uniquePanes.filter((pane) => pane.cwd === agent.cwd) : [];
88
+ if (cwdMatches.length === 1) {
89
+ return { pane: cwdMatches[0], match: "cwd" };
75
90
  }
76
91
  return undefined;
77
92
  }
@@ -81,7 +96,7 @@ export async function listTmuxPanes() {
81
96
  "list-panes",
82
97
  "-a",
83
98
  "-F",
84
- "#{session_name}:#{window_index}.#{pane_index}\t#{pane_pid}\t#{pane_current_path}",
99
+ "#{session_name}:#{window_index}.#{pane_index}\t#{pane_pid}\t#{pane_current_path}\t#{pane_id}",
85
100
  ]);
86
101
  return parseTmuxPanes(stdout);
87
102
  }
@@ -109,9 +124,69 @@ export async function getActiveTmuxPanePid() {
109
124
  return undefined;
110
125
  }
111
126
  }
127
+ /** Get the controlling tty of a PID via lsof (`-d 0` reads stdin fd → tty).
128
+ * Uses lsof instead of `ps -o tty=` because the latter returns EPERM on
129
+ * macOS for processes the caller does not own in the same session. */
130
+ export async function getProcessTty(pid) {
131
+ try {
132
+ const { stdout } = await execFileAsync("lsof", ["-a", "-p", String(pid), "-d", "0", "-Fn"], {
133
+ timeout: 2000,
134
+ });
135
+ const line = stdout
136
+ .split("\n")
137
+ .map((l) => l.trim())
138
+ .find((l) => l.startsWith("n/"));
139
+ return line ? line.slice(1) : undefined;
140
+ }
141
+ catch {
142
+ return undefined;
143
+ }
144
+ }
145
+ /** Batched variant of `getProcessTty` — one `lsof -p pid1,pid2,...` call
146
+ * returns the controlling tty for every PID at once. Returns a Map keyed
147
+ * by PID; PIDs with no tty (or lsof errors) are simply absent. lsof's `-F`
148
+ * output is one field per line, with `p<pid>` markers preceding each
149
+ * process's records, so we walk the lines with a running `currentPid` and
150
+ * pair the next `n<path>` we see with it. */
151
+ export async function getProcessTtys(pids) {
152
+ const result = new Map();
153
+ if (pids.length === 0)
154
+ return result;
155
+ try {
156
+ const { stdout } = await execFileAsync("lsof", ["-a", "-p", pids.join(","), "-d", "0", "-Fn"], {
157
+ timeout: 2000,
158
+ });
159
+ let currentPid;
160
+ for (const raw of stdout.split("\n")) {
161
+ const line = raw.trim();
162
+ if (line.startsWith("p")) {
163
+ const parsed = Number.parseInt(line.slice(1), 10);
164
+ currentPid = Number.isFinite(parsed) ? parsed : undefined;
165
+ }
166
+ else if (currentPid !== undefined && line.startsWith("n/")) {
167
+ // Keep the first `n` field per pid (stdin's tty); ignore any extras.
168
+ if (!result.has(currentPid))
169
+ result.set(currentPid, line.slice(1));
170
+ }
171
+ }
172
+ }
173
+ catch {
174
+ // partial output may still be useful if returned; otherwise empty map.
175
+ }
176
+ return result;
177
+ }
112
178
  /** 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). */
179
+ *
180
+ * Two-tier match:
181
+ * 1. pid-tree — `panePid` is the pane's shell PID; walk its descendants
182
+ * and find one matching `agentPids`. Works in most cases.
183
+ * 2. tty fallback — when the pid-tree walk misses (e.g. macOS denies
184
+ * ps walks for some processes), compare the pane's controlling tty
185
+ * with each agent process's controlling tty. The agent and the
186
+ * pane's shell share a tty when they run in the same pane.
187
+ *
188
+ * When `panePid` is provided, skips the tmux query (useful when the
189
+ * caller already resolved the active pane PID for cache-key purposes). */
115
190
  export async function findActiveAgentPid(agentPids, panePid) {
116
191
  if (agentPids.length === 0)
117
192
  return undefined;
@@ -119,21 +194,61 @@ export async function findActiveAgentPid(agentPids, panePid) {
119
194
  const activePanePid = panePid ?? (await getActiveTmuxPanePid());
120
195
  if (!activePanePid)
121
196
  return undefined;
197
+ // Tier 1: pid-tree
122
198
  const childMap = await getProcessTree();
123
- return agentPids.find((pid) => isPidInTree(activePanePid, pid, childMap));
199
+ const treeMatch = agentPids.find((pid) => isPidInTree(activePanePid, pid, childMap));
200
+ if (treeMatch !== undefined)
201
+ return treeMatch;
202
+ // Tier 2: tty fallback — one batched lsof for the pane shell + all
203
+ // agent PIDs, instead of N+1 separate calls.
204
+ const ttys = await getProcessTtys([activePanePid, ...agentPids]);
205
+ const paneTty = ttys.get(activePanePid);
206
+ if (!paneTty)
207
+ return undefined;
208
+ for (const agentPid of agentPids) {
209
+ if (ttys.get(agentPid) === paneTty)
210
+ return agentPid;
211
+ }
212
+ return undefined;
124
213
  }
125
214
  catch {
126
215
  return undefined;
127
216
  }
128
217
  }
129
218
  export async function resolveTmuxJumpTarget(agent) {
219
+ return (await resolveAgentTmuxTargets([agent])).get(agent.pid);
220
+ }
221
+ /** Resolve labels, jumps and stdout capture using process/TTY ownership.
222
+ * Cwd matching is available only to callers that explicitly request an estimate. */
223
+ export async function resolveAgentTmuxTargets(agents, allowCwdFallback = false) {
224
+ const targets = new Map();
225
+ if (agents.length === 0)
226
+ return targets;
130
227
  try {
131
- const [panes, childMap] = await Promise.all([listTmuxPanes(), getProcessTree()]);
132
- return selectTmuxPaneForAgent(agent, panes, childMap);
228
+ const [panes, tree] = await Promise.all([listTmuxPanes(), getProcessTree()]);
229
+ if (panes.length === 0)
230
+ return targets;
231
+ for (const agent of agents) {
232
+ const target = selectTmuxPaneForAgent(agent, panes, tree, new Map(), false);
233
+ if (target)
234
+ targets.set(agent.pid, target);
235
+ }
236
+ const unresolved = agents.filter((agent) => !targets.has(agent.pid));
237
+ if (unresolved.length > 0) {
238
+ const ttys = await getProcessTtys([
239
+ ...new Set([...unresolved.map((a) => a.pid), ...panes.map((p) => p.panePid)]),
240
+ ]);
241
+ for (const agent of unresolved) {
242
+ const target = selectTmuxPaneForAgent(agent, panes, tree, ttys, allowCwdFallback);
243
+ if (target)
244
+ targets.set(agent.pid, target);
245
+ }
246
+ }
133
247
  }
134
248
  catch {
135
- return undefined;
249
+ // Location is optional: keep the running CLI and fall back to PID labels.
136
250
  }
251
+ return targets;
137
252
  }
138
253
  export async function captureTmuxPaneOutput(target, lines = 30) {
139
254
  try {
@@ -141,7 +256,7 @@ export async function captureTmuxPaneOutput(target, lines = 30) {
141
256
  "capture-pane",
142
257
  "-p",
143
258
  "-t",
144
- target.pane.target,
259
+ target.pane.paneId ?? target.pane.target,
145
260
  "-S",
146
261
  `-${lines}`,
147
262
  ]);
@@ -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;