tokenusage-cli 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (125) hide show
  1. package/CHANGELOG.md +19 -0
  2. package/LICENSE +22 -0
  3. package/README.md +94 -0
  4. package/THIRD_PARTY_NOTICES.md +140 -0
  5. package/bin/tokenusage.js +69 -0
  6. package/package.json +59 -0
  7. package/src/cli.js +134 -0
  8. package/src/commands/device-login.js +205 -0
  9. package/src/commands/diagnostics.js +38 -0
  10. package/src/commands/doctor.js +110 -0
  11. package/src/commands/init.js +2436 -0
  12. package/src/commands/sessions.js +29 -0
  13. package/src/commands/status.js +1747 -0
  14. package/src/commands/sync.js +7934 -0
  15. package/src/commands/uninstall.js +312 -0
  16. package/src/lib/account-usage-dedup.js +267 -0
  17. package/src/lib/antigravity-paths.js +48 -0
  18. package/src/lib/ark-agent-plan-limits.js +438 -0
  19. package/src/lib/ark-coding-plan-limits.js +537 -0
  20. package/src/lib/async-queue-reader.js +138 -0
  21. package/src/lib/atomic-json.js +27 -0
  22. package/src/lib/bearer-token.js +11 -0
  23. package/src/lib/categorizer-utils.js +232 -0
  24. package/src/lib/claude-categorizer.js +1343 -0
  25. package/src/lib/claude-config.js +279 -0
  26. package/src/lib/claude-user-identity.js +56 -0
  27. package/src/lib/cli-ui.js +179 -0
  28. package/src/lib/cloud-account.js +541 -0
  29. package/src/lib/cloud-device-token.js +141 -0
  30. package/src/lib/cloud-sync-prefs.js +14 -0
  31. package/src/lib/cloud-usage-reset.js +115 -0
  32. package/src/lib/codex-config.js +595 -0
  33. package/src/lib/codex-context-breakdown.js +806 -0
  34. package/src/lib/codex-model-attribution.js +128 -0
  35. package/src/lib/codex-rollout-parser.js +1471 -0
  36. package/src/lib/codex-service-tier.js +49 -0
  37. package/src/lib/codex-token-refresh.js +140 -0
  38. package/src/lib/codex-token-usage.js +195 -0
  39. package/src/lib/codex-usage-record.js +195 -0
  40. package/src/lib/command-runner.js +313 -0
  41. package/src/lib/commandcode-limits.js +317 -0
  42. package/src/lib/context-health.js +124 -0
  43. package/src/lib/cursor-config.js +605 -0
  44. package/src/lib/cursor-store.js +1918 -0
  45. package/src/lib/debug-flags.js +7 -0
  46. package/src/lib/devin-limits.js +249 -0
  47. package/src/lib/devin-usage.js +212 -0
  48. package/src/lib/diagnostics.js +383 -0
  49. package/src/lib/doctor.js +385 -0
  50. package/src/lib/dumate.js +95 -0
  51. package/src/lib/fs.js +455 -0
  52. package/src/lib/function-url.js +14 -0
  53. package/src/lib/gemini-config.js +291 -0
  54. package/src/lib/git-outcomes.js +243 -0
  55. package/src/lib/grok-context-breakdown.js +890 -0
  56. package/src/lib/grok-hook.js +360 -0
  57. package/src/lib/grok-limits.js +865 -0
  58. package/src/lib/grok-usage.js +98 -0
  59. package/src/lib/heatmap-compact.js +114 -0
  60. package/src/lib/ingest-sanitize.js +41 -0
  61. package/src/lib/init-flow.js +42 -0
  62. package/src/lib/install-resolver.js +170 -0
  63. package/src/lib/jsonl-lines.js +134 -0
  64. package/src/lib/kimi-model-repair.js +173 -0
  65. package/src/lib/kimi-profile.js +61 -0
  66. package/src/lib/kimi-session.js +216 -0
  67. package/src/lib/local-api.js +3588 -0
  68. package/src/lib/machine-id.js +238 -0
  69. package/src/lib/multi-install-parser.js +113 -0
  70. package/src/lib/notify-command.js +38 -0
  71. package/src/lib/omp-hook.js +589 -0
  72. package/src/lib/openclaw-cli.js +104 -0
  73. package/src/lib/openclaw-hook.js +375 -0
  74. package/src/lib/openclaw-session-plugin.js +560 -0
  75. package/src/lib/opencode-config.js +121 -0
  76. package/src/lib/opencode-go-limits.js +807 -0
  77. package/src/lib/outcomes-engine.js +253 -0
  78. package/src/lib/passive-mode.js +219 -0
  79. package/src/lib/pet-packages.js +722 -0
  80. package/src/lib/pricing/curated-overrides.json +822 -0
  81. package/src/lib/pricing/index.js +379 -0
  82. package/src/lib/pricing/litellm-fetcher.js +172 -0
  83. package/src/lib/pricing/matcher.js +456 -0
  84. package/src/lib/pricing/seed-snapshot.json +1 -0
  85. package/src/lib/progress.js +76 -0
  86. package/src/lib/project-usage-purge.js +117 -0
  87. package/src/lib/prompt.js +24 -0
  88. package/src/lib/provider-status.js +104 -0
  89. package/src/lib/proxy-env.js +489 -0
  90. package/src/lib/proxy-settings.js +163 -0
  91. package/src/lib/qoder-cn-cli-limits.js +119 -0
  92. package/src/lib/qoder-limits.js +880 -0
  93. package/src/lib/quiet-warnings.js +26 -0
  94. package/src/lib/rollout.js +25966 -0
  95. package/src/lib/runtime-config.js +259 -0
  96. package/src/lib/scan-roots.js +277 -0
  97. package/src/lib/sentry.js +231 -0
  98. package/src/lib/session-analytics.js +2972 -0
  99. package/src/lib/session-performance.js +237 -0
  100. package/src/lib/session-upload.js +379 -0
  101. package/src/lib/skill-usage.js +267 -0
  102. package/src/lib/skills-manager.js +1591 -0
  103. package/src/lib/source-metadata.js +48 -0
  104. package/src/lib/sqlite-reader.js +215 -0
  105. package/src/lib/star-cta.js +73 -0
  106. package/src/lib/subscription-manager.js +293 -0
  107. package/src/lib/subscriptions.js +508 -0
  108. package/src/lib/telemetry.js +193 -0
  109. package/src/lib/tracker-paths.js +16 -0
  110. package/src/lib/trae-cn-config.js +548 -0
  111. package/src/lib/trae-db.js +127 -0
  112. package/src/lib/trae-snapshot.js +230 -0
  113. package/src/lib/trae-sqlite.js +143 -0
  114. package/src/lib/trae-usage.js +121 -0
  115. package/src/lib/upload-queue.js +134 -0
  116. package/src/lib/upload-throttle.js +171 -0
  117. package/src/lib/usage-limits.js +4552 -0
  118. package/src/lib/wrapped-aggregator.js +236 -0
  119. package/src/lib/wsl-probe.js +281 -0
  120. package/src/lib/zcode-limits.js +1172 -0
  121. package/src/lib/zcode-reset-credits.js +66 -0
  122. package/test/cli-smoke.test.js +53 -0
  123. package/test/ingest-sanitize.test.js +162 -0
  124. package/test/quiet-warnings.test.js +53 -0
  125. package/test/session-upload.test.js +427 -0
