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/dist/turns.js ADDED
@@ -0,0 +1,430 @@
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
+ function toEpochSec(timestamp) {
17
+ if (typeof timestamp !== "string")
18
+ return undefined;
19
+ const ms = new Date(timestamp).getTime();
20
+ return Number.isFinite(ms) ? ms / 1000 : undefined;
21
+ }
22
+ function formatToolInput(input) {
23
+ if (typeof input === "string")
24
+ return input.trim();
25
+ try {
26
+ return JSON.stringify(input, null, 2);
27
+ }
28
+ catch {
29
+ return String(input);
30
+ }
31
+ }
32
+ function formatToolResult(item) {
33
+ if (typeof item.content === "string")
34
+ return item.content.trim();
35
+ if (Array.isArray(item.content)) {
36
+ return item.content
37
+ .map((child) => {
38
+ if (!child || typeof child !== "object")
39
+ return String(child);
40
+ const c = child;
41
+ if (typeof c.text === "string")
42
+ return c.text.trim();
43
+ return JSON.stringify(c);
44
+ })
45
+ .filter(Boolean)
46
+ .join("\n\n");
47
+ }
48
+ return "";
49
+ }
50
+ /** Extract assistant text-only parts from a Claude assistant message. */
51
+ function extractAssistantText(content) {
52
+ if (typeof content === "string") {
53
+ const t = content.trim();
54
+ return t ? [t] : [];
55
+ }
56
+ if (!Array.isArray(content))
57
+ return [];
58
+ return content
59
+ .filter((c) => Boolean(c) && typeof c === "object" && c.type === "text")
60
+ .map((c) => (typeof c.text === "string" ? c.text.trim() : ""))
61
+ .filter(Boolean);
62
+ }
63
+ /** Extract bundle parts (text + tool_use + tool_result) — thinking excluded. */
64
+ function extractAssistantBundle(content) {
65
+ if (typeof content === "string") {
66
+ const t = content.trim();
67
+ return t ? [t] : [];
68
+ }
69
+ if (!Array.isArray(content))
70
+ return [];
71
+ const parts = [];
72
+ for (const item of content) {
73
+ if (!item || typeof item !== "object")
74
+ continue;
75
+ const block = item;
76
+ switch (block.type) {
77
+ case "text": {
78
+ const t = typeof block.text === "string" ? block.text.trim() : "";
79
+ if (t)
80
+ parts.push(t);
81
+ break;
82
+ }
83
+ case "tool_use": {
84
+ const name = typeof block.name === "string" ? block.name : "unknown";
85
+ parts.push(`[tool_use:${name}]\n${formatToolInput(block.input)}`);
86
+ break;
87
+ }
88
+ case "tool_result": {
89
+ const body = formatToolResult(block);
90
+ if (body)
91
+ parts.push(`[tool_result]\n${body}`);
92
+ break;
93
+ }
94
+ // "thinking" intentionally excluded
95
+ }
96
+ }
97
+ return parts;
98
+ }
99
+ /** Parse Claude user message — `tool_result`-only blocks are not real user prompts. */
100
+ function parseClaudeUserMessage(content) {
101
+ if (typeof content === "string") {
102
+ const t = content.trim();
103
+ return t ? { text: t, isToolResult: false } : undefined;
104
+ }
105
+ if (!Array.isArray(content))
106
+ return undefined;
107
+ const blockTypes = content
108
+ .map((c) => (c && typeof c === "object" ? c.type : undefined))
109
+ .filter((t) => typeof t === "string");
110
+ const onlyToolResult = blockTypes.length > 0 && blockTypes.every((t) => t === "tool_result");
111
+ // Only emit prompt text for genuine user prompts.
112
+ const textParts = content
113
+ .filter((c) => Boolean(c) && typeof c === "object" && c.type === "text")
114
+ .map((c) => (typeof c.text === "string" ? c.text.trim() : ""))
115
+ .filter(Boolean);
116
+ if (onlyToolResult) {
117
+ // Keep the raw content for bundle mode, but do not count it as a user prompt.
118
+ return { text: "", isToolResult: true };
119
+ }
120
+ return textParts.length > 0 ? { text: textParts.join("\n\n"), isToolResult: false } : undefined;
121
+ }
122
+ function flushAssistant(turns, pending) {
123
+ const text = pending.texts.join("\n\n").trim();
124
+ const bundle = pending.bundleParts.join("\n\n").trim();
125
+ if (!text && !bundle)
126
+ return;
127
+ turns.push({
128
+ role: "assistant",
129
+ startedAt: pending.startedAt,
130
+ completedAt: pending.completedAt ?? pending.startedAt,
131
+ text,
132
+ bundle: bundle || undefined,
133
+ });
134
+ }
135
+ function newPending() {
136
+ return { texts: [], bundleParts: [], startedAt: undefined, completedAt: undefined };
137
+ }
138
+ /**
139
+ * Parse a Claude session JSONL into ordered user/assistant turns.
140
+ * Lines without role information (file-history-snapshot, last-prompt, etc.)
141
+ * are ignored.
142
+ */
143
+ export function parseClaudeConversationTurns(raw) {
144
+ const turns = [];
145
+ let pending = newPending();
146
+ for (const line of raw.split("\n")) {
147
+ const trimmed = line.trim();
148
+ if (!trimmed)
149
+ continue;
150
+ let entry;
151
+ try {
152
+ entry = JSON.parse(trimmed);
153
+ }
154
+ catch {
155
+ continue;
156
+ }
157
+ const entryType = typeof entry.type === "string" ? entry.type : undefined;
158
+ if (entryType !== "user" && entryType !== "assistant")
159
+ continue;
160
+ const message = entry.message && typeof entry.message === "object"
161
+ ? entry.message
162
+ : undefined;
163
+ const ts = toEpochSec(entry.timestamp);
164
+ if (entryType === "user") {
165
+ const parsed = parseClaudeUserMessage(message?.content);
166
+ if (!parsed)
167
+ continue;
168
+ if (parsed.isToolResult) {
169
+ // tool_result entries merge into the in-progress assistant turn.
170
+ if (pending.bundleParts.length > 0 || pending.texts.length > 0) {
171
+ const body = formatToolResult(
172
+ // Re-extract the raw content into bundle form.
173
+ { content: message?.content ?? [] });
174
+ if (body)
175
+ pending.bundleParts.push(`[tool_result]\n${body}`);
176
+ if (ts !== undefined)
177
+ pending.completedAt = ts;
178
+ }
179
+ continue;
180
+ }
181
+ flushAssistant(turns, pending);
182
+ pending = newPending();
183
+ turns.push({ role: "user", startedAt: ts, completedAt: ts, text: parsed.text });
184
+ continue;
185
+ }
186
+ // assistant
187
+ const texts = extractAssistantText(message?.content);
188
+ const bundleParts = extractAssistantBundle(message?.content);
189
+ if (texts.length === 0 && bundleParts.length === 0)
190
+ continue;
191
+ if (pending.startedAt === undefined)
192
+ pending.startedAt = ts;
193
+ if (ts !== undefined)
194
+ pending.completedAt = ts;
195
+ pending.texts.push(...texts);
196
+ pending.bundleParts.push(...bundleParts);
197
+ if (message?.stop_reason === "end_turn") {
198
+ flushAssistant(turns, pending);
199
+ pending = newPending();
200
+ }
201
+ }
202
+ flushAssistant(turns, pending);
203
+ return turns;
204
+ }
205
+ /* ─── Codex rollout JSONL parser ─────────────────────────────────────── */
206
+ function extractCodexMessageTexts(content) {
207
+ if (typeof content === "string") {
208
+ const t = content.trim();
209
+ return t ? [t] : [];
210
+ }
211
+ if (!Array.isArray(content))
212
+ return [];
213
+ return content
214
+ .filter((c) => Boolean(c) && typeof c === "object")
215
+ .map((c) => {
216
+ const t = c.type;
217
+ // Both input_text (user/developer) and output_text (assistant) carry plain text.
218
+ if (t === "input_text" || t === "output_text") {
219
+ const text = c.text;
220
+ return typeof text === "string" ? text.trim() : "";
221
+ }
222
+ return "";
223
+ })
224
+ .filter(Boolean);
225
+ }
226
+ function formatCodexFunctionCall(payload) {
227
+ const name = typeof payload.name === "string" ? payload.name : "unknown";
228
+ const args = typeof payload.arguments === "string" ? payload.arguments : "";
229
+ // arguments is a stringified JSON — try to pretty-print.
230
+ let pretty = args;
231
+ try {
232
+ pretty = JSON.stringify(JSON.parse(args), null, 2);
233
+ }
234
+ catch {
235
+ // keep as-is if not valid JSON
236
+ }
237
+ return `[function_call:${name}]\n${pretty}`.trim();
238
+ }
239
+ function formatCodexFunctionOutput(payload) {
240
+ const output = typeof payload.output === "string" ? payload.output.trim() : "";
241
+ if (!output)
242
+ return "";
243
+ return `[function_call_output]\n${output}`;
244
+ }
245
+ /**
246
+ * Parse a Codex rollout JSONL into ordered user/assistant turns.
247
+ *
248
+ * Rollout structure:
249
+ * - `type: "session_meta"` / `"event_msg"` / `"turn_context"` — meta, ignored
250
+ * - `type: "response_item"` payload:
251
+ * - `type: "message"` + `role: "user"|"assistant"|"developer"`
252
+ * — content is an array of `{type: "input_text"|"output_text", text}`.
253
+ * `developer` is system-side, skipped.
254
+ * - `type: "reasoning"` — Codex's thinking, excluded (matches option B).
255
+ * - `type: "function_call"` — tool invocation (bundle-only).
256
+ * - `type: "function_call_output"` — tool result (bundle-only).
257
+ * - `type: "web_search_call"` — surfaced as a marker in bundle.
258
+ *
259
+ * Turn boundary: a new `user` message flushes the in-progress assistant.
260
+ */
261
+ export function parseCodexConversationTurns(raw) {
262
+ const turns = [];
263
+ let pending = newPending();
264
+ for (const line of raw.split("\n")) {
265
+ const trimmed = line.trim();
266
+ if (!trimmed)
267
+ continue;
268
+ let entry;
269
+ try {
270
+ entry = JSON.parse(trimmed);
271
+ }
272
+ catch {
273
+ continue;
274
+ }
275
+ if (entry.type !== "response_item")
276
+ continue;
277
+ const payload = entry.payload && typeof entry.payload === "object"
278
+ ? entry.payload
279
+ : undefined;
280
+ if (!payload)
281
+ continue;
282
+ const ts = toEpochSec(entry.timestamp);
283
+ const ptype = typeof payload.type === "string" ? payload.type : "";
284
+ if (ptype === "message") {
285
+ const role = typeof payload.role === "string" ? payload.role : "";
286
+ // Developer messages are system-side scaffolding — skip.
287
+ if (role === "developer")
288
+ continue;
289
+ const texts = extractCodexMessageTexts(payload.content);
290
+ if (texts.length === 0)
291
+ continue;
292
+ if (role === "user") {
293
+ flushAssistant(turns, pending);
294
+ pending = newPending();
295
+ const text = texts.join("\n\n").trim();
296
+ if (text)
297
+ turns.push({ role: "user", startedAt: ts, completedAt: ts, text });
298
+ continue;
299
+ }
300
+ if (role === "assistant") {
301
+ if (pending.startedAt === undefined)
302
+ pending.startedAt = ts;
303
+ if (ts !== undefined)
304
+ pending.completedAt = ts;
305
+ pending.texts.push(...texts);
306
+ pending.bundleParts.push(...texts);
307
+ continue;
308
+ }
309
+ continue;
310
+ }
311
+ if (ptype === "function_call") {
312
+ const piece = formatCodexFunctionCall(payload);
313
+ if (piece)
314
+ pending.bundleParts.push(piece);
315
+ if (ts !== undefined)
316
+ pending.completedAt = ts;
317
+ continue;
318
+ }
319
+ if (ptype === "function_call_output") {
320
+ const piece = formatCodexFunctionOutput(payload);
321
+ if (piece)
322
+ pending.bundleParts.push(piece);
323
+ if (ts !== undefined)
324
+ pending.completedAt = ts;
325
+ continue;
326
+ }
327
+ if (ptype === "web_search_call") {
328
+ pending.bundleParts.push("[web_search_call]");
329
+ if (ts !== undefined)
330
+ pending.completedAt = ts;
331
+ }
332
+ // "reasoning" intentionally excluded (option B).
333
+ }
334
+ flushAssistant(turns, pending);
335
+ return turns;
336
+ }
337
+ function extractGeminiText(msg) {
338
+ if (typeof msg.content === "string")
339
+ return msg.content.trim();
340
+ // Some Gemini variants store rich content under `parts: [{ text } | { functionCall } ...]`.
341
+ if (Array.isArray(msg.parts)) {
342
+ return msg.parts
343
+ .map((p) => {
344
+ if (!p || typeof p !== "object")
345
+ return "";
346
+ const obj = p;
347
+ if (typeof obj.text === "string")
348
+ return obj.text.trim();
349
+ return "";
350
+ })
351
+ .filter(Boolean)
352
+ .join("\n\n");
353
+ }
354
+ return "";
355
+ }
356
+ /**
357
+ * Parse a Gemini chats JSON (`messages: [{type, content, timestamp, ...}]`)
358
+ * into ordered user/assistant turns.
359
+ *
360
+ * Recognised message types:
361
+ * - `"user"` — user prompt → user turn
362
+ * - `"gemini"` — assistant response → flushed as assistant turn
363
+ * - everything else (`"info"`, `"error"`, etc.) — ignored as scaffolding
364
+ *
365
+ * NOTE: live verification is currently unavailable (the user does not run the
366
+ * Gemini CLI). Behaviour is covered by unit tests with fixture data and is
367
+ * expected to be conservative — unknown shapes degrade to no-turn rather than
368
+ * raising.
369
+ */
370
+ export function parseGeminiConversationTurns(raw) {
371
+ let data;
372
+ try {
373
+ data = JSON.parse(raw);
374
+ }
375
+ catch {
376
+ return [];
377
+ }
378
+ if (!data || !Array.isArray(data.messages))
379
+ return [];
380
+ const turns = [];
381
+ let pending = newPending();
382
+ for (const m of data.messages) {
383
+ if (!m || typeof m !== "object")
384
+ continue;
385
+ const msg = m;
386
+ const ts = toEpochSec(msg.timestamp);
387
+ const type = typeof msg.type === "string" ? msg.type : "";
388
+ const text = extractGeminiText(msg);
389
+ if (type === "user") {
390
+ flushAssistant(turns, pending);
391
+ pending = newPending();
392
+ if (text)
393
+ turns.push({ role: "user", startedAt: ts, completedAt: ts, text });
394
+ continue;
395
+ }
396
+ if (type === "gemini") {
397
+ if (!text)
398
+ continue;
399
+ if (pending.startedAt === undefined)
400
+ pending.startedAt = ts;
401
+ if (ts !== undefined)
402
+ pending.completedAt = ts;
403
+ pending.texts.push(text);
404
+ // `bundleParts` intentionally untouched: Gemini chats JSON does not
405
+ // expose tool-call / tool-result as separately addressable blocks the
406
+ // way Claude/Codex jsonl does. Producing a "bundle" that's identical
407
+ // to `text` would be a dishonest no-op, so we leave `turn.bundle`
408
+ // undefined and let `turnTextForMode(turn, 'bundle')` fall back to
409
+ // `turn.text` (the documented degradation path).
410
+ }
411
+ // info / error / unknown — skip
412
+ }
413
+ flushAssistant(turns, pending);
414
+ return turns;
415
+ }
416
+ /* ────────────────────────────────────────────────────────────────────── */
417
+ /** Pick the latest turn for a given role. */
418
+ export function selectLatestTurn(turns, role = "assistant") {
419
+ for (let i = turns.length - 1; i >= 0; i--) {
420
+ if (turns[i].role === role)
421
+ return turns[i];
422
+ }
423
+ return undefined;
424
+ }
425
+ /** Extract the copyable text from a turn for the chosen mode. */
426
+ export function turnTextForMode(turn, mode = "text") {
427
+ if (mode === "bundle" && turn.bundle)
428
+ return turn.bundle;
429
+ return turn.text;
430
+ }
package/dist/types.d.ts CHANGED
@@ -14,11 +14,13 @@ export type SessionStatus = "Active" | "Idle" | "Stalled" | "Unmatched" | "Dead"
14
14
  export type SessionPhase = "thinking" | "tool" | "permission" | "done" | undefined;
