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

usage.ts

355 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 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 };
77​
78export interface OpenCodeUsageReadResult {
79 readonly files: readonly { readonly path: string; readonly records: readonly UsageRecord[] }[];
80 readonly missing: boolean;
81 readonly error: boolean;
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 let databaseRows = 0;
115 let databasePages = 0;
116 const append = (records: UsageRecord[], record: UsageRecord | null) => {
117 if (record === null || record.timestampMs < sinceMs) return;
118 if (record.dedupeKey !== null) {
119 if (seen.has(record.dedupeKey)) return;
120 seen.add(record.dedupeKey);
121 }
122 records.push(record);
123 };
124​
125 const databases = yield* fileSystem.readDirectory(root).pipe(
126 Effect.flatMap((names) =>
127 Effect.filter(
128 names.filter((name) => /^opencode(?:-[a-zA-Z0-9_-]+)?\.db$/.test(name)),
129 (name) =>
130 entryInfo(path.join(root, name)).pipe(
131 Effect.map((info) => info.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 // Fail promptly on live-writer locks instead of stalling the server.
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 // List only rowids so SQLite can use time indexes without reading message bodies.
176 const listed = (yield* sql.unsafe<{ readonly row_id: number }>(
177 `SELECT rowid AS row_id FROM ${table}
178 ${predicates.length ? `WHERE ${predicates.join(" AND ")}` : ""}`,
179 timestamp === "NULL" ? [] : [sinceMs],
180 )).toSorted((a, b) => a.row_id - b.row_id);
181 databaseRows += listed.length;
182 // Filter and project in SQLite: user diffs and assistant bodies can be hundreds of MB.
183 const validAssistant = `CASE WHEN typeof(data) = 'text' AND json_valid(data)
184 THEN json_type(data, '$.role') IS NULL OR data ->> '$.role' = 'assistant' END`;
185 // Omit per-page spans; the enclosing scan records row and page counts.
186 for (let start = 0; start < listed.length; start += MESSAGE_PAGE_SIZE) {
187 const page = listed.slice(start, start + MESSAGE_PAGE_SIZE);
188 databasePages++;
189 const rows = yield* sql
190 .unsafe<{
191 readonly id: unknown;
192 readonly session_id: unknown;
193 readonly data: unknown;
194 readonly created: unknown;
195 }>(
196 `SELECT id, session_id, ${timestamp} AS created, json_object(
197 'tokens', data -> '$.tokens', 'cost', data -> '$.cost',
198 'model', data -> '$.model', 'modelID', data -> '$.modelID',
199 'time', data -> '$.time', 'id', data -> '$.id', 'sessionID', data -> '$.sessionID'
200 ) AS data
201 FROM ${table}
202 WHERE rowid IN (${page.map(() => "?").join(", ")}) AND ${validAssistant}
203 ORDER BY rowid`,
204 page.map((row) => row.row_id),
205 )
206 .pipe(Effect.withTracerEnabled(false));
207 for (const row of rows) {
208 append(
209 file.records,
210 parseOpenCodeMessage(text(row.data), {
211 id: text(row.id),
212 sessionId: text(row.session_id),
213 ...(typeof row.created === "number" ? { timestampMs: row.created } : {}),
214 }),
215 );
216 }
217 yield* Effect.yieldNow;
218 }
219 }
220 }).pipe(
221 (read) => Effect.flatMap(SqlClient.SqlClient, (sql) => sql.withTransaction(read)),
222 Effect.provide(NodeSqliteClient.layer({ filename: file.path, readonly: true })),
223 Effect.catchTags({
224 SqlError: () => {
225 error = true;
226 return Effect.void;
227 },
228 }),
229 );
230 }
231​
232 const directories = [path.join(root, "storage", "message")];
233 while (directories.length > 0) {
234 const directory = directories.pop()!;
235 yield* Effect.gen(function* () {
236 const names = yield* fileSystem.readDirectory(directory);
237 for (let start = 0; start < names.length; start += LEGACY_STAT_BATCH) {
238 const batch = names.slice(start, start + LEGACY_STAT_BATCH);
239 const entries = batch.map((name) => path.join(directory, name));
240 // stat follows symlinks; avoid expensive readLink failures unless link identity matters.
241 const infos = yield* Effect.forEach(
242 entries,
243 (entry) =>
244 fileSystem.stat(entry).pipe(
245 Effect.catchTags({
246 PlatformError: (cause) =>
247 isNotFound(cause)
248 ? Effect.succeed(null)
249 : isSymbolicLink(entry).pipe(
250 Effect.flatMap((link) =>
251 link ? Effect.succeed(null) : Effect.fail(cause),
252 ),
253 ),
254 }),
255 Effect.exit,
256 ),
257 { concurrency: LEGACY_STAT_CONCURRENCY },
258 );
259 for (const [index, name] of batch.entries()) {
260 const entry = entries[index]!;
261 const info = yield* infos[index]!;
262 if (info?.type === "Directory") {
263 if (!(yield* isSymbolicLink(entry))) directories.push(entry);
264 } else if (info?.type === "File" && name.endsWith(".json")) {
265 const id = name.slice(0, -5);
266 // Messages cannot postdate file mtime; older files hold no in-window usage.
267 const skip =
268 seen.has(`opencode:${id}`) ||
269 Option.exists(info.mtime, (mtime) => mtime.getTime() < sinceMs);
270 if (found && skip) continue;
271 if (yield* isSymbolicLink(entry)) continue;
272 found = true;
273 if (skip) continue;
274 const file = { path: entry, records: [] as UsageRecord[] };
275 files.push(file);
276 yield* fileSystem.readFileString(entry).pipe(
277 Effect.map((source) => append(file.records, parseOpenCodeMessage(source, { id }))),
278 Effect.catchTags({
279 PlatformError: (cause) => {
280 if (!isNotFound(cause)) error = true;
281 return Effect.void;
282 },
283 }),
284 );
285 }
286 }
287 }
288 }).pipe(
289 Effect.catchTags({
290 PlatformError: (cause) => {
291 if (!isNotFound(cause)) error = true;
292 return Effect.void;
293 },
294 }),
295 );
296 }
297 yield* Effect.annotateCurrentSpan({
298 "usage.database_rows": databaseRows,
299 "usage.database_pages": databasePages,
300 });
301 return { files, missing: !found && !error, error };
302});
303​
304const resolveOpenCodeDataDirs = Effect.fn("resolveOpenCodeDataDirs")(function* (
305 environment: NodeJS.ProcessEnv,
306) {
307 const fileSystem = yield* FileSystem.FileSystem;
308 const path = yield* Path.Path;
309 const homeDirectory = yield* HostProcess.HomeDirectory;
310 const roots = environment["OPENCODE_DATA_DIR"]
311 ?.split(",")
312 .map((value) => value.trim())
313 .filter(Boolean);
314 const dataHome = environment["XDG_DATA_HOME"]?.trim();
315 const defaults = [
316 path.join(
317 dataHome && path.isAbsolute(dataHome)
318 ? dataHome
319 : path.join(homeDirectory, ".local", "share"),
320 "opencode",
321 ),
322 ];
323 const canonical = new Set<string>();
324 for (const root of roots?.length ? roots : defaults) {
325 const resolved = path.resolve(expandHomePath(root, homeDirectory));
326 canonical.add(yield* fileSystem.realPath(resolved).pipe(Effect.orElseSucceed(() => resolved)));
327 }
328 return [...canonical];
329});
330​
331export type OpenCodeUsageReaderEnv = FileSystem.FileSystem | Path.Path;
332​
333export const openCodeUsageReader: ProviderUsageReader<OpenCodeSettings, OpenCodeUsageReaderEnv> = {
334 kind: "scan",
335 provider: "opencode",
336 scan: Effect.fn("openCodeUsageReader.scan")(function* ({ instances, windowStartMs }) {
337 const roots = new Set<string>();
338 for (const instance of instances) {
339 for (const root of yield* resolveOpenCodeDataDirs(instance.environment)) roots.add(root);
340 }
341 return yield* Effect.forEach(
342 roots,
343 (dir) =>
344 readOpenCodeUsage(dir, windowStartMs).pipe(
345 Effect.map((result) => ({
346 dir,
347 files: result.missing && !result.error ? null : result.files,
348 status: result.error ? ("partial" as const) : ("ok" as const),
349 ...(result.error ? { message: "Some OpenCode history could not be read." } : {}),
350 })),
351 ),
352 { concurrency: "unbounded" },
353 );
354 }),
355};