@@ -0,0 +1,807 @@
1
+ const crypto = require("node:crypto");
2
+ const fssync = require("node:fs");
3
+ const path = require("node:path");
4
+ const { readSqliteJsonRowsAsync } = require("./sqlite-reader");
5
+
6
+ // OpenCode Go usage limits.
7
+ //
8
+ // Three data sources are available, in priority order:
9
+ //
10
+ // 1. The official OpenCode Go usage API
11
+ // (GET https://opencode.ai/zen/go/v1/usage) with
12
+ // `Authorization: Bearer <OPENCODE_GO_API_KEY>`. It returns the server's
13
+ // authoritative rolling (5h), weekly, and monthly usage windows.
14
+ //
15
+ // 2. Web scrape of the workspace dashboard
16
+ // (https://opencode.ai/workspace/<id>/go) for existing users configured
17
+ // with OPENCODE_GO_AUTH_COOKIE. This is retained as a compatibility path.
18
+ //
19
+ // 3. Local opencode.db cost aggregation, explicitly enabled with
20
+ // TOKENUSAGE_OPENCODE_GO_LOCAL_ESTIMATE=1. The `opencode` CLI records
21
+ // every Go turn's USD `cost` in SQLite, so cost ÷ Go's dollar caps is a
22
+ // useful local estimate. It cannot prove that the account still has an
23
+ // active Go subscription, because the database contains historical turns
24
+ // but no current entitlement state.
25
+ //
26
+ // The returned shape is shared by all sources. `source` is `'api'` for the
27
+ // official endpoint, `'web'` for the compatibility scrape, or `'local-estimate'`
28
+ // for the opt-in estimate.
29
+
30
+ const SCRAPED_NUMBER_PATTERN = "([0-9]+(?:\\.[0-9]+)?)";
31
+
32
+ // Match each window's fields anchor-free, instead of pinning the exact SSR
33
+ // wrapper shape. opencode's hydration format around the data changes between
34
+ // releases (it dropped the `:$R[N]={…}` wrapper our old regexes required, which
35
+ // broke parsing in #225 even though auth worked and the page still carried the
36
+ // numbers). The field names (rollingUsage/weeklyUsage/monthlyUsage with
37
+ // usagePercent + resetInSec) are stable, so we anchor on those, the way
38
+ // steipete/codexbar's OpenCodeGoUsageFetcher does. `[^}]*?` keeps each match
39
+ // inside that window's own object, and `"?` tolerates both the unquoted SSR
40
+ // form (`usagePercent:2`) and a quoted JSON form (`"usagePercent":2`).
41
+ function windowFieldRegex(windowKey, field) {
42
+ return new RegExp(`${windowKey}[^}]*?${field}"?\\s*[:=]+\\s*${SCRAPED_NUMBER_PATTERN}`);
43
+ }
44
+
45
+ const GO_USAGE_API_URL = "https://opencode.ai/zen/go/v1/usage";
46
+ const DASHBOARD_URL_PREFIX = "https://opencode.ai/workspace/";
47
+ const DASHBOARD_URL_SUFFIX = "/go";
48
+ const USER_AGENT =
49
+ "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) Gecko/20100101 Firefox/148.0";
50
+ const DEFAULT_REQUEST_TIMEOUT_MS = 10_000;
51
+ const LOCAL_ESTIMATE_ENV = "TOKENUSAGE_OPENCODE_GO_LOCAL_ESTIMATE";
52
+
53
+ function isTruthyEnvValue(value) {
54
+ return ["1", "true", "yes", "on"].includes(String(value ?? "").trim().toLowerCase());
55
+ }
56
+
57
+ function localEstimateEnabled(env = process.env) {
58
+ return Boolean(env && typeof env === "object" && isTruthyEnvValue(env[LOCAL_ESTIMATE_ENV]));
59
+ }
60
+
61
+ // OpenCode's inactive Go workspace renders a Subscribe button and no usage
62
+ // items. Keep this detection deliberately narrow: an unknown/changed page must
63
+ // remain an error, not be guessed as an inactive subscription.
64
+ function detectSubscriptionStatus(html) {
65
+ if (typeof html !== "string") return "unknown";
66
+ const normalized = html.replace(/\\(["'])/g, "$1");
67
+ return /data-slot\s*=\s*["']subscribe-button["']/i.test(normalized)
68
+ ? "inactive"
69
+ : "unknown";
70
+ }
71
+
72
+ function readConfig(env = process.env) {
73
+ if (!env || typeof env !== "object") return null;
74
+ const workspaceId =
75
+ typeof env.OPENCODE_GO_WORKSPACE_ID === "string"
76
+ ? env.OPENCODE_GO_WORKSPACE_ID.trim()
77
+ : "";
78
+ const authCookie =
79
+ typeof env.OPENCODE_GO_AUTH_COOKIE === "string"
80
+ ? env.OPENCODE_GO_AUTH_COOKIE.trim()
81
+ : "";
82
+ if (!authCookie) return null;
83
+ return { workspaceId, authCookie };
84
+ }
85
+
86
+ function readApiKey(env = process.env) {
87
+ if (!env || typeof env !== "object") return "";
88
+ return typeof env.OPENCODE_GO_API_KEY === "string"
89
+ ? env.OPENCODE_GO_API_KEY.trim()
90
+ : "";
91
+ }
92
+
93
+ function clampPercent(value) {
94
+ if (value === null || value === undefined || value === "") return null;
95
+ let n = Number(value);
96
+ if (!Number.isFinite(n)) return null;
97
+ // Some payloads encode the percentage as a 0–1 fraction (e.g. 0.02 for 2%).
98
+ // Scale only when strictly below 1 so a genuine "1" stays 1%, not 100%.
99
+ if (n > 0 && n < 1) n *= 100;
100
+ if (n <= 0) return 0;
101
+ if (n >= 100) return 100;
102
+ return n;
103
+ }
104
+
105
+ function buildWindow({ usagePercent, resetInSec, nowMs }) {
106
+ const pct = clampPercent(usagePercent);
107
+ if (pct === null) return null;
108
+ const seconds = Number(resetInSec);
109
+ if (!Number.isFinite(seconds) || seconds < 0) return null;
110
+ const resetAtIso = new Date(nowMs + Math.floor(seconds) * 1000).toISOString();
111
+ return { used_percent: pct, reset_at: resetAtIso };
112
+ }
113
+
114
+ // Pull one window's usagePercent + resetInSec out of the page. The two fields
115
+ // are matched independently (order-independent), so it survives field
116
+ // reordering as well as wrapper changes.
117
+ function parseWindowUsage(html, windowKey) {
118
+ const pctMatch = windowFieldRegex(windowKey, "usagePercent").exec(html);
119
+ if (!pctMatch) return null;
120
+ const usagePercent = Number(pctMatch[1]);
121
+ if (!Number.isFinite(usagePercent)) return null;
122
+ const resetMatch = windowFieldRegex(windowKey, "resetInSec").exec(html);
123
+ const resetInSec = resetMatch ? Number(resetMatch[1]) : 0;
124
+ return { usagePercent, resetInSec: Number.isFinite(resetInSec) ? resetInSec : 0 };
125
+ }
126
+
127
+ // Parse "1 hour 56 minutes" / "6 days 2 hours" / "26 days 17 hours" into
128
+ // seconds. The data-slot HTML fallback uses human-readable reset strings
129
+ // when the SSR hydration output is absent.
130
+ function parseHumanReadableTime(timeStr) {
131
+ if (typeof timeStr !== "string") return null;
132
+ const normalized = timeStr.toLowerCase().trim().replace(/\s+/g, " ");
133
+ if (["reset-now", "reset now", "now", "resets now"].includes(normalized)) {
134
+ return 0;
135
+ }
136
+ const dayMatch = normalized.match(/(\d+(?:\.\d+)?)\s*days?/);
137
+ const hourMatch = normalized.match(/(\d+(?:\.\d+)?)\s*hours?/);
138
+ const minuteMatch = normalized.match(/(\d+(?:\.\d+)?)\s*minutes?/);
139
+ const secondMatch = normalized.match(/(\d+(?:\.\d+)?)\s*seconds?/);
140
+ if (!dayMatch && !hourMatch && !minuteMatch && !secondMatch) return null;
141
+ let total = 0;
142
+ if (dayMatch) total += Number(dayMatch[1]) * 86400;
143
+ if (hourMatch) total += Number(hourMatch[1]) * 3600;
144
+ if (minuteMatch) total += Number(minuteMatch[1]) * 60;
145
+ if (secondMatch) total += Number(secondMatch[1]);
146
+ return total;
147
+ }
148
+
149
+ function parseDataSlotFormat(html) {
150
+ const out = {};
151
+ const items = html.split(/data-slot="usage-item"/);
152
+ for (let i = 1; i < items.length; i++) {
153
+ const content = items[i];
154
+ const labelMatch = content.match(/data-slot="usage-label">([^<]+)</);
155
+ if (!labelMatch) continue;
156
+ const label = labelMatch[1].trim().toLowerCase();
157
+ const usageMatch = content.match(/data-slot="usage-value">[^0-9]*(\d+(?:\.\d+)?)/);
158
+ if (!usageMatch) continue;
159
+ const usagePercent = Number(usageMatch[1]);
160
+ const resetMatch = content.match(
161
+ /data-slot="(reset-time|reset-now)">([\s\S]*?)<\/span>/,
162
+ );
163
+ if (!resetMatch) continue;
164
+ const resetContent = resetMatch[2]
165
+ .replace(/<!--[\s\S]*?-->/g, "")
166
+ .replace(/Resets?\s*in\s*/i, "")
167
+ .trim();
168
+ const resetInSec =
169
+ resetMatch[1] === "reset-now" ? 0 : parseHumanReadableTime(resetContent);
170
+ if (!Number.isFinite(usagePercent) || resetInSec === null) continue;
171
+ let key = null;
172
+ if (label.includes("rolling")) key = "rolling";
173
+ else if (label.includes("weekly")) key = "weekly";
174
+ else if (label.includes("monthly")) key = "monthly";
175
+ if (key) out[key] = { usagePercent, resetInSec };
176
+ }
177
+ return out;
178
+ }
179
+
180
+ function extractWindows(html, nowMs) {
181
+ let rolling = parseWindowUsage(html, "rollingUsage");
182
+ let weekly = parseWindowUsage(html, "weeklyUsage");
183
+ let monthly = parseWindowUsage(html, "monthlyUsage");
184
+ // Fill any *individual* missing window from the data-slot HTML fallback.
185
+ // Running the fallback only when all three fail loses the case where SSR
186
+ // hydration exposes e.g. rollingUsage but drops weeklyUsage — we'd return
187
+ // `null` for that window even though parseDataSlotFormat() could still
188
+ // recover it from the rendered HTML.
189
+ if (!rolling || !weekly || !monthly) {
190
+ const fallback = parseDataSlotFormat(html);
191
+ rolling = rolling || fallback.rolling || null;
192
+ weekly = weekly || fallback.weekly || null;
193
+ monthly = monthly || fallback.monthly || null;
194
+ }
195
+ return {
196
+ rolling: rolling ? buildWindow({ ...rolling, nowMs }) : null,
197
+ weekly: weekly ? buildWindow({ ...weekly, nowMs }) : null,
198
+ monthly: monthly ? buildWindow({ ...monthly, nowMs }) : null,
199
+ };
200
+ }
201
+
202
+ function sanitizeMessage(text, maxLength = 160) {
203
+ const str = typeof text === "string" ? text : String(text ?? "");
204
+ const squashed = str.replace(/\s+/g, " ").trim();
205
+ return (squashed || "unknown").slice(0, maxLength);
206
+ }
207
+
208
+ function withTimeout(fetchImpl, timeoutMs) {
209
+ if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) return fetchImpl;
210
+ return (input, init = {}) => {
211
+ const controller = new AbortController();
212
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
213
+ const next = { ...init, signal: init.signal || controller.signal };
214
+ return fetchImpl(input, next).finally(() => clearTimeout(timer));
215
+ };
216
+ }
217
+
218
+ // TanStack server-function ID for the "list workspaces" query. Generated at
219
+ // build time by OpenCode's SolidStart bundler. To update: open opencode.ai
220
+ // with DevTools → Network, filter "_server", trigger any workspace load,
221
+ // and copy the `id` query parameter from the request URL.
222
+ const WORKSPACES_SERVER_ID =
223
+ "def39973159c7f0483d8793a822b8dbb10d067e12c65455fcb4608459ba0234f";
224
+
225
+ async function resolveWorkspaceId(authCookie, fetchImpl, timeoutMs) {
226
+ const serverId = WORKSPACES_SERVER_ID;
227
+ const instanceId = `server-fn:${crypto.randomUUID()}`;
228
+
229
+ const headers = {
230
+ "Cookie": `auth=${authCookie}`,
231
+ "X-Server-Id": serverId,
232
+ "X-Server-Instance": instanceId,
233
+ "User-Agent": USER_AGENT,
234
+ "Origin": "https://opencode.ai",
235
+ "Referer": "https://opencode.ai",
236
+ "Accept": "text/javascript, application/json;q=0.9, */*;q=0.8"
237
+ };
238
+
239
+ const getUrl = `https://opencode.ai/_server?id=${serverId}`;
240
+ let response;
241
+ try {
242
+ response = await withTimeout(fetchImpl, timeoutMs)(getUrl, {
243
+ method: "GET",
244
+ headers,
245
+ });
246
+ } catch (err) {
247
+ throw new Error(`GET _server failed: ${err.message}`);
248
+ }
249
+
250
+ if (response.status === 401 || response.status === 403) {
251
+ throw new Error("Unauthorized or forbidden (401/403)");
252
+ }
253
+
254
+ let text = await response.text();
255
+ let ids = parseWorkspaceIds(text);
256
+
257
+ if (ids.length === 0 && !looksSignedOut(text)) {
258
+ const postUrl = "https://opencode.ai/_server";
259
+ const postHeaders = {
260
+ ...headers,
261
+ "Content-Type": "application/json",
262
+ };
263
+ try {
264
+ response = await withTimeout(fetchImpl, timeoutMs)(postUrl, {
265
+ method: "POST",
266
+ headers: postHeaders,
267
+ body: "[]"
268
+ });
269
+ if (response.status === 401 || response.status === 403) {
270
+ throw new Error("Unauthorized or forbidden (401/403)");
271
+ }
272
+ text = await response.text();
273
+ ids = parseWorkspaceIds(text);
274
+ } catch (postErr) {
275
+ // GET returned content but no workspace IDs; POST also failed.
276
+ // Wrap both signals so the caller can surface a useful diagnostic.
277
+ throw new Error(`GET returned no workspace IDs and POST fallback failed: ${postErr.message}`);
278
+ }
279
+ }
280
+
281
+ return ids.length > 0 ? ids[0] : null;
282
+ }
283
+
284
+ function parseWorkspaceIds(text) {
285
+ const ids = new Set();
286
+ const re = /id\s*[:=]+\s*\\?"(wrk_[^\\"]+)\\"?/g;
287
+ let m;
288
+ while ((m = re.exec(text)) !== null) {
289
+ ids.add(m[1]);
290
+ }
291
+ if (ids.size === 0) {
292
+ try {
293
+ const walk = (o) => {
294
+ if (typeof o === "string" && o.startsWith("wrk_")) {
295
+ ids.add(o);
296
+ } else if (Array.isArray(o)) {
297
+ o.forEach(walk);
298
+ } else if (o && typeof o === "object") {
299
+ Object.values(o).forEach(walk);
300
+ }
301
+ };
302
+ walk(JSON.parse(text));
303
+ } catch (_) {}
304
+ }
305
+ return Array.from(ids);
306
+ }
307
+
308
+ function looksSignedOut(text) {
309
+ const l = String(text).toLowerCase();
310
+ // Use specific phrases to avoid false positives on workspace names containing
311
+ // common words like "login" (e.g. a workspace named "loginServiceApp").
312
+ return l.includes("please log in") || l.includes("sign in to") || l.includes("auth/authorize")
313
+ || l.includes("not associated with an account") || l.includes('actor of type "public"');
314
+ }
315
+
316
+ // --- Local opencode.db cost aggregation (auth-free source) ------------------
317
+
318
+ const SESSION_MS = 5 * 60 * 60 * 1000;
319
+ const WEEK_MS = 7 * 24 * 60 * 60 * 1000;
320
+ // OpenCode Go's official dollar caps — https://opencode.ai/docs/go
321
+ // ($12 per 5h, $30 per week, $60 per month). The limits are not stored in the
322
+ // local DB, so they are hardcoded; env-overridable in case opencode changes
323
+ // them (TOKENUSAGE_OPENCODE_GO_LIMITS="12,30,60").
324
+ const DEFAULT_GO_LIMITS = { session: 12, weekly: 30, monthly: 60 };
325
+
326
+ function goDollarLimits(env = process.env) {
327
+ const raw = String((env && env.TOKENUSAGE_OPENCODE_GO_LIMITS) || "").trim();
328
+ if (!raw) return { ...DEFAULT_GO_LIMITS };
329
+ const parts = raw.split(",").map((s) => Number(s.trim()));
330
+ if (parts.length === 3 && parts.every((n) => Number.isFinite(n) && n > 0)) {
331
+ return { session: parts[0], weekly: parts[1], monthly: parts[2] };
332
+ }
333
+ return { ...DEFAULT_GO_LIMITS };
334
+ }
335
+
336
+ // Mirror sync.js's opencode home resolution (OPENCODE_HOME / XDG_DATA_HOME /
337
+ // <home>/.local/share/opencode) so we read the SAME DB the parser reads. The
338
+ // user home comes from the `home` arg getUsageLimits already threads to every
339
+ // other home-based provider (cf. resolveZcodeHome). NOTE: we deliberately do
340
+ // NOT fall back to os.homedir() — only an explicit `home`/env HOME — so a
341
+ // synthetic test env (no home, no HOME) discovers nothing and the web-scrape
342
+ // tests stay isolated from the developer's real opencode.db.
343
+ function resolveOpencodeDataDir({ home, env = process.env } = {}) {
344
+ if (env.OPENCODE_HOME) return env.OPENCODE_HOME;
345
+ if (env.XDG_DATA_HOME) return path.join(env.XDG_DATA_HOME, "opencode");
346
+ const base = home || env.HOME || env.USERPROFILE;
347
+ if (!base) return null;
348
+ return path.join(base, ".local", "share", "opencode");
349
+ }
350
+
351
+ // Matches `opencode.db` or `opencode-<channel>.db`; excludes WAL/SHM side-files.
352
+ function isOpencodeDbFilename(name) {
353
+ if (!name.endsWith(".db")) return false;
354
+ const stem = name.slice(0, -3);
355
+ if (stem === "opencode") return true;
356
+ if (!stem.startsWith("opencode-")) return false;
357
+ const channel = stem.slice("opencode-".length);
358
+ return channel.length > 0 && /^[A-Za-z0-9._-]+$/.test(channel);
359
+ }
360
+
361
+ function discoverOpencodeDbPaths({ home, env = process.env } = {}) {
362
+ const override = String((env && env.OPENCODE_DB) || "").trim();
363
+ if (override) {
364
+ try {
365
+ if (fssync.statSync(override).isFile()) return [override];
366
+ } catch (_e) {
367
+ /* fall through to directory scan */
368
+ }
369
+ }
370
+ const dir = resolveOpencodeDataDir({ home, env });
371
+ if (!dir) return [];
372
+ let entries;
373
+ try {
374
+ entries = fssync.readdirSync(dir);
375
+ } catch (_e) {
376
+ return [];
377
+ }
378
+ return entries.filter(isOpencodeDbFilename).sort().map((n) => path.join(dir, n));
379
+ }
380
+
381
+ function weekStartMs(nowMs) {
382
+ const d = new Date(nowMs);
383
+ const day = d.getUTCDay(); // 0=Sun..6=Sat
384
+ const sinceMonday = day === 0 ? 6 : day - 1;
385
+ return Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate() - sinceMonday);
386
+ }
387
+
388
+ // Calendar-month bounds (UTC). OpenCode Go's true monthly reset is the
389
+ // subscription anniversary, which the local DB does not record; the calendar
390
+ // month is a stable, defensible approximation for the auth-free estimate.
391
+ function monthBoundsMs(nowMs) {
392
+ const now = new Date(nowMs);
393
+ return {
394
+ startMs: Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), 1),
395
+ endMs: Date.UTC(now.getUTCFullYear(), now.getUTCMonth() + 1, 1),
396
+ };
397
+ }
398
+
399
+ // Percentage clamp for the local estimate. Unlike clampPercent() (which scales
400
+ // a 0–1 fraction from the web payload), this treats its input as an already-
401
+ // computed percentage and must NOT rescale values below 1 (e.g. 0.5%).
402
+ function clampLocalPercent(n) {
403
+ if (!Number.isFinite(n)) return null;
404
+ if (n <= 0) return 0;
405
+ if (n >= 100) return 100;
406
+ return n;
407
+ }
408
+
409
+ function buildLocalWindow({ used, limit, resetMs }) {
410
+ if (!(limit > 0)) return null;
411
+ const pct = clampLocalPercent((Number(used) / limit) * 100);
412
+ if (pct === null) return null;
413
+ return { used_percent: pct, reset_at: new Date(resetMs).toISOString() };
414
+ }
415
+
416
+ // One full-table aggregate (the message table has no index on the JSON fields,
417
+ // so we sum in SQLite and return a single row rather than streaming every
418
+ // opencode-go turn into JS — keeps the limits poll cheap, cf. the spawnSync
419
+ // freeze lesson).
420
+ //
421
+ // Two schema generations share the same file (see src/lib/rollout.js):
422
+ // v1 keeps the `message` table with `$.role`/flat `$.providerID`.
423
+ // v2 (`opencode2`) moved messages to `session_message` (role is now the
424
+ // `type` column) and nests the provider under `$.model.providerID`.
425
+ function buildGoAggregateSql({ sessionStart, weekStart, weekEnd, monthStart, monthEnd }, variant = "v1") {
426
+ const isV2 = variant === "v2";
427
+ const table = isV2 ? "session_message" : "message";
428
+ const rolePredicate = isV2 ? "type = 'assistant'" : "json_extract(data,'$.role') = 'assistant'";
429
+ const providerPredicate = isV2
430
+ ? "json_extract(data,'$.model.providerID') = 'opencode-go'"
431
+ : "json_extract(data,'$.providerID') = 'opencode-go'";
432
+ return (
433
+ "SELECT " +
434
+ `COALESCE(SUM(CASE WHEN createdMs >= ${sessionStart} THEN cost ELSE 0 END), 0) AS sessionCost, ` +
435
+ `MIN(CASE WHEN createdMs >= ${sessionStart} THEN createdMs END) AS sessionOldest, ` +
436
+ `COALESCE(SUM(CASE WHEN createdMs >= ${weekStart} AND createdMs < ${weekEnd} THEN cost ELSE 0 END), 0) AS weeklyCost, ` +
437
+ `COALESCE(SUM(CASE WHEN createdMs >= ${monthStart} AND createdMs < ${monthEnd} THEN cost ELSE 0 END), 0) AS monthlyCost, ` +
438
+ "COUNT(*) AS rowCount " +
439
+ "FROM (" +
440
+ "SELECT CAST(COALESCE(json_extract(data,'$.time.created'), time_created) AS INTEGER) AS createdMs, " +
441
+ "CAST(json_extract(data,'$.cost') AS REAL) AS cost " +
442
+ `FROM ${table} ` +
443
+ "WHERE json_valid(data) " +
444
+ `AND ${providerPredicate} ` +
445
+ `AND ${rolePredicate} ` +
446
+ "AND json_type(data,'$.cost') IN ('integer','real')" +
447
+ ")"
448
+ );
449
+ }
450
+
451
+ // Detect whether the database has any rows in session_message. This is the
452
+ // shared opencode2 probe (see src/lib/rollout.js): a pure v1 database has an
453
+ // empty session_message table, and blindly running the v2 aggregate against it
454
+ // is harmless here (no JOIN, no directory lookup) — but the probe result still
455
+ // drives variant ordering so v2 is preferred when data exists.
456
+ //
457
+ // A database carrying BOTH tables resolves to "v1 first" on purpose: unlike the
458
+ // message parser (which dedups rows by sessionID|messageID), this aggregate is
459
+ // a blind SUM with no key to dedup on, so unioning two generations could
460
+ // double-count cost if the tables overlap. Undercounting an opt-in estimate is
461
+ // the safe side of that trade.
462
+ async function detectOpencodeGoHasSessionMessages(dbPath, sqliteOptions = {}) {
463
+ let rows;
464
+ try {
465
+ rows = await readSqliteJsonRowsAsync(
466
+ dbPath,
467
+ `SELECT (SELECT 1 FROM session_message LIMIT 1) AS hasRows`,
468
+ { label: "OpenCode Go", timeout: 5_000, ...sqliteOptions },
469
+ );
470
+ } catch (_e) {
471
+ return null;
472
+ }
473
+ if (!Array.isArray(rows) || rows.length === 0) return null;
474
+ return Boolean(rows[0]?.hasRows);
475
+ }
476
+
477
+ // Returns { source:'local', primary/secondary/tertiary_window } or null when no
478
+ // opencode.db / no opencode-go rows are found. The caller labels this result as
479
+ // an estimate and only exposes it when explicitly opted in.
480
+ async function collectOpencodeGoLocal({ home, env = process.env, nowMs = Date.now(), sqliteOptions = {} } = {}) {
481
+ const paths = discoverOpencodeDbPaths({ home, env });
482
+ if (paths.length === 0) return null;
483
+
484
+ const sessionStart = Math.floor(nowMs - SESSION_MS);
485
+ const weekStart = weekStartMs(nowMs);
486
+ const weekEnd = weekStart + WEEK_MS;
487
+ const { startMs: monthStart, endMs: monthEnd } = monthBoundsMs(nowMs);
488
+ const windowArgs = { sessionStart, weekStart, weekEnd, monthStart, monthEnd };
489
+
490
+ let agg = null;
491
+ for (const dbPath of paths) {
492
+ // Each database can be a different OpenCode generation. When sqlite_master
493
+ // is unreadable, fall back to v1-then-v2 so the legacy query runs first.
494
+ const hasRows = await detectOpencodeGoHasSessionMessages(dbPath, sqliteOptions);
495
+ const variants = hasRows === true ? ["v2", "v1"] : hasRows === false ? ["v1", "v2"] : ["v1", "v2"];
496
+
497
+ for (const variant of variants) {
498
+ const sql = buildGoAggregateSql(windowArgs, variant);
499
+ let rows;
500
+ try {
501
+ rows = await readSqliteJsonRowsAsync(dbPath, sql, {
502
+ label: "OpenCode Go",
503
+ timeout: 5_000,
504
+ ...sqliteOptions,
505
+ throwOnReadFailure: true,
506
+ });
507
+ } catch (_e) {
508
+ continue;
509
+ }
510
+ const row = rows && rows[0];
511
+ if (!row) continue;
512
+ const rowCount = Number(row.rowCount) || 0;
513
+ if (rowCount <= 0) continue;
514
+ if (!agg) agg = { sessionCost: 0, weeklyCost: 0, monthlyCost: 0, sessionOldest: null, rowCount: 0 };
515
+ agg.sessionCost += Number(row.sessionCost) || 0;
516
+ agg.weeklyCost += Number(row.weeklyCost) || 0;
517
+ agg.monthlyCost += Number(row.monthlyCost) || 0;
518
+ agg.rowCount += rowCount;
519
+ const oldest = row.sessionOldest == null ? null : Number(row.sessionOldest);
520
+ if (oldest != null && Number.isFinite(oldest)) {
521
+ agg.sessionOldest = agg.sessionOldest == null ? oldest : Math.min(agg.sessionOldest, oldest);
522
+ }
523
+ break; // this database answered — don't re-run the other schema on it
524
+ }
525
+ }
526
+ if (!agg || agg.rowCount <= 0) return null;
527
+
528
+ const limits = goDollarLimits(env);
529
+ const sessionReset = (agg.sessionOldest != null ? agg.sessionOldest : nowMs) + SESSION_MS;
530
+ return {
531
+ source: "local",
532
+ primary_window: buildLocalWindow({ used: agg.sessionCost, limit: limits.session, resetMs: sessionReset }),
533
+ secondary_window: buildLocalWindow({ used: agg.weeklyCost, limit: limits.weekly, resetMs: weekEnd }),
534
+ tertiary_window: buildLocalWindow({ used: agg.monthlyCost, limit: limits.monthly, resetMs: monthEnd }),
535
+ };
536
+ }
537
+
538
+ function localGoResult(local) {
539
+ return {
540
+ configured: true,
541
+ error: null,
542
+ source: "local-estimate",
543
+ subscription_status: "unknown",
544
+ // No `plan_label` — the brand name "OpenCode Go" is the row title.
545
+ primary_window: local.primary_window || null,
546
+ secondary_window: local.secondary_window || null,
547
+ tertiary_window: local.tertiary_window || null,
548
+ };
549
+ }
550
+
551
+ // --- Official usage API (exact server-side usage, API-key-gated) -------------
552
+
553
+ async function fetchOpencodeGoApiLimits({ apiKey, fetchImpl, nowMs, timeoutMs }) {
554
+ let response;
555
+ try {
556
+ response = await withTimeout(fetchImpl, timeoutMs)(GO_USAGE_API_URL, {
557
+ method: "GET",
558
+ headers: {
559
+ Authorization: `Bearer ${apiKey}`,
560
+ Accept: "application/json",
561
+ "User-Agent": USER_AGENT,
562
+ },
563
+ });
564
+ } catch (err) {
565
+ return { configured: true, error: sanitizeMessage(err?.message || err) };
566
+ }
567
+
568
+ if (response.status === 401) {
569
+ return {
570
+ configured: true,
571
+ error: "OpenCode Go API key is missing, invalid, expired, or not entitled to an OpenCode Go subscription.",
572
+ auth_error: true,
573
+ };
574
+ }
575
+ if (response.status === 403) {
576
+ return {
577
+ configured: true,
578
+ error: "OpenCode Go subscription required for this API key.",
579
+ auth_error: true,
580
+ };
581
+ }
582
+ if (!response.ok) {
583
+ return { configured: true, error: `OpenCode Go usage API error ${response.status}` };
584
+ }
585
+
586
+ let payload;
587
+ try {
588
+ payload = JSON.parse(await response.text());
589
+ } catch (err) {
590
+ return {
591
+ configured: true,
592
+ error: `Could not parse OpenCode Go usage API response: ${sanitizeMessage(err?.message || err)}`,
593
+ };
594
+ }
595
+
596
+ // Upstream has shipped two shapes:
597
+ // - Early spec (anomalyco/opencode#16513): { rollingUsage: { usagePercent, resetInSec } ... }
598
+ // - Live API (2026-08): { usage: { rolling: { percent, resetsAt }, weekly: {}, monthly: {} } }
599
+ const resolveApiWindow = (legacy, modern) => {
600
+ if (modern && typeof modern === "object") {
601
+ const pct = modern.percent ?? modern.usagePercent ?? modern.usage_percent;
602
+ const resetsAt = modern.resetsAt ?? modern.resets_at ?? modern.resetAt ?? modern.reset_at;
603
+ if (pct != null || resetsAt != null) {
604
+ const resetInSec = (() => {
605
+ if (typeof modern.resetInSec === "number" || typeof modern.resetInSec === "string") return Number(modern.resetInSec);
606
+ if (typeof modern.reset_in_sec === "number" || typeof modern.reset_in_sec === "string") return Number(modern.reset_in_sec);
607
+ if (typeof resetsAt === "string" && resetsAt) {
608
+ const ts = Date.parse(resetsAt);
609
+ if (Number.isFinite(ts)) return Math.max(0, Math.floor((ts - nowMs) / 1000));
610
+ }
611
+ return undefined;
612
+ })();
613
+ const modernWindow = buildWindow({ usagePercent: pct, resetInSec, nowMs });
614
+ // Only prefer the modern window when it actually parsed; an incomplete
615
+ // modern object (e.g. percent without reset info) must fall through to
616
+ // a valid legacy window instead of losing it.
617
+ if (modernWindow) return modernWindow;
618
+ }
619
+ }
620
+ if (legacy && typeof legacy === "object") {
621
+ return buildWindow({ usagePercent: legacy.usagePercent ?? legacy.percent, resetInSec: legacy.resetInSec ?? legacy.reset_in_sec, nowMs });
622
+ }
623
+ return null;
624
+ };
625
+
626
+ const rolling = resolveApiWindow(payload?.rollingUsage, payload?.usage?.rolling ?? payload?.rolling);
627
+ const weekly = resolveApiWindow(payload?.weeklyUsage, payload?.usage?.weekly ?? payload?.weekly);
628
+ const monthly = resolveApiWindow(payload?.monthlyUsage, payload?.usage?.monthly ?? payload?.monthly);
629
+
630
+ if (!rolling && !weekly && !monthly) {
631
+ return {
632
+ configured: true,
633
+ error: "OpenCode Go usage API response did not include any known usage windows.",
634
+ };
635
+ }
636
+
637
+ return {
638
+ configured: true,
639
+ error: null,
640
+ subscription_status: "active",
641
+ primary_window: rolling,
642
+ secondary_window: weekly,
643
+ tertiary_window: monthly,
644
+ };
645
+ }
646
+
647
+ // --- Web scrape (exact server-side usage, cookie-gated) ---------------------
648
+
649
+ async function scrapeOpencodeGoWeb({ cfg, fetchImpl, nowMs, timeoutMs }) {
650
+ let workspaceId = cfg.workspaceId;
651
+ if (!workspaceId) {
652
+ try {
653
+ workspaceId = await resolveWorkspaceId(cfg.authCookie, fetchImpl, timeoutMs);
654
+ } catch (err) {
655
+ const msg = sanitizeMessage(err?.message || err);
656
+ const isAuth = /401|403|Unauthorized or forbidden/i.test(msg);
657
+ return {
658
+ configured: true,
659
+ error: `Failed to resolve Workspace ID: ${msg}`,
660
+ ...(isAuth ? { auth_error: true } : {}),
661
+ };
662
+ }
663
+ if (!workspaceId) {
664
+ return { configured: true, error: "Could not auto-resolve OpenCode Workspace ID from cookie. Please set OPENCODE_GO_WORKSPACE_ID manually." };
665
+ }
666
+ }
667
+
668
+ const url =
669
+ DASHBOARD_URL_PREFIX + encodeURIComponent(workspaceId) + DASHBOARD_URL_SUFFIX;
670
+
671
+ let response;
672
+ try {
673
+ response = await withTimeout(fetchImpl, timeoutMs)(url, {
674
+ method: "GET",
675
+ headers: {
676
+ "User-Agent": USER_AGENT,
677
+ Accept: "text/html",
678
+ Cookie: `auth=${cfg.authCookie}`,
679
+ },
680
+ });
681
+ } catch (err) {
682
+ return { configured: true, error: sanitizeMessage(err?.message || err) };
683
+ }
684
+
685
+ if (response.status === 401 || response.status === 403) {
686
+ return {
687
+ configured: true,
688
+ error: "Not signed in to OpenCode Go. Refresh the auth cookie in OPENCODE_GO_AUTH_COOKIE.",
689
+ };
690
+ }
691
+ if (!response.ok) {
692
+ return {
693
+ configured: true,
694
+ error: `OpenCode Go dashboard error ${response.status}`,
695
+ };
696
+ }
697
+
698
+ let html;
699
+ try {
700
+ html = await response.text();
701
+ } catch (err) {
702
+ return { configured: true, error: sanitizeMessage(err?.message || err) };
703
+ }
704
+
705
+ const { rolling, weekly, monthly } = extractWindows(html, nowMs);
706
+ if (!rolling && !weekly && !monthly) {
707
+ if (detectSubscriptionStatus(html) === "inactive") {
708
+ return {
709
+ configured: true,
710
+ error: null,
711
+ subscription_status: "inactive",
712
+ };
713
+ }
714
+ return {
715
+ configured: true,
716
+ error:
717
+ "Could not parse any known OpenCode Go dashboard usage windows (rollingUsage, weeklyUsage, monthlyUsage). The page layout may have changed.",
718
+ };
719
+ }
720
+
721
+ return {
722
+ configured: true,
723
+ error: null,
724
+ subscription_status: "active",
725
+ // No `plan_label` — the brand name "OpenCode Go" is the row title, so
726
+ // appending "Go" again would render "OpenCode Go Go" in the panel.
727
+ primary_window: rolling,
728
+ secondary_window: weekly,
729
+ tertiary_window: monthly,
730
+ };
731
+ }
732
+
733
+ async function fetchOpencodeGoLimits({
734
+ home,
735
+ env = process.env,
736
+ fetchImpl = fetch,
737
+ nowMs = Date.now(),
738
+ timeoutMs = DEFAULT_REQUEST_TIMEOUT_MS,
739
+ sqliteOptions = {},
740
+ } = {}) {
741
+ const apiKey = readApiKey(env);
742
+ const cfg = readConfig(env);
743
+ const allowLocalEstimate = localEstimateEnabled(env);
744
+
745
+ // Prefer the documented API whenever an API key is explicitly configured.
746
+ // An authentication failure is actionable and must not be hidden by silently
747
+ // falling back to a possibly stale cookie. For a transient API failure, an
748
+ // existing cookie remains a compatibility fallback.
749
+ if (apiKey) {
750
+ const api = await fetchOpencodeGoApiLimits({ apiKey, fetchImpl, nowMs, timeoutMs });
751
+ if (!api?.error && (api.primary_window || api.secondary_window || api.tertiary_window)) {
752
+ return { ...api, source: "api" };
753
+ }
754
+ if (api?.auth_error) {
755
+ return { ...api, source: "api" };
756
+ }
757
+ if (!cfg) return api || { configured: true, error: "OpenCode Go unavailable" };
758
+ }
759
+
760
+ // Keep the cookie-backed dashboard path for existing configurations and as a
761
+ // fallback when the official API is temporarily unavailable.
762
+ if (cfg) {
763
+ const web = await scrapeOpencodeGoWeb({ cfg, fetchImpl, nowMs, timeoutMs });
764
+ if (web?.subscription_status === "inactive") return web;
765
+ if (web && !web.error && (web.primary_window || web.secondary_window || web.tertiary_window)) {
766
+ return { ...web, source: "web" };
767
+ }
768
+ if (allowLocalEstimate) {
769
+ const local = await collectOpencodeGoLocal({ home, env, nowMs, sqliteOptions });
770
+ if (local) return localGoResult(local);
771
+ }
772
+ return web || { configured: true, error: "OpenCode Go unavailable" };
773
+ }
774
+
775
+ // Local history cannot establish that the account is currently subscribed.
776
+ // Keep it available for users who explicitly accept that limitation.
777
+ if (!allowLocalEstimate) return { configured: false };
778
+ const local = await collectOpencodeGoLocal({ home, env, nowMs, sqliteOptions });
779
+ if (local) return localGoResult(local);
780
+ return { configured: false };
781
+ }
782
+
783
+ module.exports = {
784
+ fetchOpencodeGoLimits,
785
+ fetchOpencodeGoApiLimits,
786
+ readConfig,
787
+ readApiKey,
788
+ localEstimateEnabled,
789
+ detectSubscriptionStatus,
790
+ extractWindows,
791
+ parseWindowUsage,
792
+ parseDataSlotFormat,
793
+ parseHumanReadableTime,
794
+ buildWindow,
795
+ resolveWorkspaceId,
796
+ parseWorkspaceIds,
797
+ looksSignedOut,
798
+ // Local opencode.db cost-based estimate (auth-free source).
799
+ collectOpencodeGoLocal,
800
+ discoverOpencodeDbPaths,
801
+ resolveOpencodeDataDir,
802
+ isOpencodeDbFilename,
803
+ goDollarLimits,
804
+ weekStartMs,
805
+ monthBoundsMs,
806
+ buildLocalWindow,
807
+ };