15
15
  /** Runtime source / host environment */
16
16
  export type RuntimeSource = "cli" | "vscode" | "unknown";
17
+ export type StatuslineLabelMode = "path" | "tmux" | "auto";
17
18
  /** Child/worker process info */
18
19
  export interface WorkerProcess {
19
20
  pid: number;
20
21
  cpuPercent: number;
21
22
  memoryMb: number;
23
+ resourceUsageAvailable?: boolean;
22
24
  status: SessionStatus;
23
25
  }
24
26
  /** Detected AI agent session */
@@ -29,6 +31,8 @@ export interface AgentSession {
29
31
  cwd: string;
30
32
  cpuPercent: number;
31
33
  memoryMb: number;
34
+ /** False when resource measurement failed. Numeric resource fields are compatibility placeholders. */
35
+ resourceUsageAvailable?: boolean;
32
36
  status: SessionStatus;
33
37
  startedAt?: number;
34
38
  processStartedAt?: number;
@@ -41,6 +45,10 @@ export interface AgentSession {
41
45
  phase?: SessionPhase;
42
46
  lastResponseAt?: number;
43
47
  lastActivityAt?: number;
48
+ /** Observed-only activity: session file / index timestamps, never an inference (#113). */
49
+ observedActivityAt?: number;
50
+ /** Epoch seconds when the process last looked busy by CPU/phase alone (#113). */
51
+ inferredBusyAt?: number;
44
52
  runtimeSource?: RuntimeSource;
45
53
  branch?: string;
46
54
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "marmonitor",
3
- "version": "0.2.5",
3
+ "version": "0.2.7",
4
4
  "author": "MJ JO <mjjo16@gmail.com>",
5
5
  "description": "tmux status bar monitor for AI coding agents — track Claude Code, Codex, Gemini sessions, tokens, and phases in real time",
6
6
  "type": "module",
@@ -48,6 +48,8 @@
48
48
  "start": "node bin/marmonitor.js",
49
49
  "lint": "biome check src tests",
50
50
  "test": "node --test tests/*.test.mjs",
51
+ "verify:local": "npm run build && node scripts/verify-local.mjs",
52
+ "verify:labels": "npm run build && node scripts/verify-statusline-labels.mjs",
51
53
  "postinstall": "node bin/postinstall.cjs",
52
54
  "preuninstall": "node bin/preuninstall.cjs",
53
55
  "prepublishOnly": "npm run build && npm test"