-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathusage-core.mjs
More file actions
393 lines (330 loc) · 13.6 KB
/
Copy pathusage-core.mjs
File metadata and controls
393 lines (330 loc) · 13.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
/**
* Tide Pools v2 — Usage Core
*
* Architecture:
* Layer 1 (Accuracy): Adapter registry fetches dashboard-accurate numbers
* from provider APIs with priority + fallback.
* Layer 2 (Enrichment): JSONL session mining shows where usage went.
* 100% optional — never blocks Layer 1.
*/
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { resolveAll } from "./adapters/index.mjs";
const DEFAULT_CACHE_TTL_MS = 45_000;
// ─── Cache ──────────────────────────────────��────────────────────────────────
function resolveCachePath(customPath) {
if (customPath) return customPath;
if (process.env.TIDE_POOL_CACHE_PATH) return process.env.TIDE_POOL_CACHE_PATH;
if (process.env.LOBSTER_USAGE_CACHE_PATH) return process.env.LOBSTER_USAGE_CACHE_PATH;
return path.join(os.tmpdir(), "openclaw-tide-pools-cache.json");
}
function readCache(cachePath, ttlMs, cacheKey = null) {
if (!ttlMs || ttlMs <= 0) return null;
try {
const raw = fs.readFileSync(cachePath, "utf8");
const parsed = JSON.parse(raw);
if (!parsed || typeof parsed.cachedAtMs !== "number" || !parsed.snapshot) return null;
if (Date.now() - parsed.cachedAtMs > ttlMs) return null;
if (cacheKey) {
const expected = JSON.stringify(cacheKey);
const actual = JSON.stringify(parsed.cacheKey || null);
if (expected !== actual) return null;
}
return parsed.snapshot;
} catch {
return null;
}
}
function writeCache(cachePath, snapshot, cacheKey = null) {
try {
fs.mkdirSync(path.dirname(cachePath), { recursive: true });
fs.writeFileSync(cachePath, JSON.stringify({ cachedAtMs: Date.now(), snapshot, cacheKey }));
} catch {
// best-effort cache
}
}
// ─── Enrichment (fault-isolated import) ──────────────────────────────────────
let _enrichmentModule = null;
async function loadEnrichment() {
if (_enrichmentModule !== null) return _enrichmentModule;
try {
_enrichmentModule = await import("./enrichment.mjs");
} catch {
_enrichmentModule = false; // mark as failed so we don't retry
}
return _enrichmentModule;
}
async function safeCollectEnrichment(opts) {
try {
const mod = await loadEnrichment();
if (!mod) return { available: false };
return mod.collectEnrichment(opts);
} catch {
return { available: false };
}
}
async function safeFormatEnrichment(enrichment, opts) {
try {
const mod = await loadEnrichment();
if (!mod) return null;
return mod.formatEnrichment(enrichment, opts);
} catch {
return null;
}
}
// ─── Helpers ─────────────────────────────────────────────────────────────────
function countdown(resetAt) {
let resetAtMs;
if (typeof resetAt === "number") {
resetAtMs = resetAt;
} else if (typeof resetAt === "string") {
resetAtMs = new Date(resetAt).getTime();
} else {
return "reset unknown";
}
if (Number.isNaN(resetAtMs)) return "reset unknown";
const delta = Math.max(0, resetAtMs - Date.now());
const totalMins = Math.floor(delta / 60000);
const d = Math.floor(totalMins / 1440);
const h = Math.floor((totalMins % 1440) / 60);
const m = totalMins % 60;
const parts = [];
if (d) parts.push(`${d}d`);
if (h) parts.push(`${h}h`);
if (m || parts.length === 0) parts.push(`${m}m`);
return `in ${parts.join(" ")}`;
}
// ─── Snapshot Collection ─────────────────────────────────────────────────────
/**
* Collect a full usage snapshot: adapters + optional enrichment.
*
* @param {object} opts
* @param {boolean} opts.includeVenice
* @param {boolean} opts.includeEnrichment
* @param {number} opts.cacheTtlMs
* @param {string} opts.cachePath
* @param {boolean} opts.bypassCache
* @param {number} opts.enrichmentLookbackHours
*/
export async function collectUsageSnapshot(opts = {}) {
const includeVenice = opts.includeVenice !== false;
const includeEnrichment = opts.includeEnrichment !== false;
const anthropicSource = String(opts.anthropicSource || "auto").toLowerCase();
const cacheTtlMs = Number.isFinite(opts.cacheTtlMs)
? Number(opts.cacheTtlMs)
: DEFAULT_CACHE_TTL_MS;
const cachePath = resolveCachePath(opts.cachePath);
const bypassCache = opts.bypassCache === true;
const cacheKey = { includeVenice, includeEnrichment, anthropicSource };
// Check cache
if (!bypassCache) {
const cached = readCache(cachePath, cacheTtlMs, cacheKey);
if (cached) {
return {
...cached,
cache: { hit: true, ttlMs: cacheTtlMs, path: cachePath },
};
}
}
// Layer 1 + Layer 2 in parallel (enrichment is independent of adapters)
const [resolved, enrichment] = await Promise.all([
resolveAll({ includeVenice, anthropicSource }),
includeEnrichment
? safeCollectEnrichment({ lookbackHours: opts.enrichmentLookbackHours })
: null,
]);
const snapshot = {
generatedAt: new Date().toISOString(),
version: "2.0.0",
providers: resolved.providers,
adapterResults: resolved.adapterResults,
enrichment,
};
// Write cache
if (!bypassCache && cacheTtlMs > 0) writeCache(cachePath, snapshot, cacheKey);
return {
...snapshot,
cache: { hit: false, ttlMs: cacheTtlMs, path: cachePath },
};
}
// ─── Formatting ──────────────────────────────────────────────────────────────
function anthropicResetText(w) {
if (w?.resetIn) return `in ${w.resetIn}`;
return countdown(w?.resetAt);
}
function formatAnthropicLine(p, sourceTag) {
const name = p.displayName || "Anthropic";
const plan = p.plan ? ` [${p.plan}]` : "";
const windows = Array.isArray(p.windows) ? p.windows : [];
if (p.error && !windows.length) {
return `• **${name}${plan}**: unavailable — ${p.error}${sourceTag}`;
}
const byLabel = Object.fromEntries(windows.map((w) => [String(w.label || "").toLowerCase(), w]));
const five = byLabel["5h"];
const week = byLabel["week"];
const apiMonth = byLabel["api-month"];
const extra = byLabel["extra"];
const chunks = [];
if (five) {
const leftTxt = five.leftPercent != null ? `${five.leftPercent}% left` : "left unknown";
chunks.push(`5h: ${leftTxt} (${anthropicResetText(five)})`);
}
if (week) {
const leftTxt = week.leftPercent != null ? `${week.leftPercent}% left` : "left unknown";
chunks.push(`week: ${leftTxt} (${anthropicResetText(week)})`);
}
if (apiMonth) {
const leftTxt = apiMonth.leftPercent != null ? `${apiMonth.leftPercent}% left` : "left unknown";
chunks.push(`api-month: ${leftTxt} (${anthropicResetText(apiMonth)})`);
}
const head = chunks.length
? `• **${name}${plan}**: ${chunks.join(" | ")}${sourceTag}`
: `• **${name}${plan}**: no quota windows${sourceTag}`;
const extraParts = [];
if (extra) {
if (extra.status) extraParts.push(`status ${extra.status}`);
if (extra.spentUsd != null && extra.limitUsd != null) {
extraParts.push(`$${Number(extra.spentUsd).toFixed(2)} / $${Number(extra.limitUsd).toFixed(2)} spent`);
}
if (extra.availableUsd != null) extraParts.push(`$${Number(extra.availableUsd).toFixed(2)} available`);
if (extra.overUsd != null && Number(extra.overUsd) > 0) extraParts.push(`over by $${Number(extra.overUsd).toFixed(2)}`);
if (extra.resetAt || extra.resetIn) extraParts.push(`reset ${anthropicResetText(extra)}`);
}
if (!extraParts.length) return head;
return `${head}\n └─ 💳 **Extra usage**: ${extraParts.join(" · ")}`;
}
function formatProviderLine(p) {
const name = p.displayName || p.provider || "Unknown provider";
const plan = p.plan ? ` [${p.plan}]` : "";
const sourceTag = p.source ? ` — via ${formatSourceName(p.source)}` : "";
// Venice is special: uses Diem balance + rate limits
if (p.provider === "venice") {
return formatVeniceLine(p, sourceTag);
}
// Anthropic is special: subscription windows + extra usage details
if (String(p.provider || "").toLowerCase() === "anthropic") {
return formatAnthropicLine(p, sourceTag);
}
// OpenRouter is special: account credits + key-level usage windows
if (String(p.provider || "").toLowerCase() === "openrouter") {
return formatOpenRouterLine(p, sourceTag);
}
if (p.error) return `• **${name}${plan}**: unavailable — ${p.error}${sourceTag}`;
const windows = Array.isArray(p.windows) ? p.windows : [];
if (!windows.length) return `• **${name}${plan}**: no quota windows${sourceTag}`;
const chunks = windows.map((w) => {
const label = w.label || "window";
const leftTxt =
w.leftPercent != null ? `${w.leftPercent}% left` : "left unknown";
return `${label}: ${leftTxt} (${countdown(w.resetAt)})`;
});
return `• **${name}${plan}**: ${chunks.join(" | ")}${sourceTag}`;
}
function formatVeniceLine(p, sourceTag) {
if (p.error && !p.diem && !p.requests && !p.tokens) {
return `• **Venice [Diem]**: unavailable — ${p.error}${sourceTag}`;
}
const chunks = [];
if (p.diem != null) chunks.push(`Diem: ${Number(p.diem).toFixed(4)}`);
if (p.requests) {
chunks.push(
`Requests: ${p.requests.remaining}/${p.requests.limit} (${p.requests.leftPercent ?? "?"}% left)`
);
}
if (p.tokens) {
chunks.push(
`Tokens: ${Number(p.tokens.remaining).toLocaleString()}/${Number(p.tokens.limit).toLocaleString()} (${p.tokens.leftPercent ?? "?"}% left)`
);
}
if (!chunks.length) {
return `• **Venice [Diem]**: no balance data${sourceTag}`;
}
return `• **Venice [Diem]**: ${chunks.join(" | ")}${sourceTag}`;
}
function formatOpenRouterLine(p, sourceTag) {
const name = p.displayName || "OpenRouter";
const plan = p.plan ? ` [${p.plan}]` : "";
const data = p.openrouter || {};
const credits = data.credits || null;
const key = data.key || null;
if (p.error && !credits && !key) {
return `• **${name}${plan}**: unavailable — ${p.error}${sourceTag}`;
}
const chunks = [];
if (credits) {
const total = credits.totalCredits;
const used = credits.totalUsage;
const balance = credits.balance;
const usedPercent = credits.usedPercent;
if (total != null && used != null) {
chunks.push(
`credits: $${Number(used).toFixed(2)} / $${Number(total).toFixed(2)}${
usedPercent != null ? ` (${usedPercent}% used)` : ""
}`
);
}
if (balance != null) {
chunks.push(`balance: $${Number(balance).toFixed(2)}`);
}
}
if (key) {
if (key.limit != null && key.usage != null && key.limit > 0) {
const usedPercent = Math.max(0, Math.min(100, Math.round((key.usage / key.limit) * 100)));
const leftPercent = Math.max(0, 100 - usedPercent);
chunks.push(
`key limit: $${Number(key.usage).toFixed(2)} / $${Number(key.limit).toFixed(2)} (${leftPercent}% left)`
);
}
if (key.usageMonthly != null) chunks.push(`month: $${Number(key.usageMonthly).toFixed(2)}`);
if (key.usageWeekly != null) chunks.push(`week: $${Number(key.usageWeekly).toFixed(2)}`);
if (key.usageDaily != null) chunks.push(`day: $${Number(key.usageDaily).toFixed(2)}`);
}
const head = chunks.length
? `• **${name}${plan}**: ${chunks.join(" | ")}${sourceTag}`
: `• **${name}${plan}**: no quota windows${sourceTag}`;
const warnings = Array.isArray(data.warnings) ? data.warnings.filter(Boolean) : [];
if (!warnings.length) return head;
return `${head}\n └─ ⚠️ ${warnings.join(" · ")}`;
}
function formatSourceName(source) {
const map = {
"openai-codex-oauth": "OAuth API",
"anthropic-cli-usage": "Claude /usage",
"openclaw-status": "OpenClaw status",
"venice-diem": "Diem API",
"openrouter-api": "OpenRouter API",
};
return map[source] || source;
}
/**
* Format a full usage report from a snapshot.
*
* @param {object} snapshot - from collectUsageSnapshot()
* @param {object} opts
* @param {string} opts.theme - "plain" | "tide"
* @param {boolean} opts.includeEnrichment
*/
export async function formatUsageReport(snapshot, opts = {}) {
const theme = opts.theme || "plain";
const heading = theme === "plain" ? "📊 **Provider Quota Board**" : "🌊 **Tide Pools**";
const includeEnrichment = opts.includeEnrichment !== false;
const lines = [heading, "", "🛰️ **Providers**"];
const providers = Array.isArray(snapshot?.providers) ? snapshot.providers : [];
if (!providers.length) {
lines.push("• **No provider usage data found** (credentials/scope may be missing)");
} else {
for (const p of providers) lines.push(formatProviderLine(p));
}
// Enrichment section (fault-isolated)
if (includeEnrichment && snapshot?.enrichment) {
const enrichText = await safeFormatEnrichment(snapshot.enrichment);
if (enrichText) lines.push("", enrichText);
}
return lines.join("\n");
}
// ─── Backward Compatibility ──────────────────────────────────────────────────
// These re-exports keep the CLI and plugin working during the transition.
// They can be removed in a future version once cli.mjs and index.ts are updated.
export { collectUsageSnapshot as collectUsageSnapshotV2 };
export { formatUsageReport as formatUsageReportV2 };