@songsid/agend 2.1.1-beta.11 → 2.1.1-beta.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/backend/antigravity.js +5 -2
- package/dist/backend/antigravity.js.map +1 -1
- package/dist/backend/claude-code.js +3 -0
- package/dist/backend/claude-code.js.map +1 -1
- package/dist/backend/codex.d.ts +16 -0
- package/dist/backend/codex.js +248 -56
- package/dist/backend/codex.js.map +1 -1
- package/dist/backend/grok.js +20 -0
- package/dist/backend/grok.js.map +1 -1
- package/dist/backend/kiro.js +18 -2
- package/dist/backend/kiro.js.map +1 -1
- package/dist/backend/types.d.ts +7 -0
- package/dist/backend/types.js +1 -1
- package/dist/backend/types.js.map +1 -1
- package/dist/channel/adapters/discord.js +4 -5
- package/dist/channel/adapters/discord.js.map +1 -1
- package/dist/channel/adapters/telegram.js +50 -15
- package/dist/channel/adapters/telegram.js.map +1 -1
- package/dist/channel/ipc-bridge.d.ts +8 -0
- package/dist/channel/ipc-bridge.js +41 -14
- package/dist/channel/ipc-bridge.js.map +1 -1
- package/dist/channel/mcp-server.js +25 -10
- package/dist/channel/mcp-server.js.map +1 -1
- package/dist/channel/mcp-tools.js +25 -0
- package/dist/channel/mcp-tools.js.map +1 -1
- package/dist/channel/message-queue.d.ts +1 -0
- package/dist/channel/message-queue.js +49 -17
- package/dist/channel/message-queue.js.map +1 -1
- package/dist/channel/reconnect-backoff.d.ts +17 -0
- package/dist/channel/reconnect-backoff.js +21 -0
- package/dist/channel/reconnect-backoff.js.map +1 -0
- package/dist/cli.js +71 -26
- package/dist/cli.js.map +1 -1
- package/dist/completion.d.ts +27 -0
- package/dist/completion.js +121 -0
- package/dist/completion.js.map +1 -0
- package/dist/config-validator.js +9 -0
- package/dist/config-validator.js.map +1 -1
- package/dist/config.js +1 -0
- package/dist/config.js.map +1 -1
- package/dist/daemon.d.ts +74 -8
- package/dist/daemon.js +254 -18
- package/dist/daemon.js.map +1 -1
- package/dist/fleet-manager.d.ts +7 -1
- package/dist/fleet-manager.js +89 -16
- package/dist/fleet-manager.js.map +1 -1
- package/dist/general-knowledge/skills/cross-instance-messaging/SKILL.md +22 -0
- package/dist/general-knowledge/skills/model-discovery/SKILL.md +14 -23
- package/dist/general-knowledge/skills/session-management/SKILL.md +15 -34
- package/dist/instance-lifecycle.d.ts +13 -1
- package/dist/instance-lifecycle.js +70 -3
- package/dist/instance-lifecycle.js.map +1 -1
- package/dist/instructions.d.ts +5 -0
- package/dist/instructions.js +9 -11
- package/dist/instructions.js.map +1 -1
- package/dist/logger.js +14 -0
- package/dist/logger.js.map +1 -1
- package/dist/mcp-liveness.d.ts +21 -0
- package/dist/mcp-liveness.js +27 -0
- package/dist/mcp-liveness.js.map +1 -0
- package/dist/outbound-handlers.d.ts +9 -0
- package/dist/outbound-handlers.js +46 -26
- package/dist/outbound-handlers.js.map +1 -1
- package/dist/outbound-schemas.js +1 -1
- package/dist/outbound-schemas.js.map +1 -1
- package/dist/tmux-control.js +4 -2
- package/dist/tmux-control.js.map +1 -1
- package/dist/tmux-manager.d.ts +14 -0
- package/dist/tmux-manager.js +20 -6
- package/dist/tmux-manager.js.map +1 -1
- package/dist/topic-commands.d.ts +22 -1
- package/dist/topic-commands.js +95 -57
- package/dist/topic-commands.js.map +1 -1
- package/dist/tui-glyphs.d.ts +25 -0
- package/dist/tui-glyphs.js +26 -0
- package/dist/tui-glyphs.js.map +1 -0
- package/dist/types.d.ts +6 -0
- package/dist/ui/view.html +114 -2
- package/dist/usage/providers.d.ts +26 -0
- package/dist/usage/providers.js +447 -0
- package/dist/usage/providers.js.map +1 -0
- package/dist/usage/usage-api.d.ts +35 -0
- package/dist/usage/usage-api.js +52 -0
- package/dist/usage/usage-api.js.map +1 -0
- package/dist/view-api.d.ts +3 -0
- package/dist/view-api.js +10 -2
- package/dist/view-api.js.map +1 -1
- package/package.json +1 -1
package/dist/ui/view.html
CHANGED
|
@@ -83,6 +83,27 @@
|
|
|
83
83
|
.help-panel li { font-size: 13px; margin: 6px 0; color: var(--fg); }
|
|
84
84
|
.help-panel .close { position: absolute; top: 14px; right: 16px; cursor: pointer; color: var(--dim); font-size: 22px; line-height: 1; background: none; border: none; }
|
|
85
85
|
|
|
86
|
+
/* AI usage panel (shares .help-panel chrome) */
|
|
87
|
+
.u-provider { margin: 14px 0 4px; padding-top: 10px; border-top: 1px solid var(--border); }
|
|
88
|
+
.u-provider:first-of-type { border-top: none; padding-top: 0; }
|
|
89
|
+
.u-head { display: flex; align-items: baseline; gap: 8px; }
|
|
90
|
+
.u-head .u-name { font-size: 14px; font-weight: 600; }
|
|
91
|
+
.u-head .u-plan { color: var(--dim); font-size: 11px; }
|
|
92
|
+
.u-metric { margin: 8px 0; }
|
|
93
|
+
.u-row { display: flex; align-items: baseline; gap: 6px; font-size: 12px; }
|
|
94
|
+
.u-row .u-label { color: var(--dim); flex: 1; min-width: 0; }
|
|
95
|
+
.u-row .u-val { font-variant-numeric: tabular-nums; }
|
|
96
|
+
.u-row .u-status { font-size: 11px; font-weight: 600; }
|
|
97
|
+
.u-status.warn { color: #d29922; } .u-status.crit { color: #f85149; }
|
|
98
|
+
.u-meter { height: 6px; background: var(--border); border-radius: 3px; overflow: hidden; margin-top: 4px; }
|
|
99
|
+
.u-fill { height: 100%; border-radius: 3px; background: var(--accent); min-width: 2px; }
|
|
100
|
+
.u-fill.warn { background: #d29922; } .u-fill.crit { background: #f85149; }
|
|
101
|
+
.u-sub { color: var(--dim); font-size: 11px; margin-top: 2px; font-variant-numeric: tabular-nums; }
|
|
102
|
+
.u-err { color: #d29922; font-size: 12px; margin: 6px 0; }
|
|
103
|
+
.u-foot { color: var(--dim); font-size: 11px; margin-top: 14px; display: flex; gap: 8px; align-items: baseline; }
|
|
104
|
+
.u-foot button { background: none; border: 1px solid var(--border); border-radius: 5px; color: var(--dim); cursor: pointer; font-size: 11px; padding: 2px 8px; }
|
|
105
|
+
.u-foot button:hover { color: var(--fg); border-color: var(--accent); }
|
|
106
|
+
|
|
86
107
|
#densityBtn { font-size: 14px; font-weight: 600; letter-spacing: -.5px; }
|
|
87
108
|
@media (max-width: 700px) {
|
|
88
109
|
#sidebar { width: 180px; flex-basis: 180px; }
|
|
@@ -93,6 +114,7 @@
|
|
|
93
114
|
</style>
|
|
94
115
|
</head>
|
|
95
116
|
<body>
|
|
117
|
+
<button class="help-btn" id="usageBtn" title="AI usage" style="right:140px; display:none">📊</button>
|
|
96
118
|
<button class="help-btn" id="densityBtn" title="Font density" style="right:98px">⤢</button>
|
|
97
119
|
<button class="help-btn" id="langBtn" title="Language" style="right:56px">🌐</button>
|
|
98
120
|
<button class="help-btn" id="helpBtn" title="Help">ℹ️</button>
|
|
@@ -101,6 +123,10 @@
|
|
|
101
123
|
<button class="close" id="helpClose" title="Close">×</button>
|
|
102
124
|
<div id="helpContent"></div>
|
|
103
125
|
</aside>
|
|
126
|
+
<aside class="help-panel" id="usagePanel">
|
|
127
|
+
<button class="close" id="usageClose" title="Close">×</button>
|
|
128
|
+
<div id="usageContent"></div>
|
|
129
|
+
</aside>
|
|
104
130
|
<div id="sidebar"><h1 data-i18n="viewTitle">AgEnD · View</h1><div id="list"></div></div>
|
|
105
131
|
<div id="main">
|
|
106
132
|
<div id="term"><pre id="pre"></pre></div>
|
|
@@ -147,7 +173,10 @@
|
|
|
147
173
|
help2: "Click a group header ▼/▶ to collapse/expand", help3: "✏️ Edit changes display name, role, description",
|
|
148
174
|
help4: "Drag to reorder (needs web.token permission)",
|
|
149
175
|
help5: "Click ⤢ to cycle font density: Fit → Comfortable → Compact",
|
|
150
|
-
densityFit: "Fit", densityComfortable: "Comfortable", densityCompact: "Compact", densityLabel: "Font density"
|
|
176
|
+
densityFit: "Fit", densityComfortable: "Comfortable", densityCompact: "Compact", densityLabel: "Font density",
|
|
177
|
+
usageTitle: "📊 AI Usage", usageEmpty: "No AI CLI logins found on this machine.",
|
|
178
|
+
usageUpdated: "updated", usageRefresh: "Refresh", usageHigh: "high", usageNear: "near limit",
|
|
179
|
+
usageResets: "resets in {t}", usageSoon: "resets soon", usageFail: "Could not load usage data." },
|
|
151
180
|
"zh-TW": { viewTitle: "AgEnD · 檢視", editProfile: "✏️ 編輯", save: "儲存", cancel: "取消",
|
|
152
181
|
displayName: "顯示名稱", role: "角色", description: "描述", tokenPh: "web.token(儲存時需要)",
|
|
153
182
|
saveHint: "檢視為公開(唯讀)。儲存需要 web.token(~/.agend/web.token)。", helpTitle: "📖 使用說明",
|
|
@@ -155,7 +184,10 @@
|
|
|
155
184
|
help2: "點 group header ▼/▶ 收合/展開", help3: "✏️ Edit 可修改顯示名稱、角色、描述",
|
|
156
185
|
help4: "拖曳可調整順序(需 web.token 權限)",
|
|
157
186
|
help5: "點 ⤢ 循環切換字級密度:剛好填滿 → 舒適 → 精簡",
|
|
158
|
-
densityFit: "剛好填滿", densityComfortable: "舒適", densityCompact: "精簡", densityLabel: "字級密度"
|
|
187
|
+
densityFit: "剛好填滿", densityComfortable: "舒適", densityCompact: "精簡", densityLabel: "字級密度",
|
|
188
|
+
usageTitle: "📊 AI 訂閱用量", usageEmpty: "本機沒有偵測到已登入的 AI CLI。",
|
|
189
|
+
usageUpdated: "更新於", usageRefresh: "重新整理", usageHigh: "偏高", usageNear: "接近上限",
|
|
190
|
+
usageResets: "{t} 後重置", usageSoon: "即將重置", usageFail: "無法載入用量資料。" },
|
|
159
191
|
};
|
|
160
192
|
let lang = localStorage.getItem("agend_lang") || (navigator.language && navigator.language.toLowerCase().startsWith("zh") ? "zh-TW" : "en");
|
|
161
193
|
if (!I18N[lang]) lang = "en";
|
|
@@ -667,6 +699,86 @@
|
|
|
667
699
|
q("densityBtn").onclick = cycleDensity;
|
|
668
700
|
window.addEventListener("keydown", (e) => { if (e.key === "Escape") setHelp(false); });
|
|
669
701
|
|
|
702
|
+
// ── AI usage panel ────────────────────────────────────
|
|
703
|
+
let usageData = null;
|
|
704
|
+
let usageTimer = null;
|
|
705
|
+
|
|
706
|
+
function usageResetText(iso) {
|
|
707
|
+
if (!iso) return "";
|
|
708
|
+
const ms = new Date(iso).getTime() - Date.now();
|
|
709
|
+
if (isNaN(ms)) return "";
|
|
710
|
+
if (ms <= 0) return T("usageSoon");
|
|
711
|
+
const h = Math.floor(ms / 3600000), m = Math.floor((ms % 3600000) / 60000);
|
|
712
|
+
const t = h >= 48 ? `${Math.floor(h / 24)}d ${h % 24}h` : h > 0 ? `${h}h ${m}m` : `${m}m`;
|
|
713
|
+
return T("usageResets").replace("{t}", t);
|
|
714
|
+
}
|
|
715
|
+
|
|
716
|
+
function usageMetricHtml(m) {
|
|
717
|
+
if (m.type === "percent") {
|
|
718
|
+
const pct = Math.min(100, Math.max(0, m.used ?? 0));
|
|
719
|
+
const cls = pct >= 90 ? "crit" : pct >= 70 ? "warn" : "";
|
|
720
|
+
const word = pct >= 90 ? T("usageNear") : pct >= 70 ? T("usageHigh") : "";
|
|
721
|
+
const sub = usageResetText(m.resetsAt);
|
|
722
|
+
return `<div class="u-metric"><div class="u-row"><span class="u-label">${esc(m.label)}</span>` +
|
|
723
|
+
(word ? `<span class="u-status ${cls}">${esc(word)}</span>` : "") +
|
|
724
|
+
`<span class="u-val">${pct.toFixed(0)}%</span></div>` +
|
|
725
|
+
`<div class="u-meter"><div class="u-fill ${cls}" style="width:${pct}%"></div></div>` +
|
|
726
|
+
(sub ? `<div class="u-sub">${esc(sub)}</div>` : "") + `</div>`;
|
|
727
|
+
}
|
|
728
|
+
if (m.type === "dollars") {
|
|
729
|
+
const val = m.limit ? `$${(m.used ?? 0).toFixed(2)} / $${m.limit.toFixed(2)}` : `$${(m.used ?? 0).toFixed(2)}`;
|
|
730
|
+
return `<div class="u-metric"><div class="u-row"><span class="u-label">${esc(m.label)}</span><span class="u-val">${esc(val)}</span></div></div>`;
|
|
731
|
+
}
|
|
732
|
+
const val = `${m.value ?? ""} ${m.unit ?? ""}`.trim();
|
|
733
|
+
return `<div class="u-metric"><div class="u-row"><span class="u-label">${esc(m.label)}</span><span class="u-val">${esc(val)}</span></div>` +
|
|
734
|
+
(m.note ? `<div class="u-sub">${esc(m.note)}</div>` : "") + `</div>`;
|
|
735
|
+
}
|
|
736
|
+
|
|
737
|
+
function renderUsage() {
|
|
738
|
+
const box = q("usageContent");
|
|
739
|
+
if (!usageData || !Array.isArray(usageData.providers)) { box.innerHTML = `<h3>${T("usageTitle")}</h3><div class="u-err">${T("usageFail")}</div>`; return; }
|
|
740
|
+
let html = `<h3>${T("usageTitle")}</h3>`;
|
|
741
|
+
if (!usageData.providers.length) html += `<div class="u-err">${T("usageEmpty")}</div>`;
|
|
742
|
+
for (const p of usageData.providers) {
|
|
743
|
+
html += `<div class="u-provider"><div class="u-head"><span class="u-name">${esc(p.name)}</span>` +
|
|
744
|
+
(p.plan ? `<span class="u-plan">${esc(p.plan)}</span>` : "") + `</div>`;
|
|
745
|
+
if (p.status === "error") html += `<div class="u-err">${esc(p.error || "error")}</div>`;
|
|
746
|
+
else html += (p.metrics || []).map(usageMetricHtml).join("");
|
|
747
|
+
html += `</div>`;
|
|
748
|
+
}
|
|
749
|
+
const at = new Date(usageData.fetchedAt).toLocaleTimeString();
|
|
750
|
+
html += `<div class="u-foot"><span>${T("usageUpdated")} ${esc(at)}</span><button id="usageRefresh">${T("usageRefresh")}</button></div>`;
|
|
751
|
+
box.innerHTML = html;
|
|
752
|
+
const rb = q("usageRefresh");
|
|
753
|
+
if (rb) rb.onclick = () => loadUsage(true);
|
|
754
|
+
}
|
|
755
|
+
|
|
756
|
+
async function loadUsage(force) {
|
|
757
|
+
try {
|
|
758
|
+
const r = await fetch(`/api/ai-usage${force ? "?force=1" : ""}`);
|
|
759
|
+
if (r.status === 404) { q("usageBtn").style.display = "none"; return false; }
|
|
760
|
+
usageData = await r.json();
|
|
761
|
+
} catch { usageData = null; }
|
|
762
|
+
renderUsage();
|
|
763
|
+
return true;
|
|
764
|
+
}
|
|
765
|
+
|
|
766
|
+
const setUsage = (open) => {
|
|
767
|
+
q("usagePanel").classList.toggle("open", open);
|
|
768
|
+
q("helpBackdrop").classList.toggle("open", open);
|
|
769
|
+
if (open) { setHelp(false); loadUsage(false); if (!usageTimer) usageTimer = setInterval(() => loadUsage(false), 60_000); }
|
|
770
|
+
else if (usageTimer) { clearInterval(usageTimer); usageTimer = null; }
|
|
771
|
+
};
|
|
772
|
+
q("usageBtn").onclick = () => setUsage(!q("usagePanel").classList.contains("open"));
|
|
773
|
+
q("usageClose").onclick = () => setUsage(false);
|
|
774
|
+
q("helpBackdrop").addEventListener("click", () => setUsage(false));
|
|
775
|
+
q("helpBtn").addEventListener("click", () => setUsage(false));
|
|
776
|
+
window.addEventListener("keydown", (e) => { if (e.key === "Escape") setUsage(false); });
|
|
777
|
+
q("langBtn").addEventListener("click", () => { if (usageData) renderUsage(); });
|
|
778
|
+
// Probe once at boot: shows the 📊 button only when the endpoint is enabled,
|
|
779
|
+
// and warms the server-side 5-minute cache so the first open is instant.
|
|
780
|
+
loadUsage(false).then(ok => { if (ok !== false) q("usageBtn").style.display = ""; });
|
|
781
|
+
|
|
670
782
|
window.addEventListener("resize", scheduleFit);
|
|
671
783
|
// Catches container changes the window resize event doesn't see — chiefly the
|
|
672
784
|
// profile card expanding or collapsing.
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
export interface UsageMetric {
|
|
2
|
+
label: string;
|
|
3
|
+
type: "percent" | "dollars" | "count" | "text";
|
|
4
|
+
used?: number;
|
|
5
|
+
limit?: number;
|
|
6
|
+
value?: number | string;
|
|
7
|
+
unit?: string;
|
|
8
|
+
note?: string;
|
|
9
|
+
resetsAt?: string | null;
|
|
10
|
+
windowMs?: number | null;
|
|
11
|
+
}
|
|
12
|
+
export interface ProviderUsage {
|
|
13
|
+
id: string;
|
|
14
|
+
name: string;
|
|
15
|
+
status: "ok" | "error" | "no-credentials";
|
|
16
|
+
plan?: string | null;
|
|
17
|
+
error?: string;
|
|
18
|
+
hint?: string;
|
|
19
|
+
metrics: UsageMetric[];
|
|
20
|
+
}
|
|
21
|
+
/** Fetch every provider in parallel. Providers without local credentials are
|
|
22
|
+
* skipped (per the panel's contract: absent CLIs simply don't show). */
|
|
23
|
+
export declare function fetchAllUsage(): Promise<{
|
|
24
|
+
fetchedAt: string;
|
|
25
|
+
providers: ProviderUsage[];
|
|
26
|
+
}>;
|
|
@@ -0,0 +1,447 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* AI subscription usage providers — read the credentials the CLI backends
|
|
3
|
+
* already saved on this machine and fetch live plan usage from each vendor's
|
|
4
|
+
* own usage endpoint. Powers `GET /api/ai-usage` (usage-api.ts) and the
|
|
5
|
+
* Usage panel on /view.
|
|
6
|
+
*
|
|
7
|
+
* Vendored from ai-usage-board (https://github.com/songsid/ai-usage-board, MIT),
|
|
8
|
+
* whose provider protocol logic is in turn ported from OpenUsage
|
|
9
|
+
* (https://github.com/robinebers/openusage, MIT, © Robin Ebers). See LICENSE.md
|
|
10
|
+
* in this directory. Not affiliated with or endorsed by OpenUsage.
|
|
11
|
+
*
|
|
12
|
+
* Token policy:
|
|
13
|
+
* - Claude/Codex: read-only, never refreshed — those vendors rotate refresh
|
|
14
|
+
* tokens, and refreshing behind the CLI's back could invalidate its login.
|
|
15
|
+
* Their credential files stay fresh as long as the CLIs are used (which, in
|
|
16
|
+
* a running fleet, they are).
|
|
17
|
+
* - Grok: access tokens expire within hours, so we refresh exactly like the
|
|
18
|
+
* Grok CLI does and persist rotated tokens back to auth.json — refusing to
|
|
19
|
+
* refresh at all when the file isn't writable, rather than risk the login.
|
|
20
|
+
*/
|
|
21
|
+
import { readFile, writeFile, access, constants } from "node:fs/promises";
|
|
22
|
+
import { join } from "node:path";
|
|
23
|
+
import { homedir } from "node:os";
|
|
24
|
+
const WEEK_MS = 7 * 24 * 60 * 60 * 1000;
|
|
25
|
+
const SESSION_MS = 5 * 60 * 60 * 1000;
|
|
26
|
+
function jwtExpiryMs(token) {
|
|
27
|
+
try {
|
|
28
|
+
const payload = JSON.parse(Buffer.from(token.split(".")[1], "base64url").toString("utf8"));
|
|
29
|
+
return typeof payload.exp === "number" ? payload.exp * 1000 : null;
|
|
30
|
+
}
|
|
31
|
+
catch {
|
|
32
|
+
return null;
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
// ── Claude ───────────────────────────────────────────────────────────────────
|
|
36
|
+
const CLAUDE_USAGE_URL = "https://api.anthropic.com/api/oauth/usage";
|
|
37
|
+
function claudeResetIso(value) {
|
|
38
|
+
if (typeof value === "string" && value.trim()) {
|
|
39
|
+
const d = new Date(value);
|
|
40
|
+
if (!Number.isNaN(d.getTime()))
|
|
41
|
+
return d.toISOString();
|
|
42
|
+
}
|
|
43
|
+
if (typeof value === "number" && Number.isFinite(value)) {
|
|
44
|
+
const ms = Math.abs(value) < 1e10 ? value * 1000 : value;
|
|
45
|
+
return new Date(ms).toISOString();
|
|
46
|
+
}
|
|
47
|
+
return null;
|
|
48
|
+
}
|
|
49
|
+
async function fetchClaudeUsage() {
|
|
50
|
+
const home = process.env.CLAUDE_HOME || join(homedir(), ".claude");
|
|
51
|
+
let oauth;
|
|
52
|
+
try {
|
|
53
|
+
oauth = JSON.parse(await readFile(join(home, ".credentials.json"), "utf8")).claudeAiOauth;
|
|
54
|
+
if (!oauth?.accessToken)
|
|
55
|
+
throw new Error("no token");
|
|
56
|
+
}
|
|
57
|
+
catch {
|
|
58
|
+
return { status: "no-credentials", hint: "Log in with the Claude Code CLI (`claude`).", metrics: [] };
|
|
59
|
+
}
|
|
60
|
+
let plan = null;
|
|
61
|
+
if (oauth.subscriptionType?.trim()) {
|
|
62
|
+
plan = oauth.subscriptionType.trim().replace(/^./, c => c.toUpperCase());
|
|
63
|
+
const tier = oauth.rateLimitTier?.match(/\d+x/);
|
|
64
|
+
if (tier)
|
|
65
|
+
plan += ` ${tier[0]}`;
|
|
66
|
+
}
|
|
67
|
+
if (oauth.expiresAt && oauth.expiresAt < Date.now()) {
|
|
68
|
+
return { status: "error", plan, error: "Access token expired. Run `claude` once to refresh it.", metrics: [] };
|
|
69
|
+
}
|
|
70
|
+
let res;
|
|
71
|
+
try {
|
|
72
|
+
res = await fetch(CLAUDE_USAGE_URL, {
|
|
73
|
+
headers: {
|
|
74
|
+
Authorization: `Bearer ${oauth.accessToken.trim()}`,
|
|
75
|
+
Accept: "application/json",
|
|
76
|
+
"Content-Type": "application/json",
|
|
77
|
+
"anthropic-beta": "oauth-2025-04-20",
|
|
78
|
+
"User-Agent": "claude-code/2.1.69",
|
|
79
|
+
},
|
|
80
|
+
signal: AbortSignal.timeout(10_000),
|
|
81
|
+
});
|
|
82
|
+
}
|
|
83
|
+
catch {
|
|
84
|
+
return { status: "error", plan, error: "Could not reach api.anthropic.com.", metrics: [] };
|
|
85
|
+
}
|
|
86
|
+
if (res.status === 401 || res.status === 403) {
|
|
87
|
+
return { status: "error", plan, error: "Token rejected. Run `claude` once to refresh the login.", metrics: [] };
|
|
88
|
+
}
|
|
89
|
+
if (res.status === 429) {
|
|
90
|
+
return { status: "error", plan, error: "Rate limited by Anthropic — try again later.", metrics: [] };
|
|
91
|
+
}
|
|
92
|
+
if (!res.ok)
|
|
93
|
+
return { status: "error", plan, error: `Usage request failed (HTTP ${res.status}).`, metrics: [] };
|
|
94
|
+
let body;
|
|
95
|
+
try {
|
|
96
|
+
body = await res.json();
|
|
97
|
+
}
|
|
98
|
+
catch {
|
|
99
|
+
return { status: "error", plan, error: "Invalid response from usage endpoint.", metrics: [] };
|
|
100
|
+
}
|
|
101
|
+
const metrics = [];
|
|
102
|
+
const window = (obj, label, windowMs) => {
|
|
103
|
+
const o = obj;
|
|
104
|
+
if (typeof o?.utilization !== "number")
|
|
105
|
+
return;
|
|
106
|
+
metrics.push({ label, type: "percent", used: o.utilization, resetsAt: claudeResetIso(o.resets_at), windowMs });
|
|
107
|
+
};
|
|
108
|
+
window(body.five_hour, "Session", SESSION_MS);
|
|
109
|
+
window(body.seven_day, "Weekly", WEEK_MS);
|
|
110
|
+
window(body.seven_day_sonnet, "Sonnet (weekly)", WEEK_MS);
|
|
111
|
+
// Per-model weekly windows live in the `limits` array (kind: weekly_scoped).
|
|
112
|
+
for (const entry of Array.isArray(body.limits) ? body.limits : []) {
|
|
113
|
+
const e = entry;
|
|
114
|
+
if (e?.kind !== "weekly_scoped")
|
|
115
|
+
continue;
|
|
116
|
+
const model = e.scope?.model?.display_name;
|
|
117
|
+
if (!model || typeof e.percent !== "number")
|
|
118
|
+
continue;
|
|
119
|
+
metrics.push({ label: `${model} (weekly)`, type: "percent", used: e.percent, resetsAt: claudeResetIso(e.resets_at), windowMs: WEEK_MS });
|
|
120
|
+
}
|
|
121
|
+
const extra = body.extra_usage;
|
|
122
|
+
if (extra?.is_enabled === true && typeof extra.used_credits === "number") {
|
|
123
|
+
const used = extra.used_credits / 100;
|
|
124
|
+
const limit = typeof extra.monthly_limit === "number" && extra.monthly_limit > 0 ? extra.monthly_limit / 100 : null;
|
|
125
|
+
if (limit)
|
|
126
|
+
metrics.push({ label: "Extra usage", type: "dollars", used, limit });
|
|
127
|
+
else if (used > 0)
|
|
128
|
+
metrics.push({ label: "Extra usage", type: "dollars", used });
|
|
129
|
+
}
|
|
130
|
+
return { status: "ok", plan, metrics };
|
|
131
|
+
}
|
|
132
|
+
// ── Codex ────────────────────────────────────────────────────────────────────
|
|
133
|
+
const CODEX_USAGE_URL = "https://chatgpt.com/backend-api/wham/usage";
|
|
134
|
+
const CREDIT_USD_RATE = 0.04;
|
|
135
|
+
function codexResetIso(win, nowMs) {
|
|
136
|
+
if (typeof win.reset_at === "number" && Number.isFinite(win.reset_at))
|
|
137
|
+
return new Date(win.reset_at * 1000).toISOString();
|
|
138
|
+
if (typeof win.reset_after_seconds === "number" && Number.isFinite(win.reset_after_seconds)) {
|
|
139
|
+
return new Date(nowMs + win.reset_after_seconds * 1000).toISOString();
|
|
140
|
+
}
|
|
141
|
+
return null;
|
|
142
|
+
}
|
|
143
|
+
// Codex normally puts the 5-hour window in primary and weekly in secondary, but
|
|
144
|
+
// a window's own limit_window_seconds wins when present. Some plans (e.g. Team)
|
|
145
|
+
// report a monthly window — label by actual duration, never by slot.
|
|
146
|
+
function codexWindows(rateLimit, labels, nowMs) {
|
|
147
|
+
const candidates = [
|
|
148
|
+
{ win: rateLimit?.primary_window, fallback: "session" },
|
|
149
|
+
{ win: rateLimit?.secondary_window, fallback: "weekly" },
|
|
150
|
+
].filter(c => c.win && typeof c.win === "object");
|
|
151
|
+
const metrics = [];
|
|
152
|
+
for (const { win, fallback } of candidates) {
|
|
153
|
+
if (!win || typeof win.used_percent !== "number")
|
|
154
|
+
continue;
|
|
155
|
+
const explicitMs = typeof win.limit_window_seconds === "number" && Number.isFinite(win.limit_window_seconds)
|
|
156
|
+
? win.limit_window_seconds * 1000 : null;
|
|
157
|
+
const windowMs = explicitMs ?? (fallback === "session" ? SESSION_MS : WEEK_MS);
|
|
158
|
+
let label;
|
|
159
|
+
if (windowMs === SESSION_MS)
|
|
160
|
+
label = labels.session;
|
|
161
|
+
else if (windowMs === WEEK_MS)
|
|
162
|
+
label = labels.weekly;
|
|
163
|
+
else if (windowMs >= 27 * 864e5 && windowMs <= 32 * 864e5)
|
|
164
|
+
label = labels.monthly;
|
|
165
|
+
else if (explicitMs)
|
|
166
|
+
label = labels.other(Math.round(windowMs / 864e5));
|
|
167
|
+
else
|
|
168
|
+
label = fallback === "session" ? labels.session : labels.weekly;
|
|
169
|
+
metrics.push({ label, type: "percent", used: win.used_percent, resetsAt: codexResetIso(win, nowMs), windowMs });
|
|
170
|
+
}
|
|
171
|
+
return metrics;
|
|
172
|
+
}
|
|
173
|
+
function codexPlan(planType) {
|
|
174
|
+
if (typeof planType !== "string" || !planType.trim())
|
|
175
|
+
return null;
|
|
176
|
+
switch (planType.trim().toLowerCase()) {
|
|
177
|
+
case "prolite": return "Pro 5x";
|
|
178
|
+
case "pro": return "Pro 20x";
|
|
179
|
+
default: return planType.trim().split("_").map(w => w.charAt(0).toUpperCase() + w.slice(1)).join(" ");
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
async function fetchCodexUsage() {
|
|
183
|
+
const home = process.env.CODEX_HOME || join(homedir(), ".codex");
|
|
184
|
+
let auth;
|
|
185
|
+
try {
|
|
186
|
+
auth = JSON.parse(await readFile(join(home, "auth.json"), "utf8"));
|
|
187
|
+
}
|
|
188
|
+
catch {
|
|
189
|
+
return { status: "no-credentials", hint: "Log in with the Codex CLI (`codex`).", metrics: [] };
|
|
190
|
+
}
|
|
191
|
+
const accessToken = auth?.tokens?.access_token;
|
|
192
|
+
if (!accessToken) {
|
|
193
|
+
return { status: "no-credentials", hint: "auth.json has no OAuth login (API-key-only auth cannot read usage).", metrics: [] };
|
|
194
|
+
}
|
|
195
|
+
const exp = jwtExpiryMs(accessToken);
|
|
196
|
+
if (exp && exp < Date.now()) {
|
|
197
|
+
return { status: "error", error: "Access token expired. Run `codex` once to refresh it.", metrics: [] };
|
|
198
|
+
}
|
|
199
|
+
const headers = {
|
|
200
|
+
Authorization: `Bearer ${accessToken}`,
|
|
201
|
+
Accept: "application/json",
|
|
202
|
+
"User-Agent": "agend-usage",
|
|
203
|
+
};
|
|
204
|
+
if (auth.tokens?.account_id)
|
|
205
|
+
headers["ChatGPT-Account-Id"] = auth.tokens.account_id;
|
|
206
|
+
let res;
|
|
207
|
+
try {
|
|
208
|
+
res = await fetch(CODEX_USAGE_URL, { headers, signal: AbortSignal.timeout(10_000) });
|
|
209
|
+
}
|
|
210
|
+
catch {
|
|
211
|
+
return { status: "error", error: "Could not reach chatgpt.com.", metrics: [] };
|
|
212
|
+
}
|
|
213
|
+
if (res.status === 401 || res.status === 403) {
|
|
214
|
+
return { status: "error", error: "Token rejected. Run `codex` once to refresh the login.", metrics: [] };
|
|
215
|
+
}
|
|
216
|
+
if (!res.ok)
|
|
217
|
+
return { status: "error", error: `Usage request failed (HTTP ${res.status}).`, metrics: [] };
|
|
218
|
+
let body;
|
|
219
|
+
try {
|
|
220
|
+
body = await res.json();
|
|
221
|
+
}
|
|
222
|
+
catch {
|
|
223
|
+
return { status: "error", error: "Invalid response from usage endpoint.", metrics: [] };
|
|
224
|
+
}
|
|
225
|
+
const nowMs = Date.now();
|
|
226
|
+
const metrics = codexWindows(body.rate_limit, {
|
|
227
|
+
session: "Session", weekly: "Weekly", monthly: "Monthly", other: d => `${d}-day window`,
|
|
228
|
+
}, nowMs);
|
|
229
|
+
// Model-specific limits (e.g. Spark) ride in additional_rate_limits, same window shape.
|
|
230
|
+
for (const entry of Array.isArray(body.additional_rate_limits) ? body.additional_rate_limits : []) {
|
|
231
|
+
const e = entry;
|
|
232
|
+
if (!e || typeof e !== "object" || !e.rate_limit)
|
|
233
|
+
continue;
|
|
234
|
+
const rawName = e.limit_name || e.metered_feature || "Model limit";
|
|
235
|
+
metrics.push(...codexWindows(e.rate_limit, {
|
|
236
|
+
session: rawName, weekly: `${rawName} (weekly)`, monthly: `${rawName} (monthly)`, other: d => `${rawName} (${d}d)`,
|
|
237
|
+
}, nowMs));
|
|
238
|
+
}
|
|
239
|
+
const resets = body.rate_limit_reset_credits;
|
|
240
|
+
if (typeof resets?.available_count === "number" && resets.available_count >= 0) {
|
|
241
|
+
metrics.push({ label: "Rate limit resets", type: "count", value: Math.floor(resets.available_count), unit: "available" });
|
|
242
|
+
}
|
|
243
|
+
const credits = body.credits;
|
|
244
|
+
let remaining = null;
|
|
245
|
+
if (typeof credits?.balance === "number")
|
|
246
|
+
remaining = credits.balance;
|
|
247
|
+
else if (credits?.has_credits === false)
|
|
248
|
+
remaining = 0;
|
|
249
|
+
if (remaining !== null) {
|
|
250
|
+
const count = Math.max(0, Math.floor(remaining));
|
|
251
|
+
metrics.push({ label: "Credits", type: "count", value: count, unit: "credits", note: `≈ $${(count * CREDIT_USD_RATE).toFixed(2)}` });
|
|
252
|
+
}
|
|
253
|
+
return { status: "ok", plan: codexPlan(body.plan_type), metrics };
|
|
254
|
+
}
|
|
255
|
+
// ── Grok ─────────────────────────────────────────────────────────────────────
|
|
256
|
+
const GROK_CREDITS_URL = "https://cli-chat-proxy.grok.com/v1/billing?format=credits";
|
|
257
|
+
const GROK_SETTINGS_URL = "https://cli-chat-proxy.grok.com/v1/settings";
|
|
258
|
+
const GROK_REFRESH_URL = "https://auth.x.ai/oauth2/token";
|
|
259
|
+
const GROK_DEFAULT_CLIENT_ID = "b1a00492-073a-47ea-816f-4c329264a828";
|
|
260
|
+
const GROK_WEEKLY_PERIOD = "USAGE_PERIOD_TYPE_WEEKLY";
|
|
261
|
+
const GROK_REFRESH_BUFFER_MS = 5 * 60 * 1000;
|
|
262
|
+
function grokEntryExpiryMs(entry, token) {
|
|
263
|
+
const fromJwt = jwtExpiryMs(token);
|
|
264
|
+
if (fromJwt)
|
|
265
|
+
return fromJwt;
|
|
266
|
+
const raw = entry.expires_at || entry.expires;
|
|
267
|
+
if (typeof raw === "string") {
|
|
268
|
+
const ms = new Date(raw).getTime();
|
|
269
|
+
if (!Number.isNaN(ms))
|
|
270
|
+
return ms;
|
|
271
|
+
}
|
|
272
|
+
return null;
|
|
273
|
+
}
|
|
274
|
+
async function grokRefreshAndPersist(file, auth, entryKey, entry) {
|
|
275
|
+
// Refuse to refresh unless the rotated tokens can be written back — a rotated
|
|
276
|
+
// refresh token that only lives in our memory would break `grok` itself.
|
|
277
|
+
try {
|
|
278
|
+
await access(file, constants.W_OK);
|
|
279
|
+
}
|
|
280
|
+
catch {
|
|
281
|
+
return { error: "Token expired and auth.json is read-only. Run `grok` once to refresh it." };
|
|
282
|
+
}
|
|
283
|
+
const refreshToken = (entry.refresh_token || entry.refresh || "").trim();
|
|
284
|
+
if (!refreshToken)
|
|
285
|
+
return { error: "Token expired and no refresh token found. Run `grok login`." };
|
|
286
|
+
const clientId = entry.oidc_client_id?.trim()
|
|
287
|
+
|| entryKey.split("::").pop()?.trim()
|
|
288
|
+
|| GROK_DEFAULT_CLIENT_ID;
|
|
289
|
+
let res;
|
|
290
|
+
try {
|
|
291
|
+
res = await fetch(GROK_REFRESH_URL, {
|
|
292
|
+
method: "POST",
|
|
293
|
+
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
|
294
|
+
body: new URLSearchParams({ grant_type: "refresh_token", client_id: clientId, refresh_token: refreshToken }),
|
|
295
|
+
signal: AbortSignal.timeout(15_000),
|
|
296
|
+
});
|
|
297
|
+
}
|
|
298
|
+
catch {
|
|
299
|
+
return { error: "Could not reach auth.x.ai to refresh the token." };
|
|
300
|
+
}
|
|
301
|
+
if (!res.ok)
|
|
302
|
+
return { error: "Grok session expired. Run `grok login` again." };
|
|
303
|
+
let body;
|
|
304
|
+
try {
|
|
305
|
+
body = await res.json();
|
|
306
|
+
}
|
|
307
|
+
catch {
|
|
308
|
+
return { error: "Invalid refresh response from auth.x.ai." };
|
|
309
|
+
}
|
|
310
|
+
if (!body.access_token)
|
|
311
|
+
return { error: "Grok session expired. Run `grok login` again." };
|
|
312
|
+
// Update only this entry's fields, preserving everything else in the file
|
|
313
|
+
// (other accounts' entries included).
|
|
314
|
+
const updated = { ...(auth[entryKey] ?? {}) };
|
|
315
|
+
updated.key = body.access_token;
|
|
316
|
+
if (body.refresh_token)
|
|
317
|
+
updated.refresh_token = body.refresh_token;
|
|
318
|
+
if (body.id_token)
|
|
319
|
+
updated.id_token = body.id_token;
|
|
320
|
+
if (typeof body.expires_in === "number")
|
|
321
|
+
updated.expires_at = new Date(Date.now() + body.expires_in * 1000).toISOString();
|
|
322
|
+
try {
|
|
323
|
+
await writeFile(file, JSON.stringify({ ...auth, [entryKey]: updated }, null, 2));
|
|
324
|
+
}
|
|
325
|
+
catch {
|
|
326
|
+
return { error: "Refreshed but could not write auth.json — refusing to continue without persisting. Run `grok` once instead." };
|
|
327
|
+
}
|
|
328
|
+
return { token: body.access_token };
|
|
329
|
+
}
|
|
330
|
+
function grokHeaders(token) {
|
|
331
|
+
return {
|
|
332
|
+
Authorization: `Bearer ${token.trim()}`,
|
|
333
|
+
"X-XAI-Token-Auth": "xai-grok-cli",
|
|
334
|
+
Accept: "application/json",
|
|
335
|
+
"User-Agent": "agend-usage",
|
|
336
|
+
};
|
|
337
|
+
}
|
|
338
|
+
async function fetchGrokUsage() {
|
|
339
|
+
const home = process.env.GROK_HOME || join(homedir(), ".grok");
|
|
340
|
+
const file = join(home, "auth.json");
|
|
341
|
+
let auth;
|
|
342
|
+
try {
|
|
343
|
+
auth = JSON.parse(await readFile(file, "utf8"));
|
|
344
|
+
}
|
|
345
|
+
catch {
|
|
346
|
+
return { status: "no-credentials", hint: "Log in with the Grok CLI (`grok login`).", metrics: [] };
|
|
347
|
+
}
|
|
348
|
+
const entries = Object.entries(auth).filter(([, e]) => typeof e?.key === "string" && e.key.trim());
|
|
349
|
+
if (!entries.length)
|
|
350
|
+
return { status: "no-credentials", hint: "auth.json has no usable login. Run `grok login`.", metrics: [] };
|
|
351
|
+
const [entryKey, entry] = entries[0];
|
|
352
|
+
let token = entry.key.trim();
|
|
353
|
+
const expiry = grokEntryExpiryMs(entry, token);
|
|
354
|
+
if (expiry && expiry - Date.now() <= GROK_REFRESH_BUFFER_MS) {
|
|
355
|
+
const refreshed = await grokRefreshAndPersist(file, auth, entryKey, entry);
|
|
356
|
+
if (refreshed.error)
|
|
357
|
+
return { status: "error", error: refreshed.error, metrics: [] };
|
|
358
|
+
token = refreshed.token;
|
|
359
|
+
}
|
|
360
|
+
const fetchBoth = async (tok) => {
|
|
361
|
+
const [credits, settings] = await Promise.all([
|
|
362
|
+
fetch(GROK_CREDITS_URL, { headers: grokHeaders(tok), signal: AbortSignal.timeout(10_000) }),
|
|
363
|
+
fetch(GROK_SETTINGS_URL, { headers: grokHeaders(tok), signal: AbortSignal.timeout(10_000) }).catch(() => null),
|
|
364
|
+
]);
|
|
365
|
+
return { credits, settings };
|
|
366
|
+
};
|
|
367
|
+
let credits, settings;
|
|
368
|
+
try {
|
|
369
|
+
({ credits, settings } = await fetchBoth(token));
|
|
370
|
+
if (credits.status === 401 || credits.status === 403) {
|
|
371
|
+
const refreshed = await grokRefreshAndPersist(file, auth, entryKey, entry);
|
|
372
|
+
if (refreshed.error)
|
|
373
|
+
return { status: "error", error: refreshed.error, metrics: [] };
|
|
374
|
+
token = refreshed.token;
|
|
375
|
+
({ credits, settings } = await fetchBoth(token));
|
|
376
|
+
}
|
|
377
|
+
}
|
|
378
|
+
catch {
|
|
379
|
+
return { status: "error", error: "Could not reach cli-chat-proxy.grok.com.", metrics: [] };
|
|
380
|
+
}
|
|
381
|
+
if (credits.status === 401 || credits.status === 403) {
|
|
382
|
+
return { status: "error", error: "Grok session expired. Run `grok login` again.", metrics: [] };
|
|
383
|
+
}
|
|
384
|
+
if (!credits.ok)
|
|
385
|
+
return { status: "error", error: `Billing request failed (HTTP ${credits.status}).`, metrics: [] };
|
|
386
|
+
let body;
|
|
387
|
+
try {
|
|
388
|
+
body = await credits.json();
|
|
389
|
+
}
|
|
390
|
+
catch {
|
|
391
|
+
return { status: "error", error: "Invalid response from billing endpoint.", metrics: [] };
|
|
392
|
+
}
|
|
393
|
+
const config = body?.config;
|
|
394
|
+
const period = config?.currentPeriod;
|
|
395
|
+
if (!config || !period?.type)
|
|
396
|
+
return { status: "error", error: "Grok billing response changed.", metrics: [] };
|
|
397
|
+
const metrics = [];
|
|
398
|
+
if (period.type === GROK_WEEKLY_PERIOD) {
|
|
399
|
+
// proto-JSON drops zero-valued fields: an absent creditUsagePercent means 0%.
|
|
400
|
+
const pct = typeof config.creditUsagePercent === "number" ? config.creditUsagePercent : 0;
|
|
401
|
+
const start = new Date(period.start ?? "").getTime();
|
|
402
|
+
const end = new Date(period.end ?? "").getTime();
|
|
403
|
+
metrics.push({
|
|
404
|
+
label: "Weekly limit",
|
|
405
|
+
type: "percent",
|
|
406
|
+
used: Math.min(100, Math.max(0, pct)),
|
|
407
|
+
resetsAt: Number.isNaN(end) ? null : new Date(end).toISOString(),
|
|
408
|
+
windowMs: Number.isNaN(end - start) ? null : end - start,
|
|
409
|
+
});
|
|
410
|
+
}
|
|
411
|
+
const cap = typeof config.onDemandCap?.val === "number" ? config.onDemandCap.val : 0;
|
|
412
|
+
metrics.push({ label: "Pay as you go", type: "text", value: cap > 0 ? `${cap} cap` : "Disabled" });
|
|
413
|
+
let plan = null;
|
|
414
|
+
if (settings?.ok) {
|
|
415
|
+
try {
|
|
416
|
+
const s = await settings.json();
|
|
417
|
+
if (typeof s.subscription_tier_display === "string" && s.subscription_tier_display.trim()) {
|
|
418
|
+
plan = s.subscription_tier_display.trim();
|
|
419
|
+
}
|
|
420
|
+
}
|
|
421
|
+
catch { /* plan is optional */ }
|
|
422
|
+
}
|
|
423
|
+
return { status: "ok", plan, metrics };
|
|
424
|
+
}
|
|
425
|
+
// ── Registry ─────────────────────────────────────────────────────────────────
|
|
426
|
+
const PROVIDERS = [
|
|
427
|
+
{ id: "claude", name: "Claude", fetch: fetchClaudeUsage },
|
|
428
|
+
{ id: "codex", name: "Codex", fetch: fetchCodexUsage },
|
|
429
|
+
{ id: "grok", name: "Grok", fetch: fetchGrokUsage },
|
|
430
|
+
];
|
|
431
|
+
/** Fetch every provider in parallel. Providers without local credentials are
|
|
432
|
+
* skipped (per the panel's contract: absent CLIs simply don't show). */
|
|
433
|
+
export async function fetchAllUsage() {
|
|
434
|
+
const results = await Promise.all(PROVIDERS.map(async (p) => {
|
|
435
|
+
try {
|
|
436
|
+
return { id: p.id, name: p.name, ...(await p.fetch()) };
|
|
437
|
+
}
|
|
438
|
+
catch (err) {
|
|
439
|
+
return { id: p.id, name: p.name, status: "error", error: String(err?.message ?? err), metrics: [] };
|
|
440
|
+
}
|
|
441
|
+
}));
|
|
442
|
+
return {
|
|
443
|
+
fetchedAt: new Date().toISOString(),
|
|
444
|
+
providers: results.filter(r => r.status !== "no-credentials"),
|
|
445
|
+
};
|
|
446
|
+
}
|
|
447
|
+
//# sourceMappingURL=providers.js.map
|