@statforge/claudestat 1.5.1 → 1.6.0

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.
@@ -11,7 +11,7 @@
11
11
  ::-webkit-scrollbar-track { background: #161b22 }
12
12
  ::-webkit-scrollbar-thumb { background: #30363d; border-radius: 3px }
13
13
  </style>
14
- <script type="module" crossorigin src="/assets/index-CB01c5lb.js"></script>
14
+ <script type="module" crossorigin src="/assets/index-DgbWvj42.js"></script>
15
15
  <link rel="modulepreload" crossorigin href="/assets/vendor-lucide-Cym0q5l_.js">
16
16
  <link rel="modulepreload" crossorigin href="/assets/vendor-react-B_Jzs0gY.js">
17
17
  </head>
package/dist/daemon.js CHANGED
@@ -66,6 +66,7 @@ const history_1 = require("./routes/history");
66
66
  const misc_1 = require("./routes/misc");
67
67
  const reports_1 = require("./routes/reports");
68
68
  const top_1 = require("./routes/top");
69
+ const opencode_reader_1 = require("./routes/opencode-reader");
69
70
  const projects_cache_1 = require("./cache/projects-cache");
70
71
  const rate_limiter_1 = require("./middleware/rate-limiter");
71
72
  const summarizer_1 = require("./summarizer");
@@ -89,6 +90,7 @@ app.use(history_1.historyRouter);
89
90
  app.use(misc_1.miscRouter);
90
91
  app.use(reports_1.reportsRouter);
91
92
  app.use(top_1.topRouter);
93
+ app.use(opencode_reader_1.opencodeReaderRouter);
92
94
  // ─── GET /health — necesita acceso al tamaño del pool SSE ─────────────────────
93
95
  app.get('/health', (_req, res) => {
94
96
  res.json({ status: 'ok', port: PORT, clients: (0, stream_1.getSseClientsSize)() });
package/dist/db.d.ts CHANGED
@@ -72,6 +72,7 @@ export declare const dbOps: {
72
72
  getSessionEvents(sessionId: string): EventRow[];
73
73
  getSession(sessionId: string): SessionRow | undefined;
74
74
  getLatestSession(): SessionRow | undefined;
75
+ getLatestClaudeSession(): SessionRow | undefined;
75
76
  getAllSessions(limit?: number): SessionRow[];
76
77
  getSessionEventsRecent(sessionId: string, limit?: number): EventRow[];
77
78
  updateSessionProject(sessionId: string, projectPath: string): void;
package/dist/db.js CHANGED
@@ -155,6 +155,11 @@ const stmts = {
155
155
  `),
156
156
  getLatestSession: db.prepare(`
157
157
  SELECT * FROM sessions ORDER BY last_event_at DESC LIMIT 1
158
+ `),
159
+ getLatestClaudeSession: db.prepare(`
160
+ SELECT * FROM sessions
161
+ WHERE source IS NULL OR source = 'claude-code'
162
+ ORDER BY last_event_at DESC LIMIT 1
158
163
  `),
159
164
  getAllSessions: db.prepare(`
160
165
  SELECT * FROM sessions ORDER BY started_at DESC LIMIT 500
@@ -515,6 +520,9 @@ exports.dbOps = {
515
520
  getLatestSession() {
516
521
  return stmts.getLatestSession.get();
517
522
  },
523
+ getLatestClaudeSession() {
524
+ return stmts.getLatestClaudeSession.get();
525
+ },
518
526
  getAllSessions(limit = 500) {
519
527
  return db.prepare(`SELECT * FROM sessions ORDER BY started_at DESC LIMIT ?`).all(limit);
520
528
  },
package/dist/enricher.js CHANGED
@@ -39,6 +39,7 @@ const prevContextBySession = new Map();
39
39
  let watcher = null;
40
40
  const pendingFiles = new Map();
41
41
  const fileLocks = new Map();
42
+ const pollIntervals = [];
42
43
  // ─── Adapter lookup por filePath ───────────────────────────────────────────────
43
44
  const adapterByDir = new Map();
44
45
  function findAdapter(filePath) {
@@ -70,7 +71,6 @@ async function processFile(filePath) {
70
71
  }
71
72
  }
72
73
  // ─── Start / Stop ──────────────────────────────────────────────────────────────
73
- let offsetCleanupInterval = null;
74
74
  function startEnricher(onUpdate, onCompact) {
75
75
  const adapters = (0, adapter_1.getActiveAdapters)();
76
76
  if (adapters.length === 0) {
@@ -117,26 +117,35 @@ function startEnricher(onUpdate, onCompact) {
117
117
  };
118
118
  watcher.on('change', handleFile);
119
119
  watcher.on('add', handleFile);
120
- offsetCleanupInterval = setInterval(() => {
121
- for (const [, adapter] of adapterByDir) {
122
- if (typeof adapter.constructor?.name === 'undefined') {
123
- // cleanup per-adapter state if needed
120
+ // ─── Poll-based adapters (e.g. OpenCode SQLite) ─────────────────────────────
121
+ const POLL_INTERVAL_MS = 10000;
122
+ for (const adapter of adapters) {
123
+ if (!(0, adapter_1.isPollable)(adapter))
124
+ continue;
125
+ let lastPoll = Date.now();
126
+ const interval = setInterval(async () => {
127
+ const since = lastPoll;
128
+ lastPoll = Date.now();
129
+ const sessions = await adapter.pollSessions(since);
130
+ for (const { sessionId, cost } of sessions) {
131
+ onUpdate(sessionId, cost, adapter.name);
124
132
  }
125
- }
126
- }, 5 * 60000).unref();
133
+ }, POLL_INTERVAL_MS);
134
+ interval.unref();
135
+ pollIntervals.push(interval);
136
+ }
127
137
  }
128
138
  function stopEnricher() {
129
139
  if (watcher) {
130
140
  watcher.close();
131
141
  watcher = null;
132
142
  }
133
- if (offsetCleanupInterval) {
134
- clearInterval(offsetCleanupInterval);
135
- offsetCleanupInterval = null;
136
- }
137
143
  for (const [, timer] of pendingFiles)
138
144
  clearTimeout(timer);
139
145
  pendingFiles.clear();
146
+ for (const interval of pollIntervals)
147
+ clearInterval(interval);
148
+ pollIntervals.length = 0;
140
149
  prevContextBySession.clear();
141
150
  adapterByDir.clear();
142
151
  console.log('[enricher] Stopped');
@@ -197,11 +197,8 @@ exports.eventsRouter.post('/event', (req, res) => {
197
197
  const onCostUpdate = (sessionId, cost, source) => {
198
198
  // Ensure session row exists — sub-agent JSONLs arrive from the enricher without a
199
199
  // prior hook event (Claude Code does not fire hooks for sub-agent sessions).
200
+ db_1.dbOps.upsertSession({ id: sessionId, cwd: undefined, started_at: cost.firstTs ?? Date.now(), last_event_at: Date.now(), source });
200
201
  let sessionRow = db_1.dbOps.getSession(sessionId);
201
- if (!sessionRow) {
202
- db_1.dbOps.upsertSession({ id: sessionId, cwd: undefined, started_at: cost.firstTs ?? Date.now(), last_event_at: cost.firstTs ?? Date.now(), source });
203
- sessionRow = db_1.dbOps.getSession(sessionId);
204
- }
205
202
  // Sub-agent detection: first time we see a session, check if its firstTs falls after
206
203
  // a recent Agent PreToolUse from another session in the same CWD → tag as child.
207
204
  if (!exports.taggedSessionParents.has(sessionId) && cost.firstTs) {
@@ -110,6 +110,13 @@ exports.miscRouter.get('/sessions', (_req, res) => {
110
110
  });
111
111
  res.json(enriched);
112
112
  });
113
+ // ─── GET /api/session-events — todos los eventos de una sesión (sin límite) ──
114
+ exports.miscRouter.get('/api/session-events', (req, res) => {
115
+ const sessionId = req.query.session_id;
116
+ if (!sessionId)
117
+ return res.status(400).json({ error: 'session_id required' });
118
+ res.json({ events: db_1.dbOps.getSessionEvents(sessionId) });
119
+ });
113
120
  // ─── GET /prompts — mensajes del usuario para una sesión ─────────────────────
114
121
  exports.miscRouter.get('/prompts', async (req, res) => {
115
122
  const sessionId = req.query.session_id;
@@ -125,6 +132,33 @@ exports.miscRouter.get('/hidden-cost', (_req, res) => {
125
132
  exports.miscRouter.get('/claude-stats', (_req, res) => {
126
133
  res.json((0, claude_stats_1.readClaudeStats)());
127
134
  });
135
+ // ─── GET /api/active-sessions — fuentes activas en los últimos 5 min ──────────
136
+ exports.miscRouter.get('/api/active-sessions', (_req, res) => {
137
+ const cutoff = Date.now() - 5 * 60 * 1000;
138
+ const sessions = db_1.dbOps.getAllSessions();
139
+ const bySource = new Map();
140
+ for (const s of sessions) {
141
+ const lastSeen = s.last_event_at ?? s.started_at;
142
+ if (lastSeen < cutoff)
143
+ continue;
144
+ const src = s.source ?? 'claude-code';
145
+ const existing = bySource.get(src);
146
+ if (!existing || lastSeen > existing.last_seen_ms) {
147
+ bySource.set(src, {
148
+ sessionId: s.id,
149
+ model: s.dominant_model ?? 'unknown',
150
+ cost_usd: s.total_cost_usd ?? 0,
151
+ last_seen_ms: lastSeen,
152
+ input_tokens: s.total_input_tokens ?? 0,
153
+ output_tokens: s.total_output_tokens ?? 0,
154
+ cache_read: s.total_cache_read ?? 0,
155
+ cache_creation: s.total_cache_creation ?? 0,
156
+ });
157
+ }
158
+ }
159
+ const result = Array.from(bySource.entries()).map(([source, v]) => ({ source, ...v }));
160
+ res.json(result);
161
+ });
128
162
  // ─── GET /system-config — mapa completo del setup de Claude ──────────────────
129
163
  let _systemConfigCache = null;
130
164
  let _systemConfigCacheTs = 0;
@@ -0,0 +1,7 @@
1
+ /**
2
+ * opencode-reader.ts — Lee sesiones de OpenCode desde su SQLite y las mapea
3
+ * al formato TraceEvent[] que entiende el dashboard.
4
+ *
5
+ * GET /api/opencode/session/:id → { events: TraceEvent[], totalParts: number }
6
+ */
7
+ export declare const opencodeReaderRouter: import("express-serve-static-core").Router;
@@ -0,0 +1,129 @@
1
+ "use strict";
2
+ /**
3
+ * opencode-reader.ts — Lee sesiones de OpenCode desde su SQLite y las mapea
4
+ * al formato TraceEvent[] que entiende el dashboard.
5
+ *
6
+ * GET /api/opencode/session/:id → { events: TraceEvent[], totalParts: number }
7
+ */
8
+ var __importDefault = (this && this.__importDefault) || function (mod) {
9
+ return (mod && mod.__esModule) ? mod : { "default": mod };
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.opencodeReaderRouter = void 0;
13
+ const os_1 = __importDefault(require("os"));
14
+ const path_1 = __importDefault(require("path"));
15
+ const fs_1 = __importDefault(require("fs"));
16
+ const express_1 = require("express");
17
+ exports.opencodeReaderRouter = (0, express_1.Router)();
18
+ const OPENCODE_DB = path_1.default.join(os_1.default.homedir(), '.local', 'share', 'opencode', 'opencode.db');
19
+ // OpenCode tool names → claudestat canonical names
20
+ const TOOL_NAME_MAP = {
21
+ glob: 'Glob', read: 'Read', write: 'Write', edit: 'Edit', bash: 'Bash',
22
+ grep: 'Grep', webfetch: 'WebFetch', websearch: 'WebSearch',
23
+ skill: 'Skill', agent: 'Agent', task: 'Task',
24
+ };
25
+ function mapToolName(raw) {
26
+ return TOOL_NAME_MAP[raw.toLowerCase()] ?? (raw.charAt(0).toUpperCase() + raw.slice(1));
27
+ }
28
+ function openDb() {
29
+ const { DatabaseSync } = require('node:sqlite');
30
+ return new DatabaseSync(OPENCODE_DB, { open: true });
31
+ }
32
+ exports.opencodeReaderRouter.get('/api/opencode/session/:id', (req, res) => {
33
+ if (!fs_1.default.existsSync(OPENCODE_DB)) {
34
+ res.status(404).json({ error: 'OpenCode DB not found' });
35
+ return;
36
+ }
37
+ try {
38
+ const { id: sessionId } = req.params;
39
+ const db = openDb();
40
+ // Get all messages for this session ordered by time
41
+ const messages = db.prepare(`
42
+ SELECT id, time_created, time_updated, data
43
+ FROM message
44
+ WHERE session_id = ?
45
+ ORDER BY time_created ASC
46
+ `).all(sessionId);
47
+ const events = [];
48
+ const prompts = [];
49
+ let totalParts = 0;
50
+ let blockIndex = 0;
51
+ let pendingPrompt = null;
52
+ // Accumulated state for the current assistant turn (may span multiple messages)
53
+ let turnHasTools = false;
54
+ let turnEndTs = 0;
55
+ let turnCwd = undefined;
56
+ function closeTurn() {
57
+ if (!turnHasTools)
58
+ return;
59
+ blockIndex++;
60
+ events.push({ type: 'Stop', ts: turnEndTs, cwd: turnCwd });
61
+ if (pendingPrompt) {
62
+ prompts.push({ index: blockIndex, ts: pendingPrompt.ts, text: pendingPrompt.text });
63
+ pendingPrompt = null;
64
+ }
65
+ turnHasTools = false;
66
+ turnEndTs = 0;
67
+ turnCwd = undefined;
68
+ }
69
+ for (const msg of messages) {
70
+ const msgData = JSON.parse(msg.data);
71
+ if (msgData.role === 'user') {
72
+ // Close previous assistant turn before processing user message
73
+ closeTurn();
74
+ const parts = db.prepare(`
75
+ SELECT data FROM part WHERE message_id = ? ORDER BY time_created ASC
76
+ `).all(msg.id);
77
+ const text = parts
78
+ .map(p => { try {
79
+ return JSON.parse(p.data);
80
+ }
81
+ catch {
82
+ return null;
83
+ } })
84
+ .filter((p) => p?.type === 'text' && typeof p.text === 'string')
85
+ .map(p => p.text)
86
+ .join('\n').trim();
87
+ if (text)
88
+ pendingPrompt = { ts: msg.time_created, text };
89
+ continue;
90
+ }
91
+ if (msgData.role !== 'assistant')
92
+ continue;
93
+ const cwd = msgData.path?.cwd;
94
+ const parts = db.prepare(`
95
+ SELECT time_created, time_updated, data
96
+ FROM part
97
+ WHERE message_id = ?
98
+ ORDER BY time_created ASC
99
+ `).all(msg.id);
100
+ for (const part of parts) {
101
+ totalParts++;
102
+ const partData = JSON.parse(part.data);
103
+ if (partData.type !== 'tool' || !partData.tool || !partData.state)
104
+ continue;
105
+ const toolName = mapToolName(partData.tool);
106
+ const toolInput = partData.state.input ? JSON.stringify(partData.state.input) : undefined;
107
+ const isCompleted = partData.state.status === 'completed';
108
+ turnHasTools = true;
109
+ turnCwd = cwd ?? turnCwd;
110
+ turnEndTs = Math.max(turnEndTs, part.time_updated);
111
+ events.push({
112
+ type: isCompleted ? 'Done' : 'PreToolUse',
113
+ tool_name: toolName,
114
+ tool_input: toolInput,
115
+ ts: part.time_created,
116
+ ...(isCompleted && { duration_ms: part.time_updated - part.time_created }),
117
+ cwd,
118
+ });
119
+ }
120
+ }
121
+ // Close the last assistant turn (no trailing user message)
122
+ closeTurn();
123
+ db.close();
124
+ res.json({ events, totalParts, prompts });
125
+ }
126
+ catch (err) {
127
+ res.status(500).json({ error: String(err) });
128
+ }
129
+ });
@@ -46,7 +46,7 @@ exports.streamRouter.get('/stream', (req, res) => {
46
46
  res.flushHeaders();
47
47
  const clientId = Math.random().toString(36).slice(2);
48
48
  sseClients.set(clientId, res);
49
- const latestSession = db_1.dbOps.getLatestSession();
49
+ const latestSession = db_1.dbOps.getLatestClaudeSession();
50
50
  if (latestSession) {
51
51
  const allEvents = db_1.dbOps.getSessionEvents(latestSession.id);
52
52
  const events = allEvents.length > SSE_INIT_EVENT_LIMIT
@@ -30,6 +30,16 @@ export interface WatcherAdapter {
30
30
  /** Nombre amigable para el badge de la CLI (ej: "CC", "Codex") */
31
31
  get shortName(): string;
32
32
  }
33
+ export interface PollSession {
34
+ sessionId: string;
35
+ cost: CostUpdate;
36
+ }
37
+ /** Adapters que no usan archivos JSONL sino una DB o API propia */
38
+ export interface PollableAdapter extends WatcherAdapter {
39
+ /** Devuelve sesiones actualizadas desde `since` (epoch ms) */
40
+ pollSessions(since: number): Promise<PollSession[]>;
41
+ }
42
+ export declare function isPollable(adapter: WatcherAdapter): adapter is PollableAdapter;
33
43
  export declare function registerAdapter(adapter: WatcherAdapter): void;
34
44
  export declare function getAdapter(name: string): WatcherAdapter | undefined;
35
45
  export declare function getAllAdapters(): WatcherAdapter[];
@@ -7,11 +7,15 @@
7
7
  * que claudestat las soporte todas con una interfaz común.
8
8
  */
9
9
  Object.defineProperty(exports, "__esModule", { value: true });
10
+ exports.isPollable = isPollable;
10
11
  exports.registerAdapter = registerAdapter;
11
12
  exports.getAdapter = getAdapter;
12
13
  exports.getAllAdapters = getAllAdapters;
13
14
  exports.getActiveAdapters = getActiveAdapters;
14
15
  exports.getAdapterNames = getAdapterNames;
16
+ function isPollable(adapter) {
17
+ return 'pollSessions' in adapter && typeof adapter.pollSessions === 'function';
18
+ }
15
19
  // ─── Factory ───────────────────────────────────────────────────────────────────
16
20
  const registry = new Map();
17
21
  function registerAdapter(adapter) {
@@ -1,9 +1,9 @@
1
1
  /**
2
- * opencode.ts — WatcherAdapter para OpenCode
2
+ * opencode.ts — WatcherAdapter para OpenCode (poll-based, SQLite)
3
3
  *
4
- * OpenCode stores traces in ~/.opencode/logs/ as JSONL files.
5
- * Format is similar to Claude Code but with different field names.
6
- * This is a scaffold fill in parseEvent/getSessionCost with sample traces.
4
+ * OpenCode stores sessions in ~/.local/share/opencode/opencode.db (SQLite).
5
+ * The session table has cost, token counts, model, and timestamps directly.
6
+ * Uses PollableAdapterno JSONL files, no chokidar.
7
7
  */
8
- import { type WatcherAdapter } from './adapter';
9
- export declare const opencodeAdapter: WatcherAdapter;
8
+ import { type PollableAdapter } from './adapter';
9
+ export declare const opencodeAdapter: PollableAdapter;
@@ -1,10 +1,10 @@
1
1
  "use strict";
2
2
  /**
3
- * opencode.ts — WatcherAdapter para OpenCode
3
+ * opencode.ts — WatcherAdapter para OpenCode (poll-based, SQLite)
4
4
  *
5
- * OpenCode stores traces in ~/.opencode/logs/ as JSONL files.
6
- * Format is similar to Claude Code but with different field names.
7
- * This is a scaffold fill in parseEvent/getSessionCost with sample traces.
5
+ * OpenCode stores sessions in ~/.local/share/opencode/opencode.db (SQLite).
6
+ * The session table has cost, token counts, model, and timestamps directly.
7
+ * Uses PollableAdapterno JSONL files, no chokidar.
8
8
  */
9
9
  var __importDefault = (this && this.__importDefault) || function (mod) {
10
10
  return (mod && mod.__esModule) ? mod : { "default": mod };
@@ -15,29 +15,69 @@ const path_1 = __importDefault(require("path"));
15
15
  const os_1 = __importDefault(require("os"));
16
16
  const fs_1 = __importDefault(require("fs"));
17
17
  const adapter_1 = require("./adapter");
18
- const OPENCODE_DIR = path_1.default.join(os_1.default.homedir(), '.opencode', 'logs');
18
+ const OPENCODE_DB = path_1.default.join(os_1.default.homedir(), '.local', 'share', 'opencode', 'opencode.db');
19
+ function openDb() {
20
+ const { DatabaseSync } = require('node:sqlite');
21
+ return new DatabaseSync(OPENCODE_DB, { open: true });
22
+ }
23
+ function parseModel(raw) {
24
+ if (!raw)
25
+ return 'unknown';
26
+ try {
27
+ const obj = JSON.parse(raw);
28
+ return obj.id ?? 'unknown';
29
+ }
30
+ catch {
31
+ return 'unknown';
32
+ }
33
+ }
19
34
  exports.opencodeAdapter = {
20
35
  name: 'opencode',
21
36
  label: 'OpenCode',
22
37
  get shortName() { return 'OC'; },
23
38
  detect() {
24
39
  try {
25
- return fs_1.default.existsSync(OPENCODE_DIR);
40
+ return fs_1.default.existsSync(OPENCODE_DB);
26
41
  }
27
42
  catch {
28
43
  return false;
29
44
  }
30
45
  },
31
46
  getWatchPaths() {
32
- return [`${OPENCODE_DIR}/**/*.jsonl`];
47
+ return [];
33
48
  },
34
49
  parseEvent(_raw, _filePath) {
35
- // TODO: implement when OpenCode trace format is known
36
50
  return null;
37
51
  },
38
52
  async getSessionCost(_filePath) {
39
- // TODO: implement when OpenCode trace format is known
40
53
  return null;
41
54
  },
55
+ async pollSessions(since) {
56
+ try {
57
+ const db = openDb();
58
+ const stmt = db.prepare(`SELECT id, model, cost, tokens_input, tokens_output, tokens_cache_read, tokens_cache_write, time_updated
59
+ FROM session
60
+ WHERE time_updated >= ?
61
+ AND time_archived IS NULL`);
62
+ const rows = stmt.all(since);
63
+ db.close();
64
+ return rows.map(row => ({
65
+ sessionId: row.id,
66
+ cost: {
67
+ input_tokens: row.tokens_input,
68
+ output_tokens: row.tokens_output,
69
+ cache_read: row.tokens_cache_read,
70
+ cache_creation: row.tokens_cache_write,
71
+ cost_usd: row.cost,
72
+ context_used: 0,
73
+ context_window: 200000,
74
+ lastModel: parseModel(row.model),
75
+ },
76
+ }));
77
+ }
78
+ catch {
79
+ return [];
80
+ }
81
+ },
42
82
  };
43
83
  (0, adapter_1.registerAdapter)(exports.opencodeAdapter);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@statforge/claudestat",
3
- "version": "1.5.1",
3
+ "version": "1.6.0",
4
4
  "private": false,
5
5
  "publishConfig": {
6
6
  "access": "public"