pi-usage-hub 1.0.0
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/.github/workflows/publish.yml +23 -0
- package/LICENSE +21 -0
- package/README.md +171 -0
- package/assets/usage-hub-footer.png +0 -0
- package/assets/usage-hub-panel.png +0 -0
- package/core/cache.ts +86 -0
- package/core/config.ts +152 -0
- package/core/registry.ts +73 -0
- package/examples/auth-providers.ts +42 -0
- package/index.ts +197 -0
- package/package.json +30 -0
- package/providers/ark.ts +154 -0
- package/providers/deepseek.ts +51 -0
- package/providers/kiro.ts +289 -0
- package/providers/newapi.ts +74 -0
- package/providers/opencode-go.ts +115 -0
- package/providers/xai.ts +311 -0
- package/session/collect.ts +275 -0
- package/types.ts +94 -0
- package/ui/format-report.ts +67 -0
- package/ui/format.ts +92 -0
- package/ui/session-panel.ts +178 -0
- package/ui/usage-window.ts +132 -0
- package/utils/chrome-cookies.ts +96 -0
- package/utils/duration.ts +17 -0
package/index.ts
ADDED
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import type { UsageHub, UsageProvider } from "./types";
|
|
3
|
+
import { loadConfig } from "./core/config";
|
|
4
|
+
import { ProviderRegistry } from "./core/registry";
|
|
5
|
+
import { UsageCache } from "./core/cache";
|
|
6
|
+
import { fullReport } from "./ui/format-report";
|
|
7
|
+
import { UsageWindow } from "./ui/usage-window";
|
|
8
|
+
import { isCloseKey } from "./ui/format";
|
|
9
|
+
|
|
10
|
+
export default function register(pi: ExtensionAPI) {
|
|
11
|
+
const registry = new ProviderRegistry();
|
|
12
|
+
const cache = new UsageCache();
|
|
13
|
+
|
|
14
|
+
// Cache updates → event bus (no public subscribe)
|
|
15
|
+
cache.subscribe((e) => {
|
|
16
|
+
pi.events.emit("pi-usage-hub:updated", e);
|
|
17
|
+
});
|
|
18
|
+
|
|
19
|
+
const cfg = loadConfig();
|
|
20
|
+
registry.loadFromConfig(cfg.providers ?? []);
|
|
21
|
+
|
|
22
|
+
const hub: UsageHub = {
|
|
23
|
+
register(p) {
|
|
24
|
+
registry.register(p);
|
|
25
|
+
},
|
|
26
|
+
unregister(key) {
|
|
27
|
+
registry.unregister(key);
|
|
28
|
+
cache.invalidate(key);
|
|
29
|
+
},
|
|
30
|
+
list() {
|
|
31
|
+
return registry.list();
|
|
32
|
+
},
|
|
33
|
+
getSummary(model) {
|
|
34
|
+
const provider = registry.matchModel(model);
|
|
35
|
+
if (!provider) return null;
|
|
36
|
+
return cache.getSummary(provider.key);
|
|
37
|
+
},
|
|
38
|
+
getReport(key) {
|
|
39
|
+
return cache.getReport(key);
|
|
40
|
+
},
|
|
41
|
+
async refresh(opts) {
|
|
42
|
+
const provider = registry.matchModel(opts?.model);
|
|
43
|
+
if (!provider) return null;
|
|
44
|
+
const entry = await cache.refreshProvider(provider, opts?.force ?? false);
|
|
45
|
+
return entry.summary;
|
|
46
|
+
},
|
|
47
|
+
invalidate(key) {
|
|
48
|
+
cache.invalidate(key);
|
|
49
|
+
},
|
|
50
|
+
};
|
|
51
|
+
|
|
52
|
+
const offRegister = pi.events.on("pi-usage-hub:register", (p: UsageProvider) => {
|
|
53
|
+
if (p && typeof p === "object" && typeof (p as UsageProvider).key === "string") {
|
|
54
|
+
hub.register(p as UsageProvider);
|
|
55
|
+
}
|
|
56
|
+
});
|
|
57
|
+
const offUnregister = pi.events.on("pi-usage-hub:unregister", (data: { key?: string }) => {
|
|
58
|
+
if (data?.key) hub.unregister(data.key);
|
|
59
|
+
});
|
|
60
|
+
|
|
61
|
+
// Emit now and again on session_start so late listeners (footer-hub) still get the hub.
|
|
62
|
+
pi.events.emit("pi-usage-hub:ready", hub);
|
|
63
|
+
pi.on("session_start", async () => {
|
|
64
|
+
pi.events.emit("pi-usage-hub:ready", hub);
|
|
65
|
+
});
|
|
66
|
+
|
|
67
|
+
pi.on("session_shutdown", async () => {
|
|
68
|
+
offRegister();
|
|
69
|
+
offUnregister();
|
|
70
|
+
});
|
|
71
|
+
|
|
72
|
+
pi.registerCommand("usage-hub", {
|
|
73
|
+
description: "Show usage/quota. /usage-hub session · /usage-hub login <provider>",
|
|
74
|
+
handler: async (_args, ctx) => {
|
|
75
|
+
const args = _args.trim();
|
|
76
|
+
|
|
77
|
+
if (args.startsWith("login")) {
|
|
78
|
+
const target = args.slice(5).trim().toLowerCase();
|
|
79
|
+
const all = registry.list();
|
|
80
|
+
const loginable = all.filter(p => p.login);
|
|
81
|
+
|
|
82
|
+
if (!target) {
|
|
83
|
+
ctx.ui.notify(
|
|
84
|
+
`Usage: /usage-hub login <provider>. Try: ${loginable.map(p => p.key).join(", ") || "(none)"}`,
|
|
85
|
+
"warning",
|
|
86
|
+
);
|
|
87
|
+
return;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
const targets = all.filter(
|
|
91
|
+
p => p.login && (p.key === target || p.matchProviders?.includes(target)),
|
|
92
|
+
);
|
|
93
|
+
|
|
94
|
+
if (targets.length === 0) {
|
|
95
|
+
ctx.ui.notify(
|
|
96
|
+
`Unknown provider "${target}". Try: ${loginable.map(p => p.key).join(", ") || "(none)"}`,
|
|
97
|
+
"warning",
|
|
98
|
+
);
|
|
99
|
+
return;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
for (const p of targets) {
|
|
103
|
+
ctx.ui.notify(`Opening browser for ${p.label}…`, "info");
|
|
104
|
+
const ok = await p.login!();
|
|
105
|
+
if (ok) {
|
|
106
|
+
cache.invalidate(p.key);
|
|
107
|
+
ctx.ui.notify(`${p.label} login succeeded`, "info");
|
|
108
|
+
} else {
|
|
109
|
+
ctx.ui.notify(`${p.label} login timeout`, "warning");
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
await Promise.all(
|
|
114
|
+
registry.detectActive().map(p => cache.refreshProvider(p, true)),
|
|
115
|
+
);
|
|
116
|
+
return;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
if (ctx.mode !== "tui") {
|
|
120
|
+
ctx.ui.notify("Fetching usage data…", "info");
|
|
121
|
+
const detected = registry.detectActive();
|
|
122
|
+
if (detected.length === 0) {
|
|
123
|
+
ctx.ui.notify("No supported usage provider detected", "info");
|
|
124
|
+
return;
|
|
125
|
+
}
|
|
126
|
+
const reports = await Promise.all(
|
|
127
|
+
detected.map(async provider => {
|
|
128
|
+
const entry = await cache.refreshProvider(provider, true);
|
|
129
|
+
return { provider, report: entry.report };
|
|
130
|
+
}),
|
|
131
|
+
);
|
|
132
|
+
const lines = reports.map(r => fullReport(r.report, r.provider));
|
|
133
|
+
ctx.ui.notify(lines.join("\n\n"), "info");
|
|
134
|
+
return;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
const initialMode = args === "session" ? "session" : "quota";
|
|
138
|
+
|
|
139
|
+
let handle: { focus: () => void; isFocused: () => boolean } | undefined;
|
|
140
|
+
await ctx.ui.custom<void>((tui, theme, _kb, done) => {
|
|
141
|
+
const unsubscribeInput = ctx.ui.onTerminalInput((data) => {
|
|
142
|
+
if (!isCloseKey(data) || handle?.isFocused()) return;
|
|
143
|
+
handle?.focus();
|
|
144
|
+
return { data };
|
|
145
|
+
});
|
|
146
|
+
let quotaStarted = false;
|
|
147
|
+
let panel: UsageWindow;
|
|
148
|
+
|
|
149
|
+
const loadQuota = () => {
|
|
150
|
+
if (quotaStarted) return;
|
|
151
|
+
quotaStarted = true;
|
|
152
|
+
|
|
153
|
+
const detected = registry.detectActive();
|
|
154
|
+
if (detected.length === 0) {
|
|
155
|
+
panel.finishLoading();
|
|
156
|
+
tui.requestRender();
|
|
157
|
+
return;
|
|
158
|
+
}
|
|
159
|
+
panel.setPendingProviders(detected);
|
|
160
|
+
tui.requestRender();
|
|
161
|
+
|
|
162
|
+
void Promise.all(detected.map(async provider => {
|
|
163
|
+
const entry = await cache.refreshProvider(provider, true);
|
|
164
|
+
panel.addReport(provider, entry.report);
|
|
165
|
+
tui.requestRender();
|
|
166
|
+
})).then(() => {
|
|
167
|
+
panel.finishLoading();
|
|
168
|
+
tui.requestRender();
|
|
169
|
+
});
|
|
170
|
+
};
|
|
171
|
+
|
|
172
|
+
panel = new UsageWindow(
|
|
173
|
+
theme,
|
|
174
|
+
done,
|
|
175
|
+
() => tui.requestRender(),
|
|
176
|
+
unsubscribeInput,
|
|
177
|
+
initialMode,
|
|
178
|
+
loadQuota,
|
|
179
|
+
);
|
|
180
|
+
if (initialMode === "quota") loadQuota();
|
|
181
|
+
return panel;
|
|
182
|
+
}, {
|
|
183
|
+
overlay: true,
|
|
184
|
+
overlayOptions: {
|
|
185
|
+
width: "80%",
|
|
186
|
+
minWidth: 74,
|
|
187
|
+
maxWidth: 96,
|
|
188
|
+
maxHeight: "80%",
|
|
189
|
+
anchor: "center",
|
|
190
|
+
},
|
|
191
|
+
onHandle: overlayHandle => {
|
|
192
|
+
handle = overlayHandle;
|
|
193
|
+
},
|
|
194
|
+
});
|
|
195
|
+
},
|
|
196
|
+
});
|
|
197
|
+
}
|
package/package.json
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "pi-usage-hub",
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "Usage hub for pi — provider quota/balance registry with cache, /usage-hub panel, and pull API",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"pi",
|
|
7
|
+
"pi-package",
|
|
8
|
+
"pi-extension",
|
|
9
|
+
"usage",
|
|
10
|
+
"quota"
|
|
11
|
+
],
|
|
12
|
+
"license": "MIT",
|
|
13
|
+
"author": "ouzhenkun",
|
|
14
|
+
"repository": {
|
|
15
|
+
"type": "git",
|
|
16
|
+
"url": "https://github.com/ouzhenkun/pi-usage-hub.git"
|
|
17
|
+
},
|
|
18
|
+
"homepage": "https://github.com/ouzhenkun/pi-usage-hub",
|
|
19
|
+
"bugs": {
|
|
20
|
+
"url": "https://github.com/ouzhenkun/pi-usage-hub/issues"
|
|
21
|
+
},
|
|
22
|
+
"peerDependencies": {
|
|
23
|
+
"@earendil-works/pi-coding-agent": "*"
|
|
24
|
+
},
|
|
25
|
+
"pi": {
|
|
26
|
+
"extensions": [
|
|
27
|
+
"./index.ts"
|
|
28
|
+
]
|
|
29
|
+
}
|
|
30
|
+
}
|
package/providers/ark.ts
ADDED
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
import { execFile } from "node:child_process";
|
|
2
|
+
import type { ArkConfig, UsageProvider, UsageReport } from "../types";
|
|
3
|
+
import { readChromeCookies } from "../utils/chrome-cookies";
|
|
4
|
+
import { formatDurationSeconds } from "../utils/duration";
|
|
5
|
+
|
|
6
|
+
const COOKIE_DOMAINS = ["console.volcengine.com", ".volcengine.com"];
|
|
7
|
+
const API_URL =
|
|
8
|
+
"https://console.volcengine.com/api/top/ark/cn-beijing/2024-01-01/GetCodingPlanUsage?";
|
|
9
|
+
const FETCH_TIMEOUT_MS = 15_000;
|
|
10
|
+
|
|
11
|
+
function parseCookieHeader(header: string): Record<string, string> {
|
|
12
|
+
const map: Record<string, string> = {};
|
|
13
|
+
for (const part of header.split(";")) {
|
|
14
|
+
const idx = part.indexOf("=");
|
|
15
|
+
if (idx <= 0) continue;
|
|
16
|
+
const name = part.slice(0, idx).trim();
|
|
17
|
+
const value = part.slice(idx + 1).trim();
|
|
18
|
+
if (name) map[name] = value;
|
|
19
|
+
}
|
|
20
|
+
return map;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function chromeCookies(): Record<string, string> {
|
|
24
|
+
if (process.platform !== "darwin") return {};
|
|
25
|
+
const cookies = readChromeCookies("%volcengine%", COOKIE_DOMAINS);
|
|
26
|
+
const map: Record<string, string> = {};
|
|
27
|
+
for (const c of cookies) map[c.name] = c.value;
|
|
28
|
+
return map;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function resolveCookies(cfg: ArkConfig): { cookieHeader: string; csrf: string; digest?: string } | null {
|
|
32
|
+
if (cfg.cookie?.trim()) {
|
|
33
|
+
const map = parseCookieHeader(cfg.cookie);
|
|
34
|
+
const cookieHeader = cfg.cookie.trim();
|
|
35
|
+
const csrf = cfg.csrfToken?.trim() || map.csrfToken || "";
|
|
36
|
+
return { cookieHeader, csrf, digest: map.digest };
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
const map = chromeCookies();
|
|
40
|
+
if (!map.userInfo && !map.digest) return null;
|
|
41
|
+
const cookieHeader = Object.entries(map).map(([k, v]) => `${k}=${v}`).join("; ");
|
|
42
|
+
return { cookieHeader, csrf: cfg.csrfToken?.trim() || map.csrfToken || "", digest: map.digest };
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
async function callApi(cookieHeader: string, csrf: string): Promise<UsageReport> {
|
|
46
|
+
const controller = new AbortController();
|
|
47
|
+
const timer = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
|
|
48
|
+
|
|
49
|
+
try {
|
|
50
|
+
const res = await fetch(API_URL, {
|
|
51
|
+
method: "POST",
|
|
52
|
+
headers: {
|
|
53
|
+
accept: "application/json, text/plain, */*",
|
|
54
|
+
"content-type": "application/json",
|
|
55
|
+
cookie: cookieHeader,
|
|
56
|
+
origin: "https://console.volcengine.com",
|
|
57
|
+
referer: "https://console.volcengine.com/ark/region:ark+cn-beijing/openManagement",
|
|
58
|
+
"user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/149.0.0.0 Safari/537.36",
|
|
59
|
+
"x-csrf-token": csrf,
|
|
60
|
+
},
|
|
61
|
+
body: "{}",
|
|
62
|
+
signal: controller.signal,
|
|
63
|
+
});
|
|
64
|
+
|
|
65
|
+
if (!res.ok) return { error: `HTTP ${res.status}` };
|
|
66
|
+
|
|
67
|
+
const body: any = await res.json();
|
|
68
|
+
const err = body?.ResponseMetadata?.Error;
|
|
69
|
+
if (err) return { error: err.Message ?? err.Code };
|
|
70
|
+
|
|
71
|
+
return parseQuota(body);
|
|
72
|
+
} catch (err: any) {
|
|
73
|
+
if (err?.name === "AbortError") return { error: "timeout" };
|
|
74
|
+
return { error: err?.message ?? String(err) };
|
|
75
|
+
} finally {
|
|
76
|
+
clearTimeout(timer);
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
interface QuotaEntry {
|
|
81
|
+
Level: string;
|
|
82
|
+
Percent: number;
|
|
83
|
+
ResetTimestamp: number;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
function parseQuota(raw: any): UsageReport {
|
|
87
|
+
const entries: QuotaEntry[] = raw?.Result?.QuotaUsage ?? [];
|
|
88
|
+
if (entries.length === 0) return { error: "no QuotaUsage entries" };
|
|
89
|
+
|
|
90
|
+
const report: UsageReport = {};
|
|
91
|
+
const now = Date.now() / 1000;
|
|
92
|
+
|
|
93
|
+
for (const q of entries) {
|
|
94
|
+
const resetSec = Math.max(0, q.ResetTimestamp - now);
|
|
95
|
+
const data = { pct: q.Percent, resetsIn: formatDurationSeconds(resetSec) };
|
|
96
|
+
if (q.Level === "session") report.session = data;
|
|
97
|
+
else if (q.Level === "weekly") report.weekly = data;
|
|
98
|
+
else if (q.Level === "monthly") report.monthly = data;
|
|
99
|
+
}
|
|
100
|
+
return report;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
export function makeArkProvider(name: string, cfg: ArkConfig = {}): UsageProvider {
|
|
104
|
+
const manual = !!cfg.cookie?.trim();
|
|
105
|
+
|
|
106
|
+
return {
|
|
107
|
+
key: name,
|
|
108
|
+
matchProviders: cfg.matchProviders ?? [name, "ark"],
|
|
109
|
+
shortLabel: cfg.shortLabel ?? "ARK",
|
|
110
|
+
label: cfg.label ?? "ARK Coding",
|
|
111
|
+
detect: () => resolveCookies(cfg) !== null,
|
|
112
|
+
|
|
113
|
+
fetchUsage: async (): Promise<UsageReport> => {
|
|
114
|
+
const auth = resolveCookies(cfg);
|
|
115
|
+
if (!auth) {
|
|
116
|
+
return {
|
|
117
|
+
error: manual
|
|
118
|
+
? "invalid cookie in config"
|
|
119
|
+
: "not logged in — set cookie in config or /usage-hub login ark",
|
|
120
|
+
};
|
|
121
|
+
}
|
|
122
|
+
const result = await callApi(auth.cookieHeader, auth.csrf);
|
|
123
|
+
if (result.error === "HTTP 401" || result.error === "HTTP 403") {
|
|
124
|
+
return {
|
|
125
|
+
error: manual
|
|
126
|
+
? "session expired — refresh cookie in config"
|
|
127
|
+
: "session expired — run /usage-hub login ark",
|
|
128
|
+
};
|
|
129
|
+
}
|
|
130
|
+
return result;
|
|
131
|
+
},
|
|
132
|
+
|
|
133
|
+
login: manual
|
|
134
|
+
? undefined
|
|
135
|
+
: async (): Promise<boolean> => {
|
|
136
|
+
const oldDigest = resolveCookies(cfg)?.digest;
|
|
137
|
+
execFile("open", ["-a", "Google Chrome",
|
|
138
|
+
"https://console.volcengine.com/ark/region:ark+cn-beijing/openManagement?LLM=%7B%7D&advancedActiveKey=subscribe",
|
|
139
|
+
]);
|
|
140
|
+
const deadline = Date.now() + 300_000;
|
|
141
|
+
while (Date.now() < deadline) {
|
|
142
|
+
await new Promise(r => setTimeout(r, 2000));
|
|
143
|
+
const cur = resolveCookies(cfg)?.digest;
|
|
144
|
+
if (cur && cur !== oldDigest) return true;
|
|
145
|
+
if (!oldDigest && resolveCookies(cfg)) {
|
|
146
|
+
const auth = resolveCookies(cfg)!;
|
|
147
|
+
const probe = await callApi(auth.cookieHeader, auth.csrf);
|
|
148
|
+
if (!probe.error) return true;
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
return false;
|
|
152
|
+
},
|
|
153
|
+
};
|
|
154
|
+
}
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import type { DeepseekConfig, UsageProvider, UsageReport } from "../types";
|
|
2
|
+
|
|
3
|
+
const API_URL = "https://api.deepseek.com/user/balance";
|
|
4
|
+
const FETCH_TIMEOUT_MS = 10_000;
|
|
5
|
+
|
|
6
|
+
export function makeDeepseekProvider(name: string, cfg: DeepseekConfig): UsageProvider {
|
|
7
|
+
const apiKey = cfg.apiKey;
|
|
8
|
+
return {
|
|
9
|
+
key: name,
|
|
10
|
+
matchProviders: cfg.matchProviders ?? [name, "deepseek"],
|
|
11
|
+
shortLabel: cfg.shortLabel ?? "DS",
|
|
12
|
+
label: cfg.label ?? "DeepSeek",
|
|
13
|
+
detect: () => !!apiKey,
|
|
14
|
+
|
|
15
|
+
fetchUsage: async (): Promise<UsageReport> => {
|
|
16
|
+
if (!apiKey) return { error: "no API key configured" };
|
|
17
|
+
|
|
18
|
+
const controller = new AbortController();
|
|
19
|
+
const timer = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
|
|
20
|
+
|
|
21
|
+
try {
|
|
22
|
+
const res = await fetch(API_URL, {
|
|
23
|
+
headers: {
|
|
24
|
+
Accept: "application/json",
|
|
25
|
+
Authorization: `Bearer ${apiKey}`,
|
|
26
|
+
},
|
|
27
|
+
signal: controller.signal,
|
|
28
|
+
});
|
|
29
|
+
|
|
30
|
+
if (!res.ok) return { error: `HTTP ${res.status}` };
|
|
31
|
+
|
|
32
|
+
const body: any = await res.json();
|
|
33
|
+
const info = (body?.balance_infos ?? [{}])[0];
|
|
34
|
+
const balance = info?.total_balance ?? "0";
|
|
35
|
+
const currency = info?.currency ?? "CNY";
|
|
36
|
+
const available = body?.is_available;
|
|
37
|
+
|
|
38
|
+
if (!available) {
|
|
39
|
+
return { displayText: `\u26A0\uFE0F account unavailable` };
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
return { displayText: `\u00A5${balance} ${currency}` };
|
|
43
|
+
} catch (err: any) {
|
|
44
|
+
if (err?.name === "AbortError") return { error: "timeout" };
|
|
45
|
+
return { error: err?.message ?? String(err) };
|
|
46
|
+
} finally {
|
|
47
|
+
clearTimeout(timer);
|
|
48
|
+
}
|
|
49
|
+
},
|
|
50
|
+
};
|
|
51
|
+
}
|