ai-wrapped 1.8.1 → 1.9.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.
- package/README.md +9 -0
- package/dist/assets/{index-DTFRidCi.js → index-BcAc5_4D.js} +12 -12
- package/dist/index.html +1 -1
- package/package.json +1 -1
- package/src/bun/aggregator.test.ts +38 -0
- package/src/bun/aggregator.ts +31 -6
- package/src/bun/discovery/additional.ts +88 -0
- package/src/bun/discovery/index.ts +20 -0
- package/src/bun/index.ts +4 -8
- package/src/bun/normalizer.ts +50 -1
- package/src/bun/parsers/additional.test.ts +147 -0
- package/src/bun/parsers/additional.ts +369 -0
- package/src/bun/parsers/codex.test.ts +87 -0
- package/src/bun/parsers/codex.ts +9 -1
- package/src/bun/parsers/index.ts +30 -6
- package/src/bun/pricing.test.ts +14 -0
- package/src/bun/pricing.ts +7 -0
- package/src/bun/scan.ts +7 -5
- package/src/bun/session-schema.ts +1 -1
- package/src/bun/store.test.ts +3 -3
- package/src/bun/store.ts +1 -1
- package/src/shared/schema.ts +42 -3
- package/src/shared/session-types.ts +9 -0
- package/src/shared/shareData.test.ts +2 -2
- package/src/shared/shareData.ts +11 -8
|
@@ -0,0 +1,369 @@
|
|
|
1
|
+
import { Database } from "bun:sqlite";
|
|
2
|
+
import { readFile } from "node:fs/promises";
|
|
3
|
+
import { basename, dirname } from "node:path";
|
|
4
|
+
import type { SessionSource, TokenUsage } from "../../shared/schema";
|
|
5
|
+
import type { FileCandidate } from "../discovery";
|
|
6
|
+
import { extractText, normalizeTimestamp } from "../normalizer";
|
|
7
|
+
import type { SessionEvent } from "../session-schema";
|
|
8
|
+
import type { RawParsedSession } from "./types";
|
|
9
|
+
|
|
10
|
+
type JsonRecord = Record<string, unknown>;
|
|
11
|
+
|
|
12
|
+
const asRecord = (value: unknown): JsonRecord | null =>
|
|
13
|
+
value && typeof value === "object" && !Array.isArray(value) ? (value as JsonRecord) : null;
|
|
14
|
+
|
|
15
|
+
const asArray = (value: unknown): unknown[] => (Array.isArray(value) ? value : []);
|
|
16
|
+
|
|
17
|
+
const string = (...values: unknown[]): string | null => {
|
|
18
|
+
for (const value of values) {
|
|
19
|
+
if (typeof value === "string" && value.trim()) return value.trim();
|
|
20
|
+
}
|
|
21
|
+
return null;
|
|
22
|
+
};
|
|
23
|
+
|
|
24
|
+
const number = (...values: unknown[]): number => {
|
|
25
|
+
for (const value of values) {
|
|
26
|
+
const parsed = typeof value === "number" ? value : typeof value === "string" ? Number(value) : Number.NaN;
|
|
27
|
+
if (Number.isFinite(parsed)) return Math.max(0, parsed);
|
|
28
|
+
}
|
|
29
|
+
return 0;
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
const nested = (value: unknown, ...keys: string[]): unknown => {
|
|
33
|
+
let current: unknown = value;
|
|
34
|
+
for (const key of keys) {
|
|
35
|
+
const record = asRecord(current);
|
|
36
|
+
if (!record) return undefined;
|
|
37
|
+
current = record[key];
|
|
38
|
+
}
|
|
39
|
+
return current;
|
|
40
|
+
};
|
|
41
|
+
|
|
42
|
+
const toTokens = (value: Partial<TokenUsage>): TokenUsage => ({
|
|
43
|
+
inputTokens: Math.max(0, value.inputTokens ?? 0),
|
|
44
|
+
outputTokens: Math.max(0, value.outputTokens ?? 0),
|
|
45
|
+
cacheReadTokens: Math.max(0, value.cacheReadTokens ?? 0),
|
|
46
|
+
cacheWriteTokens: Math.max(0, value.cacheWriteTokens ?? 0),
|
|
47
|
+
reasoningTokens: Math.max(0, value.reasoningTokens ?? 0),
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
const hasTokens = (tokens: TokenUsage): boolean =>
|
|
51
|
+
tokens.inputTokens + tokens.outputTokens + tokens.cacheReadTokens + tokens.cacheWriteTokens + tokens.reasoningTokens > 0;
|
|
52
|
+
|
|
53
|
+
const parseJsonLines = (content: string): JsonRecord[] =>
|
|
54
|
+
content
|
|
55
|
+
.split(/\r?\n/)
|
|
56
|
+
.map((line) => {
|
|
57
|
+
try {
|
|
58
|
+
return asRecord(JSON.parse(line) as unknown);
|
|
59
|
+
} catch {
|
|
60
|
+
return null;
|
|
61
|
+
}
|
|
62
|
+
})
|
|
63
|
+
.filter((value): value is JsonRecord => value !== null);
|
|
64
|
+
|
|
65
|
+
const timestamp = (value: unknown, fallback: number): string =>
|
|
66
|
+
normalizeTimestamp(value) ?? new Date(fallback).toISOString();
|
|
67
|
+
|
|
68
|
+
const event = (
|
|
69
|
+
sessionId: string,
|
|
70
|
+
index: number,
|
|
71
|
+
options: {
|
|
72
|
+
timestamp: unknown;
|
|
73
|
+
fallbackTimestamp: number;
|
|
74
|
+
model?: string | null;
|
|
75
|
+
tokens: TokenUsage;
|
|
76
|
+
costUsd?: number | null;
|
|
77
|
+
text?: string | null;
|
|
78
|
+
id?: string | null;
|
|
79
|
+
},
|
|
80
|
+
): SessionEvent => ({
|
|
81
|
+
id: options.id ?? `${sessionId}:usage:${index}`,
|
|
82
|
+
sessionId,
|
|
83
|
+
kind: "assistant",
|
|
84
|
+
timestamp: timestamp(options.timestamp, options.fallbackTimestamp),
|
|
85
|
+
role: "assistant",
|
|
86
|
+
text: options.text ?? null,
|
|
87
|
+
toolName: null,
|
|
88
|
+
toolInput: null,
|
|
89
|
+
toolOutput: null,
|
|
90
|
+
model: options.model ?? null,
|
|
91
|
+
parentId: null,
|
|
92
|
+
messageId: options.id ?? null,
|
|
93
|
+
isDelta: false,
|
|
94
|
+
tokens: hasTokens(options.tokens) ? options.tokens : null,
|
|
95
|
+
costUsd: options.costUsd !== null && options.costUsd !== undefined && Number.isFinite(options.costUsd)
|
|
96
|
+
? Math.max(0, options.costUsd)
|
|
97
|
+
: null,
|
|
98
|
+
});
|
|
99
|
+
|
|
100
|
+
const rawSession = (
|
|
101
|
+
candidate: FileCandidate,
|
|
102
|
+
sessionId: string,
|
|
103
|
+
events: SessionEvent[],
|
|
104
|
+
model: string | null = null,
|
|
105
|
+
): RawParsedSession | null =>
|
|
106
|
+
events.length === 0
|
|
107
|
+
? null
|
|
108
|
+
: {
|
|
109
|
+
sessionId,
|
|
110
|
+
source: candidate.source,
|
|
111
|
+
filePath: candidate.path,
|
|
112
|
+
fileSizeBytes: candidate.size,
|
|
113
|
+
metadata: { cwd: null, gitBranch: null, model, cliVersion: null, title: null },
|
|
114
|
+
events,
|
|
115
|
+
};
|
|
116
|
+
|
|
117
|
+
const oneOrNone = (session: RawParsedSession | null): RawParsedSession[] => (session ? [session] : []);
|
|
118
|
+
|
|
119
|
+
const fileSessionId = (candidate: FileCandidate): string => basename(candidate.path).replace(/\.[^.]+(?:\.[^.]+)?$/, "");
|
|
120
|
+
|
|
121
|
+
const ampTokens = (usage: JsonRecord): TokenUsage =>
|
|
122
|
+
toTokens({
|
|
123
|
+
inputTokens: number(usage.inputTokens, usage.input_tokens, usage.input),
|
|
124
|
+
outputTokens: number(usage.outputTokens, usage.output_tokens, usage.output, usage.totalTokens, usage.total_tokens, usage.total),
|
|
125
|
+
cacheReadTokens: number(usage.cacheReadInputTokens, usage.cache_read_input_tokens),
|
|
126
|
+
cacheWriteTokens: number(usage.cacheCreationInputTokens, usage.cache_creation_input_tokens),
|
|
127
|
+
});
|
|
128
|
+
|
|
129
|
+
export const parseAmp = async (candidate: FileCandidate): Promise<RawParsedSession[]> => {
|
|
130
|
+
const root = asRecord(JSON.parse(await readFile(candidate.path, "utf8")) as unknown);
|
|
131
|
+
if (!root) return [];
|
|
132
|
+
const sessionId = string(root.id) ?? fileSessionId(candidate);
|
|
133
|
+
const messages = asArray(root.messages).map(asRecord).filter((value): value is JsonRecord => value !== null);
|
|
134
|
+
const ledger = asRecord(root.usageLedger);
|
|
135
|
+
const ledgerEvents = asArray(ledger?.events).map(asRecord).filter((value): value is JsonRecord => value !== null);
|
|
136
|
+
const source = ledgerEvents.length > 0 ? ledgerEvents : messages.filter((message) => string(message.role) === "assistant");
|
|
137
|
+
const events = source.flatMap((entry, index) => {
|
|
138
|
+
const usage = asRecord(entry.tokens) ?? asRecord(entry.usage);
|
|
139
|
+
if (!usage) return [];
|
|
140
|
+
const tokens = ampTokens(usage);
|
|
141
|
+
return hasTokens(tokens)
|
|
142
|
+
? [event(sessionId, index, {
|
|
143
|
+
timestamp: entry.timestamp,
|
|
144
|
+
fallbackTimestamp: candidate.mtime,
|
|
145
|
+
model: string(entry.model, usage.model),
|
|
146
|
+
tokens,
|
|
147
|
+
id: string(entry.id),
|
|
148
|
+
})]
|
|
149
|
+
: [];
|
|
150
|
+
});
|
|
151
|
+
return oneOrNone(rawSession(candidate, sessionId, events));
|
|
152
|
+
};
|
|
153
|
+
|
|
154
|
+
const standardTokens = (usage: JsonRecord): TokenUsage => {
|
|
155
|
+
const cache = asRecord(usage.cache);
|
|
156
|
+
return toTokens({
|
|
157
|
+
inputTokens: number(usage.inputTokens, usage.input_tokens, usage.promptTokens, usage.prompt_tokens, usage.input),
|
|
158
|
+
outputTokens: number(usage.outputTokens, usage.output_tokens, usage.completionTokens, usage.completion_tokens, usage.output),
|
|
159
|
+
cacheReadTokens: number(
|
|
160
|
+
usage.cacheReadInputTokens,
|
|
161
|
+
usage.cache_read_input_tokens,
|
|
162
|
+
nested(usage, "promptTokensDetails", "cachedTokens"),
|
|
163
|
+
nested(usage, "prompt_tokens_details", "cached_tokens"),
|
|
164
|
+
cache?.read,
|
|
165
|
+
usage.cacheRead,
|
|
166
|
+
),
|
|
167
|
+
cacheWriteTokens: number(
|
|
168
|
+
usage.cacheCreationInputTokens,
|
|
169
|
+
usage.cache_creation_input_tokens,
|
|
170
|
+
usage.cacheWrite,
|
|
171
|
+
cache?.write,
|
|
172
|
+
),
|
|
173
|
+
reasoningTokens: number(usage.reasoning, usage.reasoningTokens, usage.thoughtsTokenCount, usage.thoughts_token_count),
|
|
174
|
+
});
|
|
175
|
+
};
|
|
176
|
+
|
|
177
|
+
export const parseCodebuff = async (candidate: FileCandidate): Promise<RawParsedSession[]> => {
|
|
178
|
+
const parsed = JSON.parse(await readFile(candidate.path, "utf8")) as unknown;
|
|
179
|
+
if (!Array.isArray(parsed)) return [];
|
|
180
|
+
const sessionId = dirname(candidate.path).split("/").slice(-3).join("/") || fileSessionId(candidate);
|
|
181
|
+
const events = parsed.flatMap((value, index) => {
|
|
182
|
+
const message = asRecord(value);
|
|
183
|
+
if (!message || !["assistant", "agent", "ai"].includes(string(message.role, message.variant) ?? "")) return [];
|
|
184
|
+
const metadata = asRecord(message.metadata);
|
|
185
|
+
const codebuff = asRecord(metadata?.codebuff);
|
|
186
|
+
const usage = asRecord(metadata?.usage) ?? asRecord(codebuff?.usage);
|
|
187
|
+
if (!usage) return [];
|
|
188
|
+
const tokens = standardTokens(usage);
|
|
189
|
+
return hasTokens(tokens)
|
|
190
|
+
? [event(sessionId, index, {
|
|
191
|
+
timestamp: message.timestamp,
|
|
192
|
+
fallbackTimestamp: candidate.mtime,
|
|
193
|
+
model: string(metadata?.model, codebuff?.model),
|
|
194
|
+
tokens,
|
|
195
|
+
costUsd: number(message.costUsd, message.cost_usd) || null,
|
|
196
|
+
id: string(message.id),
|
|
197
|
+
})]
|
|
198
|
+
: [];
|
|
199
|
+
});
|
|
200
|
+
return oneOrNone(rawSession(candidate, sessionId, events));
|
|
201
|
+
};
|
|
202
|
+
|
|
203
|
+
const sqliteRows = (path: string, query: string): JsonRecord[] => {
|
|
204
|
+
const db = new Database(path, { readonly: true });
|
|
205
|
+
try {
|
|
206
|
+
return db.query(query).all() as JsonRecord[];
|
|
207
|
+
} finally {
|
|
208
|
+
db.close();
|
|
209
|
+
}
|
|
210
|
+
};
|
|
211
|
+
|
|
212
|
+
export const parseGoose = async (candidate: FileCandidate): Promise<RawParsedSession[]> => {
|
|
213
|
+
try {
|
|
214
|
+
const rows = sqliteRows(candidate.path, `
|
|
215
|
+
SELECT id, model_config_json, created_at,
|
|
216
|
+
COALESCE(accumulated_input_tokens, input_tokens, 0) AS input_tokens,
|
|
217
|
+
COALESCE(accumulated_output_tokens, output_tokens, 0) AS output_tokens,
|
|
218
|
+
COALESCE(accumulated_total_tokens, total_tokens, 0) AS total_tokens
|
|
219
|
+
FROM sessions WHERE model_config_json IS NOT NULL`);
|
|
220
|
+
return rows.flatMap((row) => {
|
|
221
|
+
const config = asRecord(JSON.parse(String(row.model_config_json)) as unknown);
|
|
222
|
+
const model = string(config?.model_name);
|
|
223
|
+
const inputTokens = number(row.input_tokens);
|
|
224
|
+
const outputTokens = number(row.output_tokens);
|
|
225
|
+
const tokens = toTokens({ inputTokens, outputTokens, reasoningTokens: Math.max(0, number(row.total_tokens) - inputTokens - outputTokens) });
|
|
226
|
+
const sessionId = string(row.id);
|
|
227
|
+
const parsed = sessionId && model && hasTokens(tokens)
|
|
228
|
+
? rawSession(candidate, sessionId, [event(sessionId, 0, { timestamp: row.created_at, fallbackTimestamp: candidate.mtime, model, tokens, id: sessionId })], model)
|
|
229
|
+
: null;
|
|
230
|
+
return parsed ? [parsed] : [];
|
|
231
|
+
});
|
|
232
|
+
} catch {
|
|
233
|
+
return [];
|
|
234
|
+
}
|
|
235
|
+
};
|
|
236
|
+
|
|
237
|
+
export const parseHermes = async (candidate: FileCandidate): Promise<RawParsedSession[]> => {
|
|
238
|
+
try {
|
|
239
|
+
const rows = sqliteRows(candidate.path, `
|
|
240
|
+
SELECT id, model, started_at, message_count, input_tokens, output_tokens,
|
|
241
|
+
cache_read_tokens, cache_write_tokens, reasoning_tokens, estimated_cost_usd, actual_cost_usd
|
|
242
|
+
FROM sessions WHERE model IS NOT NULL AND TRIM(model) != ''`);
|
|
243
|
+
return rows.flatMap((row) => {
|
|
244
|
+
const sessionId = string(row.id);
|
|
245
|
+
const model = string(row.model);
|
|
246
|
+
const tokens = toTokens({
|
|
247
|
+
inputTokens: number(row.input_tokens), outputTokens: number(row.output_tokens),
|
|
248
|
+
cacheReadTokens: number(row.cache_read_tokens), cacheWriteTokens: number(row.cache_write_tokens),
|
|
249
|
+
reasoningTokens: number(row.reasoning_tokens),
|
|
250
|
+
});
|
|
251
|
+
const parsed = sessionId && model && (hasTokens(tokens) || number(row.actual_cost_usd, row.estimated_cost_usd) > 0)
|
|
252
|
+
? rawSession(candidate, sessionId, [event(sessionId, 0, {
|
|
253
|
+
timestamp: row.started_at, fallbackTimestamp: candidate.mtime, model, tokens,
|
|
254
|
+
costUsd: number(row.actual_cost_usd, row.estimated_cost_usd) || null, id: sessionId,
|
|
255
|
+
})], model)
|
|
256
|
+
: null;
|
|
257
|
+
return parsed ? [parsed] : [];
|
|
258
|
+
});
|
|
259
|
+
} catch {
|
|
260
|
+
return [];
|
|
261
|
+
}
|
|
262
|
+
};
|
|
263
|
+
|
|
264
|
+
export const parseKilo = async (candidate: FileCandidate): Promise<RawParsedSession[]> => {
|
|
265
|
+
try {
|
|
266
|
+
const rows = sqliteRows(candidate.path, "SELECT id, session_id, data FROM message");
|
|
267
|
+
return rows.flatMap((row) => {
|
|
268
|
+
const data = asRecord(JSON.parse(String(row.data)) as unknown);
|
|
269
|
+
if (!data || string(data.role) !== "assistant") return [];
|
|
270
|
+
const tokenData = asRecord(data.tokens);
|
|
271
|
+
if (!tokenData) return [];
|
|
272
|
+
const tokens = standardTokens(tokenData);
|
|
273
|
+
const sessionId = string(data.sessionId, row.session_id);
|
|
274
|
+
const model = string(data.modelID, data.model);
|
|
275
|
+
const created = nested(data, "time", "created");
|
|
276
|
+
const parsed = sessionId && model && hasTokens(tokens)
|
|
277
|
+
? rawSession(candidate, sessionId, [event(sessionId, 0, {
|
|
278
|
+
timestamp: created, fallbackTimestamp: candidate.mtime, model, tokens,
|
|
279
|
+
costUsd: number(data.cost) || null, id: string(data.id, row.id),
|
|
280
|
+
})], model)
|
|
281
|
+
: null;
|
|
282
|
+
return parsed ? [parsed] : [];
|
|
283
|
+
});
|
|
284
|
+
} catch {
|
|
285
|
+
return [];
|
|
286
|
+
}
|
|
287
|
+
};
|
|
288
|
+
|
|
289
|
+
export const parseKimi = async (candidate: FileCandidate): Promise<RawParsedSession[]> => {
|
|
290
|
+
const sessionId = fileSessionId(candidate);
|
|
291
|
+
const events = parseJsonLines(await readFile(candidate.path, "utf8")).flatMap((line, index) => {
|
|
292
|
+
const usage = asRecord(line.usage) ?? asRecord(nested(line, "message", "payload", "token_usage"));
|
|
293
|
+
const isTurn = string(line.type) === "usage.record" ? string(line.usage_scope) === "turn" : Boolean(usage);
|
|
294
|
+
if (!usage || !isTurn) return [];
|
|
295
|
+
const tokens = toTokens({
|
|
296
|
+
inputTokens: number(usage.input_other), outputTokens: number(usage.output),
|
|
297
|
+
cacheReadTokens: number(usage.input_cache_read), cacheWriteTokens: number(usage.input_cache_creation),
|
|
298
|
+
});
|
|
299
|
+
const model = (string(line.model, nested(line, "message", "payload", "model")) ?? "kimi-code")
|
|
300
|
+
.replace(/^kimi-code\//, "");
|
|
301
|
+
return hasTokens(tokens)
|
|
302
|
+
? [event(sessionId, index, { timestamp: line.time ?? line.timestamp, fallbackTimestamp: candidate.mtime, model, tokens })]
|
|
303
|
+
: [];
|
|
304
|
+
});
|
|
305
|
+
return oneOrNone(rawSession(candidate, sessionId, events));
|
|
306
|
+
};
|
|
307
|
+
|
|
308
|
+
export const parseOpenclaw = async (candidate: FileCandidate): Promise<RawParsedSession[]> => {
|
|
309
|
+
const sessionId = fileSessionId(candidate);
|
|
310
|
+
let model: string | null = null;
|
|
311
|
+
const events = parseJsonLines(await readFile(candidate.path, "utf8")).flatMap((line, index) => {
|
|
312
|
+
const type = string(line.type);
|
|
313
|
+
if (type === "model_change" || (type === "custom" && string(line.customType) === "model-snapshot")) {
|
|
314
|
+
model = string(nested(line, "data", "modelId"), nested(line, "data", "model"), line.modelId, line.model) ?? model;
|
|
315
|
+
return [];
|
|
316
|
+
}
|
|
317
|
+
const message = asRecord(line.message);
|
|
318
|
+
if (type !== "message" || string(message?.role) !== "assistant") return [];
|
|
319
|
+
const usage = asRecord(message?.usage);
|
|
320
|
+
if (!usage) return [];
|
|
321
|
+
const tokens = standardTokens(usage);
|
|
322
|
+
const messageModel = string(message?.modelId, message?.model, model);
|
|
323
|
+
return hasTokens(tokens)
|
|
324
|
+
? [event(sessionId, index, {
|
|
325
|
+
timestamp: message?.timestamp ?? line.timestamp, fallbackTimestamp: candidate.mtime, model: messageModel, tokens,
|
|
326
|
+
costUsd: number(nested(usage, "cost", "total")) || null,
|
|
327
|
+
})]
|
|
328
|
+
: [];
|
|
329
|
+
});
|
|
330
|
+
return oneOrNone(rawSession(candidate, sessionId, events, model));
|
|
331
|
+
};
|
|
332
|
+
|
|
333
|
+
export const parsePi = async (candidate: FileCandidate): Promise<RawParsedSession[]> => {
|
|
334
|
+
const sessionId = fileSessionId(candidate);
|
|
335
|
+
const events = parseJsonLines(await readFile(candidate.path, "utf8")).flatMap((line, index) => {
|
|
336
|
+
const message = asRecord(line.message);
|
|
337
|
+
if (string(message?.role) !== "assistant") return [];
|
|
338
|
+
const usage = asRecord(message?.usage);
|
|
339
|
+
if (!usage) return [];
|
|
340
|
+
const tokens = standardTokens(usage);
|
|
341
|
+
return hasTokens(tokens)
|
|
342
|
+
? [event(sessionId, index, {
|
|
343
|
+
timestamp: line.timestamp, fallbackTimestamp: candidate.mtime, model: string(message?.model), tokens,
|
|
344
|
+
costUsd: number(nested(usage, "cost", "total")) || null,
|
|
345
|
+
})]
|
|
346
|
+
: [];
|
|
347
|
+
});
|
|
348
|
+
return oneOrNone(rawSession(candidate, sessionId, events));
|
|
349
|
+
};
|
|
350
|
+
|
|
351
|
+
export const parseQwen = async (candidate: FileCandidate): Promise<RawParsedSession[]> => {
|
|
352
|
+
const sessionId = fileSessionId(candidate);
|
|
353
|
+
const events = parseJsonLines(await readFile(candidate.path, "utf8")).flatMap((line, index) => {
|
|
354
|
+
if (string(line.type) !== "assistant") return [];
|
|
355
|
+
const usage = asRecord(line.usageMetadata);
|
|
356
|
+
if (!usage) return [];
|
|
357
|
+
const prompt = number(usage.promptTokenCount, usage.prompt_token_count);
|
|
358
|
+
const output = number(usage.candidatesTokenCount, usage.candidates_token_count);
|
|
359
|
+
const reasoning = number(usage.thoughtsTokenCount, usage.thoughts_token_count);
|
|
360
|
+
const tokens = toTokens({
|
|
361
|
+
inputTokens: prompt, outputTokens: output, reasoningTokens: reasoning,
|
|
362
|
+
cacheReadTokens: number(usage.cachedContentTokenCount, usage.cached_content_token_count),
|
|
363
|
+
});
|
|
364
|
+
return hasTokens(tokens)
|
|
365
|
+
? [event(sessionId, index, { timestamp: line.timestamp, fallbackTimestamp: candidate.mtime, model: string(line.model) ?? "unknown", tokens })]
|
|
366
|
+
: [];
|
|
367
|
+
});
|
|
368
|
+
return oneOrNone(rawSession(candidate, sessionId, events));
|
|
369
|
+
};
|
|
@@ -173,6 +173,21 @@ describe("codexParser", () => {
|
|
|
173
173
|
cacheWriteTokens: 0,
|
|
174
174
|
reasoningTokens: 15,
|
|
175
175
|
});
|
|
176
|
+
expect(normalized.session.modelUsage).toEqual([
|
|
177
|
+
{
|
|
178
|
+
model: "unknown",
|
|
179
|
+
messageCount: 0,
|
|
180
|
+
toolCallCount: 0,
|
|
181
|
+
tokens: {
|
|
182
|
+
inputTokens: 90,
|
|
183
|
+
outputTokens: 20,
|
|
184
|
+
cacheReadTokens: 80,
|
|
185
|
+
cacheWriteTokens: 0,
|
|
186
|
+
reasoningTokens: 15,
|
|
187
|
+
},
|
|
188
|
+
costUsd: 0,
|
|
189
|
+
},
|
|
190
|
+
]);
|
|
176
191
|
} finally {
|
|
177
192
|
rmSync(fixtureDir, { recursive: true, force: true });
|
|
178
193
|
}
|
|
@@ -347,4 +362,76 @@ describe("codexParser", () => {
|
|
|
347
362
|
rmSync(fixtureDir, { recursive: true, force: true });
|
|
348
363
|
}
|
|
349
364
|
});
|
|
365
|
+
|
|
366
|
+
test("attributes token deltas to the model active in each turn", async () => {
|
|
367
|
+
const fixtureDir = mkdtempSync(join(tmpdir(), "ai-stats-codex-"));
|
|
368
|
+
|
|
369
|
+
try {
|
|
370
|
+
const filePath = join(fixtureDir, "rollout-2026-07-13T13-19-00-model-switch.jsonl");
|
|
371
|
+
const content = [
|
|
372
|
+
JSON.stringify({
|
|
373
|
+
type: "session_meta",
|
|
374
|
+
timestamp: "2026-07-13T13:19:00Z",
|
|
375
|
+
payload: { id: "session-model-switch", cwd: "/tmp/project", model_provider: "gpt-5.5" },
|
|
376
|
+
}),
|
|
377
|
+
JSON.stringify({
|
|
378
|
+
type: "turn_context",
|
|
379
|
+
timestamp: "2026-07-13T13:19:01Z",
|
|
380
|
+
payload: { model: "gpt-5.5" },
|
|
381
|
+
}),
|
|
382
|
+
JSON.stringify({
|
|
383
|
+
type: "event_msg",
|
|
384
|
+
timestamp: "2026-07-13T13:19:02Z",
|
|
385
|
+
payload: {
|
|
386
|
+
type: "token_count",
|
|
387
|
+
info: { total_token_usage: { input_tokens: 100, output_tokens: 10 } },
|
|
388
|
+
},
|
|
389
|
+
}),
|
|
390
|
+
JSON.stringify({
|
|
391
|
+
type: "turn_context",
|
|
392
|
+
timestamp: "2026-07-13T13:20:00Z",
|
|
393
|
+
payload: { model: "gpt-5.6-sol" },
|
|
394
|
+
}),
|
|
395
|
+
JSON.stringify({
|
|
396
|
+
type: "event_msg",
|
|
397
|
+
timestamp: "2026-07-13T13:20:01Z",
|
|
398
|
+
payload: {
|
|
399
|
+
type: "token_count",
|
|
400
|
+
info: { total_token_usage: { input_tokens: 350, output_tokens: 40 } },
|
|
401
|
+
},
|
|
402
|
+
}),
|
|
403
|
+
].join("\n");
|
|
404
|
+
|
|
405
|
+
writeFileSync(filePath, content, "utf8");
|
|
406
|
+
const fileStat = statSync(filePath);
|
|
407
|
+
const parsed = await codexParser.parse({
|
|
408
|
+
path: filePath,
|
|
409
|
+
source: "codex",
|
|
410
|
+
mtime: fileStat.mtimeMs,
|
|
411
|
+
size: fileStat.size,
|
|
412
|
+
});
|
|
413
|
+
|
|
414
|
+
expect(parsed).not.toBeNull();
|
|
415
|
+
if (!parsed) return;
|
|
416
|
+
|
|
417
|
+
const normalized = normalizeSession(parsed);
|
|
418
|
+
expect(normalized.session.modelUsage).toHaveLength(2);
|
|
419
|
+
expect(normalized.session.modelUsage[0]).toMatchObject({
|
|
420
|
+
model: "gpt-5.5",
|
|
421
|
+
messageCount: 0,
|
|
422
|
+
toolCallCount: 0,
|
|
423
|
+
tokens: { inputTokens: 100, outputTokens: 10, cacheReadTokens: 0, cacheWriteTokens: 0, reasoningTokens: 0 },
|
|
424
|
+
});
|
|
425
|
+
expect(normalized.session.modelUsage[0]?.costUsd).toBeCloseTo(0.0008, 12);
|
|
426
|
+
expect(normalized.session.modelUsage[1]).toMatchObject({
|
|
427
|
+
model: "gpt-5.6-sol",
|
|
428
|
+
messageCount: 0,
|
|
429
|
+
toolCallCount: 0,
|
|
430
|
+
tokens: { inputTokens: 250, outputTokens: 30, cacheReadTokens: 0, cacheWriteTokens: 0, reasoningTokens: 0 },
|
|
431
|
+
});
|
|
432
|
+
expect(normalized.session.modelUsage[1]?.costUsd).toBeCloseTo(0.00215, 12);
|
|
433
|
+
} finally {
|
|
434
|
+
rmSync(fixtureDir, { recursive: true, force: true });
|
|
435
|
+
}
|
|
436
|
+
});
|
|
350
437
|
});
|
package/src/bun/parsers/codex.ts
CHANGED
|
@@ -14,6 +14,14 @@ const getString = (value: unknown): string | null => {
|
|
|
14
14
|
return typeof value === "string" && value.trim().length > 0 ? value : null;
|
|
15
15
|
};
|
|
16
16
|
|
|
17
|
+
const CODEX_PROVIDER_NAMES = new Set(["openai", "chatgpt", "codex", "omnirouter"]);
|
|
18
|
+
|
|
19
|
+
const getCodexModelProvider = (value: unknown): string | null => {
|
|
20
|
+
const candidate = getString(value);
|
|
21
|
+
if (!candidate || CODEX_PROVIDER_NAMES.has(candidate.toLowerCase())) return null;
|
|
22
|
+
return candidate;
|
|
23
|
+
};
|
|
24
|
+
|
|
17
25
|
const parseJsonl = (content: string): Array<Record<string, unknown>> => {
|
|
18
26
|
const records: Array<Record<string, unknown>> = [];
|
|
19
27
|
for (const line of content.split(/\r?\n/)) {
|
|
@@ -358,7 +366,7 @@ export const codexParser: SessionParser = {
|
|
|
358
366
|
cwd = cwd ?? getString(payload?.cwd);
|
|
359
367
|
gitBranch = gitBranch ?? getString(git?.branch);
|
|
360
368
|
cliVersion = cliVersion ?? getString(payload?.cli_version);
|
|
361
|
-
model = model ??
|
|
369
|
+
model = model ?? getCodexModelProvider(payload?.model_provider);
|
|
362
370
|
|
|
363
371
|
events.push(
|
|
364
372
|
createEvent(sessionId, lineIndex, record, "meta", {
|
package/src/bun/parsers/index.ts
CHANGED
|
@@ -1,5 +1,16 @@
|
|
|
1
1
|
import type { SessionSource } from "../../shared/schema";
|
|
2
2
|
import type { FileCandidate } from "../discovery";
|
|
3
|
+
import {
|
|
4
|
+
parseAmp,
|
|
5
|
+
parseCodebuff,
|
|
6
|
+
parseGoose,
|
|
7
|
+
parseHermes,
|
|
8
|
+
parseKilo,
|
|
9
|
+
parseKimi,
|
|
10
|
+
parseOpenclaw,
|
|
11
|
+
parsePi,
|
|
12
|
+
parseQwen,
|
|
13
|
+
} from "./additional";
|
|
3
14
|
import { claudeParser } from "./claude";
|
|
4
15
|
import { codexParser } from "./codex";
|
|
5
16
|
import { parseCopilot } from "./copilot";
|
|
@@ -9,27 +20,40 @@ import { parseGeneric } from "./generic";
|
|
|
9
20
|
import { parseOpencode } from "./opencode";
|
|
10
21
|
import type { RawParsedSession, SessionParser } from "./types";
|
|
11
22
|
|
|
12
|
-
|
|
23
|
+
type FileParser = (candidate: FileCandidate) => Promise<RawParsedSession | RawParsedSession[] | null>;
|
|
24
|
+
|
|
25
|
+
const PARSERS: Record<SessionSource, FileParser> = {
|
|
13
26
|
claude: claudeParser.parse,
|
|
14
27
|
codex: codexParser.parse,
|
|
15
28
|
gemini: parseGemini,
|
|
16
29
|
opencode: parseOpencode,
|
|
17
30
|
droid: parseDroid,
|
|
18
31
|
copilot: parseCopilot,
|
|
32
|
+
amp: parseAmp,
|
|
33
|
+
codebuff: parseCodebuff,
|
|
34
|
+
goose: parseGoose,
|
|
35
|
+
hermes: parseHermes,
|
|
36
|
+
kilo: parseKilo,
|
|
37
|
+
kimi: parseKimi,
|
|
38
|
+
openclaw: parseOpenclaw,
|
|
39
|
+
pi: parsePi,
|
|
40
|
+
qwen: parseQwen,
|
|
19
41
|
};
|
|
20
42
|
|
|
21
|
-
export const parseFile = async (candidate: FileCandidate): Promise<RawParsedSession
|
|
43
|
+
export const parseFile = async (candidate: FileCandidate): Promise<RawParsedSession[]> => {
|
|
22
44
|
try {
|
|
23
45
|
const parser = PARSERS[candidate.source];
|
|
24
46
|
const parsed = await parser(candidate);
|
|
25
|
-
if (parsed) return parsed;
|
|
26
|
-
|
|
47
|
+
if (parsed) return Array.isArray(parsed) ? parsed : [parsed];
|
|
48
|
+
const generic = await parseGeneric(candidate, candidate.source);
|
|
49
|
+
return generic ? [generic] : [];
|
|
27
50
|
} catch (error) {
|
|
28
51
|
console.error(`[parse] Failed ${candidate.source} ${candidate.path}`, error);
|
|
29
52
|
try {
|
|
30
|
-
|
|
53
|
+
const generic = await parseGeneric(candidate, candidate.source);
|
|
54
|
+
return generic ? [generic] : [];
|
|
31
55
|
} catch {
|
|
32
|
-
return
|
|
56
|
+
return [];
|
|
33
57
|
}
|
|
34
58
|
}
|
|
35
59
|
};
|
package/src/bun/pricing.test.ts
CHANGED
|
@@ -45,6 +45,20 @@ describe("computeCost", () => {
|
|
|
45
45
|
expect(cost).toBe(0);
|
|
46
46
|
});
|
|
47
47
|
|
|
48
|
+
test("prices GPT-5.6 variants and Claude Fable without a remote pricing refresh", () => {
|
|
49
|
+
const usage = {
|
|
50
|
+
inputTokens: 1_000_000,
|
|
51
|
+
outputTokens: 0,
|
|
52
|
+
cacheReadTokens: 0,
|
|
53
|
+
cacheWriteTokens: 0,
|
|
54
|
+
reasoningTokens: 0,
|
|
55
|
+
};
|
|
56
|
+
|
|
57
|
+
expect(computeCost(usage, "gpt-5.6-sol")).toBe(5);
|
|
58
|
+
expect(computeCost(usage, "gpt-5.6-terra")).toBe(2.5);
|
|
59
|
+
expect(computeCost(usage, "claude-fable-5")).toBe(10);
|
|
60
|
+
});
|
|
61
|
+
|
|
48
62
|
test("does not remap gpt-5.3-codex to gpt-5.2-codex pricing", async () => {
|
|
49
63
|
globalThis.fetch = ((async () =>
|
|
50
64
|
new Response(
|
package/src/bun/pricing.ts
CHANGED
|
@@ -35,12 +35,19 @@ export const PRICING: Record<string, ModelPricing> = {
|
|
|
35
35
|
"claude-3-5-haiku-20241022": { inputPer1M: 0.8, outputPer1M: 4, cacheReadPer1M: 0.08, cacheWritePer1M: 1 },
|
|
36
36
|
|
|
37
37
|
"gpt-5": { inputPer1M: 1.25, outputPer1M: 10, cacheReadPer1M: 0.125, cacheWritePer1M: 0 },
|
|
38
|
+
"gpt-5.5": { inputPer1M: 5, outputPer1M: 30, cacheReadPer1M: 0.5, cacheWritePer1M: 0 },
|
|
39
|
+
"gpt-5.6": { inputPer1M: 5, outputPer1M: 30, cacheReadPer1M: 0.5, cacheWritePer1M: 0 },
|
|
40
|
+
"gpt-5.6-sol": { inputPer1M: 5, outputPer1M: 30, cacheReadPer1M: 0.5, cacheWritePer1M: 0 },
|
|
41
|
+
"gpt-5.6-terra": { inputPer1M: 2.5, outputPer1M: 15, cacheReadPer1M: 0.25, cacheWritePer1M: 0 },
|
|
42
|
+
"gpt-5.6-luna": { inputPer1M: 1, outputPer1M: 6, cacheReadPer1M: 0.1, cacheWritePer1M: 0 },
|
|
38
43
|
"gpt-5.2-codex": { inputPer1M: 1.25, outputPer1M: 10, cacheReadPer1M: 0.125, cacheWritePer1M: 0 },
|
|
39
44
|
"gpt-5-codex": { inputPer1M: 1.25, outputPer1M: 10, cacheReadPer1M: 0.125, cacheWritePer1M: 0 },
|
|
40
45
|
"gpt-4o": { inputPer1M: 2.5, outputPer1M: 10, cacheReadPer1M: 1.25, cacheWritePer1M: 0 },
|
|
41
46
|
o1: { inputPer1M: 15, outputPer1M: 60, cacheReadPer1M: 7.5, cacheWritePer1M: 0 },
|
|
42
47
|
o3: { inputPer1M: 10, outputPer1M: 40, cacheReadPer1M: 2.5, cacheWritePer1M: 0 },
|
|
43
48
|
|
|
49
|
+
"claude-fable-5": { inputPer1M: 10, outputPer1M: 50, cacheReadPer1M: 1, cacheWritePer1M: 12.5 },
|
|
50
|
+
|
|
44
51
|
"gemini-2.5-pro": { inputPer1M: 1.25, outputPer1M: 10, cacheReadPer1M: 0.315, cacheWritePer1M: 4.5 },
|
|
45
52
|
"gemini-2.5-flash": { inputPer1M: 0.15, outputPer1M: 0.6, cacheReadPer1M: 0.0375, cacheWritePer1M: 1 },
|
|
46
53
|
};
|
package/src/bun/scan.ts
CHANGED
|
@@ -50,9 +50,9 @@ export const runScan = async (options: ScanOptions = {}): Promise<ScanResult> =>
|
|
|
50
50
|
const sessions: Session[] = [];
|
|
51
51
|
|
|
52
52
|
for (const candidate of changed) {
|
|
53
|
-
const
|
|
53
|
+
const parsedSessions = await parseFile(candidate);
|
|
54
54
|
|
|
55
|
-
if (
|
|
55
|
+
if (parsedSessions.length === 0) {
|
|
56
56
|
errors += 1;
|
|
57
57
|
scanState[candidate.path] = {
|
|
58
58
|
source: candidate.source,
|
|
@@ -63,14 +63,16 @@ export const runScan = async (options: ScanOptions = {}): Promise<ScanResult> =>
|
|
|
63
63
|
continue;
|
|
64
64
|
}
|
|
65
65
|
|
|
66
|
-
const
|
|
67
|
-
|
|
66
|
+
for (const parsed of parsedSessions) {
|
|
67
|
+
const { session } = normalizeSession(parsed);
|
|
68
|
+
sessions.push(session);
|
|
69
|
+
}
|
|
68
70
|
|
|
69
71
|
scanState[candidate.path] = {
|
|
70
72
|
source: candidate.source,
|
|
71
73
|
fileSize: candidate.size,
|
|
72
74
|
mtimeMs: candidate.mtime,
|
|
73
|
-
parsedAt:
|
|
75
|
+
parsedAt: new Date().toISOString(),
|
|
74
76
|
};
|
|
75
77
|
|
|
76
78
|
scanned += 1;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export type { Session, SessionEvent, SessionEventKind } from "../shared/schema";
|
|
1
|
+
export type { Session, SessionEvent, SessionEventKind, SessionModelUsage } from "../shared/schema";
|
package/src/bun/store.test.ts
CHANGED
|
@@ -117,7 +117,7 @@ describe("rawAggregationMetaNeedsTimeZoneBackfill", () => {
|
|
|
117
117
|
test("returns true when version changes", () => {
|
|
118
118
|
expect(
|
|
119
119
|
rawAggregationMetaNeedsTimeZoneBackfill(
|
|
120
|
-
{ version:
|
|
120
|
+
{ version: 1, timeZone: "America/Los_Angeles" },
|
|
121
121
|
"America/Los_Angeles",
|
|
122
122
|
),
|
|
123
123
|
).toBe(true);
|
|
@@ -126,7 +126,7 @@ describe("rawAggregationMetaNeedsTimeZoneBackfill", () => {
|
|
|
126
126
|
test("returns true when timezone changes", () => {
|
|
127
127
|
expect(
|
|
128
128
|
rawAggregationMetaNeedsTimeZoneBackfill(
|
|
129
|
-
{ version:
|
|
129
|
+
{ version: 2, timeZone: "UTC" },
|
|
130
130
|
"America/Los_Angeles",
|
|
131
131
|
),
|
|
132
132
|
).toBe(true);
|
|
@@ -135,7 +135,7 @@ describe("rawAggregationMetaNeedsTimeZoneBackfill", () => {
|
|
|
135
135
|
test("returns false for matching version and timezone", () => {
|
|
136
136
|
expect(
|
|
137
137
|
rawAggregationMetaNeedsTimeZoneBackfill(
|
|
138
|
-
{ version:
|
|
138
|
+
{ version: 3, timeZone: "America/Los_Angeles" },
|
|
139
139
|
"America/Los_Angeles",
|
|
140
140
|
),
|
|
141
141
|
).toBe(false);
|
package/src/bun/store.ts
CHANGED
|
@@ -47,7 +47,7 @@ const SCAN_STATE_PATH = join(DATA_DIR, "scan-state.json");
|
|
|
47
47
|
const DAILY_PATH = join(DATA_DIR, "daily.json");
|
|
48
48
|
const AGGREGATION_META_PATH = join(DATA_DIR, "aggregation-meta.json");
|
|
49
49
|
const SETTINGS_PATH = join(DATA_DIR, "settings.json");
|
|
50
|
-
const AGGREGATION_META_VERSION =
|
|
50
|
+
const AGGREGATION_META_VERSION = 3;
|
|
51
51
|
|
|
52
52
|
const DEFAULT_SETTINGS: AppSettings = {
|
|
53
53
|
scanOnLaunch: true,
|