Open History to see the last commit
1import { expandHomePath } from "@t3tools/provider-core/server/pathExpansion";
2import {
3 totalTokens,
4 type ProviderUsageReader,
5 type UsageRecord,
6} from "@t3tools/provider-core/server/usage";
7import * as HostProcess from "@t3tools/shared/HostProcess";
8import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";
9import * as Effect from "effect/Effect";
10import * as FileSystem from "effect/FileSystem";
11import * as Option from "effect/Option";
12import * as Path from "effect/Path";
13import type * as PlatformError from "effect/PlatformError";
14import * as SqlClient from "effect/sql/SqlClient";
15
16import type { OpenCodeSettings } from "../settings.ts";
17
18function object(value: unknown): Record<string, unknown> {
19 return typeof value === "object" && value !== null && !Array.isArray(value)
20 ? (value as Record<string, unknown>)
21 : {};
22}
23
24function tokens(value: unknown): number {
25 return typeof value === "number" && Number.isFinite(value) && value > 0 ? Math.trunc(value) : 0;
26}
27
28function text(value: unknown): string {
29 return typeof value === "string" ? value : "";
30}
31
32function parseOpenCodeMessage(
33 source: string,
34 fallback: {
35 readonly id?: string;
36 readonly sessionId?: string;
37 readonly timestampMs?: number;
38 } = {},
39): UsageRecord | null {
40 let parsed: unknown;
41 try {
42 parsed = JSON.parse(source);
43 } catch {
44 return null;
45 }
46 const message = object(parsed);
47 if (message.role !== undefined && message.role !== "assistant") return null;
48 const usage = object(message.tokens);
49 const cache = object(usage.cache);
50 const modelReference = object(message.model);
51 const model = text(modelReference.id) || text(modelReference.modelID) || text(message.modelID);
52 const timestampMs = object(message.time).created ?? fallback.timestampMs;
53 if (!model || typeof timestampMs !== "number" || !Number.isFinite(timestampMs)) return null;
54 const reasoningTokens = tokens(usage.reasoning);
55 const totals = {
56 uncachedInputTokens: tokens(usage.input),
57 cachedInputTokens: tokens(cache.read),
58 cacheCreationTokens: tokens(cache.write),
59 outputTokens: tokens(usage.output) + reasoningTokens,
60 reasoningTokens,
61 };
62 if (totalTokens(totals) === 0) return null;
63 const id = fallback.id || text(message.id);
64 const cost = message.cost;
65 return {
66 provider: "opencode",
67 timestampMs,
68 model,
69 sessionId: fallback.sessionId || text(message.sessionID),
70 totals,
71 // OpenCode uses zero for unknown rates, including paid subscriptions; let shared pricing estimate.
72 reportedCostUsd: typeof cost === "number" && Number.isFinite(cost) && cost > 0 ? cost : null,
73 speed: "standard",
74 dedupeKey: id ? `opencode:${id}` : null,
75 };
76}
77
78export interface OpenCodeUsageReadResult {
79 readonly files: readonly { readonly path: string; readonly records: readonly UsageRecord[] }[];
80 readonly missing: boolean;
81 readonly error: boolean;
82}
83
84const isNotFound = (cause: PlatformError.PlatformError) => cause.reason._tag === "NotFound";
85const MESSAGE_PAGE_SIZE = 64;
86
87const isSymbolicLink = Effect.fnUntraced(function* (path: string) {
88 const fileSystem = yield* FileSystem.FileSystem;
89 return yield* Effect.isSuccess(fileSystem.readLink(path));
90});
91
92const entryInfo = Effect.fn("entryInfo")(function* (path: string) {
93 const fileSystem = yield* FileSystem.FileSystem;
94 if (yield* isSymbolicLink(path))
95 return { type: "SymbolicLink" as const, mtime: Option.none<Date>() };
96 return yield* fileSystem.stat(path);
97});
98
99const LEGACY_STAT_CONCURRENCY = 4;
100
101// Batch stats so huge directories do not stay in memory.
102const LEGACY_STAT_BATCH = 256;
103
104export const readOpenCodeUsage = Effect.fn("readOpenCodeUsage")(function* (
105 root: string,
106 sinceMs: number,
107): Effect.fn.Return<OpenCodeUsageReadResult, never, FileSystem.FileSystem | Path.Path> {
108 const fileSystem = yield* FileSystem.FileSystem;
109 const path = yield* Path.Path;
110 const files: { path: string; records: UsageRecord[] }[] = [];
111 const seen = new Set<string>();
112 let found = false;
113 let error = false;
114 const append = (records: UsageRecord[], record: UsageRecord | null) => {
115 if (record === null || record.timestampMs < sinceMs) return;
116 if (record.dedupeKey !== null) {
117 if (seen.has(record.dedupeKey)) return;
118 seen.add(record.dedupeKey);
119 }
120 records.push(record);
121 };
122
123 const databases = yield* fileSystem.readDirectory(root).pipe(
124 Effect.flatMap((names) =>
125 Effect.filter(
126 names.filter((name) => /^opencode(?:-[a-zA-Z0-9_-]+)?\.db$/.test(name)),
127 (name) =>
128 entryInfo(path.join(root, name)).pipe(
129 Effect.map((info) => info.type === "File"),
130 Effect.catchTags({
131 PlatformError: (cause) =>
132 isNotFound(cause) ? Effect.succeed(false) : Effect.fail(cause),
133 }),
134 ),
135 ),
136 ),
137 Effect.map((names) =>
138 names.sort((a, b) =>
139 a === "opencode.db" ? -1 : b === "opencode.db" ? 1 : a.localeCompare(b),
140 ),
141 ),
142 Effect.catchTags({
143 PlatformError: (cause) => {
144 if (!isNotFound(cause)) error = true;
145 return Effect.succeed([]);
146 },
147 }),
148 );
149 for (const name of databases) {
150 found = true;
151 const file = { path: path.join(root, name), records: [] as UsageRecord[] };
152 files.push(file);
153 yield* Effect.gen(function* () {
154 const sql = yield* SqlClient.SqlClient;
155 // Fail promptly on live-writer locks instead of stalling the server.
156 yield* sql.unsafe("PRAGMA busy_timeout = 100");
157 const tables = new Set(
158 (yield* sql.unsafe<{ readonly name: unknown }>(
159 "SELECT name FROM sqlite_master WHERE type = 'table'",
160 )).map((row) => row.name),
161 );
162 if (!tables.has("message") && !tables.has("session_message")) error = true;
163 for (const table of ["message", "session_message"] as const) {
164 if (!tables.has(table)) continue;
165 const columns = new Set(
166 (yield* sql.unsafe<{ readonly name: unknown }>(`PRAGMA table_info(${table})`)).map(
167 (row) => row.name,
168 ),
169 );
170 const timestamp = columns.has("time_created") ? "time_created" : "NULL";
171 const predicates = table === "session_message" ? ["type = 'assistant'"] : [];
172 if (timestamp !== "NULL") predicates.push("time_created >= ?");
173 predicates.push("rowid > ?", "rowid <= ?");
174 const [range] = yield* sql.unsafe<{
175 readonly first_row_id: number | null;
176 readonly last_row_id: number | null;
177 }>(
178 `SELECT (SELECT MIN(rowid) FROM ${table}) AS first_row_id, (SELECT MAX(rowid) FROM ${table}) AS last_row_id`,
179 );
180 const firstRowId = range?.first_row_id;
181 const lastRowId = range?.last_row_id;
182 if (typeof firstRowId !== "number" || typeof lastRowId !== "number") continue;
183 // StatementSync.all materializes results; page by rowid and exclude mid-scan appends.
184 // Omit tracing because large histories require thousands of statements.
185 for (let after = firstRowId - 1; after < lastRowId; after += MESSAGE_PAGE_SIZE) {
186 const rows = yield* sql
187 .unsafe<{
188 readonly id: unknown;
189 readonly session_id: unknown;
190 readonly data: unknown;
191 readonly created: unknown;
192 }>(
193 `SELECT id, session_id, data, ${timestamp} AS created
194 FROM ${table} WHERE ${predicates.join(" AND ")} ORDER BY rowid`,
195 [
196 ...(timestamp === "NULL" ? [] : [sinceMs]),
197 after,
198 Math.min(after + MESSAGE_PAGE_SIZE, lastRowId),
199 ],
200 )
201 .pipe(Effect.withTracerEnabled(false));
202 for (const row of rows) {
203 append(
204 file.records,
205 parseOpenCodeMessage(text(row.data), {
206 id: text(row.id),
207 sessionId: text(row.session_id),
208 ...(typeof row.created === "number" ? { timestampMs: row.created } : {}),
209 }),
210 );
211 }
212 yield* Effect.yieldNow;
213 }
214 }
215 }).pipe(
216 Effect.provide(NodeSqliteClient.layer({ filename: file.path, readonly: true })),
217 Effect.catchTags({
218 SqlError: () => {
219 error = true;
220 return Effect.void;
221 },
222 }),
223 );
224 }
225
226 const directories = [path.join(root, "storage", "message")];
227 while (directories.length > 0) {
228 const directory = directories.pop()!;
229 yield* Effect.gen(function* () {
230 const names = yield* fileSystem.readDirectory(directory);
231 for (let start = 0; start < names.length; start += LEGACY_STAT_BATCH) {
232 const batch = names.slice(start, start + LEGACY_STAT_BATCH);
233 const entries = batch.map((name) => path.join(directory, name));
234 // stat follows symlinks; avoid expensive readLink failures unless link identity matters.
235 const infos = yield* Effect.forEach(
236 entries,
237 (entry) =>
238 fileSystem.stat(entry).pipe(
239 Effect.catchTags({
240 PlatformError: (cause) =>
241 isNotFound(cause)
242 ? Effect.succeed(null)
243 : isSymbolicLink(entry).pipe(
244 Effect.flatMap((link) =>
245 link ? Effect.succeed(null) : Effect.fail(cause),
246 ),
247 ),
248 }),
249 Effect.exit,
250 ),
251 { concurrency: LEGACY_STAT_CONCURRENCY },
252 );
253 for (const [index, name] of batch.entries()) {
254 const entry = entries[index]!;
255 const info = yield* infos[index]!;
256 if (info?.type === "Directory") {
257 if (!(yield* isSymbolicLink(entry))) directories.push(entry);
258 } else if (info?.type === "File" && name.endsWith(".json")) {
259 const id = name.slice(0, -5);
260 // Messages cannot postdate file mtime; older files hold no in-window usage.
261 const skip =
262 seen.has(`opencode:${id}`) ||
263 Option.exists(info.mtime, (mtime) => mtime.getTime() < sinceMs);
264 if (found && skip) continue;
265 if (yield* isSymbolicLink(entry)) continue;
266 found = true;
267 if (skip) continue;
268 const file = { path: entry, records: [] as UsageRecord[] };
269 files.push(file);
270 yield* fileSystem.readFileString(entry).pipe(
271 Effect.map((source) => append(file.records, parseOpenCodeMessage(source, { id }))),
272 Effect.catchTags({
273 PlatformError: (cause) => {
274 if (!isNotFound(cause)) error = true;
275 return Effect.void;
276 },
277 }),
278 );
279 }
280 }
281 }
282 }).pipe(
283 Effect.catchTags({
284 PlatformError: (cause) => {
285 if (!isNotFound(cause)) error = true;
286 return Effect.void;
287 },
288 }),
289 );
290 }
291 return { files, missing: !found && !error, error };
292});
293
294const resolveOpenCodeDataDirs = Effect.fn("resolveOpenCodeDataDirs")(function* (
295 environment: NodeJS.ProcessEnv,
296) {
297 const fileSystem = yield* FileSystem.FileSystem;
298 const path = yield* Path.Path;
299 const homeDirectory = yield* HostProcess.HomeDirectory;
300 const roots = environment["OPENCODE_DATA_DIR"]
301 ?.split(",")
302 .map((value) => value.trim())
303 .filter(Boolean);
304 const dataHome = environment["XDG_DATA_HOME"]?.trim();
305 const defaults = [
306 path.join(
307 dataHome && path.isAbsolute(dataHome)
308 ? dataHome
309 : path.join(homeDirectory, ".local", "share"),
310 "opencode",
311 ),
312 ];
313 const canonical = new Set<string>();
314 for (const root of roots?.length ? roots : defaults) {
315 const resolved = path.resolve(expandHomePath(root, homeDirectory));
316 canonical.add(yield* fileSystem.realPath(resolved).pipe(Effect.orElseSucceed(() => resolved)));
317 }
318 return [...canonical];
319});
320
321export type OpenCodeUsageReaderEnv = FileSystem.FileSystem | Path.Path;
322
323export const openCodeUsageReader: ProviderUsageReader<OpenCodeSettings, OpenCodeUsageReaderEnv> = {
324 kind: "scan",
325 provider: "opencode",
326 scan: Effect.fn("openCodeUsageReader.scan")(function* ({ instances, windowStartMs }) {
327 const roots = new Set<string>();
328 for (const instance of instances) {
329 for (const root of yield* resolveOpenCodeDataDirs(instance.environment)) roots.add(root);
330 }
331 return yield* Effect.forEach(
332 roots,
333 (dir) =>
334 readOpenCodeUsage(dir, windowStartMs).pipe(
335 Effect.map((result) => ({
336 dir,
337 files: result.missing && !result.error ? null : result.files,
338 status: result.error ? ("partial" as const) : ("ok" as const),
339 ...(result.error ? { message: "Some OpenCode history could not be read." } : {}),
340 })),
341 ),
342 { concurrency: "unbounded" },
343 );
344 }),
345};