@phren/cli 0.2.14 → 0.2.16
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/README.md +2 -2
- package/dist/agent-instructions.d.ts +12 -0
- package/dist/agent-instructions.js +52 -0
- package/dist/bridge/agent-hook-stores.d.ts +32 -0
- package/dist/bridge/agent-hook-stores.js +67 -0
- package/dist/bridge/agent-hooks.d.ts +193 -2
- package/dist/bridge/agent-hooks.js +1045 -38
- package/dist/bridge/canary.d.ts +27 -0
- package/dist/bridge/canary.js +189 -0
- package/dist/bridge/changes.d.ts +57 -0
- package/dist/bridge/changes.js +403 -0
- package/dist/bridge/client.d.ts +3 -0
- package/dist/bridge/client.js +36 -0
- package/dist/bridge/code-note.d.ts +22 -0
- package/dist/bridge/code-note.js +42 -0
- package/dist/bridge/code-routes.d.ts +133 -0
- package/dist/bridge/code-routes.js +319 -0
- package/dist/bridge/codex-threads.d.ts +27 -0
- package/dist/bridge/codex-threads.js +442 -0
- package/dist/bridge/command.d.ts +7 -0
- package/dist/bridge/command.js +50 -5
- package/dist/bridge/computer-names.d.ts +4 -0
- package/dist/bridge/computer-names.js +16 -0
- package/dist/bridge/computers.d.ts +9 -0
- package/dist/bridge/computers.js +111 -0
- package/dist/bridge/context.d.ts +14 -0
- package/dist/bridge/context.js +149 -0
- package/dist/bridge/dispatch-command.d.ts +3 -0
- package/dist/bridge/dispatch-command.js +93 -0
- package/dist/bridge/dispatch-hosts.d.ts +23 -0
- package/dist/bridge/dispatch-hosts.js +25 -0
- package/dist/bridge/dispatch-returns.d.ts +123 -0
- package/dist/bridge/dispatch-returns.js +279 -0
- package/dist/bridge/dispatch-tree.d.ts +54 -0
- package/dist/bridge/dispatch-tree.js +198 -0
- package/dist/bridge/dispatch.d.ts +207 -0
- package/dist/bridge/dispatch.js +261 -0
- package/dist/bridge/enroll.d.ts +31 -0
- package/dist/bridge/enroll.js +236 -0
- package/dist/bridge/fanout-messages.d.ts +74 -0
- package/dist/bridge/fanout-messages.js +230 -0
- package/dist/bridge/fanouts.d.ts +160 -0
- package/dist/bridge/fanouts.js +702 -0
- package/dist/bridge/file-range.d.ts +16 -0
- package/dist/bridge/file-range.js +90 -0
- package/dist/bridge/files.d.ts +20 -0
- package/dist/bridge/files.js +54 -0
- package/dist/bridge/git-publish.d.ts +23 -0
- package/dist/bridge/git-publish.js +145 -0
- package/dist/bridge/git-worktrees.d.ts +21 -0
- package/dist/bridge/git-worktrees.js +150 -0
- package/dist/bridge/git.d.ts +54 -0
- package/dist/bridge/git.js +552 -0
- package/dist/bridge/grants.d.ts +31 -0
- package/dist/bridge/grants.js +181 -0
- package/dist/bridge/hand-off.d.ts +79 -0
- package/dist/bridge/hand-off.js +151 -0
- package/dist/bridge/health.d.ts +128 -0
- package/dist/bridge/health.js +260 -0
- package/dist/bridge/herdr.d.ts +79 -6
- package/dist/bridge/herdr.js +292 -27
- package/dist/bridge/hook-main.js +2 -0
- package/dist/bridge/install.d.ts +32 -1
- package/dist/bridge/install.js +225 -38
- package/dist/bridge/launch-worktree.d.ts +21 -0
- package/dist/bridge/launch-worktree.js +70 -0
- package/dist/bridge/limits.d.ts +20 -0
- package/dist/bridge/limits.js +65 -0
- package/dist/bridge/locate.d.ts +16 -0
- package/dist/bridge/locate.js +75 -0
- package/dist/bridge/metrics.d.ts +29 -0
- package/dist/bridge/metrics.js +71 -0
- package/dist/bridge/model-switch.d.ts +35 -0
- package/dist/bridge/model-switch.js +250 -0
- package/dist/bridge/models.d.ts +46 -0
- package/dist/bridge/models.js +257 -0
- package/dist/bridge/opencode-approvals.d.ts +6 -0
- package/dist/bridge/opencode-approvals.js +60 -0
- package/dist/bridge/pane-text.d.ts +15 -0
- package/dist/bridge/pane-text.js +23 -0
- package/dist/bridge/peers.d.ts +27 -0
- package/dist/bridge/peers.js +130 -0
- package/dist/bridge/projects.d.ts +12 -1
- package/dist/bridge/projects.js +268 -20
- package/dist/bridge/protocol.d.ts +35 -2
- package/dist/bridge/protocol.js +42 -7
- package/dist/bridge/push.d.ts +83 -0
- package/dist/bridge/push.js +199 -0
- package/dist/bridge/questions.d.ts +38 -0
- package/dist/bridge/questions.js +205 -0
- package/dist/bridge/schedule-format.d.ts +103 -0
- package/dist/bridge/schedule-format.js +266 -0
- package/dist/bridge/schedule-launch.d.ts +11 -0
- package/dist/bridge/schedule-launch.js +169 -0
- package/dist/bridge/schedule-watch.d.ts +52 -0
- package/dist/bridge/schedule-watch.js +242 -0
- package/dist/bridge/schedules.d.ts +48 -0
- package/dist/bridge/schedules.js +205 -0
- package/dist/bridge/server-launch.d.ts +14 -0
- package/dist/bridge/server-launch.js +218 -0
- package/dist/bridge/server-overview.d.ts +45 -0
- package/dist/bridge/server-overview.js +102 -0
- package/dist/bridge/server-pane-routes.d.ts +29 -0
- package/dist/bridge/server-pane-routes.js +400 -0
- package/dist/bridge/server-routes.d.ts +106 -0
- package/dist/bridge/server-routes.js +538 -0
- package/dist/bridge/server-stream.d.ts +46 -0
- package/dist/bridge/server-stream.js +253 -0
- package/dist/bridge/server.d.ts +3 -15
- package/dist/bridge/server.js +162 -264
- package/dist/bridge/session-servers.d.ts +24 -0
- package/dist/bridge/session-servers.js +136 -0
- package/dist/bridge/side-questions.d.ts +74 -0
- package/dist/bridge/side-questions.js +252 -0
- package/dist/bridge/simulators.d.ts +28 -0
- package/dist/bridge/simulators.js +198 -0
- package/dist/bridge/speech-transcribe.d.ts +24 -0
- package/dist/bridge/speech-transcribe.js +124 -0
- package/dist/bridge/speech.d.ts +35 -0
- package/dist/bridge/speech.js +98 -0
- package/dist/bridge/steps.d.ts +13 -0
- package/dist/bridge/steps.js +222 -0
- package/dist/bridge/tab-activity.d.ts +18 -0
- package/dist/bridge/tab-activity.js +99 -0
- package/dist/bridge/terminal-choice.d.ts +64 -0
- package/dist/bridge/terminal-choice.js +281 -0
- package/dist/bridge/transcript-claude.d.ts +22 -0
- package/dist/bridge/transcript-claude.js +353 -0
- package/dist/bridge/transcript-codex.d.ts +30 -0
- package/dist/bridge/transcript-codex.js +282 -0
- package/dist/bridge/transcript-copilot.d.ts +4 -0
- package/dist/bridge/transcript-copilot.js +14 -0
- package/dist/bridge/transcript-opencode.d.ts +5 -0
- package/dist/bridge/transcript-opencode.js +26 -0
- package/dist/bridge/transcript-preview.d.ts +94 -0
- package/dist/bridge/transcript-preview.js +476 -0
- package/dist/bridge/transcripts.d.ts +81 -4
- package/dist/bridge/transcripts.js +332 -67
- package/dist/bridge/transport.d.ts +3 -0
- package/dist/bridge/transport.js +96 -15
- package/dist/bridge/uploads.d.ts +15 -0
- package/dist/bridge/uploads.js +44 -2
- package/dist/bridge/usage.d.ts +124 -0
- package/dist/bridge/usage.js +859 -0
- package/dist/bridge-hook.mjs +41246 -21385
- package/dist/cli/actions.js +14 -1
- package/dist/cli/config-proactivity.d.ts +3 -1
- package/dist/cli/config-proactivity.js +35 -3
- package/dist/cli/config.js +4 -1
- package/dist/cli/extract.js +3 -6
- package/dist/cli/govern.js +5 -2
- package/dist/cli/hooks-globs.js +1 -1
- package/dist/cli/hooks.d.ts +1 -1
- package/dist/cli/hooks.js +9 -7
- package/dist/cli/namespaces-projects.js +12 -6
- package/dist/cli/namespaces-store.js +37 -6
- package/dist/cli/namespaces-tasks.js +1 -1
- package/dist/cli/schedules.d.ts +1 -0
- package/dist/cli/schedules.js +164 -0
- package/dist/cli/session-background.js +1 -1
- package/dist/cli/session-git.d.ts +8 -5
- package/dist/cli/session-git.js +45 -120
- package/dist/cli/session-start.js +3 -1
- package/dist/cli/session-stop.js +19 -8
- package/dist/cli/team.js +13 -10
- package/dist/cli-handlers.d.ts +1 -1
- package/dist/cli-handlers.js +8 -4
- package/dist/cli-help.d.ts +5 -4
- package/dist/cli-help.js +15 -15
- package/dist/cli-registry.d.ts +4 -1
- package/dist/cli-registry.js +119 -6
- package/dist/content/archive.js +2 -2
- package/dist/content/citation.d.ts +11 -0
- package/dist/content/citation.js +18 -0
- package/dist/content/learning.js +2 -0
- package/dist/content/summarize.d.ts +14 -15
- package/dist/content/summarize.js +60 -5
- package/dist/content/validate.d.ts +3 -1
- package/dist/content/validate.js +26 -8
- package/dist/core/project-registry.d.ts +26 -0
- package/dist/core/project-registry.js +573 -0
- package/dist/core/project.js +2 -3
- package/dist/data/access.d.ts +7 -1
- package/dist/data/access.js +13 -3
- package/dist/data/tasks.d.ts +18 -3
- package/dist/data/tasks.js +8 -7
- package/dist/entrypoint.js +44 -10
- package/dist/fanout/adapters/claude.d.ts +2 -0
- package/dist/fanout/adapters/claude.js +7 -0
- package/dist/fanout/adapters/codex.d.ts +2 -0
- package/dist/fanout/adapters/codex.js +9 -0
- package/dist/fanout/adapters/opencode.d.ts +4 -0
- package/dist/fanout/adapters/opencode.js +9 -0
- package/dist/fanout/adapters/types.d.ts +21 -0
- package/dist/fanout/adapters/types.js +3 -0
- package/dist/fanout/command.d.ts +2 -0
- package/dist/fanout/command.js +78 -0
- package/dist/fanout/launcher.d.ts +27 -0
- package/dist/fanout/launcher.js +156 -0
- package/dist/fanout/opencode-serve.d.ts +24 -0
- package/dist/fanout/opencode-serve.js +191 -0
- package/dist/fanout/picker.d.ts +91 -0
- package/dist/fanout/picker.js +51 -0
- package/dist/fanout/usage.d.ts +5 -0
- package/dist/fanout/usage.js +51 -0
- package/dist/fanout/watchdog.d.ts +10 -0
- package/dist/fanout/watchdog.js +27 -0
- package/dist/filenames.d.ts +9 -0
- package/dist/filenames.js +11 -0
- package/dist/finding/context.js +4 -22
- package/dist/generated/memory-ui-graph.browser.js +279 -283
- package/dist/governance/policy-constants.d.ts +11 -0
- package/dist/governance/policy-constants.js +9 -0
- package/dist/governance/policy.d.ts +5 -8
- package/dist/governance/policy.js +7 -5
- package/dist/graph-core/camera.d.ts +24 -0
- package/dist/graph-core/camera.js +18 -0
- package/dist/graph-core/index.d.ts +2 -0
- package/dist/graph-core/index.js +2 -0
- package/dist/graph-core/labels.d.ts +77 -0
- package/dist/graph-core/labels.js +124 -0
- package/dist/graph-core/model.d.ts +13 -0
- package/dist/graph-core/model.js +33 -0
- package/dist/graph-core/types.d.ts +2 -0
- package/dist/home-paths.d.ts +7 -0
- package/dist/home-paths.js +21 -0
- package/dist/hooks.d.ts +3 -0
- package/dist/hooks.js +13 -0
- package/dist/index.js +24 -2
- package/dist/init/guard-globals.d.ts +1 -1
- package/dist/init/guard-globals.js +4 -4
- package/dist/init/init-configure.js +3 -3
- package/dist/init/init-uninstall.js +2 -2
- package/dist/init/init-walkthrough.d.ts +2 -0
- package/dist/init/init-walkthrough.js +17 -6
- package/dist/init/init.js +26 -6
- package/dist/init/management-preset.d.ts +1 -1
- package/dist/init/management-preset.js +2 -2
- package/dist/init/preferences.js +1 -1
- package/dist/init/self-wiring.js +1 -1
- package/dist/init/setup.d.ts +3 -26
- package/dist/init/setup.js +49 -588
- package/dist/init/shared.js +2 -0
- package/dist/init/store-gitignore.d.ts +1 -1
- package/dist/init/store-gitignore.js +2 -0
- package/dist/init/teardown.d.ts +1 -1
- package/dist/init/teardown.js +2 -2
- package/dist/link/context.js +1 -1
- package/dist/link/doctor.d.ts +22 -1
- package/dist/link/doctor.js +100 -54
- package/dist/link/link.js +29 -61
- package/dist/link/refresh.js +2 -2
- package/dist/link/skills.js +26 -5
- package/dist/machine-identity.d.ts +3 -0
- package/dist/machine-identity.js +6 -0
- package/dist/mcp/profile.d.ts +2 -15
- package/dist/mcp/profile.js +64 -9
- package/dist/memory-ui-graph.runtime.js +279 -283
- package/dist/modules/code-package.d.ts +16 -0
- package/dist/modules/code-package.js +152 -0
- package/dist/modules/command.d.ts +2 -0
- package/dist/modules/command.js +67 -0
- package/dist/modules/config.d.ts +4 -0
- package/dist/modules/config.js +70 -0
- package/dist/modules/manifest.d.ts +41 -0
- package/dist/modules/manifest.js +1 -0
- package/dist/modules/provision.d.ts +3 -0
- package/dist/modules/provision.js +84 -0
- package/dist/modules/registry.d.ts +16 -0
- package/dist/modules/registry.js +250 -0
- package/dist/modules/runtime.d.ts +15 -0
- package/dist/modules/runtime.js +59 -0
- package/dist/package-metadata.js +10 -2
- package/dist/phren-dotenv.js +4 -2
- package/dist/phren-paths.d.ts +3 -2
- package/dist/phren-paths.js +4 -5
- package/dist/profile-store.js +4 -5
- package/dist/project-config.d.ts +19 -1
- package/dist/project-config.js +29 -3
- package/dist/project-topics.js +4 -4
- package/dist/provider-adapters.js +1 -4
- package/dist/query-correlation.js +6 -6
- package/dist/session/artifacts.js +5 -5
- package/dist/session/checkpoints.js +5 -0
- package/dist/session/utils.d.ts +2 -2
- package/dist/session/utils.js +6 -6
- package/dist/shared/content.d.ts +1 -1
- package/dist/shared/content.js +1 -1
- package/dist/shared/data-utils.js +1 -1
- package/dist/shared/fragment-graph.d.ts +1 -1
- package/dist/shared/fragment-graph.js +5 -5
- package/dist/shared/index.js +48 -7
- package/dist/shared/retrieval.d.ts +18 -1
- package/dist/shared/retrieval.js +100 -11
- package/dist/shared/search-fallback.js +4 -6
- package/dist/shared/sqljs.d.ts +2 -0
- package/dist/shared/sqljs.js +4 -2
- package/dist/shared.d.ts +0 -1
- package/dist/shared.js +0 -1
- package/dist/shell/input.d.ts +1 -5
- package/dist/shell/input.js +16 -10
- package/dist/shell/palette.d.ts +2 -2
- package/dist/shell/palette.js +3 -7
- package/dist/shell/render.d.ts +3 -1
- package/dist/shell/render.js +4 -4
- package/dist/shell/shell.js +4 -1
- package/dist/shell/types.d.ts +1 -0
- package/dist/shell/types.js +4 -0
- package/dist/shell/view.d.ts +0 -4
- package/dist/shell/view.js +19 -27
- package/dist/skill/registry.js +25 -17
- package/dist/skill/state.d.ts +3 -0
- package/dist/skill/state.js +13 -7
- package/dist/status.js +38 -17
- package/dist/store-registry.d.ts +44 -18
- package/dist/store-registry.js +169 -60
- package/dist/store-weight.d.ts +1 -6
- package/dist/store-weight.js +4 -2
- package/dist/sync/auth-doctor.d.ts +8 -0
- package/dist/sync/auth-doctor.js +27 -0
- package/dist/sync/auth.d.ts +27 -0
- package/dist/sync/auth.js +114 -0
- package/dist/sync/conflict-resolve.d.ts +9 -0
- package/dist/sync/conflict-resolve.js +146 -0
- package/dist/sync/git-state.d.ts +4 -0
- package/dist/sync/git-state.js +49 -0
- package/dist/sync/outcome.d.ts +34 -0
- package/dist/sync/outcome.js +57 -0
- package/dist/sync/pull.d.ts +15 -7
- package/dist/sync/pull.js +84 -35
- package/dist/sync/store-merge.d.ts +29 -0
- package/dist/sync/store-merge.js +137 -0
- package/dist/sync/task-merge.d.ts +22 -0
- package/dist/sync/task-merge.js +158 -0
- package/dist/task/github.js +1 -1
- package/dist/task/lifecycle.d.ts +5 -0
- package/dist/task/lifecycle.js +67 -23
- package/dist/terminal-text.d.ts +5 -0
- package/dist/terminal-text.js +11 -0
- package/dist/test-global-setup.js +7 -0
- package/dist/tool-registry.d.ts +1 -1
- package/dist/tool-registry.js +3 -1
- package/dist/tools/code.d.ts +3 -0
- package/dist/tools/code.js +178 -0
- package/dist/tools/config.js +5 -0
- package/dist/tools/data.js +14 -7
- package/dist/tools/dispatch.d.ts +2 -0
- package/dist/tools/dispatch.js +66 -0
- package/dist/tools/finding.js +43 -41
- package/dist/tools/ops.js +5 -2
- package/dist/tools/search.js +21 -8
- package/dist/tools/session.js +21 -22
- package/dist/tools/tasks.js +8 -2
- package/dist/tools/types.d.ts +2 -2
- package/dist/tools/types.js +2 -2
- package/dist/ui/assets.js +1 -1
- package/dist/ui/data.js +14 -15
- package/dist/ui/deep-void.d.ts +1 -1
- package/dist/ui/deep-void.js +0 -1
- package/dist/ui/graph-chrome.d.ts +1 -1
- package/dist/ui/graph-chrome.js +51 -0
- package/dist/ui/page.js +5 -5
- package/dist/ui/scripts.js +67 -30
- package/dist/ui/server.js +34 -6
- package/dist/update.js +1 -1
- package/dist/utils-fts.js +1 -0
- package/dist/utils-helpers.d.ts +7 -0
- package/dist/utils-helpers.js +17 -0
- package/dist/utils.d.ts +1 -1
- package/dist/utils.js +1 -1
- package/package.json +45 -3
- package/plugins/opencode/phren-transcript.js +340 -0
- package/starter/README.md +4 -4
- package/starter/global/{CLAUDE.md → AGENTS.md} +2 -2
- package/starter/global/skills/conductor/SKILL.md +106 -0
- package/starter/global/skills/fanout/SKILL.md +20 -0
- package/starter/global/skills/phren-discover/SKILL.md +6 -6
- package/starter/global/skills/phren-init/SKILL.md +4 -4
- package/starter/global/skills/phren-sync/SKILL.md +3 -3
- package/starter/templates/frontend/reference/README.md +1 -1
- package/starter/templates/library/reference/README.md +1 -1
- package/starter/templates/monorepo/reference/README.md +1 -1
- package/starter/templates/python-project/reference/README.md +1 -1
- /package/starter/templates/frontend/{CLAUDE.md → AGENTS.md} +0 -0
- /package/starter/templates/library/{CLAUDE.md → AGENTS.md} +0 -0
- /package/starter/templates/monorepo/{CLAUDE.md → AGENTS.md} +0 -0
- /package/starter/templates/python-project/{CLAUDE.md → AGENTS.md} +0 -0
|
@@ -0,0 +1,859 @@
|
|
|
1
|
+
import { execFile, spawn } from "node:child_process";
|
|
2
|
+
import { createHash } from "node:crypto";
|
|
3
|
+
import { lstat, open, readFile, readdir, realpath, stat } from "node:fs/promises";
|
|
4
|
+
import { homedir } from "node:os";
|
|
5
|
+
import { claudeConfigDir, homeDir } from "../home-paths.js";
|
|
6
|
+
import path from "node:path";
|
|
7
|
+
import { promisify } from "node:util";
|
|
8
|
+
import { fanoutRoot } from "./fanouts.js";
|
|
9
|
+
import { atomicInPrivateDir, bridgeRoot, object } from "./protocol.js";
|
|
10
|
+
import { stripTerminal } from "../terminal-text.js";
|
|
11
|
+
const exec = promisify(execFile);
|
|
12
|
+
const claudeFile = () => path.join(bridgeRoot(), "usage", "claude.json");
|
|
13
|
+
const safeText = (v) => typeof v === "string" ? v.replace(/[\x00-\x1f\x7f]/g, "").slice(0, 100) : undefined;
|
|
14
|
+
function window(id, name, percent, reset) {
|
|
15
|
+
if (typeof percent !== "number" || !Number.isFinite(percent) || percent < 0 || percent > 100)
|
|
16
|
+
return;
|
|
17
|
+
const resetsAt = typeof reset === "number" && Number.isSafeInteger(reset) && reset > 0 && reset < 32_503_680_000
|
|
18
|
+
? new Date(reset * 1000).toISOString() : undefined;
|
|
19
|
+
return { id, name, usedPercent: percent, resetsAt };
|
|
20
|
+
}
|
|
21
|
+
function duration(value, fallback) {
|
|
22
|
+
if (typeof value !== "number" || !Number.isSafeInteger(value) || value <= 0 || value > 525600)
|
|
23
|
+
return fallback;
|
|
24
|
+
return value % 1440 === 0 ? `${value / 1440}-day limit` : value % 60 === 0 ? `${value / 60}-hour limit` : `${value}-minute limit`;
|
|
25
|
+
}
|
|
26
|
+
export function codexUsage(value, now = new Date()) {
|
|
27
|
+
const result = object(value), multiple = object(result.rateLimitsByLimitId);
|
|
28
|
+
const buckets = Object.keys(multiple).length
|
|
29
|
+
? Object.entries(multiple).sort(([a], [b]) => a === "codex" ? -1 : b === "codex" ? 1 : a.localeCompare(b)).slice(0, 16)
|
|
30
|
+
: [["codex", result.rateLimits]];
|
|
31
|
+
const windows = [];
|
|
32
|
+
for (const [key, raw] of buckets) {
|
|
33
|
+
const bucket = object(raw), name = safeText(bucket.limitName);
|
|
34
|
+
// Spark is a separate, lightweight lane nobody budgets by; leave it out.
|
|
35
|
+
if (/spark/i.test(String(key)) || /spark/i.test(name ?? ""))
|
|
36
|
+
continue;
|
|
37
|
+
for (const field of ["primary", "secondary"]) {
|
|
38
|
+
const item = object(bucket[field]);
|
|
39
|
+
const label = duration(item.windowDurationMins, field === "primary" ? "Primary limit" : "Secondary limit");
|
|
40
|
+
const entry = window(`${safeText(key)}:${field}`, name ? `${name} · ${label}` : label, item.usedPercent, item.resetsAt);
|
|
41
|
+
if (entry)
|
|
42
|
+
windows.push(entry);
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
return { source: "codex", windows, updatedAt: now.toISOString(),
|
|
46
|
+
...(!windows.length ? { message: "Codex has not reported account limits. Sign in with your ChatGPT account in Codex on this computer." } : {}) };
|
|
47
|
+
}
|
|
48
|
+
/** Parse OpenCode's own cost ledger. `stats --days 7` is a rolling local view. */
|
|
49
|
+
export function openCodeUsage(output, now = new Date()) {
|
|
50
|
+
const plain = stripTerminal(output);
|
|
51
|
+
const match = /Total Cost\s+\$([0-9][0-9,]*(?:\.[0-9]+)?)/i.exec(plain);
|
|
52
|
+
const amountUSD = match ? Number(match[1].replace(/,/g, "")) : Number.NaN;
|
|
53
|
+
if (!Number.isFinite(amountUSD) || amountUSD < 0 || amountUSD > 1_000_000_000) {
|
|
54
|
+
return { source: "opencode", windows: [], message: "Could not read OpenCode's seven-day cost. Run opencode stats --days 7 on this computer." };
|
|
55
|
+
}
|
|
56
|
+
return { source: "opencode", windows: [], spend: { amountUSD, period: "rolling_7_days" }, updatedAt: now.toISOString() };
|
|
57
|
+
}
|
|
58
|
+
/** Read the authoritative cost that OpenCode records for its local sessions. */
|
|
59
|
+
export async function readOpenCodeUsage(executable = "opencode", now = new Date()) {
|
|
60
|
+
try {
|
|
61
|
+
const { stdout } = await exec(executable, ["stats", "--days", "7", "--pure"], { timeout: 12_000, maxBuffer: 1_048_576 });
|
|
62
|
+
return openCodeUsage(stdout, now);
|
|
63
|
+
}
|
|
64
|
+
catch (error) {
|
|
65
|
+
return { source: "opencode", windows: [], message: openCodeFailure(error) };
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
/** Not installed, not signed in and a failing command each say so, with the command's own first line. */
|
|
69
|
+
export function openCodeFailure(error) {
|
|
70
|
+
const failure = error;
|
|
71
|
+
if (failure?.code === "ENOENT")
|
|
72
|
+
return "OpenCode is not installed on this computer (opencode was not found on PATH).";
|
|
73
|
+
const said = stripTerminal(String(failure?.stderr ?? "")).split(/\r?\n/)
|
|
74
|
+
.map(line => line.replace(/[\x00-\x1f\x7f]/g, " ").trim()).find(Boolean)?.slice(0, 200);
|
|
75
|
+
if (/not (logged|signed) in|no (credentials|providers?)|unauthori[sz]ed|opencode auth login/i.test(said ?? ""))
|
|
76
|
+
return `OpenCode is not signed in on this computer. Run opencode auth login. (${said})`;
|
|
77
|
+
if (failure?.killed || failure?.signal)
|
|
78
|
+
return "opencode stats --days 7 timed out on this computer.";
|
|
79
|
+
const exit = typeof failure?.code === "number" ? ` (exit ${failure.code})` : "";
|
|
80
|
+
return `opencode stats --days 7 failed${exit}${said ? `: ${said}` : ""}. Run it on this computer to see why.`;
|
|
81
|
+
}
|
|
82
|
+
const openCodeAuthFile = () => path.join(process.env.OPENCODE_DATA_DIR || path.join(process.env.XDG_DATA_HOME || path.join(homedir(), ".local", "share"), "opencode"), "auth.json");
|
|
83
|
+
/** OpenCode's OpenRouter key stays local and is used only with OpenRouter. */
|
|
84
|
+
export async function readOpenRouterKey() {
|
|
85
|
+
try {
|
|
86
|
+
const handle = await open(openCodeAuthFile(), "r");
|
|
87
|
+
try {
|
|
88
|
+
const stat = await handle.stat();
|
|
89
|
+
if (!stat.isFile() || stat.size > 65_536)
|
|
90
|
+
return undefined;
|
|
91
|
+
const key = object(object(JSON.parse(await handle.readFile("utf8"))).openrouter).key;
|
|
92
|
+
return typeof key === "string" && key.length >= 16 && key.length <= 4_096 && !/[\x00-\x1f\x7f]/.test(key) ? key : undefined;
|
|
93
|
+
}
|
|
94
|
+
finally {
|
|
95
|
+
await handle.close();
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
catch {
|
|
99
|
+
return undefined;
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
/** OpenCode Go's key stays local and is sent only to the Go gateway. */
|
|
103
|
+
export async function readOpenCodeGoKey() {
|
|
104
|
+
try {
|
|
105
|
+
const handle = await open(openCodeAuthFile(), "r");
|
|
106
|
+
try {
|
|
107
|
+
const metadata = await handle.stat();
|
|
108
|
+
if (!metadata.isFile() || metadata.size > 65_536)
|
|
109
|
+
return undefined;
|
|
110
|
+
const key = object(object(JSON.parse(await handle.readFile("utf8")))["opencode-go"]).key;
|
|
111
|
+
return typeof key === "string" && key.length >= 16 && key.length <= 4_096 && !/[\x00-\x1f\x7f]/.test(key) ? key : undefined;
|
|
112
|
+
}
|
|
113
|
+
finally {
|
|
114
|
+
await handle.close();
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
catch {
|
|
118
|
+
return undefined;
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
const goPeriods = [
|
|
122
|
+
{ id: "5h", label: "5h", milliseconds: 5 * 60 * 60 * 1_000 },
|
|
123
|
+
{ id: "7d", label: "7d", milliseconds: 7 * 24 * 60 * 60 * 1_000 },
|
|
124
|
+
{ id: "30d", label: "30d", milliseconds: 30 * 24 * 60 * 60 * 1_000 },
|
|
125
|
+
];
|
|
126
|
+
const GO_GATEWAY = "https://opencode.ai/zen/go/v1";
|
|
127
|
+
const MAX_GO_JOBS = 128;
|
|
128
|
+
const MAX_GO_MANIFEST_BYTES = 64 * 1_024;
|
|
129
|
+
const MAX_GO_EVENTS_BYTES = 64 * 1_024 * 1_024;
|
|
130
|
+
const GO_KEY_MESSAGE = "Connect OpenCode Go on this computer to see its usage.";
|
|
131
|
+
function goPeriod(value) {
|
|
132
|
+
const text = String(value ?? "").toLowerCase().replace(/[\s_-]/g, "");
|
|
133
|
+
if (text === "5h" || text === "5hour" || text === "fivehour" || text === "300m" || text === "300minute")
|
|
134
|
+
return "5h";
|
|
135
|
+
if (text === "7d" || text === "7day" || text === "week" || text === "weekly")
|
|
136
|
+
return "7d";
|
|
137
|
+
if (text === "30d" || text === "30day" || text === "month" || text === "monthly")
|
|
138
|
+
return "30d";
|
|
139
|
+
return undefined;
|
|
140
|
+
}
|
|
141
|
+
function goModel(value, allowBare = false) {
|
|
142
|
+
if (typeof value !== "string")
|
|
143
|
+
return undefined;
|
|
144
|
+
const model = value.trim();
|
|
145
|
+
if (/^opencode-go\/[A-Za-z0-9][A-Za-z0-9._/-]{0,190}$/.test(model))
|
|
146
|
+
return model;
|
|
147
|
+
const reserved = new Set(["data", "limits", "usage", "models", "credits", "window", "period", "monthly", "weekly",
|
|
148
|
+
"5h", "7d", "30d", "fivehour", "seven_day", "month", "limit", "quota", "max", "plan", "account", "rate", "ratelimit",
|
|
149
|
+
"ratelimits", "remaining", "reset"]);
|
|
150
|
+
return allowBare && /^[A-Za-z0-9][A-Za-z0-9._/-]{0,190}$/.test(model) && !reserved.has(model.toLowerCase())
|
|
151
|
+
? `opencode-go/${model}` : undefined;
|
|
152
|
+
}
|
|
153
|
+
function amount(value) {
|
|
154
|
+
return typeof value === "number" && Number.isFinite(value) && value >= 0 && value <= 1_000_000_000 ? value : undefined;
|
|
155
|
+
}
|
|
156
|
+
function resetAt(value) {
|
|
157
|
+
if (typeof value === "string" && Number.isFinite(Date.parse(value)))
|
|
158
|
+
return new Date(value).toISOString();
|
|
159
|
+
if (typeof value === "string" && /^\d+(?:\.\d+)?$/.test(value))
|
|
160
|
+
return resetAt(Number(value));
|
|
161
|
+
if (typeof value === "number" && Number.isFinite(value) && value > 0 && value < 32_503_680_000) {
|
|
162
|
+
return new Date(value * 1_000).toISOString();
|
|
163
|
+
}
|
|
164
|
+
return undefined;
|
|
165
|
+
}
|
|
166
|
+
function recordGoLimit(limits, model, period, limitUSD, resetsAt) {
|
|
167
|
+
if (limitUSD === undefined || limitUSD <= 0)
|
|
168
|
+
return;
|
|
169
|
+
const current = limits.get(model) ?? {};
|
|
170
|
+
const existing = current[period];
|
|
171
|
+
// A response can repeat a limit at several levels. Keep the first numeric
|
|
172
|
+
// value, but retain a reset time wherever the service supplied one.
|
|
173
|
+
current[period] = existing ? { ...existing, ...(existing.resetsAt ? {} : { resetsAt }) } : { limitUSD, resetsAt };
|
|
174
|
+
limits.set(model, current);
|
|
175
|
+
}
|
|
176
|
+
function numberFrom(value, names) {
|
|
177
|
+
for (const name of names) {
|
|
178
|
+
const found = amount(value[name]);
|
|
179
|
+
if (found !== undefined)
|
|
180
|
+
return found;
|
|
181
|
+
}
|
|
182
|
+
return undefined;
|
|
183
|
+
}
|
|
184
|
+
function parseGoLimits(value, limits, model, period, depth = 0) {
|
|
185
|
+
if (depth > 8)
|
|
186
|
+
return;
|
|
187
|
+
if (typeof value === "number") {
|
|
188
|
+
if (period)
|
|
189
|
+
recordGoLimit(limits, model ?? "*", period, amount(value));
|
|
190
|
+
return;
|
|
191
|
+
}
|
|
192
|
+
if (Array.isArray(value)) {
|
|
193
|
+
for (const item of value.slice(0, 64))
|
|
194
|
+
parseGoLimits(item, limits, model, period, depth + 1);
|
|
195
|
+
return;
|
|
196
|
+
}
|
|
197
|
+
const item = object(value);
|
|
198
|
+
if (!Object.keys(item).length)
|
|
199
|
+
return;
|
|
200
|
+
const nestedModel = goModel(item.model, true) ?? goModel(item.modelId, true) ?? goModel(item.model_id, true) ?? model;
|
|
201
|
+
const nestedPeriod = goPeriod(item.window) ?? goPeriod(item.period) ?? goPeriod(item.interval) ?? goPeriod(item.windowName) ?? period;
|
|
202
|
+
const limitUSD = numberFrom(item, ["limitUSD", "limit_usd", "dollarLimit", "dollar_limit", "creditLimit", "credit_limit", "limit", "quota", "max"]);
|
|
203
|
+
const reset = resetAt(item.resetsAt) ?? resetAt(item.resets_at) ?? resetAt(item.resetAt) ?? resetAt(item.reset_at);
|
|
204
|
+
if (nestedPeriod)
|
|
205
|
+
recordGoLimit(limits, nestedModel ?? "*", nestedPeriod, limitUSD, reset);
|
|
206
|
+
for (const [key, nested] of Object.entries(item).slice(0, 64)) {
|
|
207
|
+
const keyPeriod = goPeriod(key) ?? nestedPeriod;
|
|
208
|
+
const keyModel = goModel(key) ?? nestedModel ?? (typeof nested === "object" && !keyPeriod ? goModel(key, true) : undefined);
|
|
209
|
+
// Scalar metadata such as a plan name cannot carry a usable limit.
|
|
210
|
+
if (typeof nested !== "object" && typeof nested !== "number")
|
|
211
|
+
continue;
|
|
212
|
+
parseGoLimits(nested, limits, keyModel, keyPeriod, depth + 1);
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
function completeGoLimits(limits) {
|
|
216
|
+
for (const [model, windows] of limits) {
|
|
217
|
+
const monthly = windows["30d"]?.limitUSD ?? (windows["7d"] ? windows["7d"].limitUSD * 2 : windows["5h"] ? windows["5h"].limitUSD * 5 : undefined);
|
|
218
|
+
if (!monthly || !Number.isFinite(monthly) || monthly <= 0)
|
|
219
|
+
continue;
|
|
220
|
+
recordGoLimit(limits, model, "5h", monthly * 0.2);
|
|
221
|
+
recordGoLimit(limits, model, "7d", monthly * 0.5);
|
|
222
|
+
recordGoLimit(limits, model, "30d", monthly);
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
function header(response, name) {
|
|
226
|
+
try {
|
|
227
|
+
return response.headers.get(name) ?? undefined;
|
|
228
|
+
}
|
|
229
|
+
catch {
|
|
230
|
+
return undefined;
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
function parseGoHeaders(response, limits) {
|
|
234
|
+
const limit = amount(Number(header(response, "x-ratelimit-limit")));
|
|
235
|
+
const remaining = amount(Number(header(response, "x-ratelimit-remaining")));
|
|
236
|
+
if (limit === undefined || remaining === undefined || remaining > limit)
|
|
237
|
+
return;
|
|
238
|
+
const period = goPeriod(header(response, "x-ratelimit-window"));
|
|
239
|
+
const reset = resetAt(header(response, "x-ratelimit-reset"));
|
|
240
|
+
// Gateway headers do not identify a model. Their plan-wide limit is the
|
|
241
|
+
// monthly amount unless the response explicitly names its window.
|
|
242
|
+
recordGoLimit(limits, "*", period ?? "30d", limit, reset);
|
|
243
|
+
}
|
|
244
|
+
/** Best-effort gateway discovery. All four requests are independent because
|
|
245
|
+
* undocumented routes vary by OpenCode release and account. */
|
|
246
|
+
export async function fetchOpenCodeGoLimits(key, fetchImpl = fetch) {
|
|
247
|
+
const controller = new AbortController();
|
|
248
|
+
const timer = setTimeout(() => controller.abort(), 8_000);
|
|
249
|
+
const limits = new Map();
|
|
250
|
+
try {
|
|
251
|
+
const responses = await Promise.allSettled([
|
|
252
|
+
["GET", `${GO_GATEWAY}/usage`],
|
|
253
|
+
["GET", `${GO_GATEWAY}/limits`],
|
|
254
|
+
["GET", `${GO_GATEWAY}/credits`],
|
|
255
|
+
["HEAD", `${GO_GATEWAY}/models`],
|
|
256
|
+
].map(async ([method, url]) => {
|
|
257
|
+
const response = await fetchImpl(url, { method, headers: { authorization: `Bearer ${key}`, accept: "application/json" },
|
|
258
|
+
redirect: "error", signal: controller.signal });
|
|
259
|
+
if (!response.ok)
|
|
260
|
+
return;
|
|
261
|
+
parseGoHeaders(response, limits);
|
|
262
|
+
if (method === "GET") {
|
|
263
|
+
try {
|
|
264
|
+
parseGoLimits(await response.json(), limits);
|
|
265
|
+
}
|
|
266
|
+
catch { /* An HTML or empty gateway response has no limits. */ }
|
|
267
|
+
}
|
|
268
|
+
}));
|
|
269
|
+
// Keep every request observed: one undocumented endpoint failing must not
|
|
270
|
+
// prevent headers or a second endpoint from describing the account.
|
|
271
|
+
void responses;
|
|
272
|
+
}
|
|
273
|
+
finally {
|
|
274
|
+
clearTimeout(timer);
|
|
275
|
+
}
|
|
276
|
+
completeGoLimits(limits);
|
|
277
|
+
return limits;
|
|
278
|
+
}
|
|
279
|
+
async function containedRegularFile(root, candidate, maximum) {
|
|
280
|
+
try {
|
|
281
|
+
const link = await lstat(candidate);
|
|
282
|
+
if (!link.isFile() || link.isSymbolicLink() || link.size > maximum)
|
|
283
|
+
return undefined;
|
|
284
|
+
const resolved = await realpath(candidate);
|
|
285
|
+
if (!resolved.startsWith(root + path.sep))
|
|
286
|
+
return undefined;
|
|
287
|
+
const metadata = await stat(resolved);
|
|
288
|
+
return metadata.isFile() && metadata.size <= maximum ? resolved : undefined;
|
|
289
|
+
}
|
|
290
|
+
catch {
|
|
291
|
+
return undefined;
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
function goEventTime(value) {
|
|
295
|
+
const raw = value.timestamp ?? value.time ?? value.createdAt ?? value.created_at;
|
|
296
|
+
if (typeof raw === "string" && Number.isFinite(Date.parse(raw)))
|
|
297
|
+
return Date.parse(raw);
|
|
298
|
+
if (typeof raw !== "number" || !Number.isFinite(raw) || raw <= 0)
|
|
299
|
+
return undefined;
|
|
300
|
+
return raw < 32_503_680_000 ? raw * 1_000 : raw;
|
|
301
|
+
}
|
|
302
|
+
function goTokenCount(value, depth = 0) {
|
|
303
|
+
if (depth > 5)
|
|
304
|
+
return 0;
|
|
305
|
+
if (typeof value === "number")
|
|
306
|
+
return Number.isFinite(value) && value >= 0 && value <= 10_000_000_000 ? value : 0;
|
|
307
|
+
const item = object(value);
|
|
308
|
+
const total = amount(item.total) ?? amount(item.totalTokens) ?? amount(item.total_tokens);
|
|
309
|
+
if (total !== undefined)
|
|
310
|
+
return total;
|
|
311
|
+
return Object.values(item).reduce((sum, part) => sum + goTokenCount(part, depth + 1), 0);
|
|
312
|
+
}
|
|
313
|
+
function goStepCost(event, part) {
|
|
314
|
+
const raw = part.cost ?? event.cost;
|
|
315
|
+
if (typeof raw === "number")
|
|
316
|
+
return amount(raw);
|
|
317
|
+
const cost = object(raw);
|
|
318
|
+
return numberFrom(cost, ["total", "amount", "usd", "cost"]);
|
|
319
|
+
}
|
|
320
|
+
/** Sum only completed OpenCode Go fan-outs. Their ledger stays on the
|
|
321
|
+
* computer and malformed jobs are ignored rather than becoming usage. */
|
|
322
|
+
export async function readOpenCodeGoLedger(root = fanoutRoot(), now = new Date()) {
|
|
323
|
+
const totals = new Map();
|
|
324
|
+
let directory;
|
|
325
|
+
try {
|
|
326
|
+
directory = await realpath(root);
|
|
327
|
+
}
|
|
328
|
+
catch {
|
|
329
|
+
return totals;
|
|
330
|
+
}
|
|
331
|
+
const names = (await readdir(directory).catch(() => [])).slice(0, MAX_GO_JOBS);
|
|
332
|
+
for (const name of names) {
|
|
333
|
+
if (!/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(name))
|
|
334
|
+
continue;
|
|
335
|
+
const manifestFile = await containedRegularFile(directory, path.join(directory, name, "manifest.json"), MAX_GO_MANIFEST_BYTES);
|
|
336
|
+
if (!manifestFile)
|
|
337
|
+
continue;
|
|
338
|
+
let manifest;
|
|
339
|
+
try {
|
|
340
|
+
manifest = object(JSON.parse(await readFile(manifestFile, "utf8")));
|
|
341
|
+
}
|
|
342
|
+
catch {
|
|
343
|
+
continue;
|
|
344
|
+
}
|
|
345
|
+
const model = goModel(manifest.model);
|
|
346
|
+
const eventLog = typeof manifest.eventLog === "string" && /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}\.jsonl$/.test(manifest.eventLog)
|
|
347
|
+
? manifest.eventLog : undefined;
|
|
348
|
+
if (manifest.provider !== "opencode" || !model || !eventLog)
|
|
349
|
+
continue;
|
|
350
|
+
const jobRoot = await realpath(path.join(directory, name)).catch(() => undefined);
|
|
351
|
+
if (!jobRoot || !jobRoot.startsWith(directory + path.sep))
|
|
352
|
+
continue;
|
|
353
|
+
const eventsFile = await containedRegularFile(jobRoot, path.join(jobRoot, eventLog), MAX_GO_EVENTS_BYTES);
|
|
354
|
+
if (!eventsFile)
|
|
355
|
+
continue;
|
|
356
|
+
let events;
|
|
357
|
+
try {
|
|
358
|
+
events = await readFile(eventsFile, "utf8");
|
|
359
|
+
}
|
|
360
|
+
catch {
|
|
361
|
+
continue;
|
|
362
|
+
}
|
|
363
|
+
for (const line of events.split("\n")) {
|
|
364
|
+
if (!line || Buffer.byteLength(line) > 1_048_576)
|
|
365
|
+
continue;
|
|
366
|
+
let event;
|
|
367
|
+
try {
|
|
368
|
+
event = object(JSON.parse(line));
|
|
369
|
+
}
|
|
370
|
+
catch {
|
|
371
|
+
continue;
|
|
372
|
+
}
|
|
373
|
+
if (event.type !== "step_finish")
|
|
374
|
+
continue;
|
|
375
|
+
const at = goEventTime(event), part = object(event.part);
|
|
376
|
+
const cost = goStepCost(event, part), tokens = goTokenCount(part.tokens ?? event.tokens);
|
|
377
|
+
if (at === undefined || (cost === undefined && tokens === 0) || at > now.getTime())
|
|
378
|
+
continue;
|
|
379
|
+
for (const period of goPeriods) {
|
|
380
|
+
if (at < now.getTime() - period.milliseconds)
|
|
381
|
+
continue;
|
|
382
|
+
const modelTotals = totals.get(model) ?? {
|
|
383
|
+
"5h": { usedUSD: 0, usedTokens: 0 }, "7d": { usedUSD: 0, usedTokens: 0 }, "30d": { usedUSD: 0, usedTokens: 0 },
|
|
384
|
+
};
|
|
385
|
+
const usedUSD = modelTotals[period.id].usedUSD + (cost ?? 0);
|
|
386
|
+
if (usedUSD > 1_000_000_000)
|
|
387
|
+
continue;
|
|
388
|
+
modelTotals[period.id].usedUSD = usedUSD;
|
|
389
|
+
modelTotals[period.id].usedTokens += tokens;
|
|
390
|
+
totals.set(model, modelTotals);
|
|
391
|
+
}
|
|
392
|
+
}
|
|
393
|
+
}
|
|
394
|
+
return totals;
|
|
395
|
+
}
|
|
396
|
+
function goLimitFor(limits, model, period) {
|
|
397
|
+
return limits.get(model)?.[period] ?? limits.get("*")?.[period];
|
|
398
|
+
}
|
|
399
|
+
function goWindowID(model, period) {
|
|
400
|
+
return `opencode-go:${model.slice("opencode-go/".length).replace(/[^A-Za-z0-9]+/g, "_").replace(/^_|_$/g, "")}:${period}`;
|
|
401
|
+
}
|
|
402
|
+
function openCodeGoUsage(totals, limits, now, hasKey) {
|
|
403
|
+
const windows = [];
|
|
404
|
+
let total30Days = 0;
|
|
405
|
+
for (const model of [...totals.keys()].sort((a, b) => a.localeCompare(b))) {
|
|
406
|
+
const modelTotals = totals.get(model);
|
|
407
|
+
for (const period of goPeriods) {
|
|
408
|
+
const local = modelTotals[period.id], limit = goLimitFor(limits, model, period.id);
|
|
409
|
+
const usedPercent = limit ? Math.min(100, Math.round(local.usedUSD / limit.limitUSD * 10_000) / 100) : undefined;
|
|
410
|
+
windows.push({ id: goWindowID(model, period.id), name: `${model} · ${period.label}`, usedUSD: local.usedUSD,
|
|
411
|
+
usedTokens: local.usedTokens, ...(limit ? { limitUSD: limit.limitUSD, usedPercent, resetsAt: limit.resetsAt } : {}) });
|
|
412
|
+
}
|
|
413
|
+
total30Days += modelTotals["30d"].usedUSD;
|
|
414
|
+
}
|
|
415
|
+
return { source: "opencode-go", windows, updatedAt: now.toISOString(),
|
|
416
|
+
...(windows.length ? { spend: { amountUSD: total30Days, period: "rolling_30_days" } } : {}),
|
|
417
|
+
...(!hasKey ? { message: GO_KEY_MESSAGE } : {}) };
|
|
418
|
+
}
|
|
419
|
+
let goDiscoveryCached;
|
|
420
|
+
let goDiscoveryPending;
|
|
421
|
+
async function cachedOpenCodeGoLimits(key, now) {
|
|
422
|
+
if (!goDiscoveryCached || now.getTime() - goDiscoveryCached.at >= 10 * 60_000) {
|
|
423
|
+
goDiscoveryPending ??= fetchOpenCodeGoLimits(key).catch(() => new Map())
|
|
424
|
+
.then(limits => { goDiscoveryCached = { at: now.getTime(), limits }; return limits; })
|
|
425
|
+
.finally(() => { goDiscoveryPending = undefined; });
|
|
426
|
+
}
|
|
427
|
+
return goDiscoveryPending ? await goDiscoveryPending : goDiscoveryCached?.limits ?? new Map();
|
|
428
|
+
}
|
|
429
|
+
export async function readOpenCodeGoUsage(now = new Date(), options = {}) {
|
|
430
|
+
const [totals, key] = await Promise.all([readOpenCodeGoLedger(options.root, now), (options.readKey ?? readOpenCodeGoKey)()]);
|
|
431
|
+
if (!key)
|
|
432
|
+
return openCodeGoUsage(totals, new Map(), now, false);
|
|
433
|
+
let limits = new Map();
|
|
434
|
+
try {
|
|
435
|
+
limits = options.fetchImpl ? await fetchOpenCodeGoLimits(key, options.fetchImpl) : await cachedOpenCodeGoLimits(key, now);
|
|
436
|
+
}
|
|
437
|
+
catch { /* Gateway discovery is optional; local accounting is still useful. */ }
|
|
438
|
+
return openCodeGoUsage(totals, limits, now, true);
|
|
439
|
+
}
|
|
440
|
+
/** OpenRouter reports the current UTC calendar week's charged usage per key. */
|
|
441
|
+
export async function fetchOpenRouterUsage(key, fetchImpl = fetch, now = new Date()) {
|
|
442
|
+
const controller = new AbortController();
|
|
443
|
+
const timer = setTimeout(() => controller.abort(), 8_000);
|
|
444
|
+
try {
|
|
445
|
+
const response = await fetchImpl("https://openrouter.ai/api/v1/key", {
|
|
446
|
+
headers: { authorization: `Bearer ${key}`, accept: "application/json" },
|
|
447
|
+
redirect: "error",
|
|
448
|
+
signal: controller.signal,
|
|
449
|
+
});
|
|
450
|
+
if (!response.ok)
|
|
451
|
+
throw new Error(`OpenRouter usage endpoint returned ${response.status}.`);
|
|
452
|
+
const amountUSD = object(object(await response.json()).data).usage_weekly;
|
|
453
|
+
if (typeof amountUSD !== "number" || !Number.isFinite(amountUSD) || amountUSD < 0 || amountUSD > 1_000_000_000) {
|
|
454
|
+
throw new Error("OpenRouter returned invalid usage.");
|
|
455
|
+
}
|
|
456
|
+
return {
|
|
457
|
+
source: "openrouter",
|
|
458
|
+
accountId: createHash("sha256").update(key).digest("hex"),
|
|
459
|
+
windows: [],
|
|
460
|
+
spend: { amountUSD, period: "calendar_week" },
|
|
461
|
+
updatedAt: now.toISOString(),
|
|
462
|
+
};
|
|
463
|
+
}
|
|
464
|
+
finally {
|
|
465
|
+
clearTimeout(timer);
|
|
466
|
+
}
|
|
467
|
+
}
|
|
468
|
+
async function liveOpenRouterUsage(now) {
|
|
469
|
+
if (typeof fetch !== "function")
|
|
470
|
+
return undefined;
|
|
471
|
+
const key = await readOpenRouterKey();
|
|
472
|
+
if (!key)
|
|
473
|
+
return undefined;
|
|
474
|
+
try {
|
|
475
|
+
return await fetchOpenRouterUsage(key, fetch, now);
|
|
476
|
+
}
|
|
477
|
+
catch {
|
|
478
|
+
return { source: "openrouter", windows: [], message: "Could not read OpenRouter spend. Check its key in OpenCode." };
|
|
479
|
+
}
|
|
480
|
+
}
|
|
481
|
+
/** "seven_day_fable" → "7-day, Fable"; weekly-all stays explicit. */
|
|
482
|
+
function claudeWindowName(key) {
|
|
483
|
+
const spans = [["five_hour", "5-hour"], ["seven_day", "7-day"], ["one_hour", "1-hour"], ["one_day", "1-day"]];
|
|
484
|
+
for (const [prefix, label] of spans) {
|
|
485
|
+
if (key === prefix)
|
|
486
|
+
return key === "seven_day" ? "7-day, all models" : `${label} limit`;
|
|
487
|
+
if (key.startsWith(prefix + "_")) {
|
|
488
|
+
const model = key.slice(prefix.length + 1).split("_").filter(Boolean)
|
|
489
|
+
.map(part => part.charAt(0).toUpperCase() + part.slice(1)).join(" ");
|
|
490
|
+
return `${label}, ${model}`;
|
|
491
|
+
}
|
|
492
|
+
}
|
|
493
|
+
return key.split("_").filter(Boolean).map(part => part.charAt(0).toUpperCase() + part.slice(1)).join(" ");
|
|
494
|
+
}
|
|
495
|
+
/** Claude Code's documented status-line payload: rate_limits carries the
|
|
496
|
+
* five_hour and seven_day windows (the 5h/7d unified limits) and, when the
|
|
497
|
+
* build emits them, per-model keys such as seven_day_fable. Every window
|
|
498
|
+
* keeps its own reset time; a per-model window is its own weekly allowance
|
|
499
|
+
* with its own denominator, not a subset of seven_day, so it can show a
|
|
500
|
+
* higher percentage without contradicting the all-models window. */
|
|
501
|
+
export function claudeUsage(value, now = new Date()) {
|
|
502
|
+
const limits = object(object(value).rate_limits);
|
|
503
|
+
// Every window Claude Code reports, each on its own line: the overall
|
|
504
|
+
// ones first, then per-model windows (Fable, Opus...) in a stable order.
|
|
505
|
+
const order = (key) => key === "five_hour" ? 0 : key === "seven_day" ? 1 : 2;
|
|
506
|
+
const windows = Object.keys(limits).sort((a, b) => order(a) - order(b) || a.localeCompare(b)).slice(0, 16).flatMap(key => {
|
|
507
|
+
const item = object(limits[key]);
|
|
508
|
+
const entry = window(key, claudeWindowName(key), item.used_percentage, item.resets_at);
|
|
509
|
+
return entry ? [entry] : [];
|
|
510
|
+
});
|
|
511
|
+
return { source: "claude", windows, updatedAt: now.toISOString(), origin: "status-line",
|
|
512
|
+
...(!windows.length ? { message: "Usage appears after Claude Code replies with a subscription account on this computer." } : {}) };
|
|
513
|
+
}
|
|
514
|
+
/**
|
|
515
|
+
* Claude's per-model weekly windows (Fable today) never reach the status
|
|
516
|
+
* line, so they come from the snapshot Claude Code itself keeps of its usage
|
|
517
|
+
* endpoint in ~/.claude.json — refreshed whenever Claude opens /usage or
|
|
518
|
+
* checks a limit. Each window carries the snapshot's own time so the phone
|
|
519
|
+
* can say how old it is. No sign-in token is read or sent.
|
|
520
|
+
*/
|
|
521
|
+
export function claudeScopedWindows(config, now = new Date()) {
|
|
522
|
+
const cached = object(object(config).cachedUsageUtilization);
|
|
523
|
+
const fetched = typeof cached.fetchedAtMs === "number" && Number.isFinite(cached.fetchedAtMs) && cached.fetchedAtMs > 0
|
|
524
|
+
&& cached.fetchedAtMs <= now.getTime() + 60_000 ? new Date(cached.fetchedAtMs).toISOString() : undefined;
|
|
525
|
+
if (!fetched)
|
|
526
|
+
return [];
|
|
527
|
+
const limits = object(cached.utilization).limits;
|
|
528
|
+
if (!Array.isArray(limits))
|
|
529
|
+
return [];
|
|
530
|
+
const windows = [];
|
|
531
|
+
for (const raw of limits.slice(0, 16)) {
|
|
532
|
+
const limit = object(raw);
|
|
533
|
+
if (limit.kind !== "weekly_scoped")
|
|
534
|
+
continue;
|
|
535
|
+
const model = safeText(object(object(object(limit.scope).model)).display_name);
|
|
536
|
+
if (!model)
|
|
537
|
+
continue;
|
|
538
|
+
const reset = Date.parse(String(limit.resets_at ?? ""));
|
|
539
|
+
const entry = window(`seven_day_${model.toLowerCase().replace(/[^a-z0-9]+/g, "_")}`, `7-day, ${model}`, limit.percent, Number.isFinite(reset) ? Math.round(reset / 1000) : undefined);
|
|
540
|
+
if (entry)
|
|
541
|
+
windows.push({ ...entry, asOf: fetched });
|
|
542
|
+
}
|
|
543
|
+
return windows;
|
|
544
|
+
}
|
|
545
|
+
// Claude keeps .claude.json inside CLAUDE_CONFIG_DIR when set, else beside ~/.claude.
|
|
546
|
+
const claudeConfigFile = () => path.join(process.env.CLAUDE_CONFIG_DIR?.trim() ? claudeConfigDir() : homeDir(), ".claude.json");
|
|
547
|
+
const claudeCredentialsFile = () => path.join(claudeConfigDir(), ".credentials.json");
|
|
548
|
+
/**
|
|
549
|
+
* The OAuth usage endpoint Claude Code itself reads, mapped to the same
|
|
550
|
+
* windows the status-line snapshot produces. `limits` is the structured
|
|
551
|
+
* list (session, weekly_all, weekly_scoped with the model name); the older
|
|
552
|
+
* per-key fields are ignored because `limits` already carries them.
|
|
553
|
+
*/
|
|
554
|
+
export function claudeOAuthUsage(value, now = new Date()) {
|
|
555
|
+
const limits = object(value).limits;
|
|
556
|
+
const windows = [];
|
|
557
|
+
if (Array.isArray(limits)) {
|
|
558
|
+
for (const raw of limits.slice(0, 16)) {
|
|
559
|
+
const limit = object(raw);
|
|
560
|
+
const percent = limit.percent;
|
|
561
|
+
const reset = typeof limit.resets_at === "string" && Number.isFinite(Date.parse(limit.resets_at))
|
|
562
|
+
? Math.round(Date.parse(limit.resets_at) / 1000) : undefined;
|
|
563
|
+
if (limit.kind === "session") {
|
|
564
|
+
const entry = window("five_hour", "5-hour limit", percent, reset);
|
|
565
|
+
if (entry)
|
|
566
|
+
windows.push(entry);
|
|
567
|
+
}
|
|
568
|
+
else if (limit.kind === "weekly_all") {
|
|
569
|
+
const entry = window("seven_day", "7-day, all models", percent, reset);
|
|
570
|
+
if (entry)
|
|
571
|
+
windows.push(entry);
|
|
572
|
+
}
|
|
573
|
+
else if (limit.kind === "weekly_scoped") {
|
|
574
|
+
const model = safeText(object(object(object(limit.scope).model)).display_name);
|
|
575
|
+
if (!model)
|
|
576
|
+
continue;
|
|
577
|
+
const entry = window(`seven_day_${model.toLowerCase().replace(/[^a-z0-9]+/g, "_")}`, `7-day, ${model}`, percent, reset);
|
|
578
|
+
if (entry)
|
|
579
|
+
windows.push(entry);
|
|
580
|
+
}
|
|
581
|
+
}
|
|
582
|
+
}
|
|
583
|
+
return { source: "claude", windows, updatedAt: now.toISOString(), origin: "oauth",
|
|
584
|
+
...(!windows.length ? { message: "Claude has not reported account limits on this computer." } : {}) };
|
|
585
|
+
}
|
|
586
|
+
/**
|
|
587
|
+
* Claude Code's own sign-in token, read locally and used only against
|
|
588
|
+
* Anthropic's usage endpoint — never persisted, logged, or sent elsewhere.
|
|
589
|
+
* The file is authoritative off macOS; macOS keeps it in the login keychain,
|
|
590
|
+
* with the file left stale after a refresh.
|
|
591
|
+
*/
|
|
592
|
+
export async function readClaudeToken(execSecurity = exec, platform = process.platform) {
|
|
593
|
+
const parse = (raw) => {
|
|
594
|
+
if (raw.length > 16_384)
|
|
595
|
+
return undefined;
|
|
596
|
+
const oauth = object(object(JSON.parse(raw)).claudeAiOauth);
|
|
597
|
+
const token = typeof oauth.accessToken === "string" && oauth.accessToken.length > 0 ? oauth.accessToken : undefined;
|
|
598
|
+
const expires = typeof oauth.expiresAt === "number" ? oauth.expiresAt : undefined;
|
|
599
|
+
if (!token || (expires !== undefined && expires <= Date.now() + 60_000))
|
|
600
|
+
return undefined;
|
|
601
|
+
return token;
|
|
602
|
+
};
|
|
603
|
+
if (platform === "darwin") {
|
|
604
|
+
try {
|
|
605
|
+
const { stdout } = await execSecurity("security", ["find-generic-password", "-s", "Claude Code-credentials", "-w"], { timeout: 5_000, maxBuffer: 16_384 });
|
|
606
|
+
const token = parse(stdout.trim());
|
|
607
|
+
if (token)
|
|
608
|
+
return token;
|
|
609
|
+
}
|
|
610
|
+
catch { /* Headless installs can keep credentials in the file instead. */ }
|
|
611
|
+
}
|
|
612
|
+
try {
|
|
613
|
+
return parse(await readFile(claudeCredentialsFile(), "utf8"));
|
|
614
|
+
}
|
|
615
|
+
catch {
|
|
616
|
+
return undefined;
|
|
617
|
+
}
|
|
618
|
+
}
|
|
619
|
+
/** Fetch live limits; any failure falls back to the local snapshot. */
|
|
620
|
+
export async function fetchClaudeUsage(token, fetchImpl = fetch, now = new Date()) {
|
|
621
|
+
const controller = new AbortController();
|
|
622
|
+
const timer = setTimeout(() => controller.abort(), 8_000);
|
|
623
|
+
try {
|
|
624
|
+
const response = await fetchImpl("https://api.anthropic.com/api/oauth/usage", {
|
|
625
|
+
headers: { authorization: `Bearer ${token}`, "anthropic-beta": "oauth-2025-04-20", accept: "application/json" },
|
|
626
|
+
redirect: "error",
|
|
627
|
+
signal: controller.signal,
|
|
628
|
+
});
|
|
629
|
+
if (!response.ok)
|
|
630
|
+
throw new Error(`Claude usage endpoint returned ${response.status}.`);
|
|
631
|
+
return claudeOAuthUsage(await response.json(), now);
|
|
632
|
+
}
|
|
633
|
+
finally {
|
|
634
|
+
clearTimeout(timer);
|
|
635
|
+
}
|
|
636
|
+
}
|
|
637
|
+
async function liveClaudeUsage(now) {
|
|
638
|
+
if (typeof fetch !== "function")
|
|
639
|
+
return undefined;
|
|
640
|
+
const token = await readClaudeToken();
|
|
641
|
+
if (!token)
|
|
642
|
+
return undefined;
|
|
643
|
+
try {
|
|
644
|
+
return await fetchClaudeUsage(token, fetch, now);
|
|
645
|
+
}
|
|
646
|
+
catch {
|
|
647
|
+
return undefined;
|
|
648
|
+
}
|
|
649
|
+
}
|
|
650
|
+
/** Only initialize and read limits. Never create a thread, prompt, or login. */
|
|
651
|
+
export function readCodexLimits(executable = "codex") {
|
|
652
|
+
return new Promise(resolve => {
|
|
653
|
+
const child = spawn(executable, ["app-server"], { cwd: homedir(), stdio: ["pipe", "pipe", "ignore"] });
|
|
654
|
+
let pending = "", bytes = 0, initialized = false, done = false;
|
|
655
|
+
const finish = (result) => {
|
|
656
|
+
if (done)
|
|
657
|
+
return;
|
|
658
|
+
done = true;
|
|
659
|
+
clearTimeout(timer);
|
|
660
|
+
child.stdin.destroy();
|
|
661
|
+
child.stdout.destroy();
|
|
662
|
+
child.kill("SIGTERM");
|
|
663
|
+
const kill = setTimeout(() => { if (child.exitCode === null)
|
|
664
|
+
child.kill("SIGKILL"); }, 1000);
|
|
665
|
+
kill.unref();
|
|
666
|
+
child.once("exit", () => clearTimeout(kill));
|
|
667
|
+
resolve(result || { source: "codex", windows: [], message: "Could not read Codex limits. Open Codex on this computer, check its sign-in, then refresh." });
|
|
668
|
+
};
|
|
669
|
+
const timer = setTimeout(() => finish(), 12_000);
|
|
670
|
+
const send = (value) => { if (!done)
|
|
671
|
+
child.stdin.write(JSON.stringify(value) + "\n"); };
|
|
672
|
+
child.on("error", () => finish());
|
|
673
|
+
child.on("exit", () => finish());
|
|
674
|
+
child.stdin.on("error", () => finish());
|
|
675
|
+
child.stdout.setEncoding("utf8");
|
|
676
|
+
child.stdout.on("data", (chunk) => {
|
|
677
|
+
bytes += Buffer.byteLength(chunk);
|
|
678
|
+
if (bytes > 1_048_576) {
|
|
679
|
+
finish();
|
|
680
|
+
return;
|
|
681
|
+
}
|
|
682
|
+
pending += chunk;
|
|
683
|
+
let newline;
|
|
684
|
+
while (!done && (newline = pending.indexOf("\n")) >= 0) {
|
|
685
|
+
const line = pending.slice(0, newline);
|
|
686
|
+
pending = pending.slice(newline + 1);
|
|
687
|
+
try {
|
|
688
|
+
const response = object(JSON.parse(line));
|
|
689
|
+
if (response.id === 0 && !initialized) {
|
|
690
|
+
if (response.error || !response.result) {
|
|
691
|
+
finish();
|
|
692
|
+
return;
|
|
693
|
+
}
|
|
694
|
+
initialized = true;
|
|
695
|
+
send({ method: "initialized", params: {} });
|
|
696
|
+
send({ id: 1, method: "account/rateLimits/read" });
|
|
697
|
+
}
|
|
698
|
+
else if (response.id === 1 && initialized) {
|
|
699
|
+
finish(response.error ? undefined : codexUsage(response.result));
|
|
700
|
+
}
|
|
701
|
+
else if (response.method && response.id !== undefined) {
|
|
702
|
+
// Reject server-initiated requests, including auth refresh. No
|
|
703
|
+
// provider credential or capability token is handled by Phren.
|
|
704
|
+
send({ id: response.id, error: { code: -32601, message: "Unsupported request" } });
|
|
705
|
+
}
|
|
706
|
+
}
|
|
707
|
+
catch {
|
|
708
|
+
finish();
|
|
709
|
+
}
|
|
710
|
+
}
|
|
711
|
+
});
|
|
712
|
+
send({ id: 0, method: "initialize", params: { clientInfo: { name: "phren_usage", title: "Phren Usage", version: "1" } } });
|
|
713
|
+
});
|
|
714
|
+
}
|
|
715
|
+
export class AccountUsageReader {
|
|
716
|
+
readCodex;
|
|
717
|
+
now;
|
|
718
|
+
readClaudeLive;
|
|
719
|
+
readOpenCode;
|
|
720
|
+
readOpenRouter;
|
|
721
|
+
readOpenCodeGo;
|
|
722
|
+
cached;
|
|
723
|
+
pending;
|
|
724
|
+
claudeCached;
|
|
725
|
+
claudePending;
|
|
726
|
+
spendingCached;
|
|
727
|
+
spendingPending;
|
|
728
|
+
constructor(readCodex = readCodexLimits, now = Date.now, readClaudeLive = liveClaudeUsage, readOpenCode = now => readOpenCodeUsage("opencode", now), readOpenRouter = liveOpenRouterUsage, readOpenCodeGo = readOpenCodeGoUsage) {
|
|
729
|
+
this.readCodex = readCodex;
|
|
730
|
+
this.now = now;
|
|
731
|
+
this.readClaudeLive = readClaudeLive;
|
|
732
|
+
this.readOpenCode = readOpenCode;
|
|
733
|
+
this.readOpenRouter = readOpenRouter;
|
|
734
|
+
this.readOpenCodeGo = readOpenCodeGo;
|
|
735
|
+
}
|
|
736
|
+
async read() {
|
|
737
|
+
if (!this.cached || this.now() - this.cached.at >= 60_000) {
|
|
738
|
+
this.pending ??= this.readCodex().then(value => { this.cached = { at: this.now(), value }; return value; }).finally(() => { this.pending = undefined; });
|
|
739
|
+
}
|
|
740
|
+
const codex = this.pending ?? Promise.resolve(this.cached.value);
|
|
741
|
+
const [codexValue, claude, spending] = await Promise.all([codex, this.claude(), this.spending()]);
|
|
742
|
+
return { accounts: [codexValue, claude, ...spending] };
|
|
743
|
+
}
|
|
744
|
+
async spending() {
|
|
745
|
+
if (!this.spendingCached || this.now() - this.spendingCached.at >= 60_000) {
|
|
746
|
+
const at = this.now();
|
|
747
|
+
this.spendingPending ??= Promise.all([this.readOpenCode(new Date(at)), this.readOpenCodeGo(new Date(at)), this.readOpenRouter(new Date(at))])
|
|
748
|
+
.then(([openCode, openCodeGo, openRouter]) => [openCode, openCodeGo, ...(openRouter ? [openRouter] : [])])
|
|
749
|
+
.then(value => { this.spendingCached = { at, value }; return value; })
|
|
750
|
+
.finally(() => { this.spendingPending = undefined; });
|
|
751
|
+
}
|
|
752
|
+
return this.spendingPending ? await this.spendingPending : this.spendingCached.value;
|
|
753
|
+
}
|
|
754
|
+
/** Live first, so the phone's minute-by-minute poll keeps Claude current
|
|
755
|
+
* even when Claude Code is not running; the local snapshot is the backup. */
|
|
756
|
+
async claude() {
|
|
757
|
+
if (!this.claudeCached || this.now() - this.claudeCached.at >= 60_000) {
|
|
758
|
+
const at = this.now();
|
|
759
|
+
this.claudePending ??= this.readClaudeLive(new Date(at))
|
|
760
|
+
.then(value => { this.claudeCached = { at, value }; return value; })
|
|
761
|
+
.catch(() => { this.claudeCached = { at, value: undefined }; return undefined; })
|
|
762
|
+
.finally(() => { this.claudePending = undefined; });
|
|
763
|
+
}
|
|
764
|
+
const live = this.claudePending ? await this.claudePending : this.claudeCached?.value;
|
|
765
|
+
if (live?.windows.length)
|
|
766
|
+
return live;
|
|
767
|
+
return this.snapshotClaude();
|
|
768
|
+
}
|
|
769
|
+
async snapshotClaude() {
|
|
770
|
+
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." };
|
|
771
|
+
try {
|
|
772
|
+
const handle = await open(claudeFile(), "r");
|
|
773
|
+
try {
|
|
774
|
+
const stat = await handle.stat();
|
|
775
|
+
if (!stat.isFile() || stat.size > 16_384)
|
|
776
|
+
throw new Error("Invalid usage snapshot");
|
|
777
|
+
const saved = object(JSON.parse(await handle.readFile("utf8")));
|
|
778
|
+
const date = new Date(String(saved.updatedAt));
|
|
779
|
+
if (!Number.isFinite(date.getTime()) || date.getTime() > this.now() + 60_000)
|
|
780
|
+
throw new Error("Invalid usage timestamp");
|
|
781
|
+
claude = claudeUsage(saved, date);
|
|
782
|
+
}
|
|
783
|
+
finally {
|
|
784
|
+
await handle.close();
|
|
785
|
+
}
|
|
786
|
+
}
|
|
787
|
+
catch { /* No status-line report yet. Keep unavailable explicit. */ }
|
|
788
|
+
try {
|
|
789
|
+
const handle = await open(claudeConfigFile(), "r");
|
|
790
|
+
try {
|
|
791
|
+
const stat = await handle.stat();
|
|
792
|
+
if (!stat.isFile() || stat.size > 16_777_216)
|
|
793
|
+
throw new Error("Invalid Claude config");
|
|
794
|
+
const scoped = claudeScopedWindows(JSON.parse(await handle.readFile("utf8")), new Date(this.now()))
|
|
795
|
+
.filter(entry => !claude.windows.some(existing => existing.id === entry.id));
|
|
796
|
+
if (scoped.length)
|
|
797
|
+
claude = { ...claude, windows: [...claude.windows, ...scoped], message: undefined };
|
|
798
|
+
}
|
|
799
|
+
finally {
|
|
800
|
+
await handle.close();
|
|
801
|
+
}
|
|
802
|
+
}
|
|
803
|
+
catch { /* No snapshot from Claude Code; the status-line windows stand alone. */ }
|
|
804
|
+
return claude;
|
|
805
|
+
}
|
|
806
|
+
}
|
|
807
|
+
const quote = (value) => "'" + value.replace(/'/g, "'\\''") + "'";
|
|
808
|
+
/** Wrap an existing status line, preserving its input, output and options. */
|
|
809
|
+
export function usageStatusLine(current, program, remove) {
|
|
810
|
+
const prefix = `${quote(process.execPath)} ${quote(program)} usage-statusline `;
|
|
811
|
+
const command = object(current).command;
|
|
812
|
+
if (typeof command === "string" && command.startsWith(prefix)) {
|
|
813
|
+
if (!remove)
|
|
814
|
+
return current;
|
|
815
|
+
const encoded = command.slice(prefix.length);
|
|
816
|
+
if (!/^[A-Za-z0-9+/=]+$/.test(encoded))
|
|
817
|
+
throw new Error("Invalid Phren status line");
|
|
818
|
+
return JSON.parse(Buffer.from(encoded, "base64").toString()) ?? undefined;
|
|
819
|
+
}
|
|
820
|
+
if (remove)
|
|
821
|
+
return current;
|
|
822
|
+
if (current !== undefined && (object(current).type !== "command" || typeof command !== "string"))
|
|
823
|
+
return current;
|
|
824
|
+
const original = Buffer.from(JSON.stringify(current ?? null)).toString("base64");
|
|
825
|
+
if (original.length > 32_768)
|
|
826
|
+
return current;
|
|
827
|
+
return { ...object(current), type: "command", command: prefix + original };
|
|
828
|
+
}
|
|
829
|
+
export async function captureClaudeUsage(original) {
|
|
830
|
+
if (!/^[A-Za-z0-9+/=]{1,32768}$/.test(original))
|
|
831
|
+
return;
|
|
832
|
+
let input = "";
|
|
833
|
+
for await (const chunk of process.stdin) {
|
|
834
|
+
input += chunk.toString();
|
|
835
|
+
if (Buffer.byteLength(input) > 1_048_576)
|
|
836
|
+
return;
|
|
837
|
+
}
|
|
838
|
+
try {
|
|
839
|
+
const snapshot = claudeUsage(JSON.parse(input));
|
|
840
|
+
// Persist only normalized percentages/reset times; never session content.
|
|
841
|
+
const rate_limits = Object.fromEntries(snapshot.windows.map(w => [w.id, {
|
|
842
|
+
used_percentage: w.usedPercent, resets_at: w.resetsAt ? Date.parse(w.resetsAt) / 1000 : undefined,
|
|
843
|
+
}]));
|
|
844
|
+
await atomicInPrivateDir(claudeFile(), JSON.stringify({ rate_limits, updatedAt: snapshot.updatedAt }));
|
|
845
|
+
}
|
|
846
|
+
catch { /* Status line rendering must survive unavailable usage storage. */ }
|
|
847
|
+
const previous = object(JSON.parse(Buffer.from(original, "base64").toString()));
|
|
848
|
+
if (typeof previous.command === "string") {
|
|
849
|
+
await new Promise(resolve => {
|
|
850
|
+
// This is the user's original status-line command, invoked just as
|
|
851
|
+
// Claude did before installing the observer. The phone cannot set it.
|
|
852
|
+
const child = spawn("/bin/sh", ["-c", previous.command], { stdio: ["pipe", "inherit", "inherit"] });
|
|
853
|
+
child.on("error", () => resolve());
|
|
854
|
+
child.on("exit", () => resolve());
|
|
855
|
+
child.stdin.on("error", () => { });
|
|
856
|
+
child.stdin.end(input);
|
|
857
|
+
});
|
|
858
|
+
}
|
|
859
|
+
}
|