@geoqiao/pi-usage 0.1.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.
Files changed (62) hide show
  1. package/LICENSE +22 -0
  2. package/README.md +222 -0
  3. package/bin/pi-usage.js +69 -0
  4. package/data/models.dev-LICENSE +21 -0
  5. package/data/prices.json +2678 -0
  6. package/extensions/usage-report.js +36 -0
  7. package/package.json +51 -0
  8. package/src/analytics.js +189 -0
  9. package/src/collect.js +34 -0
  10. package/src/network.js +25 -0
  11. package/src/report.js +43 -0
  12. package/vendor/vibe-usage/NOTICE.md +58 -0
  13. package/vendor/vibe-usage/src/cindy-roots.js +85 -0
  14. package/vendor/vibe-usage/src/claude-roots.js +165 -0
  15. package/vendor/vibe-usage/src/cline-roots.js +40 -0
  16. package/vendor/vibe-usage/src/codex-roots.js +46 -0
  17. package/vendor/vibe-usage/src/craft-roots.js +15 -0
  18. package/vendor/vibe-usage/src/extra-roots.js +312 -0
  19. package/vendor/vibe-usage/src/parsers/aggregate.js +196 -0
  20. package/vendor/vibe-usage/src/parsers/alma.js +94 -0
  21. package/vendor/vibe-usage/src/parsers/amp.js +156 -0
  22. package/vendor/vibe-usage/src/parsers/antigravity-db.js +359 -0
  23. package/vendor/vibe-usage/src/parsers/antigravity.js +530 -0
  24. package/vendor/vibe-usage/src/parsers/cindy-ledger.js +157 -0
  25. package/vendor/vibe-usage/src/parsers/claude-code.js +372 -0
  26. package/vendor/vibe-usage/src/parsers/cline.js +92 -0
  27. package/vendor/vibe-usage/src/parsers/codex-cache.js +138 -0
  28. package/vendor/vibe-usage/src/parsers/codex.js +1198 -0
  29. package/vendor/vibe-usage/src/parsers/contract.js +55 -0
  30. package/vendor/vibe-usage/src/parsers/copilot-cli.js +128 -0
  31. package/vendor/vibe-usage/src/parsers/craft-agent.js +21 -0
  32. package/vendor/vibe-usage/src/parsers/cursor.js +262 -0
  33. package/vendor/vibe-usage/src/parsers/dimagent.js +127 -0
  34. package/vendor/vibe-usage/src/parsers/droid.js +113 -0
  35. package/vendor/vibe-usage/src/parsers/dsh.js +563 -0
  36. package/vendor/vibe-usage/src/parsers/fs-utils.js +36 -0
  37. package/vendor/vibe-usage/src/parsers/gemini-cli.js +190 -0
  38. package/vendor/vibe-usage/src/parsers/grok.js +395 -0
  39. package/vendor/vibe-usage/src/parsers/hermes.js +123 -0
  40. package/vendor/vibe-usage/src/parsers/index.js +61 -0
  41. package/vendor/vibe-usage/src/parsers/kimi-code.js +467 -0
  42. package/vendor/vibe-usage/src/parsers/kiro.js +788 -0
  43. package/vendor/vibe-usage/src/parsers/mcode.js +182 -0
  44. package/vendor/vibe-usage/src/parsers/mimocode.js +88 -0
  45. package/vendor/vibe-usage/src/parsers/omp.js +10 -0
  46. package/vendor/vibe-usage/src/parsers/openclaw.js +142 -0
  47. package/vendor/vibe-usage/src/parsers/opencode.js +151 -0
  48. package/vendor/vibe-usage/src/parsers/pi-coding-agent.js +27 -0
  49. package/vendor/vibe-usage/src/parsers/pi-session-jsonl.js +166 -0
  50. package/vendor/vibe-usage/src/parsers/qwen-code.js +122 -0
  51. package/vendor/vibe-usage/src/parsers/roo-code.js +123 -0
  52. package/vendor/vibe-usage/src/parsers/sqlite.js +148 -0
  53. package/vendor/vibe-usage/src/parsers/trae-cli.js +171 -0
  54. package/vendor/vibe-usage/src/parsers/workbuddy.js +322 -0
  55. package/vendor/vibe-usage/src/parsers/zcode.js +115 -0
  56. package/vendor/vibe-usage/src/pi-roots.js +125 -0
  57. package/vendor/vibe-usage/src/tools.js +422 -0
  58. package/vendor/vibe-usage/src/workbuddy-roots.js +22 -0
  59. package/vendor/vibe-usage/upstream-files.json +48 -0
  60. package/web/report.css +10 -0
  61. package/web/report.html +81 -0
  62. package/web/report.js +310 -0
