@phren/cli 0.3.10 → 0.3.11
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.
- package/dist/bridge/fanout-messages.js +2 -2
- package/dist/bridge/fanouts.js +1 -1
- package/dist/bridge/resources.d.ts +119 -0
- package/dist/bridge/resources.js +298 -0
- package/dist/bridge/server-overview.d.ts +8 -2
- package/dist/bridge/server-overview.js +16 -3
- package/dist/bridge/server-routes.d.ts +4 -1
- package/dist/bridge/server-routes.js +34 -3
- package/dist/bridge/server.js +5 -2
- package/dist/bridge/transcript-claude.js +5 -0
- package/dist/bridge/usage.d.ts +36 -20
- package/dist/bridge/usage.js +163 -301
- package/dist/bridge-hook.mjs +974 -793
- package/dist/cli-registry.d.ts +2 -0
- package/dist/cli-registry.js +13 -0
- package/dist/computers/command.d.ts +6 -0
- package/dist/computers/command.js +152 -0
- package/dist/computers/mcp.d.ts +1 -0
- package/dist/computers/mcp.js +97 -0
- package/dist/computers/read.d.ts +85 -0
- package/dist/computers/read.js +177 -0
- package/dist/entrypoint.js +10 -0
- package/dist/fanout/adapters/claude.js +15 -2
- package/dist/fanout/adapters/types.d.ts +6 -0
- package/dist/fanout/launcher.d.ts +5 -1
- package/dist/fanout/launcher.js +34 -3
- package/dist/fanout/picker.js +3 -2
- package/dist/fanout/usage.js +1 -1
- package/dist/modules/registry.js +3 -3
- package/package.json +1 -1
- package/starter/global/skills/fanout/SKILL.md +3 -0
package/dist/bridge/usage.js
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
import { execFile, spawn } from "node:child_process";
|
|
2
2
|
import { createHash } from "node:crypto";
|
|
3
|
-
import {
|
|
3
|
+
import { statSync } from "node:fs";
|
|
4
|
+
import { lstat, open, readFile, readdir } from "node:fs/promises";
|
|
4
5
|
import { homedir } from "node:os";
|
|
5
6
|
import { claudeConfigDir, homeDir } from "../home-paths.js";
|
|
6
7
|
import path from "node:path";
|
|
7
8
|
import { promisify } from "node:util";
|
|
8
|
-
import { fanoutRoot } from "./fanouts.js";
|
|
9
9
|
import { atomicInPrivateDir, bridgeRoot, object } from "./protocol.js";
|
|
10
10
|
import { stripTerminal } from "../terminal-text.js";
|
|
11
11
|
import { codexExecutable } from "./codex-binary.js";
|
|
@@ -119,324 +119,137 @@ export async function readOpenCodeGoKey() {
|
|
|
119
119
|
return undefined;
|
|
120
120
|
}
|
|
121
121
|
}
|
|
122
|
-
const goPeriods = [
|
|
123
|
-
{ id: "5h", label: "5h", milliseconds: 5 * 60 * 60 * 1_000 },
|
|
124
|
-
{ id: "7d", label: "7d", milliseconds: 7 * 24 * 60 * 60 * 1_000 },
|
|
125
|
-
{ id: "30d", label: "30d", milliseconds: 30 * 24 * 60 * 60 * 1_000 },
|
|
126
|
-
];
|
|
127
122
|
const GO_GATEWAY = "https://opencode.ai/zen/go/v1";
|
|
128
|
-
const MAX_GO_JOBS = 128;
|
|
129
|
-
const MAX_GO_MANIFEST_BYTES = 64 * 1_024;
|
|
130
|
-
const MAX_GO_EVENTS_BYTES = 64 * 1_024 * 1_024;
|
|
131
123
|
const GO_KEY_MESSAGE = "Connect OpenCode Go on this computer to see its usage.";
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
const
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
}
|
|
154
|
-
|
|
155
|
-
return typeof value === "number" && Number.isFinite(value) && value >= 0 && value <= 1_000_000_000 ? value : undefined;
|
|
156
|
-
}
|
|
157
|
-
function resetAt(value) {
|
|
158
|
-
if (typeof value === "string" && Number.isFinite(Date.parse(value)))
|
|
159
|
-
return new Date(value).toISOString();
|
|
160
|
-
if (typeof value === "string" && /^\d+(?:\.\d+)?$/.test(value))
|
|
161
|
-
return resetAt(Number(value));
|
|
162
|
-
if (typeof value === "number" && Number.isFinite(value) && value > 0 && value < 32_503_680_000) {
|
|
163
|
-
return new Date(value * 1_000).toISOString();
|
|
164
|
-
}
|
|
165
|
-
return undefined;
|
|
166
|
-
}
|
|
167
|
-
function recordGoLimit(limits, model, period, limitUSD, resetsAt) {
|
|
168
|
-
if (limitUSD === undefined || limitUSD <= 0)
|
|
169
|
-
return;
|
|
170
|
-
const current = limits.get(model) ?? {};
|
|
171
|
-
const existing = current[period];
|
|
172
|
-
// A response can repeat a limit at several levels. Keep the first numeric
|
|
173
|
-
// value, but retain a reset time wherever the service supplied one.
|
|
174
|
-
current[period] = existing ? { ...existing, ...(existing.resetsAt ? {} : { resetsAt }) } : { limitUSD, resetsAt };
|
|
175
|
-
limits.set(model, current);
|
|
176
|
-
}
|
|
177
|
-
function numberFrom(value, names) {
|
|
178
|
-
for (const name of names) {
|
|
179
|
-
const found = amount(value[name]);
|
|
180
|
-
if (found !== undefined)
|
|
181
|
-
return found;
|
|
182
|
-
}
|
|
183
|
-
return undefined;
|
|
184
|
-
}
|
|
185
|
-
function parseGoLimits(value, limits, model, period, depth = 0) {
|
|
186
|
-
if (depth > 8)
|
|
187
|
-
return;
|
|
188
|
-
if (typeof value === "number") {
|
|
189
|
-
if (period)
|
|
190
|
-
recordGoLimit(limits, model ?? "*", period, amount(value));
|
|
191
|
-
return;
|
|
192
|
-
}
|
|
193
|
-
if (Array.isArray(value)) {
|
|
194
|
-
for (const item of value.slice(0, 64))
|
|
195
|
-
parseGoLimits(item, limits, model, period, depth + 1);
|
|
196
|
-
return;
|
|
197
|
-
}
|
|
198
|
-
const item = object(value);
|
|
199
|
-
if (!Object.keys(item).length)
|
|
200
|
-
return;
|
|
201
|
-
const nestedModel = goModel(item.model, true) ?? goModel(item.modelId, true) ?? goModel(item.model_id, true) ?? model;
|
|
202
|
-
const nestedPeriod = goPeriod(item.window) ?? goPeriod(item.period) ?? goPeriod(item.interval) ?? goPeriod(item.windowName) ?? period;
|
|
203
|
-
const limitUSD = numberFrom(item, ["limitUSD", "limit_usd", "dollarLimit", "dollar_limit", "creditLimit", "credit_limit", "limit", "quota", "max"]);
|
|
204
|
-
const reset = resetAt(item.resetsAt) ?? resetAt(item.resets_at) ?? resetAt(item.resetAt) ?? resetAt(item.reset_at);
|
|
205
|
-
if (nestedPeriod)
|
|
206
|
-
recordGoLimit(limits, nestedModel ?? "*", nestedPeriod, limitUSD, reset);
|
|
207
|
-
for (const [key, nested] of Object.entries(item).slice(0, 64)) {
|
|
208
|
-
const keyPeriod = goPeriod(key) ?? nestedPeriod;
|
|
209
|
-
const keyModel = goModel(key) ?? nestedModel ?? (typeof nested === "object" && !keyPeriod ? goModel(key, true) : undefined);
|
|
210
|
-
// Scalar metadata such as a plan name cannot carry a usable limit.
|
|
211
|
-
if (typeof nested !== "object" && typeof nested !== "number")
|
|
212
|
-
continue;
|
|
213
|
-
parseGoLimits(nested, limits, keyModel, keyPeriod, depth + 1);
|
|
214
|
-
}
|
|
215
|
-
}
|
|
216
|
-
function completeGoLimits(limits) {
|
|
217
|
-
for (const [model, windows] of limits) {
|
|
218
|
-
const monthly = windows["30d"]?.limitUSD ?? (windows["7d"] ? windows["7d"].limitUSD * 2 : windows["5h"] ? windows["5h"].limitUSD * 5 : undefined);
|
|
219
|
-
if (!monthly || !Number.isFinite(monthly) || monthly <= 0)
|
|
220
|
-
continue;
|
|
221
|
-
recordGoLimit(limits, model, "5h", monthly * 0.2);
|
|
222
|
-
recordGoLimit(limits, model, "7d", monthly * 0.5);
|
|
223
|
-
recordGoLimit(limits, model, "30d", monthly);
|
|
224
|
-
}
|
|
225
|
-
}
|
|
226
|
-
function header(response, name) {
|
|
227
|
-
try {
|
|
228
|
-
return response.headers.get(name) ?? undefined;
|
|
229
|
-
}
|
|
230
|
-
catch {
|
|
231
|
-
return undefined;
|
|
232
|
-
}
|
|
233
|
-
}
|
|
234
|
-
function parseGoHeaders(response, limits) {
|
|
235
|
-
const limit = amount(Number(header(response, "x-ratelimit-limit")));
|
|
236
|
-
const remaining = amount(Number(header(response, "x-ratelimit-remaining")));
|
|
237
|
-
if (limit === undefined || remaining === undefined || remaining > limit)
|
|
238
|
-
return;
|
|
239
|
-
const period = goPeriod(header(response, "x-ratelimit-window"));
|
|
240
|
-
const reset = resetAt(header(response, "x-ratelimit-reset"));
|
|
241
|
-
// Gateway headers do not identify a model. Their plan-wide limit is the
|
|
242
|
-
// monthly amount unless the response explicitly names its window.
|
|
243
|
-
recordGoLimit(limits, "*", period ?? "30d", limit, reset);
|
|
124
|
+
const GO_WINDOWS = [
|
|
125
|
+
{ key: "rolling", id: "opencode-go:plan:5h", name: "5-hour limit" },
|
|
126
|
+
{ key: "weekly", id: "opencode-go:plan:7d", name: "Weekly limit" },
|
|
127
|
+
{ key: "monthly", id: "opencode-go:plan:30d", name: "Monthly limit" },
|
|
128
|
+
];
|
|
129
|
+
/**
|
|
130
|
+
* Go's own report of the plan, `GET /zen/go/v1/usage`:
|
|
131
|
+
* `{usage: {rolling|weekly|monthly: {status, percent, resetsAt}}}`. It is
|
|
132
|
+
* account-wide, so it already counts every computer's use, and it is what
|
|
133
|
+
* Go enforces: `status: "rate-limited"` is the window that refuses requests.
|
|
134
|
+
* It carries no dollar amounts, so none are shown.
|
|
135
|
+
*/
|
|
136
|
+
export function openCodeGoPlan(value) {
|
|
137
|
+
const usage = object(object(value).usage);
|
|
138
|
+
return GO_WINDOWS.flatMap(({ key, id, name }) => {
|
|
139
|
+
const item = object(usage[key]);
|
|
140
|
+
const percent = item.percent;
|
|
141
|
+
if (typeof percent !== "number" || !Number.isFinite(percent) || percent < 0 || percent > 100)
|
|
142
|
+
return [];
|
|
143
|
+
const resetsAt = typeof item.resetsAt === "string" && Number.isFinite(Date.parse(item.resetsAt)) ? new Date(item.resetsAt).toISOString() : undefined;
|
|
144
|
+
const limited = typeof item.status === "string" && item.status !== "ok";
|
|
145
|
+
return [{ id, name, usedPercent: Math.round(percent * 10) / 10, ...(resetsAt ? { resetsAt } : {}), ...(limited ? { limited: true } : {}) }];
|
|
146
|
+
});
|
|
244
147
|
}
|
|
245
|
-
|
|
246
|
-
* undocumented routes vary by OpenCode release and account. */
|
|
247
|
-
export async function fetchOpenCodeGoLimits(key, fetchImpl = fetch) {
|
|
148
|
+
export async function fetchOpenCodeGoPlan(key, fetchImpl = fetch) {
|
|
248
149
|
const controller = new AbortController();
|
|
249
150
|
const timer = setTimeout(() => controller.abort(), 8_000);
|
|
250
|
-
const limits = new Map();
|
|
251
151
|
try {
|
|
252
|
-
const
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
].map(async ([method, url]) => {
|
|
258
|
-
const response = await fetchImpl(url, { method, headers: { authorization: `Bearer ${key}`, accept: "application/json" },
|
|
259
|
-
redirect: "error", signal: controller.signal });
|
|
260
|
-
if (!response.ok)
|
|
261
|
-
return;
|
|
262
|
-
parseGoHeaders(response, limits);
|
|
263
|
-
if (method === "GET") {
|
|
264
|
-
try {
|
|
265
|
-
parseGoLimits(await response.json(), limits);
|
|
266
|
-
}
|
|
267
|
-
catch { /* An HTML or empty gateway response has no limits. */ }
|
|
268
|
-
}
|
|
269
|
-
}));
|
|
270
|
-
// Keep every request observed: one undocumented endpoint failing must not
|
|
271
|
-
// prevent headers or a second endpoint from describing the account.
|
|
272
|
-
void responses;
|
|
152
|
+
const response = await fetchImpl(`${GO_GATEWAY}/usage`, { headers: { authorization: `Bearer ${key}`, accept: "application/json" },
|
|
153
|
+
redirect: "error", signal: controller.signal });
|
|
154
|
+
if (!response.ok)
|
|
155
|
+
throw new Error(`OpenCode Go usage returned ${response.status}.`);
|
|
156
|
+
return openCodeGoPlan(await response.json());
|
|
273
157
|
}
|
|
274
158
|
finally {
|
|
275
159
|
clearTimeout(timer);
|
|
276
160
|
}
|
|
277
|
-
completeGoLimits(limits);
|
|
278
|
-
return limits;
|
|
279
|
-
}
|
|
280
|
-
async function containedRegularFile(root, candidate, maximum) {
|
|
281
|
-
try {
|
|
282
|
-
const link = await lstat(candidate);
|
|
283
|
-
if (!link.isFile() || link.isSymbolicLink() || link.size > maximum)
|
|
284
|
-
return undefined;
|
|
285
|
-
const resolved = await realpath(candidate);
|
|
286
|
-
if (!resolved.startsWith(root + path.sep))
|
|
287
|
-
return undefined;
|
|
288
|
-
const metadata = await stat(resolved);
|
|
289
|
-
return metadata.isFile() && metadata.size <= maximum ? resolved : undefined;
|
|
290
|
-
}
|
|
291
|
-
catch {
|
|
292
|
-
return undefined;
|
|
293
|
-
}
|
|
294
|
-
}
|
|
295
|
-
function goEventTime(value) {
|
|
296
|
-
const raw = value.timestamp ?? value.time ?? value.createdAt ?? value.created_at;
|
|
297
|
-
if (typeof raw === "string" && Number.isFinite(Date.parse(raw)))
|
|
298
|
-
return Date.parse(raw);
|
|
299
|
-
if (typeof raw !== "number" || !Number.isFinite(raw) || raw <= 0)
|
|
300
|
-
return undefined;
|
|
301
|
-
return raw < 32_503_680_000 ? raw * 1_000 : raw;
|
|
302
|
-
}
|
|
303
|
-
function goTokenCount(value, depth = 0) {
|
|
304
|
-
if (depth > 5)
|
|
305
|
-
return 0;
|
|
306
|
-
if (typeof value === "number")
|
|
307
|
-
return Number.isFinite(value) && value >= 0 && value <= 10_000_000_000 ? value : 0;
|
|
308
|
-
const item = object(value);
|
|
309
|
-
const total = amount(item.total) ?? amount(item.totalTokens) ?? amount(item.total_tokens);
|
|
310
|
-
if (total !== undefined)
|
|
311
|
-
return total;
|
|
312
|
-
return Object.values(item).reduce((sum, part) => sum + goTokenCount(part, depth + 1), 0);
|
|
313
161
|
}
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
const
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
}
|
|
329
|
-
catch {
|
|
330
|
-
return totals;
|
|
331
|
-
}
|
|
332
|
-
const names = (await readdir(directory).catch(() => [])).slice(0, MAX_GO_JOBS);
|
|
333
|
-
for (const name of names) {
|
|
334
|
-
if (!/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(name))
|
|
335
|
-
continue;
|
|
336
|
-
const manifestFile = await containedRegularFile(directory, path.join(directory, name, "manifest.json"), MAX_GO_MANIFEST_BYTES);
|
|
337
|
-
if (!manifestFile)
|
|
338
|
-
continue;
|
|
339
|
-
let manifest;
|
|
340
|
-
try {
|
|
341
|
-
manifest = object(JSON.parse(await readFile(manifestFile, "utf8")));
|
|
342
|
-
}
|
|
343
|
-
catch {
|
|
344
|
-
continue;
|
|
345
|
-
}
|
|
346
|
-
const model = goModel(manifest.model);
|
|
347
|
-
const eventLog = typeof manifest.eventLog === "string" && /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}\.jsonl$/.test(manifest.eventLog)
|
|
348
|
-
? manifest.eventLog : undefined;
|
|
349
|
-
if (manifest.provider !== "opencode" || !model || !eventLog)
|
|
350
|
-
continue;
|
|
351
|
-
const jobRoot = await realpath(path.join(directory, name)).catch(() => undefined);
|
|
352
|
-
if (!jobRoot || !jobRoot.startsWith(directory + path.sep))
|
|
353
|
-
continue;
|
|
354
|
-
const eventsFile = await containedRegularFile(jobRoot, path.join(jobRoot, eventLog), MAX_GO_EVENTS_BYTES);
|
|
355
|
-
if (!eventsFile)
|
|
162
|
+
const openCodeLogDir = () => path.join(process.env.OPENCODE_DATA_DIR || path.join(process.env.XDG_DATA_HOME || path.join(homedir(), ".local/share"), "opencode"), "log");
|
|
163
|
+
/** Refusals already read from each log, so a poll reads only what OpenCode
|
|
164
|
+
* appended since (this log grows by tens of MB a day). */
|
|
165
|
+
const refusalScans = new Map();
|
|
166
|
+
const FIRST_SCAN_BYTES = 64 * 1_048_576;
|
|
167
|
+
/** "Go usage limit exceeded" refusals in OpenCode's own log over the last
|
|
168
|
+
* `withinMs`. The first read of a log covers at most its last 64 MB. */
|
|
169
|
+
export async function readGoRefusals(now = new Date(), withinMs = 24 * 3_600_000, root = openCodeLogDir()) {
|
|
170
|
+
const since = now.getTime() - withinMs;
|
|
171
|
+
const events = [];
|
|
172
|
+
for (const name of (await readdir(root).catch(() => [])).filter(name => name.endsWith(".log")).slice(0, 32)) {
|
|
173
|
+
const file = path.join(root, name);
|
|
174
|
+
const info = await lstat(file).catch(() => undefined);
|
|
175
|
+
if (!info?.isFile() || info.isSymbolicLink() || info.mtimeMs < since)
|
|
356
176
|
continue;
|
|
357
|
-
let
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
}
|
|
364
|
-
for (const line of events.split("\n")) {
|
|
365
|
-
if (!line || Buffer.byteLength(line) > 1_048_576)
|
|
366
|
-
continue;
|
|
367
|
-
let event;
|
|
177
|
+
let scan = refusalScans.get(file);
|
|
178
|
+
// A rotated or truncated log starts over.
|
|
179
|
+
if (!scan || scan.ino !== info.ino || scan.offset > info.size)
|
|
180
|
+
scan = { ino: info.ino, offset: Math.max(0, info.size - FIRST_SCAN_BYTES), events: [] };
|
|
181
|
+
if (info.size > scan.offset) {
|
|
182
|
+
const handle = await open(file, "r");
|
|
368
183
|
try {
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
184
|
+
const length = Math.min(info.size - scan.offset, FIRST_SCAN_BYTES), bytes = Buffer.alloc(length);
|
|
185
|
+
await handle.read(bytes, 0, length, info.size - length);
|
|
186
|
+
const text = bytes.toString("utf8");
|
|
187
|
+
// Only whole lines: a line still being written is read next time.
|
|
188
|
+
const complete = text.lastIndexOf("\n") + 1;
|
|
189
|
+
for (const line of text.slice(0, complete).split("\n")) {
|
|
190
|
+
if (!line.includes("Go usage limit exceeded"))
|
|
191
|
+
continue;
|
|
192
|
+
const stamp = /timestamp=(\S+)/.exec(line)?.[1] ?? /\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z/.exec(line)?.[0];
|
|
193
|
+
const at = stamp ? Date.parse(stamp) : NaN;
|
|
194
|
+
if (Number.isFinite(at))
|
|
195
|
+
scan.events.push({ at, model: /modelID=([A-Za-z0-9._\/-]{1,120})/.exec(line)?.[1] });
|
|
196
|
+
}
|
|
197
|
+
scan.offset = info.size - length + complete;
|
|
373
198
|
}
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
const at = goEventTime(event), part = object(event.part);
|
|
377
|
-
const cost = goStepCost(event, part), tokens = goTokenCount(part.tokens ?? event.tokens);
|
|
378
|
-
if (at === undefined || (cost === undefined && tokens === 0) || at > now.getTime())
|
|
379
|
-
continue;
|
|
380
|
-
for (const period of goPeriods) {
|
|
381
|
-
if (at < now.getTime() - period.milliseconds)
|
|
382
|
-
continue;
|
|
383
|
-
const modelTotals = totals.get(model) ?? {
|
|
384
|
-
"5h": { usedUSD: 0, usedTokens: 0 }, "7d": { usedUSD: 0, usedTokens: 0 }, "30d": { usedUSD: 0, usedTokens: 0 },
|
|
385
|
-
};
|
|
386
|
-
const usedUSD = modelTotals[period.id].usedUSD + (cost ?? 0);
|
|
387
|
-
if (usedUSD > 1_000_000_000)
|
|
388
|
-
continue;
|
|
389
|
-
modelTotals[period.id].usedUSD = usedUSD;
|
|
390
|
-
modelTotals[period.id].usedTokens += tokens;
|
|
391
|
-
totals.set(model, modelTotals);
|
|
199
|
+
finally {
|
|
200
|
+
await handle.close();
|
|
392
201
|
}
|
|
393
202
|
}
|
|
203
|
+
scan.events = scan.events.filter(event => event.at >= now.getTime() - 7 * 24 * 3_600_000).slice(-10_000);
|
|
204
|
+
refusalScans.set(file, scan);
|
|
205
|
+
events.push(...scan.events.filter(event => event.at >= since && event.at <= now.getTime() + 60_000));
|
|
394
206
|
}
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
}
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
}
|
|
420
|
-
let
|
|
421
|
-
let
|
|
422
|
-
async function
|
|
423
|
-
if (!
|
|
424
|
-
|
|
425
|
-
.then(
|
|
426
|
-
.finally(() => {
|
|
427
|
-
}
|
|
428
|
-
return
|
|
207
|
+
if (!events.length)
|
|
208
|
+
return undefined;
|
|
209
|
+
events.sort((a, b) => a.at - b.at);
|
|
210
|
+
const models = [...new Set(events.flatMap(event => event.model ? [`opencode-go/${event.model}`] : []))].sort().slice(0, 8);
|
|
211
|
+
return { count: events.length, first: new Date(events[0].at).toISOString(), last: new Date(events.at(-1).at).toISOString(), models };
|
|
212
|
+
}
|
|
213
|
+
const clock = (iso) => `${iso.slice(11, 16)} UTC`;
|
|
214
|
+
export function openCodeGoUsage(windows, refusals, now, hasKey, planError) {
|
|
215
|
+
const refused = refusals
|
|
216
|
+
? `OpenCode refused ${refusals.count} Go request${refusals.count === 1 ? "" : "s"} with "usage limit exceeded" in the last day (${refusals.first.slice(0, 10) === refusals.last.slice(0, 10) ? `${clock(refusals.first)} to ${clock(refusals.last)}` : `${refusals.first.slice(0, 16).replace("T", " ")} to ${refusals.last.slice(0, 16).replace("T", " ")} UTC`}).`
|
|
217
|
+
: undefined;
|
|
218
|
+
const reached = windows.filter(window => window.limited).map(window => window.name.replace(" limit", "").toLowerCase());
|
|
219
|
+
const message = [
|
|
220
|
+
!hasKey ? GO_KEY_MESSAGE : planError ? "Could not read Go's usage report; showing what OpenCode's log says." : undefined,
|
|
221
|
+
reached.length ? `Go is refusing requests: the ${reached.join(" and ")} limit is reached.` : undefined,
|
|
222
|
+
refused,
|
|
223
|
+
].filter(Boolean).join(" ");
|
|
224
|
+
return { source: "opencode-go", windows, updatedAt: now.toISOString(), ...(message ? { message } : {}) };
|
|
225
|
+
}
|
|
226
|
+
/** The accounts one caller can read: the sources it names, and Go's plan
|
|
227
|
+
* windows only for a caller that asked for them (`goPlan=1`). */
|
|
228
|
+
export function usageForCaller(accounts, sources, goPlan) {
|
|
229
|
+
return accounts.filter(account => sources.has(account.source)).map(account => goPlan || account.source !== "opencode-go" ? account
|
|
230
|
+
: { ...account, windows: account.windows.filter(window => !window.id.startsWith("opencode-go:plan:")) });
|
|
231
|
+
}
|
|
232
|
+
let goPlanCached;
|
|
233
|
+
let goPlanPending;
|
|
234
|
+
async function cachedOpenCodeGoPlan(key, now) {
|
|
235
|
+
if (!goPlanCached || now.getTime() - goPlanCached.at >= 60_000) {
|
|
236
|
+
goPlanPending ??= fetchOpenCodeGoPlan(key)
|
|
237
|
+
.then(windows => { goPlanCached = { at: now.getTime(), windows }; return windows; })
|
|
238
|
+
.finally(() => { goPlanPending = undefined; });
|
|
239
|
+
}
|
|
240
|
+
return goPlanPending ? await goPlanPending : goPlanCached.windows;
|
|
429
241
|
}
|
|
430
242
|
export async function readOpenCodeGoUsage(now = new Date(), options = {}) {
|
|
431
|
-
const [
|
|
243
|
+
const [key, refusals] = await Promise.all([(options.readKey ?? readOpenCodeGoKey)(), (options.readRefusals ?? readGoRefusals)(now).catch(() => undefined)]);
|
|
432
244
|
if (!key)
|
|
433
|
-
return openCodeGoUsage(
|
|
434
|
-
let limits = new Map();
|
|
245
|
+
return openCodeGoUsage([], refusals, now, false);
|
|
435
246
|
try {
|
|
436
|
-
|
|
247
|
+
const windows = options.fetchImpl ? await fetchOpenCodeGoPlan(key, options.fetchImpl) : await cachedOpenCodeGoPlan(key, now);
|
|
248
|
+
return openCodeGoUsage(windows, refusals, now, true);
|
|
249
|
+
}
|
|
250
|
+
catch {
|
|
251
|
+
return openCodeGoUsage([], refusals, now, true, true);
|
|
437
252
|
}
|
|
438
|
-
catch { /* Gateway discovery is optional; local accounting is still useful. */ }
|
|
439
|
-
return openCodeGoUsage(totals, limits, now, true);
|
|
440
253
|
}
|
|
441
254
|
/** OpenRouter reports the current UTC calendar week's charged usage per key. */
|
|
442
255
|
export async function fetchOpenRouterUsage(key, fetchImpl = fetch, now = new Date()) {
|
|
@@ -713,6 +526,53 @@ export function readCodexLimits(executable = codexExecutable()) {
|
|
|
713
526
|
send({ id: 0, method: "initialize", params: { clientInfo: { name: "phren_usage", title: "Phren Usage", version: "1" } } });
|
|
714
527
|
});
|
|
715
528
|
}
|
|
529
|
+
/**
|
|
530
|
+
* GitHub Copilot's own quota report (`gh api /copilot_internal/user`): one
|
|
531
|
+
* window per limited quota (premium requests, usually) with the monthly
|
|
532
|
+
* reset. Unlimited quotas are named in the message, not drawn as 0%.
|
|
533
|
+
*/
|
|
534
|
+
export function copilotUsage(value, now = new Date()) {
|
|
535
|
+
const result = object(value), snapshots = object(result.quota_snapshots);
|
|
536
|
+
const reset = typeof result.quota_reset_date_utc === "string" && Number.isFinite(Date.parse(result.quota_reset_date_utc))
|
|
537
|
+
? new Date(Date.parse(result.quota_reset_date_utc)).toISOString() : undefined;
|
|
538
|
+
const names = { premium_interactions: "Premium requests · monthly", chat: "Chat · monthly", completions: "Completions · monthly" };
|
|
539
|
+
const windows = [], unlimited = [];
|
|
540
|
+
for (const [id, raw] of Object.entries(snapshots).slice(0, 8)) {
|
|
541
|
+
const quota = object(raw), key = safeText(id) ?? "quota";
|
|
542
|
+
if (quota.unlimited === true) {
|
|
543
|
+
unlimited.push((names[key] ?? key).replace(" · monthly", "").toLowerCase());
|
|
544
|
+
continue;
|
|
545
|
+
}
|
|
546
|
+
const remaining = quota.percent_remaining;
|
|
547
|
+
if (typeof remaining !== "number" || !Number.isFinite(remaining) || remaining < 0 || remaining > 100)
|
|
548
|
+
continue;
|
|
549
|
+
windows.push({ id: key, name: names[key] ?? key, usedPercent: Math.round((100 - remaining) * 10) / 10, ...(reset ? { resetsAt: reset } : {}) });
|
|
550
|
+
}
|
|
551
|
+
const plan = safeText(result.copilot_plan);
|
|
552
|
+
const notes = [plan ? `Plan: ${plan}.` : "", unlimited.length ? `Unlimited: ${unlimited.join(", ")}.` : ""].filter(Boolean).join(" ");
|
|
553
|
+
return { source: "copilot", windows, updatedAt: now.toISOString(),
|
|
554
|
+
...(notes || !windows.length ? { message: notes || "GitHub reported no Copilot quotas for this account." } : {}) };
|
|
555
|
+
}
|
|
556
|
+
/** The first GitHub CLI found; the Hook's service PATH may not include Homebrew. */
|
|
557
|
+
function ghExecutable() {
|
|
558
|
+
for (const candidate of ["/opt/homebrew/bin/gh", "/usr/local/bin/gh", "/usr/bin/gh"]) {
|
|
559
|
+
try {
|
|
560
|
+
if (statSync(candidate).isFile())
|
|
561
|
+
return candidate;
|
|
562
|
+
}
|
|
563
|
+
catch { /* next */ }
|
|
564
|
+
}
|
|
565
|
+
return "gh";
|
|
566
|
+
}
|
|
567
|
+
/** Reads through the GitHub CLI's own sign-in; the token never reaches Phren. */
|
|
568
|
+
export async function readCopilotUsage(now = new Date(), run = async (file, args) => (await exec(file, args, { timeout: 10_000, maxBuffer: 1_048_576, cwd: homedir() })).stdout) {
|
|
569
|
+
try {
|
|
570
|
+
return copilotUsage(JSON.parse(await run(ghExecutable(), ["api", "/copilot_internal/user"])), now);
|
|
571
|
+
}
|
|
572
|
+
catch {
|
|
573
|
+
return { source: "copilot", windows: [], message: "Could not read Copilot usage. Sign in with gh auth login on this computer (Copilot reports its quotas through GitHub)." };
|
|
574
|
+
}
|
|
575
|
+
}
|
|
716
576
|
export class AccountUsageReader {
|
|
717
577
|
readCodex;
|
|
718
578
|
now;
|
|
@@ -720,19 +580,21 @@ export class AccountUsageReader {
|
|
|
720
580
|
readOpenCode;
|
|
721
581
|
readOpenRouter;
|
|
722
582
|
readOpenCodeGo;
|
|
583
|
+
readCopilot;
|
|
723
584
|
cached;
|
|
724
585
|
pending;
|
|
725
586
|
claudeCached;
|
|
726
587
|
claudePending;
|
|
727
588
|
spendingCached;
|
|
728
589
|
spendingPending;
|
|
729
|
-
constructor(readCodex = readCodexLimits, now = Date.now, readClaudeLive = liveClaudeUsage, readOpenCode = now => readOpenCodeUsage("opencode", now), readOpenRouter = liveOpenRouterUsage, readOpenCodeGo = readOpenCodeGoUsage) {
|
|
590
|
+
constructor(readCodex = readCodexLimits, now = Date.now, readClaudeLive = liveClaudeUsage, readOpenCode = now => readOpenCodeUsage("opencode", now), readOpenRouter = liveOpenRouterUsage, readOpenCodeGo = readOpenCodeGoUsage, readCopilot = readCopilotUsage) {
|
|
730
591
|
this.readCodex = readCodex;
|
|
731
592
|
this.now = now;
|
|
732
593
|
this.readClaudeLive = readClaudeLive;
|
|
733
594
|
this.readOpenCode = readOpenCode;
|
|
734
595
|
this.readOpenRouter = readOpenRouter;
|
|
735
596
|
this.readOpenCodeGo = readOpenCodeGo;
|
|
597
|
+
this.readCopilot = readCopilot;
|
|
736
598
|
}
|
|
737
599
|
async read() {
|
|
738
600
|
if (!this.cached || this.now() - this.cached.at >= 60_000) {
|
|
@@ -745,8 +607,8 @@ export class AccountUsageReader {
|
|
|
745
607
|
async spending() {
|
|
746
608
|
if (!this.spendingCached || this.now() - this.spendingCached.at >= 60_000) {
|
|
747
609
|
const at = this.now();
|
|
748
|
-
this.spendingPending ??= Promise.all([this.readOpenCode(new Date(at)), this.readOpenCodeGo(new Date(at)), this.readOpenRouter(new Date(at))])
|
|
749
|
-
.then(([openCode, openCodeGo, openRouter]) => [openCode, openCodeGo, ...(openRouter ? [openRouter] : [])])
|
|
610
|
+
this.spendingPending ??= Promise.all([this.readOpenCode(new Date(at)), this.readOpenCodeGo(new Date(at)), this.readOpenRouter(new Date(at)), this.readCopilot(new Date(at))])
|
|
611
|
+
.then(([openCode, openCodeGo, openRouter, copilot]) => [openCode, openCodeGo, ...(openRouter ? [openRouter] : []), copilot])
|
|
750
612
|
.then(value => { this.spendingCached = { at, value }; return value; })
|
|
751
613
|
.finally(() => { this.spendingPending = undefined; });
|
|
752
614
|
}
|