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

usage.ts

356 lines13.3 KB

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 : {};
23​
24function tokens(value: unknown): number {
25 return typeof value === "number" && Number.isFinite(value) && value > 0 ? Math.trunc(value) : 0;
27​
28function text(value: unknown): string {
29 return typeof value === "string" ? value : "";
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 writes zero for models without a known rate, including paid
72 // subscription models. Let the shared price table estimate those records.
73 reportedCostUsd: typeof cost === "number" && Number.isFinite(cost) && cost > 0 ? cost : null,
74 speed: "standard",
75 dedupeKey: id ? `opencode:${id}` : null,
76 };
78​
79export interface OpenCodeUsageReadResult {
80 readonly files: readonly { readonly path: string; readonly records: readonly UsageRecord[] }[];
81 readonly missing: boolean;
82 readonly error: boolean;
84​
85const isNotFound = (cause: PlatformError.PlatformError) => cause.reason._tag === "NotFound";
86const MESSAGE_PAGE_SIZE = 64;
87​
88const isSymbolicLink = Effect.fnUntraced(function* (path: string) {
89 const fileSystem = yield* FileSystem.FileSystem;
90 return yield* Effect.isSuccess(fileSystem.readLink(path));
91});
92​
93const entryInfo = Effect.fn("entryInfo")(function* (path: string) {
94 const fileSystem = yield* FileSystem.FileSystem;
95 if (yield* isSymbolicLink(path))
96 return { type: "SymbolicLink" as const, mtime: Option.none<Date>() };
97 return yield* fileSystem.stat(path);
98});
99​
100/**
101 * Stats run in the libuv thread pool, so a few at a time cut the walk's wall
102 * time without lengthening any event-loop turn.
103 */
104const LEGACY_STAT_CONCURRENCY = 4;
105​
106/** Entries stat'd before any is processed, so one huge directory is not held in memory at once. */
107const LEGACY_STAT_BATCH = 256;
108​
109export const readOpenCodeUsage = Effect.fn("readOpenCodeUsage")(function* (
110 root: string,
111 sinceMs: number,
112): Effect.fn.Return<OpenCodeUsageReadResult, never, FileSystem.FileSystem | Path.Path> {
113 const fileSystem = yield* FileSystem.FileSystem;
114 const path = yield* Path.Path;
115 const files: { path: string; records: UsageRecord[] }[] = [];
116 const seen = new Set<string>();
117 let found = false;
118 let error = false;
119 const append = (records: UsageRecord[], record: UsageRecord | null) => {
120 if (record === null || record.timestampMs < sinceMs) return;
121 if (record.dedupeKey !== null) {
122 if (seen.has(record.dedupeKey)) return;
123 seen.add(record.dedupeKey);
124 }
125 records.push(record);
126 };
127​
128 const databases = yield* fileSystem.readDirectory(root).pipe(
129 Effect.flatMap((names) =>
130 Effect.filter(
131 names.filter((name) => /^opencode(?:-[a-zA-Z0-9_-]+)?\.db$/.test(name)),
132 (name) =>
133 entryInfo(path.join(root, name)).pipe(
134 Effect.map((info) => info.type === "File"),
135 Effect.catchTags({
136 PlatformError: (cause) =>
137 isNotFound(cause) ? Effect.succeed(false) : Effect.fail(cause),
138 }),
139 ),
140 ),
141 ),
142 Effect.map((names) =>
143 names.sort((a, b) =>
144 a === "opencode.db" ? -1 : b === "opencode.db" ? 1 : a.localeCompare(b),
145 ),
146 ),
147 Effect.catchTags({
148 PlatformError: (cause) => {
149 if (!isNotFound(cause)) error = true;
150 return Effect.succeed([]);
151 },
152 }),
153 );
154 for (const name of databases) {
155 found = true;
156 const file = { path: path.join(root, name), records: [] as UsageRecord[] };
157 files.push(file);
158 yield* Effect.gen(function* () {
159 const sql = yield* SqlClient.SqlClient;
160 // A busy live provider should fail this source promptly rather than
161 // stalling the server while SQLite waits for its writer.
162 yield* sql.unsafe("PRAGMA busy_timeout = 100");
163 const tables = new Set(
164 (yield* sql.unsafe<{ readonly name: unknown }>(
165 "SELECT name FROM sqlite_master WHERE type = 'table'",
166 )).map((row) => row.name),
167 );
168 if (!tables.has("message") && !tables.has("session_message")) error = true;
169 for (const table of ["message", "session_message"] as const) {
170 if (!tables.has(table)) continue;
171 const columns = new Set(
172 (yield* sql.unsafe<{ readonly name: unknown }>(`PRAGMA table_info(${table})`)).map(
173 (row) => row.name,
174 ),
175 );
176 const timestamp = columns.has("time_created") ? "time_created" : "NULL";
177 const predicates = table === "session_message" ? ["type = 'assistant'"] : [];
178 if (timestamp !== "NULL") predicates.push("time_created >= ?");
179 predicates.push("rowid > ?", "rowid <= ?");
180 const [range] = yield* sql.unsafe<{
181 readonly first_row_id: number | null;
182 readonly last_row_id: number | null;
183 }>(
184 `SELECT (SELECT MIN(rowid) FROM ${table}) AS first_row_id, (SELECT MAX(rowid) FROM ${table}) AS last_row_id`,
185 );
186 const firstRowId = range?.first_row_id;
187 const lastRowId = range?.last_row_id;
188 if (typeof firstRowId !== "number" || typeof lastRowId !== "number") continue;
189 // SqlClient materializes each result with StatementSync.all(), and the
190 // window can exclude most rows. Each statement covers MESSAGE_PAGE_SIZE
191 // rowids, however few match, and rows appended mid-scan are left out.
192 // Untraced, as a large history runs thousands of them.
193 for (let after = firstRowId - 1; after < lastRowId; after += MESSAGE_PAGE_SIZE) {
194 const rows = yield* sql
195 .unsafe<{
196 readonly id: unknown;
197 readonly session_id: unknown;
198 readonly data: unknown;
199 readonly created: unknown;
200 }>(
201 `SELECT id, session_id, data, ${timestamp} AS created
202 FROM ${table} WHERE ${predicates.join(" AND ")} ORDER BY rowid`,
203 [
204 ...(timestamp === "NULL" ? [] : [sinceMs]),
205 after,
206 Math.min(after + MESSAGE_PAGE_SIZE, lastRowId),
207 ],
208 )
209 .pipe(Effect.withTracerEnabled(false));
210 for (const row of rows) {
211 append(
212 file.records,
213 parseOpenCodeMessage(text(row.data), {
214 id: text(row.id),
215 sessionId: text(row.session_id),
216 ...(typeof row.created === "number" ? { timestampMs: row.created } : {}),
217 }),
218 );
219 }
220 yield* Effect.yieldNow;
221 }
222 }
223 }).pipe(
224 Effect.provide(NodeSqliteClient.layer({ filename: file.path, readonly: true })),
225 Effect.catchTags({
226 SqlError: () => {
227 error = true;
228 return Effect.void;
229 },
230 }),
231 );
232 }
233​
234 const directories = [path.join(root, "storage", "message")];
235 while (directories.length > 0) {
236 const directory = directories.pop()!;
237 yield* Effect.gen(function* () {
238 const names = yield* fileSystem.readDirectory(directory);
239 for (let start = 0; start < names.length; start += LEGACY_STAT_BATCH) {
240 const batch = names.slice(start, start + LEGACY_STAT_BATCH);
241 const entries = batch.map((name) => path.join(directory, name));
242 // `stat` follows symlinks and `readLink` fails, expensively, for
243 // everything else. Stat a batch, then ask whether an entry is a symlink
244 // only where the answer changes the result.
245 const infos = yield* Effect.forEach(
246 entries,
247 (entry) =>
248 fileSystem.stat(entry).pipe(
249 Effect.catchTags({
250 PlatformError: (cause) =>
251 isNotFound(cause)
252 ? Effect.succeed(null)
253 : isSymbolicLink(entry).pipe(
254 Effect.flatMap((link) =>
255 link ? Effect.succeed(null) : Effect.fail(cause),
256 ),
257 ),
258 }),
259 Effect.exit,
260 ),
261 { concurrency: LEGACY_STAT_CONCURRENCY },
262 );
263 for (const [index, name] of batch.entries()) {
264 const entry = entries[index]!;
265 const info = yield* infos[index]!;
266 if (info?.type === "Directory") {
267 if (!(yield* isSymbolicLink(entry))) directories.push(entry);
268 } else if (info?.type === "File" && name.endsWith(".json")) {
269 const id = name.slice(0, -5);
270 // A message cannot be created after its file was last written, so a
271 // file untouched since the window opened holds nothing in range.
272 const skip =
273 seen.has(`opencode:${id}`) ||
274 Option.exists(info.mtime, (mtime) => mtime.getTime() < sinceMs);
275 if (found && skip) continue;
276 if (yield* isSymbolicLink(entry)) continue;
277 found = true;
278 if (skip) continue;
279 const file = { path: entry, records: [] as UsageRecord[] };
280 files.push(file);
281 yield* fileSystem.readFileString(entry).pipe(
282 Effect.map((source) => append(file.records, parseOpenCodeMessage(source, { id }))),
283 Effect.catchTags({
284 PlatformError: (cause) => {
285 if (!isNotFound(cause)) error = true;
286 return Effect.void;
287 },
288 }),
289 );
290 }
291 }
292 }
293 }).pipe(
294 Effect.catchTags({
295 PlatformError: (cause) => {
296 if (!isNotFound(cause)) error = true;
297 return Effect.void;
298 },
299 }),
300 );
301 }
302 return { files, missing: !found && !error, error };
303});
304​
305const resolveOpenCodeDataDirs = Effect.fn("resolveOpenCodeDataDirs")(function* (
306 environment: NodeJS.ProcessEnv,
307) {
308 const fileSystem = yield* FileSystem.FileSystem;
309 const path = yield* Path.Path;
310 const homeDirectory = yield* HostProcess.HomeDirectory;
311 const roots = environment["OPENCODE_DATA_DIR"]
312 ?.split(",")
313 .map((value) => value.trim())
314 .filter(Boolean);
315 const dataHome = environment["XDG_DATA_HOME"]?.trim();
316 const defaults = [
317 path.join(
318 dataHome && path.isAbsolute(dataHome)
319 ? dataHome
320 : path.join(homeDirectory, ".local", "share"),
321 "opencode",
322 ),
323 ];
324 const canonical = new Set<string>();
325 for (const root of roots?.length ? roots : defaults) {
326 const resolved = path.resolve(expandHomePath(root, homeDirectory));
327 canonical.add(yield* fileSystem.realPath(resolved).pipe(Effect.orElseSucceed(() => resolved)));
328 }
329 return [...canonical];
330});
331​
332export type OpenCodeUsageReaderEnv = FileSystem.FileSystem | Path.Path;
333​
334export const openCodeUsageReader: ProviderUsageReader<OpenCodeSettings, OpenCodeUsageReaderEnv> = {
335 kind: "scan",
336 provider: "opencode",
337 scan: Effect.fn("openCodeUsageReader.scan")(function* ({ instances, windowStartMs }) {
338 const roots = new Set<string>();
339 for (const instance of instances) {
340 for (const root of yield* resolveOpenCodeDataDirs(instance.environment)) roots.add(root);
341 }
342 return yield* Effect.forEach(
343 roots,
344 (dir) =>
345 readOpenCodeUsage(dir, windowStartMs).pipe(
346 Effect.map((result) => ({
347 dir,
348 files: result.missing && !result.error ? null : result.files,
349 status: result.error ? ("partial" as const) : ("ok" as const),
350 ...(result.error ? { message: "Some OpenCode history could not be read." } : {}),
351 })),
352 ),
353 { concurrency: "unbounded" },
354 );
355 }),
356};