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
package/README.ko.md CHANGED
@@ -41,6 +41,7 @@ tmux에서 여러 AI 코딩 에이전트를 동시에 실행하는 건 이제
41
41
 
42
42
  **tmux 상태바** — 터미널 하단에 항상 표시:
43
43
  - 에이전트 수 (`Cl 12`, `Cx 2`, `Gm 1`) — 실행 중인 세션 수
44
+ - 실행 수는 세션 파일 연결 여부와 별개입니다. 아직 메타데이터를 연결하지 못한 CLI도 포함하며, GUI 본체·서버·보조 프로세스는 제외합니다.
44
45
  - 단계 알림 (`⏳ 1`, `🤔 2`, `🔧 1`) — 주의가 필요한 세션
45
46
  - 번호 필 (`1 ⏳Cl my-project allow`, `2 •Cx api-server 6m`) — `Option+1~5`로 세션 바로 이동
46
47
 
@@ -104,6 +105,11 @@ PID
104
105
  | **Codex** | `cwd + processStartedAt`를 SQLite thread index와 매칭 | `pid + processStartedAt` 키의 binding registry를 통해 rollout JSONL 또는 SQLite row | binding registry TTL 기반 freshness 보정 |
105
106
  | **Gemini** | `cwd` → `~/.gemini/tmp/` 하위 project dir 탐색 | mtime 기준 최신 `chats/session-*.json` | 경량 — 프로젝트 디렉터리당 단일 활성 세션 |
106
107
 
108
+ 명령행의 대화 ID는 Codex 실행 파일의 실제 resume 인자 또는 명시적 session-ID
109
+ 옵션에서 읽습니다. 프롬프트·설정 값·자식 도구 명령에 들어 있는 UUID는 제외합니다.
110
+ 알 수 없는 옵션이나 경계가 모호한 여러 이미지 인자는 명령행 대화 ID의 근거로
111
+ 사용하지 않습니다.
112
+
107
113
  ### 왜 중요한가
108
114
 
109
115
  바인딩 레이어가 상태바에 표시되는 숫자의 신뢰성을 결정합니다. `direct` 바인딩은 세션 메타데이터로 파일 경로가 확인된 상태 — 근거 없이는 교체되지 않습니다. `provisional` 바인딩은 direct 파일이 확인될 때까지 유지되다 자동으로 승격됩니다. Reconciliation은 특정 조건(mtime 격차, 메타데이터 확인, 활성 파일 가드)이 충족될 때만 override를 실행하며, 매 스캔마다 재판단하지 않습니다.
@@ -204,6 +210,7 @@ marmonitor restart # 데몬 재시작 (예: npm 업데이트 후)
204
210
  |--------|------|
205
211
  | `prefix + a` | 어텐션 팝업 — 검토할 세션 선택 |
206
212
  | `prefix + j` | 점프 팝업 — 이동할 세션 선택 |
213
+ | `prefix + y` | 활성 패널의 최신 AI 답변 턴 복사 |
207
214
  | `prefix + m` | 독 — 컴팩트 모니터 패널 |
208
215
  | `Option+1~5` | 어텐션 세션 #1~5로 바로 이동 |
209
216
  | `Option+`` | 이전 패널로 돌아가기 |
@@ -214,11 +221,24 @@ marmonitor restart # 데몬 재시작 (예: npm 업데이트 후)
214
221
  marmonitor status # 전체 세션 목록
215
222
  marmonitor attention # 입력이 필요한 세션 확인
216
223
  marmonitor activity # 각 세션의 활동 내역 (도구 호출 + 토큰)
224
+ marmonitor copy-latest-turn # 활성 tmux 패널의 최신 AI/user 턴 복사
217
225
  marmonitor watch # 실시간 전체 화면 모니터
218
226
  marmonitor jump-back # 마지막 점프 이전 패널로 복귀
219
227
  marmonitor help # 모든 명령어 및 옵션
220
228
  ```
221
229
 
230
+ `marmonitor status --json`은 snapshot이 최신이면 `agents`가 빈 배열이어도
231
+ 종료코드 0을 반환합니다. 성공 응답에는 `system`, `agents`와 함께
232
+ `snapshot: { "health": "fresh", "ageMs": ... }`가 포함됩니다.
233
+ 최신 snapshot의 세션이 0개이면 상태바에는 `AI:0`으로 표시합니다.
234
+
235
+ snapshot을 사용할 수 없으면 종료코드 1과 함께 다음과 같은 JSON을 반환합니다.
236
+ `{ "error": "snapshot-unavailable", "snapshot": { "health": "stale", "ageMs": 20000 } }`
237
+ 다른 health 값은 `missing`, `invalid`, `unreadable`입니다. 오류 응답에는
238
+ `agents`가 없으므로 연동 프로그램은 종료코드를 확인한 뒤 목록을 읽어야 합니다.
239
+ snapshot health는 파일의 가용성과 최신성을 나타냅니다. 데몬 프로세스의 생존은
240
+ 별도로 확인해야 합니다.
241
+
222
242
  ### 활동 로그
223
243
 
