pi-usage-hub 1.1.1 → 1.1.3

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.
@@ -11,13 +11,10 @@ jobs:
11
11
  contents: read
12
12
  id-token: write
13
13
  steps:
14
- - uses: actions/checkout@v4
15
-
16
- - uses: actions/setup-node@v4
14
+ - uses: actions/checkout@v6
15
+ - uses: actions/setup-node@v6
17
16
  with:
18
- node-version: 20
17
+ node-version: 24
19
18
  registry-url: https://registry.npmjs.org
20
-
21
- - run: npm publish --provenance --access public
22
- env:
23
- NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
19
+ package-manager-cache: false
20
+ - run: npm publish --access public
package/README.md CHANGED
@@ -84,7 +84,7 @@ Create `~/.pi/agent/pi-usage-hub.json`. Provider order is preserved in the panel
84
84
  |------|-------------|-------|---------|
85
85
  | `deepseek` | `apiKey` | Account balance | [deepseek](https://platform.deepseek.com) |
86
86
  | `newapi` | `host`, `token`, `userId` | Balance and today's spend; supports multiple instances | [newapi](https://www.newapi.ai) |
87
- | `opencode-go` | `workspaceId`; optional `auth` | Uses the configured auth cookie or macOS Chrome | [opencode](https://opencode.ai) |
87
+ | `opencode-go` | `workspaceId`; optional `auth` | Go plan five-hour/weekly/monthly spend; uses the configured console session cookie or macOS Chrome | [opencode](https://opencode.ai) |
88
88
  | `ark` | optional `cookie`, `csrfToken` | Uses the configured Cookie header or macOS Chrome | [火山引擎](https://console.volcengine.com/ark) |
89
89
  | `xai` | — | Reads `auth.json` or `~/.grok/auth.json` | [x.ai/grok](https://x.ai/grok) |
90
90
  | `kiro` | — | Reads the Kiro OAuth entry from `auth.json` | [kiro.dev](https://kiro.dev) |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-usage-hub",
3
- "version": "1.1.1",
3
+ "version": "1.1.3",
4
4
  "description": "Usage hub for pi — provider quota/balance registry with cache, /usage-hub panel, and pull API",
5
5
  "keywords": [
6
6
  "pi",
@@ -3,39 +3,37 @@ import type { OpencodeGoConfig, UsageProvider, UsageReport } from "../types";
3
3
  import { readChromeCookies } from "../utils/chrome-cookies";
4
4
  import { formatDurationSeconds } from "../utils/duration";
5
5
 
6
- const SCRAPED_NUMBER = "(-?\\d+(?:\\.\\d+)?)";
7
6
  const FETCH_TIMEOUT_MS = 10_000;
7
+ const SESSION_COOKIE = "__Host-console_session";
8
+ const STATUS_URL = "https://opencode.ai/console/api/go/status";
8
9
 
9
- function makeRe(key: string): RegExp[] {
10
- const pctFirst = new RegExp(`${key}:\\$R\\[\\d+\\]=\\{[^}]*usagePercent:${SCRAPED_NUMBER}[^}]*resetInSec:${SCRAPED_NUMBER}[^}]*\\}`);
11
- const resetFirst = new RegExp(`${key}:\\$R\\[\\d+\\]=\\{[^}]*resetInSec:${SCRAPED_NUMBER}[^}]*usagePercent:${SCRAPED_NUMBER}[^}]*\\}`);
12
- return [pctFirst, resetFirst];
13
- }
14
-
15
- function parseWindow(html: string, key: string): { pct: number; resetsInSec: number } | null {
16
- const [rePct, reReset] = makeRe(key);
17
- const m1 = rePct.exec(html);
18
- if (m1) {
19
- const pct = Number(m1[1]), sec = Number(m1[2]);
20
- if (Number.isFinite(pct) && Number.isFinite(sec)) return { pct, resetsInSec: sec };
21
- }
22
- const m2 = reReset.exec(html);
23
- if (m2) {
24
- const sec = Number(m2[1]), pct = Number(m2[2]);
25
- if (Number.isFinite(pct) && Number.isFinite(sec)) return { pct, resetsInSec: sec };
26
- }
27
- return null;
28
- }
10
+ type Meter = {
11
+ limitMicroCents?: string;
12
+ usedMicroCents?: string;
13
+ resetsAt?: string;
14
+ };
29
15
 
30
- function readChromeAuthCookie(): string | null {
16
+ function readChromeSessionCookie(): string | null {
31
17
  if (process.platform !== "darwin") return null;
32
18
  const cookies = readChromeCookies("%opencode.ai%", ["opencode.ai", ".opencode.ai"]);
33
- return cookies.find(c => c.name === "auth")?.value ?? null;
19
+ return cookies.find(c => c.name === SESSION_COOKIE)?.value ?? null;
34
20
  }
35
21
 
36
- function resolveAuth(cfg: OpencodeGoConfig): string | null {
22
+ function resolveSession(cfg: OpencodeGoConfig): string | null {
37
23
  if (cfg.auth?.trim()) return cfg.auth.trim();
38
- return readChromeAuthCookie();
24
+ return readChromeSessionCookie();
25
+ }
26
+
27
+ function toWindow(
28
+ meter: Meter | undefined,
29
+ fallbackResetsAt?: string,
30
+ ): { pct: number; resetsIn: string } | null {
31
+ const limit = Number(meter?.limitMicroCents);
32
+ const used = Number(meter?.usedMicroCents);
33
+ if (!Number.isFinite(limit) || limit <= 0 || !Number.isFinite(used)) return null;
34
+ const resetsAt = meter?.resetsAt ?? fallbackResetsAt;
35
+ const resetsInSec = resetsAt ? (Date.parse(resetsAt) - Date.now()) / 1000 : Number.NaN;
36
+ return { pct: (used / limit) * 100, resetsIn: formatDurationSeconds(resetsInSec) };
39
37
  }
40
38
 
41
39
  export function makeOpencodeGoProvider(name: string, cfg: OpencodeGoConfig): UsageProvider {
@@ -48,13 +46,13 @@ export function makeOpencodeGoProvider(name: string, cfg: OpencodeGoConfig): Usa
48
46
  shortLabel: cfg.shortLabel ?? "OCG",
49
47
  label: cfg.label ?? "OpenCode Go",
50
48
  hidden: cfg.hidden,
51
- detect: () => !!workspaceId && (!!resolveAuth(cfg) || !manual),
49
+ detect: () => !!workspaceId && (!!resolveSession(cfg) || !manual),
52
50
 
53
51
  fetchUsage: async (): Promise<UsageReport> => {
54
52
  if (!workspaceId) return { error: "no credentials configured" };
55
53
 
56
- const authCookie = resolveAuth(cfg);
57
- if (!authCookie) {
54
+ const session = resolveSession(cfg);
55
+ if (!session) {
58
56
  return {
59
57
  error: manual
60
58
  ? "invalid auth in config"
@@ -66,31 +64,38 @@ export function makeOpencodeGoProvider(name: string, cfg: OpencodeGoConfig): Usa
66
64
  const timer = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
67
65
 
68
66
  try {
69
- const res = await fetch(
70
- `https://opencode.ai/workspace/${encodeURIComponent(workspaceId)}/go`,
71
- {
72
- headers: {
73
- "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) Gecko/20100101 Firefox/148.0",
74
- Accept: "text/html",
75
- Cookie: `auth=${authCookie}`,
76
- },
77
- signal: controller.signal,
67
+ const res = await fetch(STATUS_URL, {
68
+ headers: {
69
+ "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) Gecko/20100101 Firefox/148.0",
70
+ Accept: "application/json",
71
+ "x-org-id": workspaceId,
72
+ Cookie: `${SESSION_COOKIE}=${session}`,
78
73
  },
79
- );
74
+ signal: controller.signal,
75
+ });
80
76
 
77
+ if (res.status === 401 || res.status === 403) {
78
+ return { error: "session expired — /usage-hub login ocg" };
79
+ }
81
80
  if (!res.ok) return { error: `HTTP ${res.status}` };
82
81
 
83
- const html = await res.text();
84
- const rolling = parseWindow(html, "rollingUsage");
85
- const weekly = parseWindow(html, "weeklyUsage");
86
- const monthly = parseWindow(html, "monthlyUsage");
82
+ let data: { access?: { endsAt?: string; meters?: Record<string, Meter> } };
83
+ try {
84
+ data = await res.json();
85
+ } catch {
86
+ return { error: "could not parse usage from response" };
87
+ }
87
88
 
88
- if (!rolling && !weekly && !monthly) return { error: "could not parse usage from dashboard" };
89
+ const meters = data?.access?.meters;
90
+ const fiveHour = toWindow(meters?.fiveHour);
91
+ const weekly = toWindow(meters?.week);
92
+ const monthly = toWindow(meters?.month, data?.access?.endsAt);
93
+ if (!fiveHour && !weekly && !monthly) return { error: "could not parse usage from response" };
89
94
 
90
95
  const report: UsageReport = {};
91
- if (rolling) report.session = { pct: rolling.pct, resetsIn: formatDurationSeconds(rolling.resetsInSec) };
92
- if (weekly) report.weekly = { pct: weekly.pct, resetsIn: formatDurationSeconds(weekly.resetsInSec) };
93
- if (monthly) report.monthly = { pct: monthly.pct, resetsIn: formatDurationSeconds(monthly.resetsInSec) };
96
+ if (fiveHour) report.session = fiveHour;
97
+ if (weekly) report.weekly = weekly;
98
+ if (monthly) report.monthly = monthly;
94
99
  return report;
95
100
  } catch (err: any) {
96
101
  if (err?.name === "AbortError") return { error: "timeout" };
@@ -104,11 +109,11 @@ export function makeOpencodeGoProvider(name: string, cfg: OpencodeGoConfig): Usa
104
109
  ? undefined
105
110
  : async (): Promise<boolean> => {
106
111
  if (!workspaceId) return false;
107
- execFile("open", ["-a", "Google Chrome", `https://opencode.ai/workspace/${workspaceId}/go`]);
112
+ execFile("open", ["-a", "Google Chrome", `https://opencode.ai/console/${workspaceId}/go`]);
108
113
  const deadline = Date.now() + 300_000;
109
114
  while (Date.now() < deadline) {
110
115
  await new Promise(r => setTimeout(r, 2000));
111
- if (readChromeAuthCookie()) return true;
116
+ if (readChromeSessionCookie()) return true;
112
117
  }
113
118
  return false;
114
119
  },
package/types.ts CHANGED
@@ -67,7 +67,7 @@ export interface ArkConfig extends ProviderMeta {
67
67
 
68
68
  export interface OpencodeGoConfig extends ProviderMeta {
69
69
  workspaceId: string;
70
- /** `auth` cookie value; if set, skips Chrome. */
70
+ /** OpenCode console session cookie value; if set, skips Chrome. */
71
71
  auth?: string;
72
72
  }
73
73