Open History to see the last commit
1/**
2 * Usage history for OpenCode, read from its SQLite databases and legacy JSON
3 * message store under each data directory.
4 *
5 * @module provider-opencode/server/usage
6 */
7import * as NodeOS from "node:os";
8
9import { expandHomePath } from "@t3tools/provider-core/server/pathExpansion";
10import {
11 totalTokens,
12 type ProviderUsageReader,
13 type UsageRecord,
14} from "@t3tools/provider-core/server/usage";
15import { HostProcessEnvironment } from "@t3tools/shared/hostProcess";
16import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";
17import * as Effect from "effect/Effect";
18import * as Exit from "effect/Exit";
19import * as FileSystem from "effect/FileSystem";
20import * as Path from "effect/Path";
21import type * as PlatformError from "effect/PlatformError";
22import * as SqlClient from "effect/sql/SqlClient";
23
24import type { OpenCodeSettings } from "../settings.ts";
25
26function object(value: unknown): Record<string, unknown> {
27 return typeof value === "object" && value !== null && !Array.isArray(value)
28 ? (value as Record<string, unknown>)
29 : {};
30}
31
32function tokens(value: unknown): number {
33 return typeof value === "number" && Number.isFinite(value) && value > 0 ? Math.trunc(value) : 0;
34}
35
36function text(value: unknown): string {
37 return typeof value === "string" ? value : "";
38}
39
40/** OpenCode stores uncached input and reasoning separately from input/output. */
41function parseOpenCodeMessage(
42 source: string,
43 fallback: {
44 readonly id?: string;
45 readonly sessionId?: string;
46 readonly timestampMs?: number;
47 } = {},
48): UsageRecord | null {
49 let parsed: unknown;
50 try {
51 parsed = JSON.parse(source);
52 } catch {
53 return null;
54 }
55 const message = object(parsed);
56 if (message.role !== undefined && message.role !== "assistant") return null;
57 const usage = object(message.tokens);
58 const cache = object(usage.cache);
59 const modelReference = object(message.model);
60 const model = text(modelReference.id) || text(modelReference.modelID) || text(message.modelID);
61 const timestampMs = object(message.time).created ?? fallback.timestampMs;
62 if (!model || typeof timestampMs !== "number" || !Number.isFinite(timestampMs)) return null;
63 const reasoningTokens = tokens(usage.reasoning);
64 const totals = {
65 uncachedInputTokens: tokens(usage.input),
66 cachedInputTokens: tokens(cache.read),
67 cacheCreationTokens: tokens(cache.write),
68 outputTokens: tokens(usage.output) + reasoningTokens,
69 reasoningTokens,
70 };
71 if (totalTokens(totals) === 0) return null;
72 const id = fallback.id || text(message.id);
73 const cost = message.cost;
74 return {
75 provider: "opencode",
76 timestampMs,
77 model,
78 sessionId: fallback.sessionId || text(message.sessionID),
79 totals,
80 // OpenCode writes zero for models without a known rate, including paid
81 // subscription models. Let the shared price table estimate those records.
82 reportedCostUsd: typeof cost === "number" && Number.isFinite(cost) && cost > 0 ? cost : null,
83 speed: "standard",
84 dedupeKey: id ? `opencode:${id}` : null,
85 };
86}
87
88export interface OpenCodeUsageReadResult {
89 readonly files: readonly { readonly path: string; readonly records: readonly UsageRecord[] }[];
90 readonly missing: boolean;
91 readonly error: boolean;
92}
93
94const isNotFound = (cause: PlatformError.PlatformError) => cause.reason._tag === "NotFound";
95
96/** A regular file or directory, never a symlink to one. */
97const entryType = Effect.fn("entryType")(function* (path: string) {
98 const fileSystem = yield* FileSystem.FileSystem;
99 const link = yield* Effect.exit(fileSystem.readLink(path));
100 if (Exit.isSuccess(link)) return "SymbolicLink" as const;
101 return (yield* fileSystem.stat(path)).type;
102});
103
104/** Reads current SQLite and pre-migration JSON stores without modifying either. */
105export const readOpenCodeUsage = Effect.fn("readOpenCodeUsage")(function* (
106 root: string,
107 sinceMs: number,
108): Effect.fn.Return<OpenCodeUsageReadResult, never, FileSystem.FileSystem | Path.Path> {
109 const fileSystem = yield* FileSystem.FileSystem;
110 const path = yield* Path.Path;
111 const files: { path: string; records: UsageRecord[] }[] = [];
112 const seen = new Set<string>();
113 let found = false;
114 let error = false;
115 const append = (records: UsageRecord[], record: UsageRecord | null) => {
116 if (record === null || record.timestampMs < sinceMs) return;
117 if (record.dedupeKey !== null) {
118 if (seen.has(record.dedupeKey)) return;
119 seen.add(record.dedupeKey);
120 }
121 records.push(record);
122 };
123
124 const databases = yield* fileSystem.readDirectory(root).pipe(
125 Effect.flatMap((names) =>
126 Effect.filter(
127 names.filter((name) => /^opencode(?:-[a-zA-Z0-9_-]+)?\.db$/.test(name)),
128 // One database removed between listing and stat must not hide the rest.
129 (name) =>
130 entryType(path.join(root, name)).pipe(
131 Effect.map((type) => type === "File"),
132 Effect.catchTags({
133 PlatformError: (cause) =>
134 isNotFound(cause) ? Effect.succeed(false) : Effect.fail(cause),
135 }),
136 ),
137 ),
138 ),
139 Effect.map((names) =>
140 names.sort((a, b) =>
141 a === "opencode.db" ? -1 : b === "opencode.db" ? 1 : a.localeCompare(b),
142 ),
143 ),
144 Effect.catchTags({
145 PlatformError: (cause) => {
146 if (!isNotFound(cause)) error = true;
147 return Effect.succeed([]);
148 },
149 }),
150 );
151 for (const name of databases) {
152 found = true;
153 const file = { path: path.join(root, name), records: [] as UsageRecord[] };
154 files.push(file);
155 yield* Effect.gen(function* () {
156 const sql = yield* SqlClient.SqlClient;
157 // A busy live provider should fail this source promptly rather than
158 // stalling the server while SQLite waits for its writer.
159 yield* sql.unsafe("PRAGMA busy_timeout = 100");
160 const tables = new Set(
161 (yield* sql.unsafe<{ readonly name: unknown }>(
162 "SELECT name FROM sqlite_master WHERE type = 'table'",
163 )).map((row) => row.name),
164 );
165 if (!tables.has("message") && !tables.has("session_message")) error = true;
166 for (const table of ["message", "session_message"] as const) {
167 if (!tables.has(table)) continue;
168 const columns = new Set(
169 (yield* sql.unsafe<{ readonly name: unknown }>(`PRAGMA table_info(${table})`)).map(
170 (row) => row.name,
171 ),
172 );
173 const timestamp = columns.has("time_created") ? "time_created" : "NULL";
174 const predicates = table === "session_message" ? ["type = 'assistant'"] : [];
175 if (timestamp !== "NULL") predicates.push("time_created >= ?");
176 const where = predicates.length > 0 ? ` WHERE ${predicates.join(" AND ")}` : "";
177 const rows = yield* sql.unsafe<{
178 readonly id: unknown;
179 readonly session_id: unknown;
180 readonly data: unknown;
181 readonly created: unknown;
182 }>(
183 `SELECT id, session_id, data, ${timestamp} AS created FROM ${table}${where}`,
184 timestamp === "NULL" ? [] : [sinceMs],
185 );
186 for (const [index, row] of rows.entries()) {
187 append(
188 file.records,
189 parseOpenCodeMessage(text(row.data), {
190 id: text(row.id),
191 sessionId: text(row.session_id),
192 ...(typeof row.created === "number" ? { timestampMs: row.created } : {}),
193 }),
194 );
195 if (index % 256 === 255) yield* Effect.yieldNow;
196 }
197 }
198 }).pipe(
199 Effect.provide(NodeSqliteClient.layer({ filename: file.path, readonly: true })),
200 Effect.catchTags({
201 SqlError: () => {
202 error = true;
203 return Effect.void;
204 },
205 }),
206 );
207 }
208
209 // Do not follow symlinks, including cycles. Database records win over their
210 // old JSON copies when OpenCode has migrated a store in place.
211 const directories = [path.join(root, "storage", "message")];
212 while (directories.length > 0) {
213 const directory = directories.pop()!;
214 yield* Effect.gen(function* () {
215 for (const name of yield* fileSystem.readDirectory(directory)) {
216 const entry = path.join(directory, name);
217 const type = yield* entryType(entry).pipe(
218 Effect.catchTags({
219 PlatformError: (cause) =>
220 isNotFound(cause) ? Effect.succeed(null) : Effect.fail(cause),
221 }),
222 );
223 if (type === "Directory") {
224 directories.push(entry);
225 } else if (type === "File" && name.endsWith(".json")) {
226 found = true;
227 const id = name.slice(0, -5);
228 if (seen.has(`opencode:${id}`)) continue;
229 const file = { path: entry, records: [] as UsageRecord[] };
230 files.push(file);
231 yield* fileSystem.readFileString(entry).pipe(
232 Effect.map((source) => append(file.records, parseOpenCodeMessage(source, { id }))),
233 Effect.catchTags({
234 PlatformError: (cause) => {
235 if (!isNotFound(cause)) error = true;
236 return Effect.void;
237 },
238 }),
239 );
240 }
241 }
242 }).pipe(
243 Effect.catchTags({
244 PlatformError: (cause) => {
245 if (!isNotFound(cause)) error = true;
246 return Effect.void;
247 },
248 }),
249 );
250 }
251 return { files, missing: !found && !error, error };
252});
253
254/**
255 * The data directories to read: `OPENCODE_DATA_DIR` (comma-separated) or the
256 * XDG default, canonicalized so aliases count once.
257 */
258const resolveOpenCodeDataDirs = Effect.fn("resolveOpenCodeDataDirs")(function* () {
259 const fileSystem = yield* FileSystem.FileSystem;
260 const path = yield* Path.Path;
261 const environment = yield* HostProcessEnvironment;
262 const roots = environment["OPENCODE_DATA_DIR"]
263 ?.split(",")
264 .map((value) => value.trim())
265 .filter(Boolean);
266 const dataHome = environment["XDG_DATA_HOME"]?.trim();
267 const defaults = [
268 path.join(
269 dataHome && path.isAbsolute(dataHome)
270 ? dataHome
271 : path.join(NodeOS.homedir(), ".local", "share"),
272 "opencode",
273 ),
274 ];
275 const canonical = new Set<string>();
276 for (const root of roots?.length ? roots : defaults) {
277 const resolved = path.resolve(expandHomePath(root));
278 canonical.add(yield* fileSystem.realPath(resolved).pipe(Effect.orElseSucceed(() => resolved)));
279 }
280 return [...canonical];
281});
282
283export type OpenCodeUsageReaderEnv = FileSystem.FileSystem | Path.Path;
284
285export const openCodeUsageReader: ProviderUsageReader<OpenCodeSettings, OpenCodeUsageReaderEnv> = {
286 kind: "scan",
287 provider: "opencode",
288 scan: Effect.fn("openCodeUsageReader.scan")(function* ({ windowStartMs }) {
289 const roots = yield* resolveOpenCodeDataDirs();
290 return yield* Effect.forEach(
291 roots,
292 (dir) =>
293 readOpenCodeUsage(dir, windowStartMs).pipe(
294 Effect.map((result) => ({
295 dir,
296 files: result.missing && !result.error ? null : result.files,
297 status: result.error ? ("partial" as const) : ("ok" as const),
298 ...(result.error ? { message: "Some OpenCode history could not be read." } : {}),
299 })),
300 ),
301 { concurrency: "unbounded" },
302 );
303 }),
304};