@statforge/claudestat 1.5.1 → 1.6.1

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)() });
@@ -246,7 +248,7 @@ function startDaemon() {
246
248
  process.on('SIGINT', () => { if (_server)
247
249
  shutdown(_server); process.exit(0); });
248
250
  console.log(`\n● claudestat daemon → http://localhost:${PORT}`);
249
- console.log(` Waiting for Claude Code events...\n`);
251
+ console.log(` Watching for events...\n`);
250
252
  console.log(` In another terminal: \x1b[36mclaudestat watch\x1b[0m\n`);
251
253
  // Weekly insight — se muestra una vez por semana al iniciar el daemon
252
254
  Promise.resolve().then(() => __importStar(require('./insights'))).then(({ getWeeklyInsightData, shouldShowInsight, markInsightShown, renderWeeklyInsight }) => {
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');
@@ -150,6 +159,8 @@ async function processLatestForSession(sessionId, onUpdate, source) {
150
159
  ? [(0, adapter_1.getAdapter)(source)].filter(Boolean)
151
160
  : (0, adapter_1.getActiveAdapters)();
152
161
  for (const adapter of adapters) {
162
+ if ((0, adapter_1.isPollable)(adapter))
163
+ continue;
153
164
  for (const watchPath of adapter.getWatchPaths()) {
154
165
  const baseDir = watchPath.split('/**')[0];
155
166
  if (!baseDir)
package/dist/paths.d.ts CHANGED
@@ -72,6 +72,11 @@ export declare function homeSlugRegex(): RegExp;
72
72
  * Windows: C:\Users\db → C--Users-db
73
73
  */
74
74
  export declare function getHomeSlug(): string;
75
+ /**
76
+ * Returns the OpenCode SQLite database path.
77
+ * Can be overridden via OPENCODE_DB env var.
78
+ */
79
+ export declare function getOpencodeDb(): string;
75
80
  /**
76
81
  * Returns the appropriate command to find an executable in PATH.
77
82
  * Unix: which <name>
package/dist/paths.js CHANGED
@@ -26,6 +26,7 @@ exports.encodeClaudePath = encodeClaudePath;
26
26
  exports.decodeClaudePath = decodeClaudePath;
27
27
  exports.homeSlugRegex = homeSlugRegex;
28
28
  exports.getHomeSlug = getHomeSlug;
29
+ exports.getOpencodeDb = getOpencodeDb;
29
30
  exports.whichCmd = whichCmd;
30
31
  exports.whichAllCmd = whichAllCmd;
31
32
  exports.portCheckCmd = portCheckCmd;
@@ -145,6 +146,14 @@ function homeSlugRegex() {
145
146
  function getHomeSlug() {
146
147
  return encodeClaudePath(os_1.default.homedir());
147
148
  }
149
+ // ─── OpenCode data directory ───────────────────────────────────────────────────
150
+ /**
151
+ * Returns the OpenCode SQLite database path.
152
+ * Can be overridden via OPENCODE_DB env var.
153
+ */
154
+ function getOpencodeDb() {
155
+ return process.env.OPENCODE_DB ?? path_1.default.join(os_1.default.homedir(), '.local', 'share', 'opencode', 'opencode.db');
156
+ }
148
157
  // ─── Platform utilities ────────────────────────────────────────────────────────
149
158
  /**
150
159
  * Returns the appropriate command to find an executable in PATH.
@@ -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 ?? 'unknown';
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,127 @@
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 fs_1 = __importDefault(require("fs"));
14
+ const express_1 = require("express");
15
+ const paths_1 = require("../paths");
16
+ exports.opencodeReaderRouter = (0, express_1.Router)();
17
+ // OpenCode tool names → claudestat canonical names
18
+ const TOOL_NAME_MAP = {
19
+ glob: 'Glob', read: 'Read', write: 'Write', edit: 'Edit', bash: 'Bash',
20
+ grep: 'Grep', webfetch: 'WebFetch', websearch: 'WebSearch',
21
+ skill: 'Skill', agent: 'Agent', task: 'Task',
22
+ };
23
+ function mapToolName(raw) {
24
+ return TOOL_NAME_MAP[raw.toLowerCase()] ?? (raw.charAt(0).toUpperCase() + raw.slice(1));
25
+ }
26
+ function openDb() {
27
+ const { DatabaseSync } = require('node:sqlite');
28
+ return new DatabaseSync((0, paths_1.getOpencodeDb)(), { open: true });
29
+ }
30
+ exports.opencodeReaderRouter.get('/api/opencode/session/:id', (req, res) => {
31
+ if (!fs_1.default.existsSync((0, paths_1.getOpencodeDb)())) {
32
+ res.status(404).json({ error: 'OpenCode DB not found' });
33
+ return;
34
+ }
35
+ try {
36
+ const { id: sessionId } = req.params;
37
+ const db = openDb();
38
+ // Get all messages for this session ordered by time
39
+ const messages = db.prepare(`
40
+ SELECT id, time_created, time_updated, data
41
+ FROM message
42
+ WHERE session_id = ?
43
+ ORDER BY time_created ASC
44
+ `).all(sessionId);
45
+ const events = [];
46
+ const prompts = [];
47
+ let totalParts = 0;
48
+ let blockIndex = 0;
49
+ let pendingPrompt = null;
50
+ // Accumulated state for the current assistant turn (may span multiple messages)
51
+ let turnHasTools = false;
52
+ let turnEndTs = 0;
53
+ let turnCwd = undefined;
54
+ function closeTurn() {
55
+ if (!turnHasTools)
56
+ return;
57
+ blockIndex++;
58
+ events.push({ type: 'Stop', ts: turnEndTs, cwd: turnCwd });
59
+ if (pendingPrompt) {
60
+ prompts.push({ index: blockIndex, ts: pendingPrompt.ts, text: pendingPrompt.text });
61
+ pendingPrompt = null;
62
+ }
63
+ turnHasTools = false;
64
+ turnEndTs = 0;
65
+ turnCwd = undefined;
66
+ }
67
+ for (const msg of messages) {
68
+ const msgData = JSON.parse(msg.data);
69
+ if (msgData.role === 'user') {
70
+ // Close previous assistant turn before processing user message
71
+ closeTurn();
72
+ const parts = db.prepare(`
73
+ SELECT data FROM part WHERE message_id = ? ORDER BY time_created ASC
74
+ `).all(msg.id);
75
+ const text = parts
76
+ .map(p => { try {
77
+ return JSON.parse(p.data);
78
+ }
79
+ catch {
80
+ return null;
81
+ } })
82
+ .filter((p) => p?.type === 'text' && typeof p.text === 'string')
83
+ .map(p => p.text)
84
+ .join('\n').trim();
85
+ if (text)
86
+ pendingPrompt = { ts: msg.time_created, text };
87
+ continue;
88
+ }
89
+ if (msgData.role !== 'assistant')
90
+ continue;
91
+ const cwd = msgData.path?.cwd;
92
+ const parts = db.prepare(`
93
+ SELECT time_created, time_updated, data
94
+ FROM part
95
+ WHERE message_id = ?
96
+ ORDER BY time_created ASC
97
+ `).all(msg.id);
98
+ for (const part of parts) {
99
+ totalParts++;
100
+ const partData = JSON.parse(part.data);
101
+ if (partData.type !== 'tool' || !partData.tool || !partData.state)
102
+ continue;
103
+ const toolName = mapToolName(partData.tool);
104
+ const toolInput = partData.state.input ? JSON.stringify(partData.state.input) : undefined;
105
+ const isCompleted = partData.state.status === 'completed';
106
+ turnHasTools = true;
107
+ turnCwd = cwd ?? turnCwd;
108
+ turnEndTs = Math.max(turnEndTs, part.time_updated);
109
+ events.push({
110
+ type: isCompleted ? 'Done' : 'PreToolUse',
111
+ tool_name: toolName,
112
+ tool_input: toolInput,
113
+ ts: part.time_created,
114
+ ...(isCompleted && { duration_ms: part.time_updated - part.time_created }),
115
+ cwd,
116
+ });
117
+ }
118
+ }
119
+ // Close the last assistant turn (no trailing user message)
120
+ closeTurn();
121
+ db.close();
122
+ res.json({ events, totalParts, prompts });
123
+ }
124
+ catch (err) {
125
+ res.status(500).json({ error: String(err) });
126
+ }
127
+ });
@@ -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,43 +1,83 @@
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 };
11
11
  };
12
12
  Object.defineProperty(exports, "__esModule", { value: true });
13
13
  exports.opencodeAdapter = void 0;
14
- const path_1 = __importDefault(require("path"));
15
- const os_1 = __importDefault(require("os"));
16
14
  const fs_1 = __importDefault(require("fs"));
17
15
  const adapter_1 = require("./adapter");
18
- const OPENCODE_DIR = path_1.default.join(os_1.default.homedir(), '.opencode', 'logs');
16
+ const paths_1 = require("../paths");
17
+ function openDb() {
18
+ const { DatabaseSync } = require('node:sqlite');
19
+ return new DatabaseSync((0, paths_1.getOpencodeDb)(), { open: true });
20
+ }
21
+ function parseModel(raw) {
22
+ if (!raw)
23
+ return 'unknown';
24
+ try {
25
+ const obj = JSON.parse(raw);
26
+ return obj.id ?? 'unknown';
27
+ }
28
+ catch {
29
+ return 'unknown';
30
+ }
31
+ }
19
32
  exports.opencodeAdapter = {
20
33
  name: 'opencode',
21
34
  label: 'OpenCode',
22
35
  get shortName() { return 'OC'; },
23
36
  detect() {
24
37
  try {
25
- return fs_1.default.existsSync(OPENCODE_DIR);
38
+ return fs_1.default.existsSync((0, paths_1.getOpencodeDb)());
26
39
  }
27
40
  catch {
28
41
  return false;
29
42
  }
30
43
  },
31
44
  getWatchPaths() {
32
- return [`${OPENCODE_DIR}/**/*.jsonl`];
45
+ return [];
33
46
  },
34
47
  parseEvent(_raw, _filePath) {
35
- // TODO: implement when OpenCode trace format is known
36
48
  return null;
37
49
  },
38
50
  async getSessionCost(_filePath) {
39
- // TODO: implement when OpenCode trace format is known
40
51
  return null;
41
52
  },
53
+ async pollSessions(since) {
54
+ let db = null;
55
+ try {
56
+ db = openDb();
57
+ const rows = db.prepare(`SELECT id, model, cost, tokens_input, tokens_output, tokens_cache_read, tokens_cache_write, time_updated
58
+ FROM session
59
+ WHERE time_updated >= ?
60
+ AND time_archived IS NULL`).all(since);
61
+ return rows.map(row => ({
62
+ sessionId: row.id,
63
+ cost: {
64
+ input_tokens: row.tokens_input,
65
+ output_tokens: row.tokens_output,
66
+ cache_read: row.tokens_cache_read,
67
+ cache_creation: row.tokens_cache_write,
68
+ cost_usd: row.cost,
69
+ context_used: 0,
70
+ context_window: 200000,
71
+ lastModel: parseModel(row.model),
72
+ },
73
+ }));
74
+ }
75
+ catch {
76
+ return [];
77
+ }
78
+ finally {
79
+ db?.close();
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.1",
4
4
  "private": false,
5
5
  "publishConfig": {
6
6
  "access": "public"