224
244
  AI 세션이 실제로 수행한 작업을 추적합니다 — 파일 편집, bash 명령어, 사용 토큰:
@@ -250,20 +270,35 @@ marmonitor activity --json # JSON 출력
250
270
  | `[Idle]` | 프로세스는 살아 있지만 최근 활동 없음 |
251
271
  | `[Stalled]` | 장기간 활동 없음 |
252
272
  | `[Dead]` | 세션 파일은 있지만 프로세스가 종료됨 |
253
- | `[Unmatched]` | AI 프로세스는 발견되었지만 일치하는 세션 없음 |
273
+ | `[Unmatched]` | 실행 중인 CLI의 세션 메타데이터를 아직 연결하지 못함 (실행 수에는 포함) |
274
+
275
+ 자원 측정에 실패해도 확인된 CLI는 목록에 유지하고 `resourceUsageAvailable: false`로
276
+ 표시합니다. 자원 값은 화면에 `?`로 표시하며, JSON 소비자는 이 값이 false이면
277
+ 숫자 CPU·메모리 필드를 측정값으로 사용하지 않아야 합니다. CPU 측정 실패만으로
278
+ 세션이 멈췄다고 판정하지 않습니다.
279
+
280
+ 배치 자원 조회가 거부되면 PID별로 재측정합니다. 유효한 측정값이 없는 PID는
281
+ 대화 연결 전에 signal 0으로 확인해 `ESRCH`이면 제외하고, `EPERM`이면 생존한
282
+ 실행으로 유지합니다.
254
283
 
255
284
  ## tmux 플러그인
256
285
 
