Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

opencodeUsageReader.ts

188 lines7.0 KB

1// node:sqlite reads live OpenCode databases; Node fs walks legacy JSON history.
2// @effect-diagnostics nodeBuiltinImport:off
3import * as NodeFSP from "node:fs/promises";
4import * as NodePath from "node:path";
5import * as NodeSqlite from "node:sqlite";
6import * as NodeTimersPromises from "node:timers/promises";
7​
8import { totalTokens, type UsageRecord } from "./usageTranscripts.ts";
9​
10function object(value: unknown): Record<string, unknown> {
11 return typeof value === "object" && value !== null && !Array.isArray(value)
12 ? (value as Record<string, unknown>)
13 : {};
15​
16function tokens(value: unknown): number {
17 return typeof value === "number" && Number.isFinite(value) && value > 0 ? Math.trunc(value) : 0;
19​
20function text(value: unknown): string {
21 return typeof value === "string" ? value : "";
23​
24/** OpenCode stores uncached input and reasoning separately from input/output. */
25function parseOpenCodeMessage(
26 source: string,
27 fallback: {
28 readonly id?: string;
29 readonly sessionId?: string;
30 readonly timestampMs?: number;
31 } = {},
32): UsageRecord | null {
33 let parsed: unknown;
34 try {
35 parsed = JSON.parse(source);
36 } catch {
37 return null;
38 }
39 const message = object(parsed);
40 if (message.role !== undefined && message.role !== "assistant") return null;
41 const usage = object(message.tokens);
42 const cache = object(usage.cache);
43 const modelReference = object(message.model);
44 const model = text(modelReference.id) || text(modelReference.modelID) || text(message.modelID);
45 const timestampMs = object(message.time).created ?? fallback.timestampMs;
46 if (!model || typeof timestampMs !== "number" || !Number.isFinite(timestampMs)) return null;
47 const reasoningTokens = tokens(usage.reasoning);
48 const totals = {
49 uncachedInputTokens: tokens(usage.input),
50 cachedInputTokens: tokens(cache.read),
51 cacheCreationTokens: tokens(cache.write),
52 outputTokens: tokens(usage.output) + reasoningTokens,
53 reasoningTokens,
54 };
55 if (totalTokens(totals) === 0) return null;
56 const id = fallback.id || text(message.id);
57 const cost = message.cost;
58 return {
59 provider: "opencode",
60 timestampMs,
61 model,
62 sessionId: fallback.sessionId || text(message.sessionID),
63 totals,
64 // OpenCode writes zero for models without a known rate, including paid
65 // subscription models. Let the shared price table estimate those records.
66 reportedCostUsd: typeof cost === "number" && Number.isFinite(cost) && cost > 0 ? cost : null,
67 speed: "standard",
68 dedupeKey: id ? `opencode:${id}` : null,
69 };
71​
72export interface OpenCodeUsageReadResult {
73 readonly files: readonly { readonly path: string; readonly records: readonly UsageRecord[] }[];
74 readonly missing: boolean;
75 readonly error: boolean;
77​
78/** Reads current SQLite and pre-migration JSON stores without modifying either. */
79export async function readOpenCodeUsage(
80 root: string,
81 sinceMs: number,
82): Promise<OpenCodeUsageReadResult> {
83 const files: { path: string; records: UsageRecord[] }[] = [];
84 const seen = new Set<string>();
85 let found = false;
86 let error = false;
87 const append = (records: UsageRecord[], record: UsageRecord | null) => {
88 if (record === null || record.timestampMs < sinceMs) return;
89 if (record.dedupeKey !== null) {
90 if (seen.has(record.dedupeKey)) return;
91 seen.add(record.dedupeKey);
92 }
93 records.push(record);
94 };
95​
96 let databases: string[] = [];
97 try {
98 databases = (await NodeFSP.readdir(root, { withFileTypes: true }))
99 .filter((entry) => entry.isFile() && /^opencode(?:-[a-zA-Z0-9_-]+)?\.db$/.test(entry.name))
100 .map((entry) => entry.name)
101 .sort((a, b) => (a === "opencode.db" ? -1 : b === "opencode.db" ? 1 : a.localeCompare(b)));
102 } catch (cause) {
103 if (object(cause).code !== "ENOENT") error = true;
104 }
105 for (const name of databases) {
106 found = true;
107 const file = { path: NodePath.join(root, name), records: [] as UsageRecord[] };
108 files.push(file);
109 let database: NodeSqlite.DatabaseSync | undefined;
110 try {
111 database = new NodeSqlite.DatabaseSync(NodePath.join(root, name), { readOnly: true });
112 // A busy live provider should fail this source promptly rather than
113 // stalling the server while SQLite waits for its writer.
114 database.exec("PRAGMA busy_timeout = 100");
115 const tables = new Set(
116 database
117 .prepare("SELECT name FROM sqlite_master WHERE type = 'table'")
118 .all()
119 .map((row) => row.name),
120 );
121 if (!tables.has("message") && !tables.has("session_message")) error = true;
122 for (const table of ["message", "session_message"] as const) {
123 if (!tables.has(table)) continue;
124 const columns = new Set(
125 database
126 .prepare(`PRAGMA table_info(${table})`)
127 .all()
128 .map((row) => row.name),
129 );
130 const timestamp = columns.has("time_created") ? "time_created" : "NULL";
131 const predicates = table === "session_message" ? ["type = 'assistant'"] : [];
132 if (timestamp !== "NULL") predicates.push("time_created >= ?");
133 const where = predicates.length > 0 ? ` WHERE ${predicates.join(" AND ")}` : "";
134 const statement = database.prepare(
135 `SELECT id, session_id, data, ${timestamp} AS created FROM ${table}${where}`,
136 );
137 let count = 0;
138 for (const row of statement.iterate(...(timestamp === "NULL" ? [] : [sinceMs]))) {
139 append(
140 file.records,
141 parseOpenCodeMessage(text(row.data), {
142 id: text(row.id),
143 sessionId: text(row.session_id),
144 ...(typeof row.created === "number" ? { timestampMs: row.created } : {}),
145 }),
146 );
147 if (++count % 256 === 0) await NodeTimersPromises.setImmediate();
148 }
149 }
150 } catch {
151 error = true;
152 } finally {
153 database?.close();
154 }
155 }
156​
157 // Do not follow symlinks, including cycles. Database records win over their
158 // old JSON copies when OpenCode has migrated a store in place.
159 const directories = [NodePath.join(root, "storage", "message")];
160 while (directories.length > 0) {
161 const directory = directories.pop()!;
162 try {
163 for (const entry of await NodeFSP.readdir(directory, { withFileTypes: true })) {
164 const path = NodePath.join(directory, entry.name);
165 if (entry.isDirectory()) {
166 directories.push(path);
167 } else if (entry.isFile() && entry.name.endsWith(".json")) {
168 found = true;
169 const id = entry.name.slice(0, -5);
170 if (seen.has(`opencode:${id}`)) continue;
171 const file = { path, records: [] as UsageRecord[] };
172 files.push(file);
173 try {
174 append(
175 file.records,
176 parseOpenCodeMessage(await NodeFSP.readFile(path, "utf8"), { id }),
177 );
178 } catch (cause) {
179 if (object(cause).code !== "ENOENT") error = true;
180 }
181 }
182 }
183 } catch (cause) {
184 if (object(cause).code !== "ENOENT") error = true;
185 }
186 }
187 return { files, missing: !found && !error, error };