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 */
7
8import { expandHomePath } from "@t3tools/provider-core/server/pathExpansion";
9import {
10 totalTokens,
11 type ProviderUsageReader,
12 type UsageRecord,
13} from "@t3tools/provider-core/server/usage";
14import * as HostProcess from "@t3tools/shared/HostProcess";
15import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";
16import * as Effect from "effect/Effect";
17import * as Exit from "effect/Exit";
18import * as FileSystem from "effect/FileSystem";
19import * as Path from "effect/Path";
20import type * as PlatformError from "effect/PlatformError";
21import * as SqlClient from "effect/sql/SqlClient";
22
23import type { OpenCodeSettings } from "../settings.ts";
24
25function object(value: unknown): Record<string, unknown> {
26 return typeof value === "object" && value !== null && !Array.isArray(value)
27 ? (value as Record<string, unknown>)
28 : {};
29}
30
31function tokens(value: unknown): number {
32 return typeof value === "number" && Number.isFinite(value) && value > 0 ? Math.trunc(value) : 0;
33}
34
35function text(value: unknown): string {
36 return typeof value === "string" ? value : "";
37}
38
39/** OpenCode stores uncached input and reasoning separately from input/output. */
40function parseOpenCodeMessage(
41 source: string,
42 fallback: {
43 readonly id?: string;
44 readonly sessionId?: string;
45 readonly timestampMs?: number;
46 } = {},
47): UsageRecord | null {
48 let parsed: unknown;
49 try {
50 parsed = JSON.parse(source);
51 } catch {
52 return null;
53 }
54 const message = object(parsed);
55 if (message.role !== undefined && message.role !== "assistant") return null;
56 const usage = object(message.tokens);
57 const cache = object(usage.cache);
58 const modelReference = object(message.model);
59 const model = text(modelReference.id) || text(modelReference.modelID) || text(message.modelID);
60 const timestampMs = object(message.time).created ?? fallback.timestampMs;
61 if (!model || typeof timestampMs !== "number" || !Number.isFinite(timestampMs)) return null;
62 const reasoningTokens = tokens(usage.reasoning);
63 const totals = {
64 uncachedInputTokens: tokens(usage.input),
65 cachedInputTokens: tokens(cache.read),
66 cacheCreationTokens: tokens(cache.write),
67 outputTokens: tokens(usage.output) + reasoningTokens,
68 reasoningTokens,
69 };
70 if (totalTokens(totals) === 0) return null;
71 const id = fallback.id || text(message.id);
72 const cost = message.cost;
73 return {
74 provider: "opencode",
75 timestampMs,
76 model,
77 sessionId: fallback.sessionId || text(message.sessionID),
78 totals,
79 // OpenCode writes zero for models without a known rate, including paid
80 // subscription models. Let the shared price table estimate those records.
81 reportedCostUsd: typeof cost === "number" && Number.isFinite(cost) && cost > 0 ? cost : null,
82 speed: "standard",
83 dedupeKey: id ? `opencode:${id}` : null,
84 };
85}
86
87export interface OpenCodeUsageReadResult {
88 readonly files: readonly { readonly path: string; readonly records: readonly UsageRecord[] }[];
89 readonly missing: boolean;
90 readonly error: boolean;
91}
92
93const isNotFound = (cause: PlatformError.PlatformError) => cause.reason._tag === "NotFound";
94
95/** A regular file or directory, never a symlink to one. */
96const entryType = Effect.fn("entryType")(function* (path: string) {
97 const fileSystem = yield* FileSystem.FileSystem;
98 const link = yield* Effect.exit(fileSystem.readLink(path));
99 if (Exit.isSuccess(link)) return "SymbolicLink" as const;
100 return (yield* fileSystem.stat(path)).type;
101});
102
103/** Reads current SQLite and pre-migration JSON stores without modifying either. */
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 // One database removed between listing and stat must not hide the rest.
128 (name) =>
129 entryType(path.join(root, name)).pipe(
130 Effect.map((type) => type === "File"),
131 Effect.catchTags({
132 PlatformError: (cause) =>
133 isNotFound(cause) ? Effect.succeed(false) : Effect.fail(cause),
134 }),
135 ),
136 ),
137 ),
138 Effect.map((names) =>
139 names.sort((a, b) =>
140 a === "opencode.db" ? -1 : b === "opencode.db" ? 1 : a.localeCompare(b),
141 ),
142 ),
143 Effect.catchTags({
144 PlatformError: (cause) => {
145 if (!isNotFound(cause)) error = true;
146 return Effect.succeed([]);
147 },
148 }),
149 );
150 for (const name of databases) {
151 found = true;
152 const file = { path: path.join(root, name), records: [] as UsageRecord[] };
153 files.push(file);
154 yield* Effect.gen(function* () {
155 const sql = yield* SqlClient.SqlClient;
156 // A busy live provider should fail this source promptly rather than
157 // stalling the server while SQLite waits for its writer.
158 yield* sql.unsafe("PRAGMA busy_timeout = 100");
159 const tables = new Set(
160 (yield* sql.unsafe<{ readonly name: unknown }>(
161 "SELECT name FROM sqlite_master WHERE type = 'table'",
162 )).map((row) => row.name),
163 );
164 if (!tables.has("message") && !tables.has("session_message")) error = true;
165 for (const table of ["message", "session_message"] as const) {
166 if (!tables.has(table)) continue;
167 const columns = new Set(
168 (yield* sql.unsafe<{ readonly name: unknown }>(`PRAGMA table_info(${table})`)).map(
169 (row) => row.name,
170 ),
171 );
172 const timestamp = columns.has("time_created") ? "time_created" : "NULL";
173 const predicates = table === "session_message" ? ["type = 'assistant'"] : [];
174 if (timestamp !== "NULL") predicates.push("time_created >= ?");
175 const where = predicates.length > 0 ? ` WHERE ${predicates.join(" AND ")}` : "";
176 const rows = yield* sql.unsafe<{
177 readonly id: unknown;
178 readonly session_id: unknown;
179 readonly data: unknown;
180 readonly created: unknown;
181 }>(
182 `SELECT id, session_id, data, ${timestamp} AS created FROM ${table}${where}`,
183 timestamp === "NULL" ? [] : [sinceMs],
184 );
185 for (const [index, row] of rows.entries()) {
186 append(
187 file.records,
188 parseOpenCodeMessage(text(row.data), {
189 id: text(row.id),
190 sessionId: text(row.session_id),
191 ...(typeof row.created === "number" ? { timestampMs: row.created } : {}),
192 }),
193 );
194 if (index % 256 === 255) yield* Effect.yieldNow;
195 }
196 }
197 }).pipe(
198 Effect.provide(NodeSqliteClient.layer({ filename: file.path, readonly: true })),
199 Effect.catchTags({
200 SqlError: () => {
201 error = true;
202 return Effect.void;
203 },
204 }),
205 );
206 }
207
208 // Do not follow symlinks, including cycles. Database records win over their
209 // old JSON copies when OpenCode has migrated a store in place.
210 const directories = [path.join(root, "storage", "message")];
211 while (directories.length > 0) {
212 const directory = directories.pop()!;
213 yield* Effect.gen(function* () {
214 for (const name of yield* fileSystem.readDirectory(directory)) {
215 const entry = path.join(directory, name);
216 const type = yield* entryType(entry).pipe(
217 Effect.catchTags({
218 PlatformError: (cause) =>
219 isNotFound(cause) ? Effect.succeed(null) : Effect.fail(cause),
220 }),
221 );
222 if (type === "Directory") {
223 directories.push(entry);
224 } else if (type === "File" && name.endsWith(".json")) {
225 found = true;
226 const id = name.slice(0, -5);
227 if (seen.has(`opencode:${id}`)) continue;
228 const file = { path: entry, records: [] as UsageRecord[] };
229 files.push(file);
230 yield* fileSystem.readFileString(entry).pipe(
231 Effect.map((source) => append(file.records, parseOpenCodeMessage(source, { id }))),
232 Effect.catchTags({
233 PlatformError: (cause) => {
234 if (!isNotFound(cause)) error = true;
235 return Effect.void;
236 },
237 }),
238 );
239 }
240 }
241 }).pipe(
242 Effect.catchTags({
243 PlatformError: (cause) => {
244 if (!isNotFound(cause)) error = true;
245 return Effect.void;
246 },
247 }),
248 );
249 }
250 return { files, missing: !found && !error, error };
251});
252
253/**
254 * The data directories to read: `OPENCODE_DATA_DIR` (comma-separated) or the
255 * XDG default, canonicalized so aliases count once.
256 */
257const resolveOpenCodeDataDirs = Effect.fn("resolveOpenCodeDataDirs")(function* () {
258 const fileSystem = yield* FileSystem.FileSystem;
259 const path = yield* Path.Path;
260 const environment = yield* HostProcess.Environment;
261 const homeDirectory = yield* HostProcess.HomeDirectory;
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(homeDirectory, ".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, homeDirectory));
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};