257
286
  [marmonitor-tmux](https://github.com/mjjo16/marmonitor-tmux) 플러그인이 tmux 설정을 자동으로 처리합니다:
258
287
 
259
288
  - 에이전트 뱃지와 어텐션 필이 포함된 2번째 상태 라인
260
- - 팝업, 점프, 독 키 바인딩
289
+ - 팝업, 점프, 최신 턴 복사, 독 키 바인딩
261
290
  - Option+1~5 다이렉트 점프
262
291
 
263
292
  `@marmonitor-*` 옵션으로 원하는 대로 바꿀 수 있습니다. 자세한 내용은 [플러그인 README](https://github.com/mjjo16/marmonitor-tmux)를 참조하세요.
264
293
 
265
294
  ### 뱃지 스타일
266
295
 
296
+ 하단바 이름은 `display.statuslineLabel`로 설정합니다. 기본 `auto`는 같은 경로나 축약 이름이 겹칠 때만 `@local:2.3` 같은 tmux 위치를 붙입니다. `path`는 기존 경로 표시, `tmux`는 확인된 tmux 위치를 사용합니다. 위치를 확인하지 못한 중복 세션은 PID로 구분합니다. 좁은 폭에서 위치가 너무 길어도 PID를 표시하며 클릭 대상은 계속 해당 CLI의 PID입니다.
297
+
298
+ 세션 이동과 터미널 화면 기반 상태 조회에는 PID 계보 또는 TTY 소유 근거가
299
+ 필요합니다. 소유를 확인할 수 없으면 같은 작업 경로의 pane이 하나뿐이어도
300
+ 위치를 미확정으로 처리합니다.
301
+
267
302
  `integration.tmux.badgeStyle`로 tmux 뱃지와 터미널 텍스트 출력의 스타일을 통일할 수 있습니다.
268
303
 
269
304
  - `basic` — 기본 컬러 필
@@ -294,7 +329,8 @@ marmonitor settings-init --stdout
294
329
  {
295
330
  "display": {
296
331
  "attentionLimit": 10,
297
- "statuslineAttentionLimit": 5
332
+ "statuslineAttentionLimit": 5,
333
+ "statuslineLabel": "auto"
298
334
  },
299
335
  "status": {
300
336
  "stalledAfterMin": 20,
package/README.md CHANGED
@@ -104,6 +104,11 @@ Each agent traverses this chain differently:
104
104
  | **Codex** | `cwd + processStartedAt` matched against SQLite thread index | Rollout JSONL or SQLite row, via binding registry keyed on `pid + processStartedAt` | Freshness correction via binding registry TTL |
105
105
  | **Gemini** | `cwd` → resolved project dir under `~/.gemini/tmp/` | Latest `chats/session-*.json` by mtime | Lightweight — single active session per project dir |
106
106
 
107
+ Command-line session identity is read from the Codex executable's actual resume
108
+ argument or explicit session-ID option. UUIDs inside prompts, configuration values,
109
+ and child-tool commands are excluded. Unknown options or ambiguous variadic image
110
+ arguments do not establish command-line session identity.
111
+
107
112
  ### Why this matters
108
113
 
109
114
  The binding layer is what makes the numbers in your status bar trustworthy. A `direct` binding means the file path was confirmed from session metadata — marmonitor won't swap it without evidence. A `provisional` binding is held until a direct file appears, then promoted automatically. Reconciliation only overrides when specific conditions are met (mtime lead, metadata confirmation, active file guard) — not on every scan.
@@ -206,6 +211,7 @@ The daemon must be running for all other commands to work. `marmonitor setup tmu
206
211
  |----------|--------|
207
212
  | `prefix + a` | Attention popup — choose a session to review |
208
213
  | `prefix + j` | Jump popup — pick a session to jump to |
214
+ | `prefix + y` | Copy the latest AI assistant turn from the active pane |
209
215
  | `prefix + m` | Dock — compact monitor pane |
210
216
  | `Option+1~5` | Direct jump to attention session #1~5 |
211
217
  | `Option+`` | Jump back to previous pane |
@@ -216,11 +222,24 @@ The daemon must be running for all other commands to work. `marmonitor setup tmu
216
222
  marmonitor status # Full session inventory
217
223
  marmonitor attention # What needs your input?
218
224
  marmonitor activity # What did each session do? (tool calls + tokens)
225
+ marmonitor copy-latest-turn # Copy the latest AI/user turn from the active tmux pane
219
226
  marmonitor watch # Live full-screen monitor
220
227
  marmonitor jump-back # Return to pane before last jump
221
228
  marmonitor help # All commands and options
222
229
  ```
223
230
 
231
+ `marmonitor status --json` exits with code 0 when its snapshot is fresh, including
232
+ when `agents` is an empty array. Successful responses include
233
+ `snapshot: { "health": "fresh", "ageMs": ... }` alongside `system` and `agents`.
234
+ The statusline displays a fresh empty inventory as `AI:0`.
235
+
236
+ An unavailable snapshot produces exit code 1 and JSON such as
237
+ `{ "error": "snapshot-unavailable", "snapshot": { "health": "stale", "ageMs": 20000 } }`.
238
+ Other health values are `missing`, `invalid`, and `unreadable`. These error responses
239
+ omit `agents`; integrations should check the exit code before reading the inventory.
240
+ Snapshot health describes file availability and freshness. Daemon process health
241
+ requires a separate check.
242
+
224
243
  ### Activity log
225
244
 
226
245
  Track what your AI sessions actually did — file edits, bash commands, tokens used:
@@ -252,20 +271,35 @@ Activity is collected automatically by the daemon and stored in `~/.config/marmo
252
271
  | `[Idle]` | Process alive, no recent activity |
253
272
  | `[Stalled]` | No activity for extended period |
254
273
  | `[Dead]` | Session file exists but process is gone |
255
- | `[Unmatched]` | AI process found but no matching session |
274
+ | `[Unmatched]` | Running CLI whose session metadata is not yet bound (included in session counts) |
275
+
276
+ When resource measurement fails, detected CLIs remain in the inventory with
277
+ `resourceUsageAvailable: false`. Resource displays use `?`. JSON consumers should
278
+ ignore the numeric CPU/memory placeholders when this flag is false. A failed CPU
279
+ measurement alone cannot establish that a session is stalled.
280
+
281
+ Rejected resource batches are retried per PID. PIDs without valid measurements
282
+ are checked with signal zero before session matching: `ESRCH` excludes an exited
283
+ process, while `EPERM` preserves it as an existing process.
256
284
 
257
285
  ## tmux Plugin
258
286
 
259
287
  The [marmonitor-tmux](https://github.com/mjjo16/marmonitor-tmux) plugin handles all tmux setup automatically:
260
288
 
261
289
  - 2nd status line with agent badges and attention pills
262
- - Key bindings for popup, jump, and dock
290
+ - Key bindings for popup, jump, latest-turn copy, and dock
263
291
  - Option+1~5 direct jump
264
292
 
265
293
  All settings are customizable via `@marmonitor-*` options. See the [plugin README](https://github.com/mjjo16/marmonitor-tmux) for details.
266
294
 
267
295
  ### Badge styles
268
296
 
297
+ Set `display.statuslineLabel` to `auto` (default), `path`, or `tmux`. Auto keeps unique path labels short and appends verified coordinates such as `@local:2.3` when paths or shortened names collide. If a duplicate session has no verified pane, or its location is too long for a narrow layout, a PID suffix keeps it distinct. Click targets remain PID-based.
298
+
299
+ Session jumps and terminal-screen status checks require verified process-tree or
300
+ terminal ownership. When ownership cannot be established, marmonitor leaves the
301
+ location unresolved even if exactly one pane has the same working directory.
302
+
269
303
  tmux badges and terminal text output can share one style via `integration.tmux.badgeStyle`.
270
304
 
271
305
  - `basic` — default colored pills
@@ -287,11 +321,13 @@ Useful commands:
287
321
  marmonitor alerts
288
322
  marmonitor alerts on
289
323
  marmonitor alerts off
324
+ marmonitor alerts tokens on
325
+ marmonitor alerts tokens off
290
326
  marmonitor alerts notify on
291
327
  marmonitor alerts notify off
292
328
  ```
293
329
 
294
- Desktop notifications can be enabled separately from alert collection. After changing alert settings, restart the daemon to apply them:
330
+ Desktop notifications can be enabled separately from alert collection, and token/context alerts can be silenced without turning off security alerts. After changing alert settings, restart the daemon to apply them:
295
331
 
296
332
  ```bash
297
333
  marmonitor restart
@@ -320,7 +356,8 @@ marmonitor settings-init --stdout
320
356
  {
321
357
  "display": {
322
358
  "attentionLimit": 10,
323
- "statuslineAttentionLimit": 5
359
+ "statuslineAttentionLimit": 5,
360
+ "statuslineLabel": "auto"
324
361
  },
325
362
  "status": {
326
363
  "stalledAfterMin": 20,
@@ -35,8 +35,16 @@ export function checkTokenAlert(store, agent, thresholds = DEFAULT_TOKEN_THRESHO
35
35
  if (!usage)
36
36
  return undefined;
37
37
  // lastInputTokens = most recent API call's input_tokens = actual current context size.
38
- // Fall back to cumulative inputTokens only if lastInputTokens is unavailable.
39
- const used = usage.lastInputTokens ?? usage.inputTokens;
38
+ // Only fire when this definitive signal is available as a finite number.
39
+ // `Number.isFinite` rejects undefined / null (e.g. from external JSON) / NaN /
40
+ // Infinity in one check. Falling back to the cumulative inputTokens (which
41
+ // grows unboundedly across a session) would massively overstate the context %
42
+ // for agents that do not populate lastInputTokens — most notably Codex.
43
+ // Tracked as GitHub #55 / local #102 (root fix: split TokenUsage into
44
+ // cumulative vs context-window fields).
45
+ if (!Number.isFinite(usage.lastInputTokens))
46
+ return undefined;
47
+ const used = usage.lastInputTokens;
40
48
  const limit = contextLimit(agent.model);
41
49
  const ratio = used / limit;
42
50
  if (ratio >= thresholds.critAt) {
package/dist/cli.js CHANGED
@@ -3,15 +3,16 @@ import { tmpdir } from "node:os";
3
3
  import { dirname, join } from "node:path";
4
4
  import { Command } from "commander";
5
5
  import { renderInstallBanner, renderRuntimeBanner } from "./banner/index.js";
6
+ import { ClipboardError, writeClipboard } from "./clipboard.js";
6
7
  import { getConfigDir, getConfigSearchPaths, getDefaultConfigPath, loadConfig, resolveConfigPath as resolveLoadedConfigPath, } from "./config/index.js";
7
8
  import { detectGuardTriggers, evaluateGuard, formatGuardOutput, parseHookEvent, readStdin, } from "./guard/index.js";
8
9
  import { applyTerminalStyle, printAttention, printAttentionJson, printCleanJson, printCleanPlan, printDock, printJumpJson, printJumpResult, printStatus, printStatusJson, renderJumpAttentionChooser, renderStatusline, renderUnavailableStatusline, } from "./output/index.js";
9
10
  import { buildJumpAttentionItems, parseSelectionInput, selectJumpAttentionItem, selectJumpAttentionItemOnPage, selectUnmatchedTargets, } from "./output/utils.js";
10
11
  import { TERMINAL_RESTORE_SEQUENCE, formatProcessFailure } from "./process-safety.js";
11
- import { detectClaudePhase } from "./scanner/claude.js";
12
+ import { detectClaudePhase, resolveClaudeSessionFile } from "./scanner/claude.js";
12
13
  import { detectCodexPhase, indexCodexSessions, matchCodexSession } from "./scanner/codex.js";
13
- import { readDaemonSnapshot } from "./scanner/daemon-utils.js";
14
- import { parseGeminiSession } from "./scanner/gemini.js";
14
+ import { readDaemonSnapshot, readDaemonSnapshotResult, } from "./scanner/daemon-utils.js";
15
+ import { parseGeminiSession, resolveGeminiChatFile } from "./scanner/gemini.js";
15
16
  import { scanAgents } from "./scanner/index.js";
16
17
  import { loadRegistryFromFile } from "./scanner/session-registry.js";
17
18
  import { detectCliStdoutPhase } from "./scanner/status.js";
@@ -80,7 +81,7 @@ function buildHelpAppendix() {
80
81
  " watch Live full-screen monitor",
81
82
  " dock Persistent tmux-friendly monitor",
82
83
  " --statusline Status bar output for tmux",
83
- " clean Review or kill unmatched leftovers",
84
+ " clean Review or kill unmatched CLIs by PID",
84
85
  " debug-phase Inspect raw phase signals for one PID",
85
86
  " guard Claude hook evaluator; fail-open on malformed input/errors",
86
87
  " settings-* Locate, inspect, or initialize settings.json",
@@ -113,7 +114,7 @@ function buildHelpAppendix() {
113
114
  " [Idle] Process alive, no recent activity",
114
115
  " [Stalled] No activity for extended period",
115
116
  " [Dead] Session file exists but process gone",
116
- " [Unmatched] AI process without matching session",
117
+ " [Unmatched] Running CLI whose session metadata is not yet bound",
117
118
  "",
118
119
  "Common settings:",
119
120
  " display.attentionLimit / display.statuslineAttentionLimit",
@@ -263,6 +264,7 @@ function buildMinimalConfigSample() {
263
264
  display: {
264
265
  attentionLimit: 10,
265
266
  statuslineAttentionLimit: 5,
267
+ statuslineLabel: "auto",
266
268
  },
267
269
  integration: {
268
270
  tmux: {
@@ -295,6 +297,7 @@ function buildAdvancedConfigSample() {
295
297
  display: {
296
298
  attentionLimit: 10,
297
299
  statuslineAttentionLimit: 5,
300
+ statuslineLabel: "auto",
298
301
  },
299
302
  integration: {
300
303
  tmux: {
@@ -411,15 +414,15 @@ function resolveAttentionLimit(opts, configuredLimit, interactive = false) {
411
414
  return Math.max(Math.floor(fallback), 1);
412
415
  return Math.min(Math.max(Math.floor(fallback), 1), 10);
413
416
  }
414
- function statuslineCacheFile(format, attentionLimit, width) {
417
+ function statuslineCacheFile(format, attentionLimit, width, labelMode = "auto") {
415
418
  const widthKey = width && width > 0 ? String(width) : "auto";
416
- return join(tmpdir(), "marmonitor", `statusline-${format}-${attentionLimit}-${widthKey}.txt`);
419
+ return join(tmpdir(), "marmonitor", `statusline-${format}-${attentionLimit}-${widthKey}-${labelMode}.txt`);
417
420
  }
418
421
  /** Read cached statusline. When activePanePid is provided, the cache is
419
422
  * only valid if the stored panePid (first line) matches — otherwise the
420
423
  * active-window highlight would be stale. Returns {content, panePid}. */
421
- async function readCachedStatusline(format, attentionLimit, width, ttlMs) {
422
- const path = statuslineCacheFile(format, attentionLimit, width);
424
+ async function readCachedStatusline(format, attentionLimit, width, ttlMs, labelMode = "auto") {
425
+ const path = statuslineCacheFile(format, attentionLimit, width, labelMode);
423
426
  try {
424
427
  const fileStat = await stat(path);
425
428
  if (Date.now() - fileStat.mtimeMs > ttlMs)
@@ -439,8 +442,8 @@ async function readCachedStatusline(format, attentionLimit, width, ttlMs) {
439
442
  return undefined;
440
443
  }
441
444
  }
442
- async function writeCachedStatusline(format, attentionLimit, width, value, activePanePid) {
443
- const path = statuslineCacheFile(format, attentionLimit, width);
445
+ async function writeCachedStatusline(format, attentionLimit, width, value, activePanePid, labelMode = "auto") {
446
+ const path = statuslineCacheFile(format, attentionLimit, width, labelMode);
444
447
  const data = activePanePid ? `${activePanePid}\n${value}` : value;
445
448
  try {
446
449
  await mkdir(join(tmpdir(), "marmonitor"), { recursive: true });
@@ -453,17 +456,29 @@ async function writeCachedStatusline(format, attentionLimit, width, value, activ
453
456
  const DAEMON_DIR = join(tmpdir(), "marmonitor");
454
457
  const DAEMON_PID_PATH = join(DAEMON_DIR, "daemon.pid");
455
458
  const DAEMON_SNAPSHOT_PATH = join(DAEMON_DIR, "daemon-snapshot.json");
456
- const DAEMON_NOT_RUNNING = "Daemon not running. Run: marmonitor start";
457
459
  async function getAgentsSnapshot() {
458
460
  return (await readDaemonSnapshot(DAEMON_SNAPSHOT_PATH, 5_000));
459
461
  }
460
- async function requireDaemonSnapshot() {
461
- const agents = await getAgentsSnapshot();
462
- if (agents.length === 0) {
463
- console.error(DAEMON_NOT_RUNNING);
462
+ async function requireFreshSnapshot(jsonErrors = false) {
463
+ const snapshot = await readDaemonSnapshotResult(DAEMON_SNAPSHOT_PATH, 5_000);
464
+ if (snapshot.health !== "fresh") {
465
+ const detail = snapshot.health === "stale" ? ` (${Math.round(snapshot.ageMs)}ms old)` : "";
466
+ if (jsonErrors) {
467
+ console.log(JSON.stringify({
468
+ error: "snapshot-unavailable",
469
+ snapshot: {
470
+ health: snapshot.health,
471
+ ...(snapshot.health === "stale" ? { ageMs: snapshot.ageMs } : {}),
472
+ },
473
+ }));
474
+ }
475
+ console.error(`Daemon snapshot ${snapshot.health}${detail}; current sessions are unavailable.`);
464
476
  process.exit(1);
465
477
  }
466
- return agents;
478
+ return snapshot;
479
+ }
480
+ async function requireDaemonSnapshot() {
481
+ return (await requireFreshSnapshot()).agents;
467
482
  }
468
483
  async function loadSessionRegistry() {
469
484
  const registry = new Map();
@@ -494,7 +509,7 @@ program
494
509
  // Try cache first. For tmux-badges the cached panePid is checked
495
510
  // against the live pane only on cache hit — the tmux call is
496
511
  // deferred so cache-miss paths pay for it just once.
497
- const cached = await readCachedStatusline(opts.statuslineFormat, attentionLimit, width, config.performance.statuslineTtlMs);
512
+ const cached = await readCachedStatusline(opts.statuslineFormat, attentionLimit, width, config.performance.statuslineTtlMs, config.display.statuslineLabel);
498
513
  if (cached) {
499
514
  if (isTmuxBadges && cached.panePid !== undefined) {
500
515
  const { getActiveTmuxPanePid } = await import("./tmux/index.js");
@@ -512,11 +527,12 @@ program
512
527
  return;
513
528
  }
514
529
  }
515
- const agents = await getAgentsSnapshot();
516
- if (agents.length === 0) {
530
+ const snapshot = await readDaemonSnapshotResult(DAEMON_SNAPSHOT_PATH, 5_000);
531
+ if (snapshot.health !== "fresh") {
517
532
  console.log(renderUnavailableStatusline(opts.statuslineFormat));
518
533
  return;
519
534
  }
535
+ const agents = snapshot.agents;
520
536
  // Check jump-back anchor and resolve active agent for tmux-badges
521
537
  let hasJumpAnchor = false;
522
538
  let activeAgentPid;
@@ -534,8 +550,8 @@ program
534
550
  hasJumpAnchor = Boolean(await loadJumpAnchor(pj(td(), "marmonitor", "jump-anchors.json"), tty));
535
551
  }
536
552
  }
537
- const rendered = await renderStatusline(agents, opts.statuslineFormat, attentionLimit, width, config.integration.tmux.badgeStyle, hasJumpAnchor, activeAgentPid);
538
- await writeCachedStatusline(opts.statuslineFormat, attentionLimit, width, rendered, activePanePid);
553
+ const rendered = await renderStatusline(agents, opts.statuslineFormat, attentionLimit, width, config.integration.tmux.badgeStyle, hasJumpAnchor, activeAgentPid, config.display.statuslineLabel);
554
+ await writeCachedStatusline(opts.statuslineFormat, attentionLimit, width, rendered, activePanePid, config.display.statuslineLabel);
539
555
  console.log(rendered);
540
556
  return;
541
557
  }
@@ -552,11 +568,12 @@ program
552
568
  .option("--json", "Output as JSON")
553
569
  .option("--config <path>", "Path to settings.json")
554
570
  .action(async (opts) => {
555
- const agents = await requireDaemonSnapshot();
571
+ const snapshot = await requireFreshSnapshot(opts.json);
572
+ const agents = snapshot.agents;
556
573
  const config = await loadConfig(resolveConfigPath(opts));
557
574
  applyTerminalStyle(config.integration.tmux.badgeStyle);
558
575
  if (opts.json) {
559
- await printStatusJson(agents);
576
+ await printStatusJson(agents, { health: snapshot.health, ageMs: snapshot.ageMs });
560
577
  }
561
578
  else {
562
579
  await printStatus(agents);
@@ -790,6 +807,7 @@ const alertsCmd = program
790
807
  console.log(`alerts.enabled : ${a.enabled}`);
791
808
  console.log(`alerts.desktop : ${a.desktop}`);
792
809
  console.log(`alerts.log : ${a.log}`);
810
+ console.log(`alerts.tokens : ${a.tokens} (token/context threshold alerts)`);
793
811
  console.log(`alerts.contextCritThreshold: ${a.contextCritThreshold} (${Math.round(a.contextCritThreshold * 100)}%)`);
794
812
  console.log(`alerts.contextWarnThreshold: ${a.contextWarnThreshold === 1.0 ? "disabled" : `${a.contextWarnThreshold} (${Math.round(a.contextWarnThreshold * 100)}%)`}`);
795
813
  });
@@ -824,6 +842,19 @@ alertsCmd
824
842
  await patchAlertsConfig(p, { desktop: toggle === "on" });
825
843
  console.log(`Desktop notifications ${toggle === "on" ? "enabled" : "disabled"}. Restart daemon to apply: marmonitor restart`);
826
844
  });
845
+ alertsCmd
846
+ .command("tokens <on|off>")
847
+ .description("Toggle token/context threshold alerts (security alerts unaffected)")
848
+ .option("--config <path>", "Path to settings.json")
849
+ .action(async (toggle, opts) => {
850
+ if (toggle !== "on" && toggle !== "off") {
851
+ console.error("Usage: marmonitor alerts tokens on|off");
852
+ process.exit(1);
853
+ }
854
+ const p = resolveConfigPath(opts) ?? getDefaultConfigPath();
855
+ await patchAlertsConfig(p, { tokens: toggle === "on" });
856
+ console.log(`Token/context alerts ${toggle === "on" ? "enabled" : "disabled"}. Restart daemon to apply: marmonitor restart`);
857
+ });
827
858
  // ── end alerts command ───────────────────────────────────────────────────────
828
859
  program
829
860
  .command("debug-phase")
@@ -1208,19 +1239,26 @@ function truncateForDisplay(value, maxLength) {
1208
1239
  }
1209
1240
  program
1210
1241
  .command("clean")
1211
- .description("Show or terminate unmatched processes")
1242
+ .description("Show unmatched CLIs or terminate selected PIDs")
1212
1243
  .option("--config <path>", "Path to settings.json")
1213
1244
  .option("--json", "Output as JSON")
1214
- .option("--kill", "Send SIGTERM to selected unmatched processes")
1245
+ .option("--kill", "Send SIGTERM to the unmatched PID(s) given with --pid")
1215
1246
  .option("--pid <pid...>", "Only include specific unmatched PID(s)")
1216
1247
  .action(async (opts) => {
1217
- const config = await loadConfig(resolveConfigPath(opts));
1218
- const agents = await scanAgents(config, { sessionRegistry: await loadSessionRegistry() });
1219
1248
  const selectedPids = Array.isArray(opts.pid)
1220
1249
  ? opts.pid
1221
1250
  .map((value) => Number.parseInt(value, 10))
1222
1251
  .filter((value) => !Number.isNaN(value))
1223
1252
  : undefined;
1253
+ // Unmatched CLIs are live sessions awaiting metadata, so never kill them
1254
+ // in bulk. Require the caller to name each PID explicitly.
1255
+ if (opts.kill && (!selectedPids || selectedPids.length === 0)) {
1256
+ console.error("--kill requires --pid <pid...>; review candidates with `marmonitor clean`.");
1257
+ process.exitCode = 1;
1258
+ return;
1259
+ }
1260
+ const config = await loadConfig(resolveConfigPath(opts));
1261
+ const agents = await scanAgents(config, { sessionRegistry: await loadSessionRegistry() });
1224
1262
  const targets = selectUnmatchedTargets(agents, selectedPids);
1225
1263
  if (opts.kill) {
1226
1264
  for (const target of targets) {
@@ -1430,5 +1468,140 @@ program
1430
1468
  await startDaemon();
1431
1469
  process.exit(0);
1432
1470
  });
1471
+ // ── copy-latest-turn command ─────────────────────────────────────────────────
1472
+ program
1473
+ .command("copy-latest-turn")
1474
+ .description("Copy the most recent AI turn of the active tmux pane to the clipboard (Claude / Codex / Gemini)")
1475
+ .option("--role <role>", "Which turn to copy: assistant (default) or user", "assistant")
1476
+ .option("--mode <mode>", "Extraction mode: text (default) or bundle", "text")
1477
+ .option("--pane-pid <pid>", "Override active pane PID (default: tmux active pane). Useful for tmux key bindings that pass #{pane_pid}.")
1478
+ .option("--stdout", "Print the turn to stdout instead of copying to clipboard")
1479
+ .option("--config <path>", "Path to settings.json")
1480
+ .action(async (opts) => {
1481
+ const { parseClaudeConversationTurns, parseCodexConversationTurns, parseGeminiConversationTurns, selectLatestTurn, turnTextForMode, } = await import("./turns.js");
1482
+ const role = opts.role === "user" ? "user" : "assistant";
1483
+ const mode = opts.mode === "bundle" ? "bundle" : "text";
1484
+ const agents = await requireDaemonSnapshot();
1485
+ let agent;
1486
+ let panePidOverridden = false;
1487
+ if (typeof opts.panePid === "string") {
1488
+ const panePid = Number.parseInt(opts.panePid, 10);
1489
+ if (!Number.isFinite(panePid)) {
1490
+ console.error(`Invalid --pane-pid value: ${opts.panePid}`);
1491
+ process.exit(1);
1492
+ }
1493
+ panePidOverridden = true;
1494
+ const agentPids = agents.map((a) => a.pid);
1495
+ const matchedPid = await findActiveAgentPid(agentPids, panePid);
1496
+ if (matchedPid !== undefined) {
1497
+ agent = agents.find((a) => a.pid === matchedPid);
1498
+ }
1499
+ }
1500
+ else {
1501
+ // Active tmux pane fallback
1502
+ const agentPids = agents.map((a) => a.pid);
1503
+ const matchedPid = await findActiveAgentPid(agentPids);
1504
+ if (matchedPid !== undefined) {
1505
+ agent = agents.find((a) => a.pid === matchedPid);
1506
+ }
1507
+ }
1508
+ if (!agent) {
1509
+ console.error(panePidOverridden
1510
+ ? `No AI session matched the given pane PID (${opts.panePid}).`
1511
+ : "No AI session in this tmux pane. Switch to a Claude pane and try again.");
1512
+ process.exit(1);
1513
+ }
1514
+ const config = await loadConfig(resolveConfigPath(opts));
1515
+ // Resolve the agent-specific source file and parse to SessionTurn[].
1516
+ let sessionFile;
1517
+ let turns = [];
1518
+ if (agent.agentName === "Claude Code") {
1519
+ // Trust the daemon snapshot's per-PID sessionId. Earlier we tried a
1520
+ // cwd-keyed live re-resolve here (F1, see #62 review), but that lost
1521
+ // PID identity when two Claude sessions share the same cwd —
1522
+ // `matchClaudeSessionByMtime` returned whichever jsonl scored best by
1523
+ // cwd alone, so `prefix+y` in pane A could copy pane B's turn. The
1524
+ // narrower `/resume` staleness concern that motivated F1 is tracked
1525
+ // separately under #107 (daemon snapshot freshness).
1526
+ if (!agent.sessionId) {
1527
+ console.error("Active Claude session has no sessionId yet — try again in a moment.");
1528
+ process.exit(1);
1529
+ }
1530
+ sessionFile = await resolveClaudeSessionFile(agent.sessionId, agent.cwd, agent.startedAt, config);
1531
+ if (!sessionFile) {
1532
+ console.error("Claude session file not found for this pane.");
1533
+ process.exit(1);
1534
+ }
1535
+ const raw = await readFile(sessionFile, "utf-8");
1536
+ turns = parseClaudeConversationTurns(raw);
1537
+ }
1538
+ else if (agent.agentName === "Codex") {
1539
+ // Mirror scanner's session resolution priority: persistent binding
1540
+ // registry (PID × processStartedAt → rollout) first, fallback to
1541
+ // cwd + processStartedAt matching. Same-cwd multi-Codex environments
1542
+ // would otherwise route to the wrong rollout file.
1543
+ const codexSessions = await indexCodexSessions(config, { activeCwds: [agent.cwd] });
1544
+ const { loadCodexBindingRegistryFromFile, selectCodexBindingSession } = await import("./scanner/codex-binding-registry.js");
1545
+ const bindingRegistry = new Map();
1546
+ await loadCodexBindingRegistryFromFile(join(getConfigDir(), "codex-binding-registry.json"), bindingRegistry);
1547
+ const matched = selectCodexBindingSession(bindingRegistry, agent.pid, agent.processStartedAt, agent.cwd, codexSessions) ?? matchCodexSession(agent.cwd, agent.processStartedAt, codexSessions);
1548
+ if (!matched?.filePath) {
1549
+ console.error("Codex rollout file not found for this pane.");
1550
+ process.exit(1);
1551
+ }
1552
+ sessionFile = matched.filePath;
1553
+ const raw = await readFile(sessionFile, "utf-8");
1554
+ turns = parseCodexConversationTurns(raw);
1555
+ }
1556
+ else if (agent.agentName === "Gemini") {
1557
+ // Match the snapshot's sessionId against on-disk Gemini chats first so
1558
+ // multi-session same-cwd environments don't fall back to "latest mtime
1559
+ // wins". parseGeminiSession (latest mtime) remains as a graceful fallback.
1560
+ sessionFile = await resolveGeminiChatFile(agent.cwd, agent.sessionId);
1561
+ if (!sessionFile) {
1562
+ const gemini = await parseGeminiSession(agent.cwd);
1563
+ sessionFile = gemini.sessionFile;
1564
+ }
1565
+ if (!sessionFile) {
1566
+ console.error("Gemini chat file not found for this pane.");
1567
+ process.exit(1);
1568
+ }
1569
+ const raw = await readFile(sessionFile, "utf-8");
1570
+ turns = parseGeminiConversationTurns(raw);
1571
+ }
1572
+ else {
1573
+ console.error(`Turn copy is not supported for ${agent.agentName} yet.`);
1574
+ process.exit(1);
1575
+ }
1576
+ const turn = selectLatestTurn(turns, role);
1577
+ if (!turn) {
1578
+ console.error(`No recent ${role} turn found in this ${agent.agentName} session.`);
1579
+ process.exit(1);
1580
+ }
1581
+ const text = turnTextForMode(turn, mode);
1582
+ if (!text) {
1583
+ console.error(`Latest ${role} turn has no ${mode === "bundle" ? "bundle" : "text"} content.`);
1584
+ process.exit(1);
1585
+ }
1586
+ if (opts.stdout) {
1587
+ console.log(text);
1588
+ return;
1589
+ }
1590
+ try {
1591
+ await writeClipboard(text);
1592
+ const chars = text.length;
1593
+ const label = role === "assistant" ? "AI" : "user";
1594
+ console.log(`marmonitor: copied ${label} turn (${chars} chars)`);
1595
+ }
1596
+ catch (err) {
1597
+ if (err instanceof ClipboardError) {
1598
+ console.error(err.message);
1599
+ }
1600
+ else {
1601
+ console.error(`Clipboard copy failed: ${err.message}. Try --stdout instead.`);
1602
+ }
1603
+ process.exit(1);
1604
+ }
1605
+ });
1433
1606
  installProcessSafetyHandlers();
1434
1607
  program.parse();
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Cross-platform clipboard writer with fallback chain.
3
+ *
4
+ * macOS : pbcopy
5
+ * Linux : wl-copy → xclip → xsel (in that order)
6
+ *
7
+ * Throws ClipboardError with a human-readable reason when all commands fail.
8
+ */
9
+ export declare class ClipboardError extends Error {
10
+ constructor(message: string);
11
+ }
12
+ export declare function writeClipboard(text: string): Promise<void>;