@phren/cli 0.3.10 → 0.3.12
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/agent-hook-stores.d.ts +3 -0
- package/dist/bridge/agent-hook-stores.js +5 -0
- package/dist/bridge/agent-hooks.d.ts +159 -5
- package/dist/bridge/agent-hooks.js +663 -49
- package/dist/bridge/approval-summary.d.ts +16 -0
- package/dist/bridge/approval-summary.js +133 -0
- package/dist/bridge/authority-command.d.ts +20 -0
- package/dist/bridge/authority-command.js +120 -0
- package/dist/bridge/authority.d.ts +223 -0
- package/dist/bridge/authority.js +231 -0
- package/dist/bridge/claude-account-setup.d.ts +14 -0
- package/dist/bridge/claude-account-setup.js +69 -0
- package/dist/bridge/claude-accounts.d.ts +49 -0
- package/dist/bridge/claude-accounts.js +195 -0
- package/dist/bridge/code-routes.js +2 -2
- package/dist/bridge/codex-app-server.d.ts +144 -0
- package/dist/bridge/codex-app-server.js +319 -0
- package/dist/bridge/codex-auth-refresh.d.ts +33 -0
- package/dist/bridge/codex-auth-refresh.js +71 -0
- package/dist/bridge/codex-question-reply.d.ts +16 -0
- package/dist/bridge/codex-question-reply.js +57 -0
- package/dist/bridge/codex-review-mode.d.ts +10 -0
- package/dist/bridge/codex-review-mode.js +74 -0
- package/dist/bridge/codex-servers.d.ts +217 -0
- package/dist/bridge/codex-servers.js +636 -0
- package/dist/bridge/command.js +94 -4
- package/dist/bridge/computer-identity.d.ts +75 -0
- package/dist/bridge/computer-identity.js +166 -0
- package/dist/bridge/conductor-group.d.ts +91 -8
- package/dist/bridge/conductor-group.js +105 -9
- package/dist/bridge/conductor-role.d.ts +94 -0
- package/dist/bridge/conductor-role.js +176 -0
- package/dist/bridge/conductor-sets.d.ts +20 -0
- package/dist/bridge/conductor-sets.js +59 -0
- package/dist/bridge/dispatch-command.d.ts +3 -0
- package/dist/bridge/dispatch-command.js +75 -11
- package/dist/bridge/dispatch-returns.d.ts +123 -19
- package/dist/bridge/dispatch-returns.js +357 -50
- package/dist/bridge/dispatch.d.ts +103 -2
- package/dist/bridge/dispatch.js +272 -40
- package/dist/bridge/fanout-messages.js +2 -2
- package/dist/bridge/fanouts.d.ts +7 -1
- package/dist/bridge/fanouts.js +40 -5
- package/dist/bridge/folder-trust.d.ts +56 -0
- package/dist/bridge/folder-trust.js +195 -0
- package/dist/bridge/grants.d.ts +22 -1
- package/dist/bridge/grants.js +57 -9
- package/dist/bridge/hand-off.d.ts +21 -9
- package/dist/bridge/hand-off.js +58 -45
- package/dist/bridge/harness-status.d.ts +11 -0
- package/dist/bridge/harness-status.js +32 -0
- package/dist/bridge/harnesses.d.ts +39 -0
- package/dist/bridge/harnesses.js +65 -0
- package/dist/bridge/health.d.ts +2 -0
- package/dist/bridge/health.js +1 -1
- package/dist/bridge/herdr.d.ts +11 -2
- package/dist/bridge/herdr.js +98 -23
- package/dist/bridge/hook-fast.d.ts +4 -0
- package/dist/bridge/hook-fast.js +68 -0
- package/dist/bridge/install.d.ts +16 -1
- package/dist/bridge/install.js +88 -21
- package/dist/bridge/launch-brief.d.ts +96 -0
- package/dist/bridge/launch-brief.js +164 -0
- package/dist/bridge/model-switch.d.ts +3 -0
- package/dist/bridge/model-switch.js +17 -1
- package/dist/bridge/models.d.ts +8 -4
- package/dist/bridge/models.js +24 -8
- package/dist/bridge/mux-wire.d.ts +9 -0
- package/dist/bridge/mux-wire.js +19 -0
- package/dist/bridge/opencode-pane-server.d.ts +113 -0
- package/dist/bridge/opencode-pane-server.js +332 -0
- package/dist/bridge/opencode-panes.d.ts +111 -0
- package/dist/bridge/opencode-panes.js +295 -0
- package/dist/bridge/pane-accounts.d.ts +8 -0
- package/dist/bridge/pane-accounts.js +46 -0
- package/dist/bridge/prompt-startup.d.ts +5 -0
- package/dist/bridge/prompt-startup.js +24 -0
- package/dist/bridge/protocol.d.ts +5 -0
- package/dist/bridge/protocol.js +4 -0
- package/dist/bridge/push.d.ts +5 -4
- package/dist/bridge/push.js +6 -4
- package/dist/bridge/questions.d.ts +37 -2
- package/dist/bridge/questions.js +158 -15
- package/dist/bridge/resources.d.ts +125 -0
- package/dist/bridge/resources.js +314 -0
- package/dist/bridge/schedule-format.d.ts +2 -0
- package/dist/bridge/schedule-format.js +3 -0
- package/dist/bridge/schedule-launch.d.ts +2 -1
- package/dist/bridge/schedule-launch.js +23 -53
- package/dist/bridge/schedule-watch.d.ts +10 -1
- package/dist/bridge/schedule-watch.js +54 -2
- package/dist/bridge/server-launch.d.ts +22 -5
- package/dist/bridge/server-launch.js +225 -29
- package/dist/bridge/server-overview.d.ts +8 -2
- package/dist/bridge/server-overview.js +26 -5
- package/dist/bridge/server-pane-routes.d.ts +2 -0
- package/dist/bridge/server-pane-routes.js +145 -15
- package/dist/bridge/server-routes.d.ts +11 -1
- package/dist/bridge/server-routes.js +195 -36
- package/dist/bridge/server-stream.d.ts +2 -0
- package/dist/bridge/server-stream.js +22 -8
- package/dist/bridge/server.d.ts +6 -1
- package/dist/bridge/server.js +47 -12
- package/dist/bridge/session-activity.d.ts +81 -0
- package/dist/bridge/session-activity.js +117 -0
- package/dist/bridge/session-rename.d.ts +48 -0
- package/dist/bridge/session-rename.js +190 -0
- package/dist/bridge/session-servers.js +2 -2
- package/dist/bridge/settings-switch.d.ts +60 -0
- package/dist/bridge/settings-switch.js +287 -0
- package/dist/bridge/speech-voice.d.ts +55 -0
- package/dist/bridge/speech-voice.js +132 -0
- package/dist/bridge/speech.d.ts +70 -11
- package/dist/bridge/speech.js +169 -41
- package/dist/bridge/terminal-herdr.js +9 -3
- package/dist/bridge/terminal-tmux.d.ts +3 -3
- package/dist/bridge/terminal-tmux.js +24 -9
- package/dist/bridge/terminal.d.ts +27 -4
- package/dist/bridge/terminal.js +8 -1
- package/dist/bridge/transcript-claude.js +62 -12
- package/dist/bridge/transcript-codex.d.ts +0 -2
- package/dist/bridge/transcript-codex.js +29 -4
- package/dist/bridge/transcript-preview.d.ts +1 -0
- package/dist/bridge/transcript-preview.js +24 -4
- package/dist/bridge/transcripts.d.ts +15 -2
- package/dist/bridge/transcripts.js +47 -16
- package/dist/bridge/turn-records.d.ts +85 -0
- package/dist/bridge/turn-records.js +143 -0
- package/dist/bridge/uploads.d.ts +3 -0
- package/dist/bridge/uploads.js +14 -0
- package/dist/bridge/usage.d.ts +73 -28
- package/dist/bridge/usage.js +313 -340
- package/dist/bridge-hook.mjs +24624 -18450
- package/dist/cli/claude-unmanaged.d.ts +12 -0
- package/dist/cli/claude-unmanaged.js +105 -0
- package/dist/cli/schedules.js +2 -1
- package/dist/cli/session-start.js +10 -1
- package/dist/cli/session-stop.js +9 -1
- package/dist/cli-registry.d.ts +2 -0
- package/dist/cli-registry.js +37 -5
- 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/data/task-receipts.d.ts +19 -0
- package/dist/data/task-receipts.js +68 -0
- package/dist/data/tasks.js +4 -1
- 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/generated/memory-ui-graph.browser.js +63 -63
- package/dist/graph-core/model.js +24 -3
- package/dist/graph-core/types.d.ts +4 -1
- package/dist/graph-core/types.js +1 -0
- package/dist/init/init-preset.js +7 -3
- package/dist/init/init-uninstall.js +2 -11
- package/dist/init/teardown.d.ts +3 -0
- package/dist/init/teardown.js +47 -0
- package/dist/link/context.js +21 -9
- package/dist/mcp/plugin-mode.js +1 -1
- package/dist/memory-ui-graph.runtime.js +63 -63
- package/dist/modules/code-package.d.ts +1 -0
- package/dist/modules/code-package.js +36 -7
- package/dist/modules/registry.js +14 -13
- package/dist/profile-store.d.ts +6 -0
- package/dist/profile-store.js +25 -1
- package/dist/shell/graph/glyphs.js +4 -0
- package/dist/shell/graph/graph-view.js +2 -0
- package/dist/status.js +7 -1
- package/dist/sync/task-claim.js +3 -2
- package/dist/task/lifecycle.js +25 -4
- package/dist/test-global-setup.js +5 -0
- package/dist/tools/dispatch.js +35 -2
- package/dist/tools/tasks.js +10 -1
- package/package.json +1 -1
- package/plugins/opencode/phren-transcript.js +87 -4
- package/starter/global/skills/conductor/SKILL.md +17 -2
- package/starter/global/skills/fanout/SKILL.md +3 -0
package/dist/bridge/usage.js
CHANGED
|
@@ -1,16 +1,19 @@
|
|
|
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
|
-
import { claudeConfigDir
|
|
6
|
+
import { claudeConfigDir } 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";
|
|
12
|
+
import { readSpeechKey } from "./speech-key.js";
|
|
13
|
+
import { CODEX_ACCOUNT, claudeAccountEmail, claudeAccountRef, claudeHomeOfEnv, claudeHomes } from "./claude-accounts.js";
|
|
12
14
|
const exec = promisify(execFile);
|
|
13
|
-
|
|
15
|
+
/** The status-line snapshot: `usage/claude.json` for the default home, `usage/claude-<id>.json` for others. */
|
|
16
|
+
const claudeFile = (home) => path.join(bridgeRoot(), "usage", home && !home.isDefault ? `claude-${home.id}.json` : "claude.json");
|
|
14
17
|
const safeText = (v) => typeof v === "string" ? v.replace(/[\x00-\x1f\x7f]/g, "").slice(0, 100) : undefined;
|
|
15
18
|
function window(id, name, percent, reset) {
|
|
16
19
|
if (typeof percent !== "number" || !Number.isFinite(percent) || percent < 0 || percent > 100)
|
|
@@ -119,324 +122,137 @@ export async function readOpenCodeGoKey() {
|
|
|
119
122
|
return undefined;
|
|
120
123
|
}
|
|
121
124
|
}
|
|
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
125
|
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
126
|
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
|
-
}
|
|
127
|
+
const GO_WINDOWS = [
|
|
128
|
+
{ key: "rolling", id: "opencode-go:plan:5h", name: "5-hour limit" },
|
|
129
|
+
{ key: "weekly", id: "opencode-go:plan:7d", name: "Weekly limit" },
|
|
130
|
+
{ key: "monthly", id: "opencode-go:plan:30d", name: "Monthly limit" },
|
|
131
|
+
];
|
|
132
|
+
/**
|
|
133
|
+
* Go's own report of the plan, `GET /zen/go/v1/usage`:
|
|
134
|
+
* `{usage: {rolling|weekly|monthly: {status, percent, resetsAt}}}`. It is
|
|
135
|
+
* account-wide, so it already counts every computer's use, and it is what
|
|
136
|
+
* Go enforces: `status: "rate-limited"` is the window that refuses requests.
|
|
137
|
+
* It carries no dollar amounts, so none are shown.
|
|
138
|
+
*/
|
|
139
|
+
export function openCodeGoPlan(value) {
|
|
140
|
+
const usage = object(object(value).usage);
|
|
141
|
+
return GO_WINDOWS.flatMap(({ key, id, name }) => {
|
|
142
|
+
const item = object(usage[key]);
|
|
143
|
+
const percent = item.percent;
|
|
144
|
+
if (typeof percent !== "number" || !Number.isFinite(percent) || percent < 0 || percent > 100)
|
|
145
|
+
return [];
|
|
146
|
+
const resetsAt = typeof item.resetsAt === "string" && Number.isFinite(Date.parse(item.resetsAt)) ? new Date(item.resetsAt).toISOString() : undefined;
|
|
147
|
+
const limited = typeof item.status === "string" && item.status !== "ok";
|
|
148
|
+
return [{ id, name, usedPercent: Math.round(percent * 10) / 10, ...(resetsAt ? { resetsAt } : {}), ...(limited ? { limited: true } : {}) }];
|
|
149
|
+
});
|
|
233
150
|
}
|
|
234
|
-
function
|
|
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);
|
|
244
|
-
}
|
|
245
|
-
/** Best-effort gateway discovery. All four requests are independent because
|
|
246
|
-
* undocumented routes vary by OpenCode release and account. */
|
|
247
|
-
export async function fetchOpenCodeGoLimits(key, fetchImpl = fetch) {
|
|
151
|
+
export async function fetchOpenCodeGoPlan(key, fetchImpl = fetch) {
|
|
248
152
|
const controller = new AbortController();
|
|
249
153
|
const timer = setTimeout(() => controller.abort(), 8_000);
|
|
250
|
-
const limits = new Map();
|
|
251
154
|
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;
|
|
155
|
+
const response = await fetchImpl(`${GO_GATEWAY}/usage`, { headers: { authorization: `Bearer ${key}`, accept: "application/json" },
|
|
156
|
+
redirect: "error", signal: controller.signal });
|
|
157
|
+
if (!response.ok)
|
|
158
|
+
throw new Error(`OpenCode Go usage returned ${response.status}.`);
|
|
159
|
+
return openCodeGoPlan(await response.json());
|
|
273
160
|
}
|
|
274
161
|
finally {
|
|
275
162
|
clearTimeout(timer);
|
|
276
163
|
}
|
|
277
|
-
completeGoLimits(limits);
|
|
278
|
-
return limits;
|
|
279
164
|
}
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
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
|
-
}
|
|
314
|
-
function goStepCost(event, part) {
|
|
315
|
-
const raw = part.cost ?? event.cost;
|
|
316
|
-
if (typeof raw === "number")
|
|
317
|
-
return amount(raw);
|
|
318
|
-
const cost = object(raw);
|
|
319
|
-
return numberFrom(cost, ["total", "amount", "usd", "cost"]);
|
|
320
|
-
}
|
|
321
|
-
/** Sum only completed OpenCode Go fan-outs. Their ledger stays on the
|
|
322
|
-
* computer and malformed jobs are ignored rather than becoming usage. */
|
|
323
|
-
export async function readOpenCodeGoLedger(root = fanoutRoot(), now = new Date()) {
|
|
324
|
-
const totals = new Map();
|
|
325
|
-
let directory;
|
|
326
|
-
try {
|
|
327
|
-
directory = await realpath(root);
|
|
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)
|
|
165
|
+
const openCodeLogDir = () => path.join(process.env.OPENCODE_DATA_DIR || path.join(process.env.XDG_DATA_HOME || path.join(homedir(), ".local/share"), "opencode"), "log");
|
|
166
|
+
/** Refusals already read from each log, so a poll reads only what OpenCode
|
|
167
|
+
* appended since (this log grows by tens of MB a day). */
|
|
168
|
+
const refusalScans = new Map();
|
|
169
|
+
const FIRST_SCAN_BYTES = 64 * 1_048_576;
|
|
170
|
+
/** "Go usage limit exceeded" refusals in OpenCode's own log over the last
|
|
171
|
+
* `withinMs`. The first read of a log covers at most its last 64 MB. */
|
|
172
|
+
export async function readGoRefusals(now = new Date(), withinMs = 24 * 3_600_000, root = openCodeLogDir()) {
|
|
173
|
+
const since = now.getTime() - withinMs;
|
|
174
|
+
const events = [];
|
|
175
|
+
for (const name of (await readdir(root).catch(() => [])).filter(name => name.endsWith(".log")).slice(0, 32)) {
|
|
176
|
+
const file = path.join(root, name);
|
|
177
|
+
const info = await lstat(file).catch(() => undefined);
|
|
178
|
+
if (!info?.isFile() || info.isSymbolicLink() || info.mtimeMs < since)
|
|
350
179
|
continue;
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
if (
|
|
356
|
-
|
|
357
|
-
let events;
|
|
358
|
-
try {
|
|
359
|
-
events = await readFile(eventsFile, "utf8");
|
|
360
|
-
}
|
|
361
|
-
catch {
|
|
362
|
-
continue;
|
|
363
|
-
}
|
|
364
|
-
for (const line of events.split("\n")) {
|
|
365
|
-
if (!line || Buffer.byteLength(line) > 1_048_576)
|
|
366
|
-
continue;
|
|
367
|
-
let event;
|
|
180
|
+
let scan = refusalScans.get(file);
|
|
181
|
+
// A rotated or truncated log starts over.
|
|
182
|
+
if (!scan || scan.ino !== info.ino || scan.offset > info.size)
|
|
183
|
+
scan = { ino: info.ino, offset: Math.max(0, info.size - FIRST_SCAN_BYTES), events: [] };
|
|
184
|
+
if (info.size > scan.offset) {
|
|
185
|
+
const handle = await open(file, "r");
|
|
368
186
|
try {
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
187
|
+
const length = Math.min(info.size - scan.offset, FIRST_SCAN_BYTES), bytes = Buffer.alloc(length);
|
|
188
|
+
await handle.read(bytes, 0, length, info.size - length);
|
|
189
|
+
const text = bytes.toString("utf8");
|
|
190
|
+
// Only whole lines: a line still being written is read next time.
|
|
191
|
+
const complete = text.lastIndexOf("\n") + 1;
|
|
192
|
+
for (const line of text.slice(0, complete).split("\n")) {
|
|
193
|
+
if (!line.includes("Go usage limit exceeded"))
|
|
194
|
+
continue;
|
|
195
|
+
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];
|
|
196
|
+
const at = stamp ? Date.parse(stamp) : NaN;
|
|
197
|
+
if (Number.isFinite(at))
|
|
198
|
+
scan.events.push({ at, model: /modelID=([A-Za-z0-9._\/-]{1,120})/.exec(line)?.[1] });
|
|
199
|
+
}
|
|
200
|
+
scan.offset = info.size - length + complete;
|
|
373
201
|
}
|
|
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);
|
|
202
|
+
finally {
|
|
203
|
+
await handle.close();
|
|
392
204
|
}
|
|
393
205
|
}
|
|
206
|
+
scan.events = scan.events.filter(event => event.at >= now.getTime() - 7 * 24 * 3_600_000).slice(-10_000);
|
|
207
|
+
refusalScans.set(file, scan);
|
|
208
|
+
events.push(...scan.events.filter(event => event.at >= since && event.at <= now.getTime() + 60_000));
|
|
394
209
|
}
|
|
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
|
|
210
|
+
if (!events.length)
|
|
211
|
+
return undefined;
|
|
212
|
+
events.sort((a, b) => a.at - b.at);
|
|
213
|
+
const models = [...new Set(events.flatMap(event => event.model ? [`opencode-go/${event.model}`] : []))].sort().slice(0, 8);
|
|
214
|
+
return { count: events.length, first: new Date(events[0].at).toISOString(), last: new Date(events.at(-1).at).toISOString(), models };
|
|
215
|
+
}
|
|
216
|
+
const clock = (iso) => `${iso.slice(11, 16)} UTC`;
|
|
217
|
+
export function openCodeGoUsage(windows, refusals, now, hasKey, planError) {
|
|
218
|
+
const refused = refusals
|
|
219
|
+
? `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`}).`
|
|
220
|
+
: undefined;
|
|
221
|
+
const reached = windows.filter(window => window.limited).map(window => window.name.replace(" limit", "").toLowerCase());
|
|
222
|
+
const message = [
|
|
223
|
+
!hasKey ? GO_KEY_MESSAGE : planError ? "Could not read Go's usage report; showing what OpenCode's log says." : undefined,
|
|
224
|
+
reached.length ? `Go is refusing requests: the ${reached.join(" and ")} limit is reached.` : undefined,
|
|
225
|
+
refused,
|
|
226
|
+
].filter(Boolean).join(" ");
|
|
227
|
+
return { source: "opencode-go", windows, updatedAt: now.toISOString(), ...(message ? { message } : {}) };
|
|
228
|
+
}
|
|
229
|
+
/** The accounts one caller can read: the sources it names, and Go's plan
|
|
230
|
+
* windows only for a caller that asked for them (`goPlan=1`). */
|
|
231
|
+
export function usageForCaller(accounts, sources, goPlan) {
|
|
232
|
+
return accounts.filter(account => sources.has(account.source)).map(account => goPlan || account.source !== "opencode-go" ? account
|
|
233
|
+
: { ...account, windows: account.windows.filter(window => !window.id.startsWith("opencode-go:plan:")) });
|
|
234
|
+
}
|
|
235
|
+
let goPlanCached;
|
|
236
|
+
let goPlanPending;
|
|
237
|
+
async function cachedOpenCodeGoPlan(key, now) {
|
|
238
|
+
if (!goPlanCached || now.getTime() - goPlanCached.at >= 60_000) {
|
|
239
|
+
goPlanPending ??= fetchOpenCodeGoPlan(key)
|
|
240
|
+
.then(windows => { goPlanCached = { at: now.getTime(), windows }; return windows; })
|
|
241
|
+
.finally(() => { goPlanPending = undefined; });
|
|
242
|
+
}
|
|
243
|
+
return goPlanPending ? await goPlanPending : goPlanCached.windows;
|
|
429
244
|
}
|
|
430
245
|
export async function readOpenCodeGoUsage(now = new Date(), options = {}) {
|
|
431
|
-
const [
|
|
246
|
+
const [key, refusals] = await Promise.all([(options.readKey ?? readOpenCodeGoKey)(), (options.readRefusals ?? readGoRefusals)(now).catch(() => undefined)]);
|
|
432
247
|
if (!key)
|
|
433
|
-
return openCodeGoUsage(
|
|
434
|
-
let limits = new Map();
|
|
248
|
+
return openCodeGoUsage([], refusals, now, false);
|
|
435
249
|
try {
|
|
436
|
-
|
|
250
|
+
const windows = options.fetchImpl ? await fetchOpenCodeGoPlan(key, options.fetchImpl) : await cachedOpenCodeGoPlan(key, now);
|
|
251
|
+
return openCodeGoUsage(windows, refusals, now, true);
|
|
252
|
+
}
|
|
253
|
+
catch {
|
|
254
|
+
return openCodeGoUsage([], refusals, now, true, true);
|
|
437
255
|
}
|
|
438
|
-
catch { /* Gateway discovery is optional; local accounting is still useful. */ }
|
|
439
|
-
return openCodeGoUsage(totals, limits, now, true);
|
|
440
256
|
}
|
|
441
257
|
/** OpenRouter reports the current UTC calendar week's charged usage per key. */
|
|
442
258
|
export async function fetchOpenRouterUsage(key, fetchImpl = fetch, now = new Date()) {
|
|
@@ -479,6 +295,49 @@ async function liveOpenRouterUsage(now) {
|
|
|
479
295
|
return { source: "openrouter", windows: [], message: "Could not read OpenRouter spend. Check its key in OpenCode." };
|
|
480
296
|
}
|
|
481
297
|
}
|
|
298
|
+
/** ElevenLabs' subscription: characters used this billing period against the plan's limit. */
|
|
299
|
+
export function elevenLabsUsage(value, now = new Date()) {
|
|
300
|
+
const sub = object(value);
|
|
301
|
+
const used = sub.character_count, limit = sub.character_limit;
|
|
302
|
+
const count = (n) => typeof n === "number" && Number.isSafeInteger(n) && n >= 0;
|
|
303
|
+
if (!count(used) || !count(limit) || limit === 0) {
|
|
304
|
+
return { source: "elevenlabs", windows: [], updatedAt: now.toISOString(), message: "ElevenLabs did not report a character limit for this key." };
|
|
305
|
+
}
|
|
306
|
+
const entry = window("elevenlabs:characters", "Characters this period", Math.min(100, Math.round(used / limit * 1000) / 10), sub.next_character_count_reset_unix);
|
|
307
|
+
return { source: "elevenlabs", windows: entry ? [{ ...entry, usedCharacters: used, limitCharacters: limit }] : [], updatedAt: now.toISOString() };
|
|
308
|
+
}
|
|
309
|
+
/** The key the Hook already uses for /v1/speech, sent only to ElevenLabs; the answer carries counts, never the key. */
|
|
310
|
+
export async function fetchElevenLabsUsage(key, fetchImpl = fetch, now = new Date()) {
|
|
311
|
+
const controller = new AbortController();
|
|
312
|
+
const timer = setTimeout(() => controller.abort(), 8_000);
|
|
313
|
+
try {
|
|
314
|
+
const response = await fetchImpl("https://api.elevenlabs.io/v1/user/subscription", {
|
|
315
|
+
headers: { "xi-api-key": key, accept: "application/json" },
|
|
316
|
+
redirect: "error",
|
|
317
|
+
signal: controller.signal,
|
|
318
|
+
});
|
|
319
|
+
if (!response.ok)
|
|
320
|
+
throw new Error(`ElevenLabs subscription endpoint returned ${response.status}.`);
|
|
321
|
+
return elevenLabsUsage(await response.json(), now);
|
|
322
|
+
}
|
|
323
|
+
finally {
|
|
324
|
+
clearTimeout(timer);
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
/** No row without a key: most computers have no spoken replies set up. `PHREN_ELEVENLABS_USAGE=off` skips it (the test suite does). */
|
|
328
|
+
async function liveElevenLabsUsage(now) {
|
|
329
|
+
if (typeof fetch !== "function" || process.env.PHREN_ELEVENLABS_USAGE === "off")
|
|
330
|
+
return undefined;
|
|
331
|
+
const key = await readSpeechKey().catch(() => undefined);
|
|
332
|
+
if (!key)
|
|
333
|
+
return undefined;
|
|
334
|
+
try {
|
|
335
|
+
return await fetchElevenLabsUsage(key, fetch, now);
|
|
336
|
+
}
|
|
337
|
+
catch {
|
|
338
|
+
return { source: "elevenlabs", windows: [], updatedAt: now.toISOString(), message: "Could not read ElevenLabs usage. Check this computer's ElevenLabs key." };
|
|
339
|
+
}
|
|
340
|
+
}
|
|
482
341
|
/** "seven_day_fable" → "7-day, Fable"; weekly-all stays explicit. */
|
|
483
342
|
function claudeWindowName(key) {
|
|
484
343
|
const spans = [["five_hour", "5-hour"], ["seven_day", "7-day"], ["one_hour", "1-hour"], ["one_day", "1-day"]];
|
|
@@ -543,9 +402,7 @@ export function claudeScopedWindows(config, now = new Date()) {
|
|
|
543
402
|
}
|
|
544
403
|
return windows;
|
|
545
404
|
}
|
|
546
|
-
|
|
547
|
-
const claudeConfigFile = () => path.join(process.env.CLAUDE_CONFIG_DIR?.trim() ? claudeConfigDir() : homeDir(), ".claude.json");
|
|
548
|
-
const claudeCredentialsFile = () => path.join(claudeConfigDir(), ".credentials.json");
|
|
405
|
+
const claudeCredentialsFile = (home) => path.join(home?.dir ?? claudeConfigDir(), ".credentials.json");
|
|
549
406
|
/**
|
|
550
407
|
* The OAuth usage endpoint Claude Code itself reads, mapped to the same
|
|
551
408
|
* windows the status-line snapshot produces. `limits` is the structured
|
|
@@ -588,9 +445,10 @@ export function claudeOAuthUsage(value, now = new Date()) {
|
|
|
588
445
|
* Claude Code's own sign-in token, read locally and used only against
|
|
589
446
|
* Anthropic's usage endpoint — never persisted, logged, or sent elsewhere.
|
|
590
447
|
* The file is authoritative off macOS; macOS keeps it in the login keychain,
|
|
591
|
-
* with the file left stale after a refresh.
|
|
448
|
+
* with the file left stale after a refresh. A non-default `home` reads only its
|
|
449
|
+
* own file, and nothing on macOS (its keychain item name is unverified).
|
|
592
450
|
*/
|
|
593
|
-
export async function readClaudeToken(execSecurity = exec, platform = process.platform) {
|
|
451
|
+
export async function readClaudeToken(execSecurity = exec, platform = process.platform, home) {
|
|
594
452
|
const parse = (raw) => {
|
|
595
453
|
if (raw.length > 16_384)
|
|
596
454
|
return undefined;
|
|
@@ -601,6 +459,9 @@ export async function readClaudeToken(execSecurity = exec, platform = process.pl
|
|
|
601
459
|
return undefined;
|
|
602
460
|
return token;
|
|
603
461
|
};
|
|
462
|
+
const other = home !== undefined && !home.isDefault;
|
|
463
|
+
if (other && platform === "darwin")
|
|
464
|
+
return undefined;
|
|
604
465
|
if (platform === "darwin") {
|
|
605
466
|
try {
|
|
606
467
|
const { stdout } = await execSecurity("security", ["find-generic-password", "-s", "Claude Code-credentials", "-w"], { timeout: 5_000, maxBuffer: 16_384 });
|
|
@@ -611,7 +472,7 @@ export async function readClaudeToken(execSecurity = exec, platform = process.pl
|
|
|
611
472
|
catch { /* Headless installs can keep credentials in the file instead. */ }
|
|
612
473
|
}
|
|
613
474
|
try {
|
|
614
|
-
return parse(await readFile(claudeCredentialsFile(), "utf8"));
|
|
475
|
+
return parse(await readFile(claudeCredentialsFile(home), "utf8"));
|
|
615
476
|
}
|
|
616
477
|
catch {
|
|
617
478
|
return undefined;
|
|
@@ -635,10 +496,10 @@ export async function fetchClaudeUsage(token, fetchImpl = fetch, now = new Date(
|
|
|
635
496
|
clearTimeout(timer);
|
|
636
497
|
}
|
|
637
498
|
}
|
|
638
|
-
async function liveClaudeUsage(now) {
|
|
499
|
+
async function liveClaudeUsage(now, home) {
|
|
639
500
|
if (typeof fetch !== "function")
|
|
640
501
|
return undefined;
|
|
641
|
-
const token = await readClaudeToken();
|
|
502
|
+
const token = await readClaudeToken(exec, process.platform, home);
|
|
642
503
|
if (!token)
|
|
643
504
|
return undefined;
|
|
644
505
|
try {
|
|
@@ -713,6 +574,83 @@ export function readCodexLimits(executable = codexExecutable()) {
|
|
|
713
574
|
send({ id: 0, method: "initialize", params: { clientInfo: { name: "phren_usage", title: "Phren Usage", version: "1" } } });
|
|
714
575
|
});
|
|
715
576
|
}
|
|
577
|
+
/**
|
|
578
|
+
* GitHub Copilot's own quota report (`gh api /copilot_internal/user`): one
|
|
579
|
+
* window per limited quota (premium requests, usually) with the monthly
|
|
580
|
+
* reset. Unlimited quotas are named in the message, not drawn as 0%.
|
|
581
|
+
*/
|
|
582
|
+
export function copilotUsage(value, now = new Date()) {
|
|
583
|
+
const result = object(value), snapshots = object(result.quota_snapshots);
|
|
584
|
+
const reset = typeof result.quota_reset_date_utc === "string" && Number.isFinite(Date.parse(result.quota_reset_date_utc))
|
|
585
|
+
? new Date(Date.parse(result.quota_reset_date_utc)).toISOString() : undefined;
|
|
586
|
+
const names = { premium_interactions: "Premium requests · monthly", chat: "Chat · monthly", completions: "Completions · monthly" };
|
|
587
|
+
const windows = [], unlimited = [];
|
|
588
|
+
for (const [id, raw] of Object.entries(snapshots).slice(0, 8)) {
|
|
589
|
+
const quota = object(raw), key = safeText(id) ?? "quota";
|
|
590
|
+
if (quota.unlimited === true) {
|
|
591
|
+
unlimited.push((names[key] ?? key).replace(" · monthly", "").toLowerCase());
|
|
592
|
+
continue;
|
|
593
|
+
}
|
|
594
|
+
const remaining = quota.percent_remaining;
|
|
595
|
+
if (typeof remaining !== "number" || !Number.isFinite(remaining) || remaining < 0 || remaining > 100)
|
|
596
|
+
continue;
|
|
597
|
+
windows.push({ id: key, name: names[key] ?? key, usedPercent: Math.round((100 - remaining) * 10) / 10, ...(reset ? { resetsAt: reset } : {}) });
|
|
598
|
+
}
|
|
599
|
+
const plan = safeText(result.copilot_plan);
|
|
600
|
+
const notes = [plan ? `Plan: ${plan}.` : "", unlimited.length ? `Unlimited: ${unlimited.join(", ")}.` : ""].filter(Boolean).join(" ");
|
|
601
|
+
return { source: "copilot", windows, updatedAt: now.toISOString(),
|
|
602
|
+
...(notes || !windows.length ? { message: notes || "GitHub reported no Copilot quotas for this account." } : {}) };
|
|
603
|
+
}
|
|
604
|
+
/** The first GitHub CLI found; the Hook's service PATH may not include Homebrew. */
|
|
605
|
+
function ghExecutable() {
|
|
606
|
+
for (const candidate of ["/opt/homebrew/bin/gh", "/usr/local/bin/gh", "/usr/bin/gh"]) {
|
|
607
|
+
try {
|
|
608
|
+
if (statSync(candidate).isFile())
|
|
609
|
+
return candidate;
|
|
610
|
+
}
|
|
611
|
+
catch { /* next */ }
|
|
612
|
+
}
|
|
613
|
+
return "gh";
|
|
614
|
+
}
|
|
615
|
+
/** Reads through the GitHub CLI's own sign-in; the token never reaches Phren. */
|
|
616
|
+
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) {
|
|
617
|
+
try {
|
|
618
|
+
return copilotUsage(JSON.parse(await run(ghExecutable(), ["api", "/copilot_internal/user"])), now);
|
|
619
|
+
}
|
|
620
|
+
catch (error) {
|
|
621
|
+
const failure = object(error);
|
|
622
|
+
const detail = [failure.stderr, failure.message].filter((part) => typeof part === "string").join(" ");
|
|
623
|
+
return { source: "copilot", windows: [], message: /\bHTTP 404\b/i.test(detail)
|
|
624
|
+
? "No Copilot subscription on this GitHub account"
|
|
625
|
+
: "Could not read Copilot usage. Sign in with gh auth login on this computer (Copilot reports its quotas through GitHub)." };
|
|
626
|
+
}
|
|
627
|
+
}
|
|
628
|
+
/** A Claude report older than this says nothing about the account now. */
|
|
629
|
+
export const CLAUDE_REPORT_MAX_AGE_MS = 3 * 86_400_000;
|
|
630
|
+
/**
|
|
631
|
+
* What a saved Claude report still says at `now`: a window whose reset time
|
|
632
|
+
* has passed is reported as reset without its old percent, and a report
|
|
633
|
+
* older than three days is dropped, so a stale number never reaches the
|
|
634
|
+
* phone's cards, rings or widgets.
|
|
635
|
+
*/
|
|
636
|
+
export function settleClaudeUsage(usage, now) {
|
|
637
|
+
if (!usage.windows.length)
|
|
638
|
+
return usage;
|
|
639
|
+
const reported = (w) => Date.parse(w.asOf ?? usage.updatedAt ?? "");
|
|
640
|
+
const windows = usage.windows
|
|
641
|
+
.filter(w => { const at = reported(w); return !Number.isFinite(at) || now - at < CLAUDE_REPORT_MAX_AGE_MS; })
|
|
642
|
+
.map(w => {
|
|
643
|
+
const reset = w.resetsAt ? Date.parse(w.resetsAt) : NaN;
|
|
644
|
+
if (!Number.isFinite(reset) || reset > now)
|
|
645
|
+
return w;
|
|
646
|
+
const { usedPercent: _old, ...rest } = w;
|
|
647
|
+
return { ...rest, reset: true };
|
|
648
|
+
});
|
|
649
|
+
if (windows.length)
|
|
650
|
+
return { ...usage, windows };
|
|
651
|
+
const since = usage.updatedAt?.slice(0, 10);
|
|
652
|
+
return { ...usage, windows, message: `No usage report from Claude on this computer${since ? ` since ${since}` : ""}. It updates when Claude Code runs here.` };
|
|
653
|
+
}
|
|
716
654
|
export class AccountUsageReader {
|
|
717
655
|
readCodex;
|
|
718
656
|
now;
|
|
@@ -720,57 +658,87 @@ export class AccountUsageReader {
|
|
|
720
658
|
readOpenCode;
|
|
721
659
|
readOpenRouter;
|
|
722
660
|
readOpenCodeGo;
|
|
661
|
+
readCopilot;
|
|
662
|
+
platform;
|
|
663
|
+
readElevenLabs;
|
|
723
664
|
cached;
|
|
724
665
|
pending;
|
|
725
|
-
claudeCached;
|
|
726
|
-
claudePending;
|
|
727
|
-
spendingCached;
|
|
728
|
-
spendingPending;
|
|
729
|
-
constructor(readCodex = readCodexLimits, now = Date.now, readClaudeLive = liveClaudeUsage, readOpenCode = now => readOpenCodeUsage("opencode", now), readOpenRouter = liveOpenRouterUsage, readOpenCodeGo = readOpenCodeGoUsage) {
|
|
666
|
+
claudeCached = new Map();
|
|
667
|
+
claudePending = new Map();
|
|
668
|
+
spendingCached = new Map();
|
|
669
|
+
spendingPending = new Map();
|
|
670
|
+
constructor(readCodex = readCodexLimits, now = Date.now, readClaudeLive = liveClaudeUsage, readOpenCode = now => readOpenCodeUsage("opencode", now), readOpenRouter = liveOpenRouterUsage, readOpenCodeGo = readOpenCodeGoUsage, readCopilot = readCopilotUsage, platform = process.platform, readElevenLabs = liveElevenLabsUsage) {
|
|
730
671
|
this.readCodex = readCodex;
|
|
731
672
|
this.now = now;
|
|
732
673
|
this.readClaudeLive = readClaudeLive;
|
|
733
674
|
this.readOpenCode = readOpenCode;
|
|
734
675
|
this.readOpenRouter = readOpenRouter;
|
|
735
676
|
this.readOpenCodeGo = readOpenCodeGo;
|
|
677
|
+
this.readCopilot = readCopilot;
|
|
678
|
+
this.platform = platform;
|
|
679
|
+
this.readElevenLabs = readElevenLabs;
|
|
736
680
|
}
|
|
737
|
-
|
|
681
|
+
/** `allAccounts`: one Claude row per home. Otherwise only the default home's, as
|
|
682
|
+
* before accounts existed, since older phones refuse two rows of one source. */
|
|
683
|
+
async read(sources, allAccounts = false) {
|
|
738
684
|
if (!this.cached || this.now() - this.cached.at >= 60_000) {
|
|
739
685
|
this.pending ??= this.readCodex().then(value => { this.cached = { at: this.now(), value }; return value; }).finally(() => { this.pending = undefined; });
|
|
740
686
|
}
|
|
741
687
|
const codex = this.pending ?? Promise.resolve(this.cached.value);
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
688
|
+
// Every home, default first; the labels and keys are read once per poll.
|
|
689
|
+
const homes = allAccounts ? claudeHomes() : claudeHomes().slice(0, 1);
|
|
690
|
+
const claudeRow = async (home) => {
|
|
691
|
+
const email = claudeAccountEmail(home);
|
|
692
|
+
return { ...settleClaudeUsage(await this.claude(home), this.now()), account: { ...claudeAccountRef(home), ...(email ? { email } : {}) } };
|
|
693
|
+
};
|
|
694
|
+
const [codexValue, claude, spending] = await Promise.all([codex, Promise.all(homes.map(claudeRow)),
|
|
695
|
+
this.spending(sources?.has("copilot") ?? true, sources?.has("elevenlabs") ?? true)]);
|
|
696
|
+
return { accounts: [{ ...codexValue, account: CODEX_ACCOUNT }, ...claude, ...spending] };
|
|
697
|
+
}
|
|
698
|
+
/** ElevenLabs is read only when the caller shows it: every read spends a request against the key's quota. */
|
|
699
|
+
async spending(includeCopilot, includeElevenLabs) {
|
|
700
|
+
const key = `${includeCopilot}:${includeElevenLabs}`;
|
|
701
|
+
const cached = this.spendingCached.get(key);
|
|
702
|
+
if (!cached || this.now() - cached.at >= 60_000) {
|
|
747
703
|
const at = this.now();
|
|
748
|
-
|
|
749
|
-
.
|
|
750
|
-
|
|
751
|
-
|
|
704
|
+
if (!this.spendingPending.has(key)) {
|
|
705
|
+
const pending = Promise.all([this.readOpenCode(new Date(at)), this.readOpenCodeGo(new Date(at)), this.readOpenRouter(new Date(at)),
|
|
706
|
+
includeCopilot ? this.readCopilot(new Date(at)) : Promise.resolve(undefined),
|
|
707
|
+
includeElevenLabs ? this.readElevenLabs(new Date(at)).catch(() => undefined) : Promise.resolve(undefined)])
|
|
708
|
+
.then(([openCode, openCodeGo, openRouter, copilot, elevenLabs]) => [openCode, openCodeGo, ...(openRouter ? [openRouter] : []), ...(copilot ? [copilot] : []), ...(elevenLabs ? [elevenLabs] : [])])
|
|
709
|
+
.then(value => { this.spendingCached.set(key, { at, value }); return value; })
|
|
710
|
+
.finally(() => { this.spendingPending.delete(key); });
|
|
711
|
+
this.spendingPending.set(key, pending);
|
|
712
|
+
}
|
|
752
713
|
}
|
|
753
|
-
return this.spendingPending
|
|
714
|
+
return this.spendingPending.get(key) ?? cached.value;
|
|
754
715
|
}
|
|
755
716
|
/** Live first, so the phone's minute-by-minute poll keeps Claude current
|
|
756
|
-
* even when Claude Code is not running; the local snapshot is the backup.
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
717
|
+
* even when Claude Code is not running; the local snapshot is the backup.
|
|
718
|
+
* Off macOS a non-default home reads its own credentials file; on macOS it
|
|
719
|
+
* has no live read (the keychain item name for custom homes is unverified). */
|
|
720
|
+
async claude(home) {
|
|
721
|
+
if (home.isDefault || this.platform !== "darwin") {
|
|
722
|
+
const cached = this.claudeCached.get(home.dir);
|
|
723
|
+
if (!cached || this.now() - cached.at >= 60_000) {
|
|
724
|
+
const at = this.now();
|
|
725
|
+
if (!this.claudePending.has(home.dir))
|
|
726
|
+
this.claudePending.set(home.dir, this.readClaudeLive(new Date(at), home)
|
|
727
|
+
.then(value => { this.claudeCached.set(home.dir, { at, value }); return value; })
|
|
728
|
+
.catch(() => { this.claudeCached.set(home.dir, { at, value: undefined }); return undefined; })
|
|
729
|
+
.finally(() => { this.claudePending.delete(home.dir); }));
|
|
730
|
+
}
|
|
731
|
+
const pending = this.claudePending.get(home.dir);
|
|
732
|
+
const live = pending ? await pending : this.claudeCached.get(home.dir)?.value;
|
|
733
|
+
if (live?.windows.length)
|
|
734
|
+
return live;
|
|
764
735
|
}
|
|
765
|
-
|
|
766
|
-
if (live?.windows.length)
|
|
767
|
-
return live;
|
|
768
|
-
return this.snapshotClaude();
|
|
736
|
+
return this.snapshotClaude(home);
|
|
769
737
|
}
|
|
770
|
-
async snapshotClaude() {
|
|
738
|
+
async snapshotClaude(home) {
|
|
771
739
|
let claude = { source: "claude", windows: [], message: "Usage appears after Claude Code replies on this computer. Run phren bridge install if usage reporting is not set up yet." };
|
|
772
740
|
try {
|
|
773
|
-
const handle = await open(claudeFile(), "r");
|
|
741
|
+
const handle = await open(claudeFile(home), "r");
|
|
774
742
|
try {
|
|
775
743
|
const stat = await handle.stat();
|
|
776
744
|
if (!stat.isFile() || stat.size > 16_384)
|
|
@@ -787,7 +755,7 @@ export class AccountUsageReader {
|
|
|
787
755
|
}
|
|
788
756
|
catch { /* No status-line report yet. Keep unavailable explicit. */ }
|
|
789
757
|
try {
|
|
790
|
-
const handle = await open(
|
|
758
|
+
const handle = await open(home.configFile, "r");
|
|
791
759
|
try {
|
|
792
760
|
const stat = await handle.stat();
|
|
793
761
|
if (!stat.isFile() || stat.size > 16_777_216)
|
|
@@ -837,12 +805,17 @@ export async function captureClaudeUsage(original) {
|
|
|
837
805
|
return;
|
|
838
806
|
}
|
|
839
807
|
try {
|
|
808
|
+
// The home Claude runs in names the file; an unknown CLAUDE_CONFIG_DIR records nothing.
|
|
809
|
+
// Homes are resolved without this process's CLAUDE_CONFIG_DIR: that is the account's own dir here, not the default.
|
|
810
|
+
const home = claudeHomeOfEnv(process.env.CLAUDE_CONFIG_DIR, { ...process.env, CLAUDE_CONFIG_DIR: undefined });
|
|
811
|
+
if (!home)
|
|
812
|
+
throw new Error("Unknown Claude home");
|
|
840
813
|
const snapshot = claudeUsage(JSON.parse(input));
|
|
841
814
|
// Persist only normalized percentages/reset times; never session content.
|
|
842
815
|
const rate_limits = Object.fromEntries(snapshot.windows.map(w => [w.id, {
|
|
843
816
|
used_percentage: w.usedPercent, resets_at: w.resetsAt ? Date.parse(w.resetsAt) / 1000 : undefined,
|
|
844
817
|
}]));
|
|
845
|
-
await atomicInPrivateDir(claudeFile(), JSON.stringify({ rate_limits, updatedAt: snapshot.updatedAt }));
|
|
818
|
+
await atomicInPrivateDir(claudeFile(home), JSON.stringify({ rate_limits, updatedAt: snapshot.updatedAt }));
|
|
846
819
|
}
|
|
847
820
|
catch { /* Status line rendering must survive unavailable usage storage. */ }
|
|
848
821
|
const previous = object(JSON.parse(Buffer.from(original, "base64").toString()));
|