marmonitor 0.2.4 → 0.2.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.ko.md +52 -1
- package/README.md +76 -1
- 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 +73 -0
- package/dist/alerts/types.d.ts +23 -0
- package/dist/alerts/types.js +2 -0
- package/dist/cli.js +341 -23
- package/dist/clipboard.d.ts +12 -0
- package/dist/clipboard.js +56 -0
- package/dist/config/index.d.ts +14 -0
- package/dist/config/index.js +8 -0
- package/dist/guard/index.js +51 -5
- package/dist/output/badge-themes.d.ts +3 -0
- package/dist/output/badge-themes.js +12 -0
- package/dist/output/index.d.ts +1 -1
- package/dist/output/index.js +2 -2
- package/dist/output/utils.d.ts +2 -1
- package/dist/output/utils.js +9 -4
- package/dist/scanner/claude.js +212 -90
- package/dist/scanner/codex.d.ts +2 -0
- package/dist/scanner/codex.js +40 -9
- package/dist/scanner/daemon-entry.js +2 -0
- package/dist/scanner/daemon-loop.d.ts +4 -0
- package/dist/scanner/daemon-loop.js +25 -1
- package/dist/scanner/gemini.d.ts +10 -0
- package/dist/scanner/gemini.js +82 -0
- package/dist/scanner/process.js +11 -1
- package/dist/tmux/index.d.ts +26 -0
- package/dist/tmux/index.js +102 -0
- package/dist/turns.d.ts +68 -0
- package/dist/turns.js +430 -0
- package/dist/types.d.ts +2 -0
- package/package.json +3 -1
package/README.ko.md
CHANGED
|
@@ -63,6 +63,55 @@ tmux에서 여러 AI 코딩 에이전트를 동시에 실행하는 건 이제
|
|
|
63
63
|
|
|
64
64
|
> **tmux + AI 멀티세션 워크플로우에 맞춰 만들었습니다.** 매일 5개 이상의 AI 코딩 세션을 여러 프로젝트에서 실행한다면, marmonitor가 컨텍스트 전환을 추측에서 상태바 한 번 확인으로 바꿔줍니다.
|
|
65
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>
|
|
114
|
+
|
|
66
115
|
## 지원 에이전트
|
|
67
116
|
|
|
68
117
|
| 에이전트 | 탐지 방식 | 세션 정보 | 단계 추적 |
|
|
@@ -155,6 +204,7 @@ marmonitor restart # 데몬 재시작 (예: npm 업데이트 후)
|
|
|
155
204
|
|--------|------|
|
|
156
205
|
| `prefix + a` | 어텐션 팝업 — 검토할 세션 선택 |
|
|
157
206
|
| `prefix + j` | 점프 팝업 — 이동할 세션 선택 |
|
|
207
|
+
| `prefix + y` | 활성 패널의 최신 AI 답변 턴 복사 |
|
|
158
208
|
| `prefix + m` | 독 — 컴팩트 모니터 패널 |
|
|
159
209
|
| `Option+1~5` | 어텐션 세션 #1~5로 바로 이동 |
|
|
160
210
|
| `Option+`` | 이전 패널로 돌아가기 |
|
|
@@ -165,6 +215,7 @@ marmonitor restart # 데몬 재시작 (예: npm 업데이트 후)
|
|
|
165
215
|
marmonitor status # 전체 세션 목록
|
|
166
216
|
marmonitor attention # 입력이 필요한 세션 확인
|
|
167
217
|
marmonitor activity # 각 세션의 활동 내역 (도구 호출 + 토큰)
|
|
218
|
+
marmonitor copy-latest-turn # 활성 tmux 패널의 최신 AI/user 턴 복사
|
|
168
219
|
marmonitor watch # 실시간 전체 화면 모니터
|
|
169
220
|
marmonitor jump-back # 마지막 점프 이전 패널로 복귀
|
|
170
221
|
marmonitor help # 모든 명령어 및 옵션
|
|
@@ -208,7 +259,7 @@ marmonitor activity --json # JSON 출력
|
|
|
208
259
|
[marmonitor-tmux](https://github.com/mjjo16/marmonitor-tmux) 플러그인이 tmux 설정을 자동으로 처리합니다:
|
|
209
260
|
|
|
210
261
|
- 에이전트 뱃지와 어텐션 필이 포함된 2번째 상태 라인
|
|
211
|
-
- 팝업, 점프, 독 키 바인딩
|
|
262
|
+
- 팝업, 점프, 최신 턴 복사, 독 키 바인딩
|
|
212
263
|
- Option+1~5 다이렉트 점프
|
|
213
264
|
|
|
214
265
|
`@marmonitor-*` 옵션으로 원하는 대로 바꿀 수 있습니다. 자세한 내용은 [플러그인 README](https://github.com/mjjo16/marmonitor-tmux)를 참조하세요.
|
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 |
|
|
@@ -157,6 +206,7 @@ The daemon must be running for all other commands to work. `marmonitor setup tmu
|
|
|
157
206
|
|----------|--------|
|
|
158
207
|
| `prefix + a` | Attention popup — choose a session to review |
|
|
159
208
|
| `prefix + j` | Jump popup — pick a session to jump to |
|
|
209
|
+
| `prefix + y` | Copy the latest AI assistant turn from the active pane |
|
|
160
210
|
| `prefix + m` | Dock — compact monitor pane |
|
|
161
211
|
| `Option+1~5` | Direct jump to attention session #1~5 |
|
|
162
212
|
| `Option+`` | Jump back to previous pane |
|
|
@@ -167,6 +217,7 @@ The daemon must be running for all other commands to work. `marmonitor setup tmu
|
|
|
167
217
|
marmonitor status # Full session inventory
|
|
168
218
|
marmonitor attention # What needs your input?
|
|
169
219
|
marmonitor activity # What did each session do? (tool calls + tokens)
|
|
220
|
+
marmonitor copy-latest-turn # Copy the latest AI/user turn from the active tmux pane
|
|
170
221
|
marmonitor watch # Live full-screen monitor
|
|
171
222
|
marmonitor jump-back # Return to pane before last jump
|
|
172
223
|
marmonitor help # All commands and options
|
|
@@ -210,7 +261,7 @@ Activity is collected automatically by the daemon and stored in `~/.config/marmo
|
|
|
210
261
|
The [marmonitor-tmux](https://github.com/mjjo16/marmonitor-tmux) plugin handles all tmux setup automatically:
|
|
211
262
|
|
|
212
263
|
- 2nd status line with agent badges and attention pills
|
|
213
|
-
- Key bindings for popup, jump, and dock
|
|
264
|
+
- Key bindings for popup, jump, latest-turn copy, and dock
|
|
214
265
|
- Option+1~5 direct jump
|
|
215
266
|
|
|
216
267
|
All settings are customizable via `@marmonitor-*` options. See the [plugin README](https://github.com/mjjo16/marmonitor-tmux) for details.
|
|
@@ -226,6 +277,30 @@ tmux badges and terminal text output can share one style via `integration.tmux.b
|
|
|
226
277
|
- `text` — plain colored text, no filled background
|
|
227
278
|
- `text-mono` — grayscale text only
|
|
228
279
|
|
|
280
|
+
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.
|
|
281
|
+
|
|
282
|
+
### Alerts
|
|
283
|
+
|
|
284
|
+
`marmonitor` includes an alert system for important runtime signals such as critical token/context usage and guard-triggered risk events.
|
|
285
|
+
|
|
286
|
+
Useful commands:
|
|
287
|
+
|
|
288
|
+
```bash
|
|
289
|
+
marmonitor alerts
|
|
290
|
+
marmonitor alerts on
|
|
291
|
+
marmonitor alerts off
|
|
292
|
+
marmonitor alerts tokens on
|
|
293
|
+
marmonitor alerts tokens off
|
|
294
|
+
marmonitor alerts notify on
|
|
295
|
+
marmonitor alerts notify off
|
|
296
|
+
```
|
|
297
|
+
|
|
298
|
+
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:
|
|
299
|
+
|
|
300
|
+
```bash
|
|
301
|
+
marmonitor restart
|
|
302
|
+
```
|
|
303
|
+
|
|
229
304
|
## Configuration
|
|
230
305
|
|
|
231
306
|
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,73 @@
|
|
|
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
|
+
// 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;
|
|
48
|
+
const limit = contextLimit(agent.model);
|
|
49
|
+
const ratio = used / limit;
|
|
50
|
+
if (ratio >= thresholds.critAt) {
|
|
51
|
+
return store.create({
|
|
52
|
+
type: "context_critical",
|
|
53
|
+
severity: "critical",
|
|
54
|
+
agentPid: agent.pid,
|
|
55
|
+
sessionId: agent.sessionId,
|
|
56
|
+
cwd: agent.cwd,
|
|
57
|
+
message: `Context ${Math.round(ratio * 100)}% full — /clear or new session recommended`,
|
|
58
|
+
detail: `used=${used.toLocaleString()} limit=${limit.toLocaleString()} model=${agent.model ?? "unknown"}`,
|
|
59
|
+
});
|
|
60
|
+
}
|
|
61
|
+
if (ratio >= thresholds.warnAt) {
|
|
62
|
+
return store.create({
|
|
63
|
+
type: "context_warn",
|
|
64
|
+
severity: "warn",
|
|
65
|
+
agentPid: agent.pid,
|
|
66
|
+
sessionId: agent.sessionId,
|
|
67
|
+
cwd: agent.cwd,
|
|
68
|
+
message: `Context ${Math.round(ratio * 100)}% full`,
|
|
69
|
+
detail: `used=${used.toLocaleString()} limit=${limit.toLocaleString()} model=${agent.model ?? "unknown"}`,
|
|
70
|
+
});
|
|
71
|
+
}
|
|
72
|
+
return undefined;
|
|
73
|
+
}
|
|
@@ -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
|
+
}
|