marmonitor 0.2.3 → 0.2.5
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.
- package/README.ko.md +109 -17
- package/README.md +73 -0
- package/dist/alerts/desktop.d.ts +3 -0
- package/dist/alerts/desktop.js +23 -0
- package/dist/alerts/index.d.ts +7 -0
- package/dist/alerts/index.js +5 -0
- package/dist/alerts/log.d.ts +3 -0
- package/dist/alerts/log.js +14 -0
- package/dist/alerts/snapshot.d.ts +4 -0
- package/dist/alerts/snapshot.js +25 -0
- package/dist/alerts/store.d.ts +23 -0
- package/dist/alerts/store.js +61 -0
- package/dist/alerts/token.d.ts +18 -0
- package/dist/alerts/token.js +65 -0
- package/dist/alerts/types.d.ts +23 -0
- package/dist/alerts/types.js +2 -0
- package/dist/cli.js +318 -124
- package/dist/config/index.d.ts +13 -1
- package/dist/config/index.js +7 -0
- package/dist/guard/index.js +51 -5
- package/dist/output/badge-themes.d.ts +3 -0
- package/dist/output/badge-themes.js +26 -0
- package/dist/output/index.d.ts +2 -1
- package/dist/output/index.js +156 -34
- package/dist/output/utils.d.ts +4 -2
- package/dist/output/utils.js +10 -4
- package/dist/scanner/claude.js +174 -90
- package/dist/scanner/codex.js +2 -0
- package/dist/scanner/daemon-entry.js +2 -0
- package/dist/scanner/daemon-loop.d.ts +2 -0
- package/dist/scanner/daemon-loop.js +25 -27
- package/dist/scanner/index.js +14 -0
- package/dist/scanner/process.js +6 -0
- package/dist/tmux/index.d.ts +6 -0
- package/dist/tmux/index.js +28 -0
- package/dist/types.d.ts +3 -0
- package/package.json +3 -1
package/README.ko.md
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
</p>
|
|
4
4
|
|
|
5
5
|
<p align="center">
|
|
6
|
-
<strong>Claude Code
|
|
6
|
+
<strong>Claude Code · Codex · Gemini용 tmux 상태바 모니터 — AI 코딩 세션을 실시간으로 추적하세요</strong>
|
|
7
7
|
</p>
|
|
8
8
|
|
|
9
9
|
<p align="center">
|
|
@@ -21,20 +21,20 @@
|
|
|
21
21
|
|
|
22
22
|
## 왜 marmonitor인가?
|
|
23
23
|
|
|
24
|
-
tmux에서 여러 AI 코딩 에이전트를 동시에 실행하는
|
|
24
|
+
tmux에서 여러 AI 코딩 에이전트를 동시에 실행하는 건 이제 일상입니다 — Claude Code가 백엔드를 리팩토링하고, Codex가 다른 패널에서 테스트를 작성하고, Gemini가 문서를 검토합니다. 하지만 세션이 늘어날수록 같은 문제에 부딪힙니다:
|
|
25
25
|
|
|
26
26
|
- 패널로 전환했더니 에이전트가 10분째 `allow` 승인을 기다리고 있었다
|
|
27
27
|
- 방금 작업하던 Codex 세션이 어느 윈도우에 있는지 기억나지 않는다
|
|
28
28
|
- 여러 세션에서 토큰을 얼마나 소모했는지 알 수 없다
|
|
29
29
|
|
|
30
|
-
|
|
30
|
+
**이걸 보여주는 대시보드가 없습니다.** 패널을 하나하나 돌아가며 직접 확인해야 합니다.
|
|
31
31
|
|
|
32
|
-
**marmonitor**가 이 문제를 해결합니다. tmux.conf에 한 줄만 추가하면, 상태바가 머신에서 실행 중인 모든 AI
|
|
32
|
+
**marmonitor**가 이 문제를 해결합니다. tmux.conf에 한 줄만 추가하면, 상태바가 로컬 머신에서 실행 중인 모든 AI 세션을 실시간으로 보여주는 컨트롤 패널이 됩니다.
|
|
33
33
|
|
|
34
34
|
<p align="center">
|
|
35
35
|
<img src="docs/use_sample.png" alt="marmonitor tmux 상태바" width="640">
|
|
36
36
|
<br>
|
|
37
|
-
<em>에이전트 수, 단계 뱃지,
|
|
37
|
+
<em>에이전트 수, 단계 뱃지, 번호 붙은 어텐션 필 — 모두 tmux 상태바에서 확인할 수 있습니다</em>
|
|
38
38
|
</p>
|
|
39
39
|
|
|
40
40
|
### 주요 기능
|
|
@@ -59,9 +59,58 @@ tmux에서 여러 AI 코딩 에이전트를 동시에 실행하는 것은 이제
|
|
|
59
59
|
<em>모든 세션의 상태, 토큰, 단계, CPU/MEM, 워커 프로세스 트리</em>
|
|
60
60
|
</p>
|
|
61
61
|
|
|
62
|
-
|
|
62
|
+
**에이전트 수정 불필요** — API 키, 플러그인, 코드 변경 없이 바로 쓸 수 있습니다. marmonitor는 외부에서 로컬 프로세스 정보와 세션 파일을 읽습니다. 명령어 두 개만 실행하면 됩니다: `npm install -g marmonitor`, `marmonitor setup tmux`.
|
|
63
63
|
|
|
64
|
-
> **tmux + AI 멀티세션
|
|
64
|
+
> **tmux + AI 멀티세션 워크플로우에 맞춰 만들었습니다.** 매일 5개 이상의 AI 코딩 세션을 여러 프로젝트에서 실행한다면, marmonitor가 컨텍스트 전환을 추측에서 상태바 한 번 확인으로 바꿔줍니다.
|
|
65
|
+
|
|
66
|
+
<details>
|
|
67
|
+
<summary><h3>🔩 내부 구조: 에이전트 세션 바인딩</h3></summary>
|
|
68
|
+
|
|
69
|
+
### 문제
|
|
70
|
+
|
|
71
|
+
주요 AI 코딩 에이전트 중 외부 세션 조회 API를 제공하는 것은 없습니다. `claude sessions list` 같은 명령어도, 세션 상태 변경 웹훅도 존재하지 않습니다. 실시간 토큰 사용량, phase, `lastResponseAt`을 표시하려면 marmonitor는 각 에이전트의 내부 데이터 포맷을 직접 읽고 해석해야 합니다 — 에이전트마다 포맷이 완전히 다르고, 공식 문서도 없으며, 언제든 바뀔 수 있습니다.
|
|
72
|
+
|
|
73
|
+
하지만 더 어려운 문제는 파일 파싱이 아닙니다. **실행 중인 OS 프로세스를 올바른 세션 파일에 안정적으로 연결하고, 세션이 변화하는 동안에도 그 연결을 유지하는 것**입니다.
|
|
74
|
+
|
|
75
|
+
### 바인딩이 어려운 이유
|
|
76
|
+
|
|
77
|
+
"에이전트 프로세스를 찾아 가장 최신 세션 파일을 읽는다"는 단순한 접근은 실제 환경에서 자주 깨집니다:
|
|
78
|
+
|
|
79
|
+
- **Claude Code의 `/clear`** — `/clear` 실행 시 PID는 그대로인 채로 새 session UUID와 새 JSONL 파일이 생성됩니다. 재매핑 없이는 이전 파일을 계속 읽어 토큰과 `lastResponseAt`이 frozen 상태로 표시됩니다.
|
|
80
|
+
- **Stale PID 메타데이터** — Claude는 `~/.claude/sessions/{pid}.json`에 현재 session ID를 기록하지만, `/clear` 직후에는 이 파일이 새 세션을 반영하지 못하고 잠시 지연되는 구간이 있습니다.
|
|
81
|
+
- **같은 cwd의 다중 세션** — 동일 프로젝트 디렉터리에서 두 Claude 세션을 실행하면, mtime 기반 파일 선택이 조용히 잘못된 JSONL을 잡아 한 세션의 활동이 다른 세션에 귀속됩니다.
|
|
82
|
+
- **지연된 파일 생성** — 프로세스가 처음 감지될 시점에 세션 파일이 아직 디스크에 없을 수 있어, 파일이 생성될 때까지 잠정적(provisional) 바인딩을 유지하다 승격해야 합니다.
|
|
83
|
+
|
|
84
|
+
이 중 하나라도 실패하면 하위 메트릭 전체가 오염됩니다 — 토큰 사용량, phase 감지, `lastResponseAt` 모두 바인딩된 파일에서 읽기 때문입니다.
|
|
85
|
+
|
|
86
|
+
### 바인딩 파이프라인
|
|
87
|
+
|
|
88
|
+
감지된 모든 에이전트 프로세스에 대해 marmonitor는 다섯 단계를 순서대로 처리합니다:
|
|
89
|
+
|
|
90
|
+
```
|
|
91
|
+
PID
|
|
92
|
+
└─ Identity Resolver → session identity (sessionId 또는 thread index)
|
|
93
|
+
└─ File Binding → session file 경로 (direct 또는 provisional)
|
|
94
|
+
└─ Reconciliation → stale/clear 보정
|
|
95
|
+
└─ Binding Cache → 인메모리, 현재 바인딩만 유지
|
|
96
|
+
└─ Binding History → 디스크 registry, 세션별 누적 이력
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
에이전트별 처리 방식:
|
|
100
|
+
|
|
101
|
+
| | Identity Resolver | File Binding | Reconciliation |
|
|
102
|
+
|--|--|--|--|
|
|
103
|
+
| **Claude Code** | `~/.claude/sessions/{pid}.json` → `sessionId` | `{sessionId}.jsonl` (direct) 또는 mtime 근접도 매칭 (provisional) | `chooseStaleSessionOverride()` — `/clear` 및 stale 메타 감지 |
|
|
104
|
+
| **Codex** | `cwd + processStartedAt`를 SQLite thread index와 매칭 | `pid + processStartedAt` 키의 binding registry를 통해 rollout JSONL 또는 SQLite row | binding registry TTL 기반 freshness 보정 |
|
|
105
|
+
| **Gemini** | `cwd` → `~/.gemini/tmp/` 하위 project dir 탐색 | mtime 기준 최신 `chats/session-*.json` | 경량 — 프로젝트 디렉터리당 단일 활성 세션 |
|
|
106
|
+
|
|
107
|
+
### 왜 중요한가
|
|
108
|
+
|
|
109
|
+
바인딩 레이어가 상태바에 표시되는 숫자의 신뢰성을 결정합니다. `direct` 바인딩은 세션 메타데이터로 파일 경로가 확인된 상태 — 근거 없이는 교체되지 않습니다. `provisional` 바인딩은 direct 파일이 확인될 때까지 유지되다 자동으로 승격됩니다. Reconciliation은 특정 조건(mtime 격차, 메타데이터 확인, 활성 파일 가드)이 충족될 때만 override를 실행하며, 매 스캔마다 재판단하지 않습니다.
|
|
110
|
+
|
|
111
|
+
이 설계 덕분에 marmonitor는 `/clear`, 재시작, 같은 프로젝트의 병렬 세션처럼 단순한 모니터가 조용히 틀린 데이터로 fallback하는 상황에서도 올바르게 추적할 수 있습니다.
|
|
112
|
+
|
|
113
|
+
</details>
|
|
65
114
|
|
|
66
115
|
## 지원 에이전트
|
|
67
116
|
|
|
@@ -87,7 +136,7 @@ marmonitor setup tmux
|
|
|
87
136
|
|
|
88
137
|
[marmonitor-tmux](https://github.com/mjjo16/marmonitor-tmux) 플러그인을 `~/.tmux.conf`에 추가합니다. tmux 안에서 `prefix + I`을 눌러 활성화하세요.
|
|
89
138
|
|
|
90
|
-
`marmonitor`를 업그레이드한 뒤에는
|
|
139
|
+
`marmonitor`를 업그레이드한 뒤에는 tmux 연동도 업데이트가 필요한지 확인하세요:
|
|
91
140
|
|
|
92
141
|
```bash
|
|
93
142
|
marmonitor update-integration
|
|
@@ -137,7 +186,19 @@ npm link
|
|
|
137
186
|
|
|
138
187
|
## 빠른 시작
|
|
139
188
|
|
|
140
|
-
|
|
189
|
+
### 데몬 시작
|
|
190
|
+
|
|
191
|
+
marmonitor는 2초마다 AI 세션을 스캔하는 백그라운드 데몬으로 실행됩니다:
|
|
192
|
+
|
|
193
|
+
```bash
|
|
194
|
+
marmonitor start # 데몬 시작
|
|
195
|
+
marmonitor stop # 데몬 중지
|
|
196
|
+
marmonitor restart # 데몬 재시작 (예: npm 업데이트 후)
|
|
197
|
+
```
|
|
198
|
+
|
|
199
|
+
모든 명령어가 동작하려면 데몬이 실행 중이어야 합니다. `marmonitor setup tmux`를 실행하면 자동으로 시작됩니다.
|
|
200
|
+
|
|
201
|
+
### tmux 단축키
|
|
141
202
|
|
|
142
203
|
| 단축키 | 동작 |
|
|
143
204
|
|--------|------|
|
|
@@ -145,16 +206,33 @@ npm link
|
|
|
145
206
|
| `prefix + j` | 점프 팝업 — 이동할 세션 선택 |
|
|
146
207
|
| `prefix + m` | 독 — 컴팩트 모니터 패널 |
|
|
147
208
|
| `Option+1~5` | 어텐션 세션 #1~5로 바로 이동 |
|
|
209
|
+
| `Option+`` | 이전 패널로 돌아가기 |
|
|
148
210
|
|
|
149
|
-
CLI
|
|
211
|
+
### CLI 명령어
|
|
150
212
|
|
|
151
213
|
```bash
|
|
152
214
|
marmonitor status # 전체 세션 목록
|
|
153
215
|
marmonitor attention # 입력이 필요한 세션 확인
|
|
216
|
+
marmonitor activity # 각 세션의 활동 내역 (도구 호출 + 토큰)
|
|
154
217
|
marmonitor watch # 실시간 전체 화면 모니터
|
|
218
|
+
marmonitor jump-back # 마지막 점프 이전 패널로 복귀
|
|
155
219
|
marmonitor help # 모든 명령어 및 옵션
|
|
156
220
|
```
|
|
157
221
|
|
|
222
|
+
### 활동 로그
|
|
223
|
+
|
|
224
|
+
AI 세션이 실제로 수행한 작업을 추적합니다 — 파일 편집, bash 명령어, 사용 토큰:
|
|
225
|
+
|
|
226
|
+
```bash
|
|
227
|
+
marmonitor activity # 오늘의 활동
|
|
228
|
+
marmonitor activity --pid 1234 # PID로 필터링
|
|
229
|
+
marmonitor activity --session abc # 세션 ID로 필터링
|
|
230
|
+
marmonitor activity --days 3 # 최근 3일
|
|
231
|
+
marmonitor activity --json # JSON 출력
|
|
232
|
+
```
|
|
233
|
+
|
|
234
|
+
활동 내역은 데몬이 자동으로 수집하며 `~/.config/marmonitor/activity-log/`에 저장됩니다 (7일 보관).
|
|
235
|
+
|
|
158
236
|
## 단계 아이콘
|
|
159
237
|
|
|
160
238
|
| 아이콘 | 단계 | 의미 |
|
|
@@ -169,10 +247,10 @@ marmonitor help # 모든 명령어 및 옵션
|
|
|
169
247
|
| 레이블 | 의미 |
|
|
170
248
|
|--------|------|
|
|
171
249
|
| `[Active]` | CPU 활동 감지됨 |
|
|
172
|
-
| `[Idle]` |
|
|
250
|
+
| `[Idle]` | 프로세스는 살아 있지만 최근 활동 없음 |
|
|
173
251
|
| `[Stalled]` | 장기간 활동 없음 |
|
|
174
252
|
| `[Dead]` | 세션 파일은 있지만 프로세스가 종료됨 |
|
|
175
|
-
| `[Unmatched]` | AI 프로세스는 발견되었지만
|
|
253
|
+
| `[Unmatched]` | AI 프로세스는 발견되었지만 일치하는 세션 없음 |
|
|
176
254
|
|
|
177
255
|
## tmux 플러그인
|
|
178
256
|
|
|
@@ -182,11 +260,20 @@ marmonitor help # 모든 명령어 및 옵션
|
|
|
182
260
|
- 팝업, 점프, 독 키 바인딩
|
|
183
261
|
- Option+1~5 다이렉트 점프
|
|
184
262
|
|
|
185
|
-
|
|
263
|
+
`@marmonitor-*` 옵션으로 원하는 대로 바꿀 수 있습니다. 자세한 내용은 [플러그인 README](https://github.com/mjjo16/marmonitor-tmux)를 참조하세요.
|
|
264
|
+
|
|
265
|
+
### 뱃지 스타일
|
|
266
|
+
|
|
267
|
+
`integration.tmux.badgeStyle`로 tmux 뱃지와 터미널 텍스트 출력의 스타일을 통일할 수 있습니다.
|
|
268
|
+
|
|
269
|
+
- `basic` — 기본 컬러 필
|
|
270
|
+
- `basic-mono` — Powerline 테두리의 단색 필
|
|
271
|
+
- `text` — 배경 없는 컬러 텍스트
|
|
272
|
+
- `text-mono` — 회색조 텍스트 전용
|
|
186
273
|
|
|
187
274
|
## 설정
|
|
188
275
|
|
|
189
|
-
|
|
276
|
+
다음 경로를 순서대로 찾아 먼저 발견된 파일을 적용합니다:
|
|
190
277
|
|
|
191
278
|
1. `$XDG_CONFIG_HOME/marmonitor/settings.json`
|
|
192
279
|
2. `~/.config/marmonitor/settings.json`
|
|
@@ -220,6 +307,7 @@ marmonitor settings-init --stdout
|
|
|
220
307
|
},
|
|
221
308
|
"integration": {
|
|
222
309
|
"tmux": {
|
|
310
|
+
"badgeStyle": "basic",
|
|
223
311
|
"keys": {
|
|
224
312
|
"attentionPopup": "a",
|
|
225
313
|
"jumpPopup": "j",
|
|
@@ -241,10 +329,14 @@ npm uninstall -g marmonitor # CLI 제거
|
|
|
241
329
|
## 안전성
|
|
242
330
|
|
|
243
331
|
- **기본적으로 읽기 전용** — 관찰만 하며, 세션을 수정하지 않습니다
|
|
244
|
-
- **네트워크 미사용** —
|
|
332
|
+
- **네트워크 미사용** — 외부로 연결하지 않으며, 모든 데이터는 로컬에 남습니다
|
|
245
333
|
- **보수적인 기본값** — 모든 연동 기능은 옵트인 방식입니다
|
|
246
334
|
- **tmux 우선** — WezTerm/iTerm2 네이티브 지원은 현재 일시 중단 상태입니다
|
|
247
335
|
|
|
336
|
+
## 변경 이력
|
|
337
|
+
|
|
338
|
+
릴리스 이력과 호환성 변경사항은 [CHANGELOG.md](CHANGELOG.md)를 참조하세요.
|
|
339
|
+
|
|
248
340
|
## 기여하기
|
|
249
341
|
|
|
250
342
|
설정, 커밋 규칙, PR 가이드라인은 [CONTRIBUTING.md](CONTRIBUTING.md)를 참조하세요. 아키텍처 세부사항은 [ARCHITECTURE.md](ARCHITECTURE.md)를 확인하세요.
|
|
@@ -252,10 +344,10 @@ npm uninstall -g marmonitor # CLI 제거
|
|
|
252
344
|
## 알려진 제한사항
|
|
253
345
|
|
|
254
346
|
- 패널 점프 기능은 tmux가 필요합니다
|
|
255
|
-
- WezTerm / iTerm2 네이티브 바 지원은
|
|
347
|
+
- WezTerm / iTerm2 네이티브 바 지원은 일시 중단 상태이며, 현재 tmux만 지원합니다
|
|
256
348
|
- Gemini 권한 감지는 Ink TUI 아키텍처로 인해 제한적입니다
|
|
257
349
|
- 단계 감지는 휴리스틱 기반으로, 에이전트별 정확도가 다를 수 있습니다
|
|
258
|
-
- macOS
|
|
350
|
+
- macOS 기준으로 개발했으며, Linux에서는 아직 테스트하지 않았습니다
|
|
259
351
|
|
|
260
352
|
## 라이선스
|
|
261
353
|
|
package/README.md
CHANGED
|
@@ -63,6 +63,55 @@ Running multiple AI coding agents in tmux is now the norm — Claude Code refact
|
|
|
63
63
|
|
|
64
64
|
> **Built for the tmux + AI multi-session workflow.** If you run 5+ AI coding sessions daily across different projects, marmonitor turns context-switching from guesswork into a glance at your status bar.
|
|
65
65
|
|
|
66
|
+
<details>
|
|
67
|
+
<summary><h3>🔩 Under the hood: Agent Session Binding</h3></summary>
|
|
68
|
+
|
|
69
|
+
### The problem
|
|
70
|
+
|
|
71
|
+
None of the major AI coding agents expose an external API for session introspection. There's no `claude sessions list`, no webhook when a session changes state. To show you live token counts, phase, and `lastResponseAt`, marmonitor has to read and interpret each agent's internal data formats — which are completely different across agents, undocumented, and subject to change.
|
|
72
|
+
|
|
73
|
+
But the harder problem isn't parsing files. It's **reliably binding a live OS process to the right session file** — and keeping that binding correct as sessions evolve.
|
|
74
|
+
|
|
75
|
+
### Why binding is hard
|
|
76
|
+
|
|
77
|
+
A naïve approach — "find the agent process, read the newest session file" — breaks under common real-world conditions:
|
|
78
|
+
|
|
79
|
+
- **`/clear` in Claude Code** creates a new session UUID and a new JSONL file while the PID stays the same. Without re-mapping, marmonitor would keep reading the old file and report stale tokens and a frozen `lastResponseAt`.
|
|
80
|
+
- **Stale PID metadata** — Claude writes `~/.claude/sessions/{pid}.json` with the current session ID, but after `/clear` this file can lag behind the actual new session for a window of time.
|
|
81
|
+
- **Multiple sessions sharing a cwd** — when you run two Claude sessions in the same project directory, mtime-based file selection silently picks the wrong JSONL, misattributing one session's activity to another.
|
|
82
|
+
- **Delayed file creation** — a session file may not exist on disk yet when the process is first detected, requiring provisional binding with promotion once the file appears.
|
|
83
|
+
|
|
84
|
+
Any of these failures corrupts downstream metrics: token usage, phase detection, and `lastResponseAt` all read from the bound file.
|
|
85
|
+
|
|
86
|
+
### The binding pipeline
|
|
87
|
+
|
|
88
|
+
For every detected agent process, marmonitor resolves a chain of five steps:
|
|
89
|
+
|
|
90
|
+
```
|
|
91
|
+
PID
|
|
92
|
+
└─ Identity Resolver → session identity (sessionId or thread index)
|
|
93
|
+
└─ File Binding → session file path (direct or provisional)
|
|
94
|
+
└─ Reconciliation → stale/clear correction when needed
|
|
95
|
+
└─ Binding Cache → in-memory, current binding only
|
|
96
|
+
└─ Binding History → disk registry, per-session accumulation
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
Each agent traverses this chain differently:
|
|
100
|
+
|
|
101
|
+
| | Identity Resolver | File Binding | Reconciliation |
|
|
102
|
+
|--|--|--|--|
|
|
103
|
+
| **Claude Code** | `~/.claude/sessions/{pid}.json` → `sessionId` | `{sessionId}.jsonl` (direct) or mtime-proximity match (provisional) | `chooseStaleSessionOverride()` detects `/clear` and stale pid metadata |
|
|
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
|
+
| **Gemini** | `cwd` → resolved project dir under `~/.gemini/tmp/` | Latest `chats/session-*.json` by mtime | Lightweight — single active session per project dir |
|
|
106
|
+
|
|
107
|
+
### Why this matters
|
|
108
|
+
|
|
109
|
+
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.
|
|
110
|
+
|
|
111
|
+
This design is also the reason marmonitor can correctly track sessions across `/clear`, restarts, and parallel sessions in the same project — scenarios where simpler monitors silently fall back to wrong data.
|
|
112
|
+
|
|
113
|
+
</details>
|
|
114
|
+
|
|
66
115
|
## Supported Agents
|
|
67
116
|
|
|
68
117
|
| Agent | Detection | Session Enrichment | Phase Tracking |
|
|
@@ -221,9 +270,33 @@ tmux badges and terminal text output can share one style via `integration.tmux.b
|
|
|
221
270
|
|
|
222
271
|
- `basic` — default colored pills
|
|
223
272
|
- `basic-mono` — monochrome pills with Powerline borders
|
|
273
|
+
- `block` — filled background badges without Powerline separator glyphs
|
|
274
|
+
- `block-mono` — monochrome filled badges without Powerline separator glyphs
|
|
224
275
|
- `text` — plain colored text, no filled background
|
|
225
276
|
- `text-mono` — grayscale text only
|
|
226
277
|
|
|
278
|
+
The currently active tmux pane is also highlighted in the attention pill row so it is easier to see which session belongs to the focused window.
|
|
279
|
+
|
|
280
|
+
### Alerts
|
|
281
|
+
|
|
282
|
+
`marmonitor` includes an alert system for important runtime signals such as critical token/context usage and guard-triggered risk events.
|
|
283
|
+
|
|
284
|
+
Useful commands:
|
|
285
|
+
|
|
286
|
+
```bash
|
|
287
|
+
marmonitor alerts
|
|
288
|
+
marmonitor alerts on
|
|
289
|
+
marmonitor alerts off
|
|
290
|
+
marmonitor alerts notify on
|
|
291
|
+
marmonitor alerts notify off
|
|
292
|
+
```
|
|
293
|
+
|
|
294
|
+
Desktop notifications can be enabled separately from alert collection. After changing alert settings, restart the daemon to apply them:
|
|
295
|
+
|
|
296
|
+
```bash
|
|
297
|
+
marmonitor restart
|
|
298
|
+
```
|
|
299
|
+
|
|
227
300
|
## Configuration
|
|
228
301
|
|
|
229
302
|
Config is loaded from (first found wins):
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
/** macOS / Linux desktop notification via node-notifier */
|
|
2
|
+
const APP_NAME = "marmonitor";
|
|
3
|
+
function title(alert) {
|
|
4
|
+
switch (alert.type) {
|
|
5
|
+
case "context_critical":
|
|
6
|
+
return "⚠️ Context Critical";
|
|
7
|
+
case "context_warn":
|
|
8
|
+
return "Context Warning";
|
|
9
|
+
case "security":
|
|
10
|
+
return "🚨 Security Alert";
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
export async function sendDesktopNotification(alert) {
|
|
14
|
+
try {
|
|
15
|
+
// Dynamic import — node-notifier is optional; fail silently if missing
|
|
16
|
+
const notifier = await import("node-notifier");
|
|
17
|
+
const message = alert.detail ? `${alert.message}\n${alert.detail}` : alert.message;
|
|
18
|
+
notifier.default.notify({ title: title(alert), message });
|
|
19
|
+
}
|
|
20
|
+
catch {
|
|
21
|
+
// node-notifier unavailable or notification failed — silent
|
|
22
|
+
}
|
|
23
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
export type { Alert, AlertSeverity, AlertType, AlertsSnapshot } from "./types.js";
|
|
2
|
+
export { AlertStore } from "./store.js";
|
|
3
|
+
export { appendAlertLog } from "./log.js";
|
|
4
|
+
export { checkTokenAlert, DEFAULT_TOKEN_THRESHOLDS } from "./token.js";
|
|
5
|
+
export type { TokenAlertThresholds } from "./token.js";
|
|
6
|
+
export { writeAlertsSnapshot, readAlertsSnapshot } from "./snapshot.js";
|
|
7
|
+
export { sendDesktopNotification } from "./desktop.js";
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
export { AlertStore } from "./store.js";
|
|
2
|
+
export { appendAlertLog } from "./log.js";
|
|
3
|
+
export { checkTokenAlert, DEFAULT_TOKEN_THRESHOLDS } from "./token.js";
|
|
4
|
+
export { writeAlertsSnapshot, readAlertsSnapshot } from "./snapshot.js";
|
|
5
|
+
export { sendDesktopNotification } from "./desktop.js";
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/** Append-only alert log writer → ~/.config/marmonitor/alerts.log */
|
|
2
|
+
import { appendFile, mkdir } from "node:fs/promises";
|
|
3
|
+
import { dirname } from "node:path";
|
|
4
|
+
export async function appendAlertLog(logPath, alert) {
|
|
5
|
+
try {
|
|
6
|
+
await mkdir(dirname(logPath), { recursive: true });
|
|
7
|
+
const ts = new Date(alert.createdAt).toISOString();
|
|
8
|
+
const line = `${ts} [${alert.severity.toUpperCase()}] ${alert.type} pid=${alert.agentPid} ${alert.message}${alert.detail ? ` | ${alert.detail}` : ""}\n`;
|
|
9
|
+
await appendFile(logPath, line, "utf-8");
|
|
10
|
+
}
|
|
11
|
+
catch {
|
|
12
|
+
// log failures must never crash callers
|
|
13
|
+
}
|
|
14
|
+
}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
/** Write/read alerts snapshot alongside daemon snapshot */
|
|
2
|
+
import type { Alert } from "./types.js";
|
|
3
|
+
export declare function writeAlertsSnapshot(path: string, active: Alert[]): Promise<void>;
|
|
4
|
+
export declare function readAlertsSnapshot(path: string, ttlMs?: number): Promise<Alert[]>;
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
/** Write/read alerts snapshot alongside daemon snapshot */
|
|
2
|
+
import { mkdir, readFile, writeFile } from "node:fs/promises";
|
|
3
|
+
import { dirname } from "node:path";
|
|
4
|
+
export async function writeAlertsSnapshot(path, active) {
|
|
5
|
+
try {
|
|
6
|
+
await mkdir(dirname(path), { recursive: true });
|
|
7
|
+
const snap = { active, updatedAt: Date.now() };
|
|
8
|
+
await writeFile(path, JSON.stringify(snap), "utf-8");
|
|
9
|
+
}
|
|
10
|
+
catch {
|
|
11
|
+
// snapshot write failures must never crash callers
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
export async function readAlertsSnapshot(path, ttlMs = 10_000) {
|
|
15
|
+
try {
|
|
16
|
+
const raw = await readFile(path, "utf-8");
|
|
17
|
+
const snap = JSON.parse(raw);
|
|
18
|
+
if (Date.now() - snap.updatedAt > ttlMs)
|
|
19
|
+
return [];
|
|
20
|
+
return snap.active ?? [];
|
|
21
|
+
}
|
|
22
|
+
catch {
|
|
23
|
+
return [];
|
|
24
|
+
}
|
|
25
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
/** In-memory AlertStore with dedup and auto-expiry */
|
|
2
|
+
import type { Alert, AlertSeverity, AlertType } from "./types.js";
|
|
3
|
+
export interface CreateAlertOptions {
|
|
4
|
+
type: AlertType;
|
|
5
|
+
severity: AlertSeverity;
|
|
6
|
+
agentPid: number;
|
|
7
|
+
message: string;
|
|
8
|
+
sessionId?: string;
|
|
9
|
+
cwd?: string;
|
|
10
|
+
detail?: string;
|
|
11
|
+
/** ms until auto-expiry. Defaults: security=0 (manual), context=5min */
|
|
12
|
+
ttlMs?: number;
|
|
13
|
+
}
|
|
14
|
+
export declare class AlertStore {
|
|
15
|
+
private alerts;
|
|
16
|
+
/** Create and store an alert. Returns the alert if new, undefined if duplicate. */
|
|
17
|
+
create(opts: CreateAlertOptions): Alert | undefined;
|
|
18
|
+
dismiss(id: string): void;
|
|
19
|
+
/** Prune expired and dismissed alerts */
|
|
20
|
+
prune(): void;
|
|
21
|
+
active(): Alert[];
|
|
22
|
+
count(): number;
|
|
23
|
+
}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
/** In-memory AlertStore with dedup and auto-expiry */
|
|
2
|
+
/** 5-minute dedup bucket (ms) */
|
|
3
|
+
const DEDUP_BUCKET_MS = 5 * 60 * 1000;
|
|
4
|
+
function makeBucket(createdAt) {
|
|
5
|
+
return Math.floor(createdAt / DEDUP_BUCKET_MS);
|
|
6
|
+
}
|
|
7
|
+
function makeId(type, agentPid, bucket) {
|
|
8
|
+
return `${type}:${agentPid}:${bucket}`;
|
|
9
|
+
}
|
|
10
|
+
export class AlertStore {
|
|
11
|
+
alerts = new Map();
|
|
12
|
+
/** Create and store an alert. Returns the alert if new, undefined if duplicate. */
|
|
13
|
+
create(opts) {
|
|
14
|
+
const now = Date.now();
|
|
15
|
+
const bucket = makeBucket(now);
|
|
16
|
+
const id = makeId(opts.type, opts.agentPid, bucket);
|
|
17
|
+
if (this.alerts.has(id))
|
|
18
|
+
return undefined;
|
|
19
|
+
const ttlMs = opts.ttlMs ?? (opts.type === "security" ? 0 : DEDUP_BUCKET_MS);
|
|
20
|
+
const alert = {
|
|
21
|
+
id,
|
|
22
|
+
type: opts.type,
|
|
23
|
+
severity: opts.severity,
|
|
24
|
+
agentPid: opts.agentPid,
|
|
25
|
+
sessionId: opts.sessionId,
|
|
26
|
+
cwd: opts.cwd,
|
|
27
|
+
message: opts.message,
|
|
28
|
+
detail: opts.detail,
|
|
29
|
+
createdAt: now,
|
|
30
|
+
expiresAt: ttlMs > 0 ? now + ttlMs : undefined,
|
|
31
|
+
};
|
|
32
|
+
this.alerts.set(id, alert);
|
|
33
|
+
return alert;
|
|
34
|
+
}
|
|
35
|
+
dismiss(id) {
|
|
36
|
+
const alert = this.alerts.get(id);
|
|
37
|
+
if (alert) {
|
|
38
|
+
alert.dismissedAt = Date.now();
|
|
39
|
+
this.alerts.delete(id);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
/** Prune expired and dismissed alerts */
|
|
43
|
+
prune() {
|
|
44
|
+
const now = Date.now();
|
|
45
|
+
for (const [id, alert] of this.alerts) {
|
|
46
|
+
if (alert.dismissedAt) {
|
|
47
|
+
this.alerts.delete(id);
|
|
48
|
+
}
|
|
49
|
+
else if (alert.expiresAt && now > alert.expiresAt) {
|
|
50
|
+
this.alerts.delete(id);
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
active() {
|
|
55
|
+
this.prune();
|
|
56
|
+
return [...this.alerts.values()];
|
|
57
|
+
}
|
|
58
|
+
count() {
|
|
59
|
+
return this.active().length;
|
|
60
|
+
}
|
|
61
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/** Token threshold alert trigger */
|
|
2
|
+
import type { AgentSession } from "../types.js";
|
|
3
|
+
import type { AlertStore } from "./store.js";
|
|
4
|
+
import type { Alert } from "./types.js";
|
|
5
|
+
export interface TokenAlertThresholds {
|
|
6
|
+
/** 경고 임계값 (0~1). 1.0이면 비활성화. */
|
|
7
|
+
warnAt: number;
|
|
8
|
+
/** 위험 임계값 (0~1). */
|
|
9
|
+
critAt: number;
|
|
10
|
+
}
|
|
11
|
+
/** Phase 1 기본값: warn 비활성(1.0), crit 85% */
|
|
12
|
+
export declare const DEFAULT_TOKEN_THRESHOLDS: TokenAlertThresholds;
|
|
13
|
+
/**
|
|
14
|
+
* Check an agent's token usage against thresholds.
|
|
15
|
+
* Creates an alert in store if threshold exceeded (deduped).
|
|
16
|
+
* Returns the created alert or undefined if no threshold crossed or deduped.
|
|
17
|
+
*/
|
|
18
|
+
export declare function checkTokenAlert(store: AlertStore, agent: AgentSession, thresholds?: TokenAlertThresholds): Alert | undefined;
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
/** Token threshold alert trigger */
|
|
2
|
+
/** Known model context window sizes (tokens) */
|
|
3
|
+
const MODEL_CONTEXT_LIMITS = {
|
|
4
|
+
"claude-opus-4": 200_000,
|
|
5
|
+
"claude-sonnet-4": 200_000,
|
|
6
|
+
"claude-haiku-4": 200_000,
|
|
7
|
+
"claude-3-5-sonnet": 200_000,
|
|
8
|
+
"claude-3-5-haiku": 200_000,
|
|
9
|
+
"claude-3-opus": 200_000,
|
|
10
|
+
"claude-3-sonnet": 200_000,
|
|
11
|
+
"claude-3-haiku": 200_000,
|
|
12
|
+
};
|
|
13
|
+
const DEFAULT_CONTEXT_LIMIT = 200_000;
|
|
14
|
+
function contextLimit(model) {
|
|
15
|
+
if (!model)
|
|
16
|
+
return DEFAULT_CONTEXT_LIMIT;
|
|
17
|
+
for (const [key, limit] of Object.entries(MODEL_CONTEXT_LIMITS)) {
|
|
18
|
+
if (model.toLowerCase().includes(key))
|
|
19
|
+
return limit;
|
|
20
|
+
}
|
|
21
|
+
return DEFAULT_CONTEXT_LIMIT;
|
|
22
|
+
}
|
|
23
|
+
/** Phase 1 기본값: warn 비활성(1.0), crit 85% */
|
|
24
|
+
export const DEFAULT_TOKEN_THRESHOLDS = {
|
|
25
|
+
warnAt: 1.0,
|
|
26
|
+
critAt: 0.85,
|
|
27
|
+
};
|
|
28
|
+
/**
|
|
29
|
+
* Check an agent's token usage against thresholds.
|
|
30
|
+
* Creates an alert in store if threshold exceeded (deduped).
|
|
31
|
+
* Returns the created alert or undefined if no threshold crossed or deduped.
|
|
32
|
+
*/
|
|
33
|
+
export function checkTokenAlert(store, agent, thresholds = DEFAULT_TOKEN_THRESHOLDS) {
|
|
34
|
+
const usage = agent.tokenUsage;
|
|
35
|
+
if (!usage)
|
|
36
|
+
return undefined;
|
|
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;
|
|
40
|
+
const limit = contextLimit(agent.model);
|
|
41
|
+
const ratio = used / limit;
|
|
42
|
+
if (ratio >= thresholds.critAt) {
|
|
43
|
+
return store.create({
|
|
44
|
+
type: "context_critical",
|
|
45
|
+
severity: "critical",
|
|
46
|
+
agentPid: agent.pid,
|
|
47
|
+
sessionId: agent.sessionId,
|
|
48
|
+
cwd: agent.cwd,
|
|
49
|
+
message: `Context ${Math.round(ratio * 100)}% full — /clear or new session recommended`,
|
|
50
|
+
detail: `used=${used.toLocaleString()} limit=${limit.toLocaleString()} model=${agent.model ?? "unknown"}`,
|
|
51
|
+
});
|
|
52
|
+
}
|
|
53
|
+
if (ratio >= thresholds.warnAt) {
|
|
54
|
+
return store.create({
|
|
55
|
+
type: "context_warn",
|
|
56
|
+
severity: "warn",
|
|
57
|
+
agentPid: agent.pid,
|
|
58
|
+
sessionId: agent.sessionId,
|
|
59
|
+
cwd: agent.cwd,
|
|
60
|
+
message: `Context ${Math.round(ratio * 100)}% full`,
|
|
61
|
+
detail: `used=${used.toLocaleString()} limit=${limit.toLocaleString()} model=${agent.model ?? "unknown"}`,
|
|
62
|
+
});
|
|
63
|
+
}
|
|
64
|
+
return undefined;
|
|
65
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
/** Alert system types for marmonitor */
|
|
2
|
+
export type AlertType = "context_warn" | "context_critical" | "security";
|
|
3
|
+
export type AlertSeverity = "info" | "warn" | "critical";
|
|
4
|
+
export interface Alert {
|
|
5
|
+
/** Deterministic dedup ID: `type:agentPid:bucket` */
|
|
6
|
+
id: string;
|
|
7
|
+
type: AlertType;
|
|
8
|
+
severity: AlertSeverity;
|
|
9
|
+
agentPid: number;
|
|
10
|
+
sessionId?: string;
|
|
11
|
+
cwd?: string;
|
|
12
|
+
message: string;
|
|
13
|
+
/** Extra context: token count, command, etc. */
|
|
14
|
+
detail?: string;
|
|
15
|
+
createdAt: number;
|
|
16
|
+
dismissedAt?: number;
|
|
17
|
+
expiresAt?: number;
|
|
18
|
+
}
|
|
19
|
+
/** Snapshot of active alerts written alongside agent snapshot */
|
|
20
|
+
export interface AlertsSnapshot {
|
|
21
|
+
active: Alert[];
|
|
22
|
+
updatedAt: number;
|
|
23
|
+
}
|