@@ -0,0 +1,171 @@
1
+ import { createReadStream, existsSync, readdirSync } from 'node:fs';
2
+ import { createInterface } from 'node:readline';
3
+ import { join } from 'node:path';
4
+ import { findTraeCliDataDirs } from '../tools.js';
5
+ import { aggregateToBuckets, extractSessions } from './aggregate.js';
6
+ import { readJsonSafe, projectFromPath } from './fs-utils.js';
7
+
8
+ // Trae writes each LLM call as several nested spans that share one session-level
9
+ // traceID and copy the same usage onto every layer:
10
+ // model.stream.eino (authoritative: includes reasoning tokens)
11
+ // model.real_call (duplicate)
12
+ // model.call (duplicate)
13
+ // model.generate is a separate failover call (different model), not a duplicate.
14
+ // Counting every layer would 3x; merging by traceID with max() collapses a
15
+ // whole session of sequential calls into a single request. Keep one unique
16
+ // layer per call, then SUM.
17
+ const PRIMARY_LLM_CATEGORY = 'model.stream.eino';
18
+ const FAILOVER_LLM_CATEGORY = 'model.generate';
19
+ const FALLBACK_LLM_CATEGORIES = ['model.real_call', 'model.call'];
20
+
21
+ function tagMapFrom(tags) {
22
+ const tagMap = {};
23
+ if (!Array.isArray(tags)) return tagMap;
24
+ for (const t of tags) {
25
+ if (t && typeof t === 'object' && t.key) tagMap[t.key] = t.value;
26
+ }
27
+ return tagMap;
28
+ }
29
+
30
+ function spanCategory(tagMap) {
31
+ return typeof tagMap['span.category'] === 'string' ? tagMap['span.category'] : '';
32
+ }
33
+
34
+ function usageFromTagMap(tagMap) {
35
+ const inputTokens = Math.max(0, Number(tagMap['usage.input_tokens']) || 0);
36
+ const outputTokens = Math.max(0, Number(tagMap['usage.output_tokens']) || 0);
37
+ const cacheReadTokens = Math.max(0, Number(tagMap['usage.cache_read_tokens']) || 0);
38
+ const reasoningTokens = Math.max(0, Number(tagMap['usage.reasoning_tokens']) || 0);
39
+ return { inputTokens, outputTokens, cacheReadTokens, reasoningTokens };
40
+ }
41
+
42
+ function hasUsage(usage) {
43
+ return usage.inputTokens + usage.outputTokens + usage.cacheReadTokens + usage.reasoningTokens > 0;
44
+ }
45
+
46
+ /**
47
+ * Pick the unique LLM-call spans from a session's traces.
48
+ * Prefer model.stream.eino (+ model.generate failovers). If a session has no
49
+ * primary layer (older traces), fall back to model.real_call, then model.call.
50
+ * @param {{category: string, usage: object, model: string|null, startTime: number}[]} spans
51
+ */
52
+ export function selectTraeUsageSpans(spans) {
53
+ const withUsage = spans.filter((s) => hasUsage(s.usage));
54
+ const primary = withUsage.filter((s) => s.category === PRIMARY_LLM_CATEGORY);
55
+ const failover = withUsage.filter((s) => s.category === FAILOVER_LLM_CATEGORY);
56
+ if (primary.length > 0 || failover.length > 0) return primary.concat(failover);
57
+ for (const cat of FALLBACK_LLM_CATEGORIES) {
58
+ const subset = withUsage.filter((s) => s.category === cat);
59
+ if (subset.length > 0) return subset;
60
+ }
61
+ return withUsage;
62
+ }
63
+
64
+ /** Stream a JSONL file line by line. Skips missing files and malformed lines. */
65
+ export async function forEachJsonl(path, onObj) {
66
+ if (!existsSync(path)) return;
67
+ const stream = createReadStream(path, { encoding: 'utf8' });
68
+ const lines = createInterface({ input: stream, crlfDelay: Infinity });
69
+ try {
70
+ for await (const line of lines) {
71
+ const trimmed = line.trim();
72
+ if (!trimmed) continue;
73
+ let obj;
74
+ try {
75
+ obj = JSON.parse(trimmed);
76
+ } catch {
77
+ continue;
78
+ }
79
+ if (obj && typeof obj === 'object') onObj(obj);
80
+ }
81
+ } finally {
82
+ lines.close();
83
+ stream.destroy();
84
+ }
85
+ }
86
+
87
+ export async function parse() {
88
+ const cacheDirs = findTraeCliDataDirs();
89
+ if (cacheDirs.length === 0) return { buckets: [], sessions: [] };
90
+
91
+ const entries = [];
92
+ const events = [];
93
+
94
+ for (const cacheDir of cacheDirs) {
95
+ let sessionDirs = [];
96
+ try {
97
+ sessionDirs = readdirSync(cacheDir, { withFileTypes: true })
98
+ .filter(entry => entry.isDirectory())
99
+ .map(entry => entry.name);
100
+ } catch {
101
+ continue;
102
+ }
103
+
104
+ for (const sessionId of sessionDirs) {
105
+ const sessionPath = join(cacheDir, sessionId);
106
+ const sessionJson = readJsonSafe(join(sessionPath, 'session.json')) || {};
107
+ const project = projectFromPath(sessionJson.metadata?.cwd);
108
+ const fallbackModel = sessionJson.metadata?.model_name || 'trae-unknown';
109
+
110
+ const spans = [];
111
+ await forEachJsonl(join(sessionPath, 'traces.jsonl'), (line) => {
112
+ const tagMap = tagMapFrom(line.tags);
113
+ const usage = usageFromTagMap(tagMap);
114
+ if (!hasUsage(usage)) return;
115
+ const startTime = Number(line.startTime);
116
+ if (!Number.isFinite(startTime) || startTime <= 0) return;
117
+ spans.push({
118
+ category: spanCategory(tagMap),
119
+ model: tagMap['model.name'] || tagMap['semantic.name'] || null,
120
+ startTime,
121
+ usage,
122
+ });
123
+ });
124
+
125
+ for (const span of selectTraeUsageSpans(spans)) {
126
+ // Trae startTime is microseconds; Date expects milliseconds.
127
+ const timestamp = new Date(span.startTime / 1000);
128
+ if (Number.isNaN(timestamp.getTime())) continue;
129
+ entries.push({
130
+ source: 'trae-cli',
131
+ model: span.model || fallbackModel,
132
+ project,
133
+ timestamp,
134
+ inputTokens: span.usage.inputTokens,
135
+ outputTokens: span.usage.outputTokens,
136
+ cachedInputTokens: span.usage.cacheReadTokens,
137
+ reasoningOutputTokens: span.usage.reasoningTokens,
138
+ });
139
+ }
140
+
141
+ await forEachJsonl(join(sessionPath, 'events.jsonl'), (line) => {
142
+ if (!line.created_at) return;
143
+ const timestamp = new Date(line.created_at);
144
+ if (Number.isNaN(timestamp.getTime())) return;
145
+
146
+ if (line.agent_start) {
147
+ events.push({
148
+ sessionId,
149
+ source: 'trae-cli',
150
+ project,
151
+ timestamp,
152
+ role: 'user',
153
+ });
154
+ } else if (line.agent_end || line.tool_call || (line.message && line.message.message?.role === 'assistant')) {
155
+ events.push({
156
+ sessionId,
157
+ source: 'trae-cli',
158
+ project,
159
+ timestamp,
160
+ role: 'assistant',
161
+ });
162
+ }
163
+ });
164
+ }
165
+ }
166
+
167
+ return {
168
+ buckets: aggregateToBuckets(entries),
169
+ sessions: extractSessions(events),
170
+ };
171
+ }
@@ -0,0 +1,322 @@
1
+ import { createReadStream, readdirSync, statSync } from 'node:fs';
2
+ import { createInterface } from 'node:readline';
3
+ import { basename, join, relative, sep } from 'node:path';
4
+ import { findWorkbuddyDataDirs } from '../workbuddy-roots.js';
5
+ import { aggregateToBuckets, extractSessions } from './aggregate.js';
6
+
7
+ const SOURCE = 'workbuddy';
8
+ const MAX_WARNINGS = 20;
9
+
10
+ function warn(ctx, message) {
11
+ ctx.skipped = true;
12
+ if (ctx.warnings.length < MAX_WARNINGS && !ctx.warnings.includes(message)) {
13
+ ctx.warnings.push(message);
14
+ }
15
+ }
16
+
17
+ function finite(value) {
18
+ const number = Number(value);
19
+ return Number.isFinite(number) && number >= 0 ? number : 0;
20
+ }
21
+
22
+ function dateFrom(value) {
23
+ if (value instanceof Date && !Number.isNaN(value.getTime())) return value;
24
+ if (typeof value === 'number' && Number.isFinite(value)) {
25
+ const date = new Date(value < 1e12 ? value * 1000 : value);
26
+ return Number.isNaN(date.getTime()) ? null : date;
27
+ }
28
+ if (typeof value === 'string' && value.trim()) {
29
+ const date = new Date(value);
30
+ return Number.isNaN(date.getTime()) ? null : date;
31
+ }
32
+ return null;
33
+ }
34
+
35
+ function projectFromFile(filePath, projectsDir) {
36
+ const first = relative(projectsDir, filePath).split(sep).filter(Boolean)[0];
37
+ return first ? basename(first) : 'unknown';
38
+ }
39
+
40
+ function projectFromRecord(record) {
41
+ const cwd = typeof record.cwd === 'string' ? record.cwd.trim() : '';
42
+ if (!cwd) return null;
43
+ const parts = cwd
44
+ .replace(/[\\/]+$/, '')
45
+ .split(/[\\/]/)
46
+ .filter(Boolean)
47
+ .filter(part => !/^[a-zA-Z]:$/.test(part));
48
+ return parts.at(-1) || null;
49
+ }
50
+
51
+ function findJsonlFiles(dir, ctx) {
52
+ let children;
53
+ try {
54
+ children = readdirSync(dir, { withFileTypes: true })
55
+ .sort((a, b) => a.name.localeCompare(b.name));
56
+ } catch (error) {
57
+ if (error?.code === 'ENOENT') return [];
58
+ warn(ctx, 'workbuddy: cannot read a data directory');
59
+ return [];
60
+ }
61
+
62
+ const files = [];
63
+ for (const child of children) {
64
+ const filePath = join(dir, child.name);
65
+ if (child.isDirectory()) {
66
+ for (const nested of findJsonlFiles(filePath, ctx)) files.push(nested);
67
+ } else if (child.isFile() && child.name.endsWith('.jsonl')) {
68
+ files.push(filePath);
69
+ }
70
+ }
71
+ return files;
72
+ }
73
+
74
+ async function readJsonl(filePath, size, onRecord, ctx) {
75
+ if (size <= 0) return;
76
+ const stream = createReadStream(filePath, {
77
+ encoding: 'utf8',
78
+ start: 0,
79
+ end: size - 1,
80
+ });
81
+ let streamError = null;
82
+ stream.on('error', error => { streamError = error; });
83
+ const lines = createInterface({ input: stream, crlfDelay: Infinity });
84
+
85
+ try {
86
+ for await (const line of lines) {
87
+ if (!line.trim()) continue;
88
+ let record;
89
+ try {
90
+ record = JSON.parse(line);
91
+ } catch {
92
+ continue;
93
+ }
94
+ if (record && typeof record === 'object') onRecord(record);
95
+ }
96
+ if (streamError) throw streamError;
97
+ } catch {
98
+ warn(ctx, 'workbuddy: cannot read a session file');
99
+ } finally {
100
+ lines.close();
101
+ stream.destroy();
102
+ }
103
+ }
104
+
105
+ function recordId(record) {
106
+ if (typeof record.id !== 'string' && typeof record.id !== 'number') return null;
107
+ const id = String(record.id).trim();
108
+ return id || null;
109
+ }
110
+
111
+ function roleFor(record) {
112
+ const role = record.role ?? record.message?.role;
113
+ if (role === 'user') return 'user';
114
+ if (role === 'assistant' || role === 'assistant_message') return 'assistant';
115
+ return null;
116
+ }
117
+
118
+ function isCompletedAssistant(record) {
119
+ if (record.type !== 'message' || roleFor(record) !== 'assistant') return false;
120
+ const status = String(
121
+ record.status ?? record.message?.status ?? record.state ?? record.message?.state ?? ''
122
+ ).toLowerCase();
123
+ return status === 'completed' || status === 'complete' || status === 'success';
124
+ }
125
+
126
+ function isUsageRecord(record) {
127
+ return isCompletedAssistant(record)
128
+ || (record.type === 'function_call'
129
+ && record.providerData
130
+ && typeof record.providerData === 'object');
131
+ }
132
+
133
+ function modelFor(record) {
134
+ const providerData = record.providerData && typeof record.providerData === 'object'
135
+ ? record.providerData
136
+ : {};
137
+ for (const value of [
138
+ providerData.requestModelId,
139
+ record.requestModelName,
140
+ providerData.requestModelName,
141
+ providerData.model,
142
+ ]) {
143
+ if (typeof value === 'string' && value.trim()) return value.trim();
144
+ }
145
+ return 'unknown';
146
+ }
147
+
148
+ function firstDetailValue(details, ...keys) {
149
+ for (const detail of Array.isArray(details) ? details : [details]) {
150
+ if (!detail || typeof detail !== 'object') continue;
151
+ for (const key of keys) {
152
+ if (detail[key] != null) return finite(detail[key]);
153
+ }
154
+ }
155
+ return 0;
156
+ }
157
+
158
+ function usageFor(record) {
159
+ const providerData = record.providerData && typeof record.providerData === 'object'
160
+ ? record.providerData
161
+ : {};
162
+ const primary = providerData.usage && typeof providerData.usage === 'object'
163
+ ? providerData.usage
164
+ : record.message?.usage && typeof record.message.usage === 'object'
165
+ ? record.message.usage
166
+ : null;
167
+ const raw = providerData.rawUsage && typeof providerData.rawUsage === 'object'
168
+ ? providerData.rawUsage
169
+ : null;
170
+ if (!primary && !raw) return null;
171
+
172
+ const inputDetails = primary?.input_details
173
+ ?? primary?.inputDetails
174
+ ?? primary?.inputTokensDetails
175
+ ?? raw?.prompt_tokens_details;
176
+ const outputDetails = primary?.output_details
177
+ ?? primary?.outputDetails
178
+ ?? primary?.outputTokensDetails
179
+ ?? raw?.completion_tokens_details;
180
+ const cachedInputTokens = firstDetailValue(inputDetails, 'cached_tokens', 'cachedTokens')
181
+ || finite(
182
+ primary?.cachedInputTokens
183
+ ?? primary?.cache_read_input_tokens
184
+ ?? primary?.cacheReadInputTokens
185
+ ?? raw?.prompt_cache_hit_tokens
186
+ ?? raw?.cache_read_input_tokens
187
+ );
188
+ const reasoningOutputTokens = firstDetailValue(outputDetails, 'reasoning_tokens', 'reasoningTokens')
189
+ || finite(
190
+ primary?.reasoningOutputTokens
191
+ ?? primary?.completion_thinking_tokens
192
+ ?? primary?.reasoning_tokens
193
+ ?? primary?.reasoningTokens
194
+ ?? raw?.completion_thinking_tokens
195
+ );
196
+ const inclusiveInput = finite(primary?.inputTokens ?? primary?.input_tokens ?? raw?.prompt_tokens);
197
+ const inclusiveOutput = finite(primary?.outputTokens ?? primary?.output_tokens ?? raw?.completion_tokens);
198
+ const cacheMiss = finite(raw?.prompt_cache_miss_tokens);
199
+
200
+ // WorkBuddy's aggregate input/output fields include cache reads/reasoning.
201
+ // Prefer the provider's exclusive cache-miss field when available.
202
+ const inputTokens = cacheMiss > 0
203
+ ? cacheMiss
204
+ : Math.max(0, inclusiveInput - cachedInputTokens);
205
+ const outputTokens = Math.max(0, inclusiveOutput - reasoningOutputTokens);
206
+ const score = inputTokens + outputTokens + cachedInputTokens + reasoningOutputTokens;
207
+ if (score === 0) return null;
208
+
209
+ return {
210
+ inputTokens,
211
+ outputTokens,
212
+ cachedInputTokens,
213
+ reasoningOutputTokens,
214
+ score,
215
+ };
216
+ }
217
+
218
+ function timestampFor(record) {
219
+ return dateFrom(
220
+ record.completedAt
221
+ ?? record.completed_at
222
+ ?? record.timestamp
223
+ ?? record.createdAt
224
+ ?? record.created_at
225
+ ?? record.message?.createdAt
226
+ );
227
+ }
228
+
229
+ function sessionEventsWithPrompts(events) {
230
+ const sessionsWithUsers = new Set(
231
+ events.filter(event => event.role === 'user').map(event => event.sessionId)
232
+ );
233
+ return events.filter(event => sessionsWithUsers.has(event.sessionId));
234
+ }
235
+
236
+ export async function parse() {
237
+ const entriesById = new Map();
238
+ const eventsByKey = new Map();
239
+ const ctx = { skipped: false, warnings: [] };
240
+ const projectDirs = [...new Set(findWorkbuddyDataDirs().map(root => (
241
+ basename(root) === 'projects' ? root : join(root, 'projects')
242
+ )))];
243
+
244
+ for (const projectsDir of projectDirs) {
245
+ for (const filePath of findJsonlFiles(projectsDir, ctx)) {
246
+ let size;
247
+ try {
248
+ size = statSync(filePath).size;
249
+ } catch {
250
+ warn(ctx, 'workbuddy: cannot stat a session file');
251
+ continue;
252
+ }
253
+
254
+ const fallbackSessionId = basename(filePath, '.jsonl');
255
+ let project = projectFromFile(filePath, projectsDir);
256
+ const fileEntries = [];
257
+ const fileEvents = [];
258
+
259
+ await readJsonl(filePath, size, record => {
260
+ project = projectFromRecord(record) || project;
261
+ const timestamp = timestampFor(record);
262
+ const id = recordId(record);
263
+ const role = roleFor(record);
264
+ const explicitSessionId = record.sessionId ?? record.session_id;
265
+ const sessionId = explicitSessionId == null || String(explicitSessionId).trim() === ''
266
+ ? fallbackSessionId
267
+ : String(explicitSessionId);
268
+
269
+ const usage = isUsageRecord(record) ? usageFor(record) : null;
270
+ const eventRole = role === 'user'
271
+ ? 'user'
272
+ : isCompletedAssistant(record) || (record.type === 'function_call' && usage)
273
+ ? 'assistant'
274
+ : null;
275
+ if (timestamp && eventRole) {
276
+ fileEvents.push({ id, sessionId, timestamp, role: eventRole });
277
+ }
278
+
279
+ if (!id || !timestamp || !usage) return;
280
+ fileEntries.push({
281
+ id,
282
+ score: usage.score,
283
+ entry: {
284
+ source: SOURCE,
285
+ model: modelFor(record),
286
+ timestamp,
287
+ inputTokens: usage.inputTokens,
288
+ outputTokens: usage.outputTokens,
289
+ cachedInputTokens: usage.cachedInputTokens,
290
+ reasoningOutputTokens: usage.reasoningOutputTokens,
291
+ },
292
+ });
293
+ }, ctx);
294
+
295
+ for (const candidate of fileEntries) {
296
+ candidate.entry.project = project;
297
+ const current = entriesById.get(candidate.id);
298
+ if (!current || candidate.score > current.score) entriesById.set(candidate.id, candidate);
299
+ }
300
+ for (const candidate of fileEvents) {
301
+ const event = {
302
+ sessionId: candidate.sessionId,
303
+ source: SOURCE,
304
+ project,
305
+ timestamp: candidate.timestamp,
306
+ role: candidate.role,
307
+ };
308
+ const key = candidate.id
309
+ ? `id:${candidate.sessionId}:${candidate.id}:${candidate.role}`
310
+ : `fallback:${candidate.sessionId}:${candidate.role}:${candidate.timestamp.toISOString()}`;
311
+ eventsByKey.set(key, event);
312
+ }
313
+ }
314
+ }
315
+
316
+ return {
317
+ buckets: aggregateToBuckets([...entriesById.values()].map(({ entry }) => entry)),
318
+ sessions: extractSessions(sessionEventsWithPrompts([...eventsByKey.values()])),
319
+ ...(ctx.skipped ? { skipped: true } : {}),
320
+ ...(ctx.warnings.length > 0 ? { warnings: ctx.warnings } : {}),
321
+ };
322
+ }
@@ -0,0 +1,115 @@
1
+ import { existsSync } from 'node:fs';
2
+ import { join, basename } from 'node:path';
3
+ import { homedir } from 'node:os';
4
+ import { aggregateToBuckets, extractSessions } from './aggregate.js';
5
+ import { queryDbJson, sqliteUnavailableError, isSqliteUnavailableError } from './sqlite.js';
6
+
7
+ // ZCode (z.ai / Zhipu's coding agent) stores everything in a SQLite database
8
+ // at ~/.zcode/cli/db/db.sqlite. The `message` table is the canonical source:
9
+ // each row is one user or assistant message, with an assistant message carrying
10
+ // per-request token usage and the working directory. We read it directly rather
11
+ // than the parallel `model_usage` ledger because `message` gives us BOTH session
12
+ // timing (user + assistant rows) and token usage in one pass, with the project
13
+ // path attached to each message.
14
+ const DB_PATH = join(homedir(), '.zcode', 'cli', 'db', 'db.sqlite');
15
+
16
+ /**
17
+ * Project name from a ZCode message's path. ZCode records both `cwd` and `root`;
18
+ * prefer `root` (the workspace root) and fall back to `cwd`, then to the
19
+ * session's `directory` column (joined in via the query) — taking the last path
20
+ * component, matching how every other parser names projects.
21
+ */
22
+ function projectName(root, cwd, sessionDir) {
23
+ const p = root || cwd || sessionDir;
24
+ if (!p) return 'unknown';
25
+ return basename(String(p).replace(/[/\\]+$/, '')) || 'unknown';
26
+ }
27
+
28
+ export async function parse({ dbPath = DB_PATH } = {}) {
29
+ if (!existsSync(dbPath)) return { buckets: [], sessions: [] };
30
+
31
+ // Older databases may not have parts. Absence of a table is not evidence
32
+ // of absence of tools. EXISTS preserves one usage row even for parallel calls.
33
+ const columns = queryDbJson(dbPath, 'PRAGMA table_info(part)').map(row => row.name);
34
+ const hasParts = ['message_id', 'data'].every(name => columns.includes(name));
35
+ const requestType = hasParts ? `CASE
36
+ WHEN EXISTS (SELECT 1 FROM part p WHERE p.message_id = m.id
37
+ AND CASE WHEN json_valid(p.data) THEN json_extract(p.data, '$.type') = 'tool' ELSE 0 END) THEN 'tool'
38
+ WHEN json_extract(m.data, '$.finish') = 'stop'
39
+ AND NOT EXISTS (SELECT 1 FROM part p WHERE p.message_id = m.id AND NOT json_valid(p.data)) THEN 'non_tool'
40
+ ELSE 'other' END` : "'other'";
41
+
42
+ // Join each message to its session so we can fall back to the session's
43
+ // directory when an individual message has no path (older rows, lite agents).
44
+ const query = `SELECT
45
+ ${requestType} AS requestType,
46
+ m.session_id AS sessionId,
47
+ m.time_created AS created,
48
+ json_extract(m.data, '$.role') AS role,
49
+ json_extract(m.data, '$.modelID') AS modelID,
50
+ json_extract(m.data, '$.tokens') AS tokens,
51
+ json_extract(m.data, '$.path.root') AS pathRoot,
52
+ json_extract(m.data, '$.path.cwd') AS pathCwd,
53
+ s.directory AS sessionDir
54
+ FROM message m
55
+ LEFT JOIN session s ON s.id = m.session_id`;
56
+
57
+ let rows;
58
+ try {
59
+ rows = queryDbJson(dbPath, query);
60
+ } catch (err) {
61
+ if (isSqliteUnavailableError(err)) throw sqliteUnavailableError('ZCode');
62
+ throw err;
63
+ }
64
+ if (!rows.length) return { buckets: [], sessions: [] };
65
+
66
+ const entries = [];
67
+ const sessionEvents = [];
68
+
69
+ for (const row of rows) {
70
+ const timestamp = new Date(row.created);
71
+ if (isNaN(timestamp.getTime())) continue;
72
+
73
+ const project = projectName(row.pathRoot, row.pathCwd, row.sessionDir);
74
+ const sessionId = row.sessionId || 'unknown';
75
+
76
+ sessionEvents.push({
77
+ sessionId,
78
+ source: 'zcode',
79
+ project,
80
+ timestamp,
81
+ role: row.role === 'user' ? 'user' : 'assistant',
82
+ });
83
+
84
+ if (row.role !== 'assistant') continue;
85
+
86
+ let tokens;
87
+ try {
88
+ tokens = typeof row.tokens === 'string' ? JSON.parse(row.tokens) : row.tokens;
89
+ } catch {
90
+ continue;
91
+ }
92
+ if (!tokens || (!tokens.input && !tokens.output)) continue;
93
+
94
+ // ZCode follows Anthropic-style usage where `input` INCLUDES the cache-read
95
+ // tokens and `output` INCLUDES reasoning (verified: input + output == total).
96
+ // Normalize to this codebase's non-overlapping fields so cached/reasoning
97
+ // tokens aren't double-counted inside input/output.
98
+ const cachedInput = tokens.cache?.read || 0;
99
+ const reasoning = tokens.reasoning || 0;
100
+
101
+ entries.push({
102
+ source: 'zcode',
103
+ requestType: row.requestType,
104
+ model: row.modelID || 'unknown',
105
+ project,
106
+ timestamp,
107
+ inputTokens: (tokens.input || 0) - cachedInput,
108
+ outputTokens: (tokens.output || 0) - reasoning,
109
+ cachedInputTokens: cachedInput,
110
+ reasoningOutputTokens: reasoning,
111
+ });
112
+ }
113
+
114
+ return { buckets: aggregateToBuckets(entries), sessions: extractSessions(sessionEvents) };
115
+ }