pi-usage-hub 1.1.3 → 1.1.5

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/core/cache.ts CHANGED
@@ -14,6 +14,7 @@ type Subscriber = (e: { key: string; summary: string | null }) => void;
14
14
  export class UsageCache {
15
15
  private entries = new Map<string, CacheEntry>();
16
16
  private inflight = new Map<string, Promise<CacheEntry>>();
17
+ private generation = new Map<string, number>();
17
18
  private subscribers = new Set<Subscriber>();
18
19
 
19
20
  constructor(private ttlMs = DEFAULT_TTL_MS) {}
@@ -28,13 +29,19 @@ export class UsageCache {
28
29
 
29
30
  invalidate(key?: string): void {
30
31
  if (key) {
31
- this.entries.delete(key);
32
- this.notify(key, null);
32
+ this.drop(key);
33
33
  return;
34
34
  }
35
- const keys = [...this.entries.keys()];
36
- this.entries.clear();
37
- for (const k of keys) this.notify(k, null);
35
+ const keys = new Set([...this.entries.keys(), ...this.inflight.keys()]);
36
+ for (const k of keys) this.drop(k);
37
+ }
38
+
39
+ /** Bump the generation so requests started before this point cannot repopulate the cache. */
40
+ private drop(key: string): void {
41
+ this.generation.set(key, (this.generation.get(key) ?? 0) + 1);
42
+ this.inflight.delete(key);
43
+ this.entries.delete(key);
44
+ this.notify(key, null);
38
45
  }
39
46
 
40
47
  subscribe(fn: Subscriber): () => void {
@@ -48,10 +55,13 @@ export class UsageCache {
48
55
  const hit = this.entries.get(provider.key);
49
56
  if (!force && hit && Date.now() - hit.fetchedAt < this.ttlMs) return hit;
50
57
 
51
- const existing = this.inflight.get(provider.key);
58
+ const key = provider.key;
59
+ const existing = this.inflight.get(key);
52
60
  if (existing) return existing;
53
61
 
54
- const job = (async () => {
62
+ const generation = this.generation.get(key) ?? 0;
63
+ let job: Promise<CacheEntry>;
64
+ job = (async () => {
55
65
  let report: UsageReport;
56
66
  try {
57
67
  report = await provider.fetchUsage();
@@ -63,14 +73,16 @@ export class UsageCache {
63
73
  summary: shortReport(report, provider),
64
74
  fetchedAt: Date.now(),
65
75
  };
66
- this.entries.set(provider.key, entry);
67
- this.notify(provider.key, entry.summary);
76
+ if ((this.generation.get(key) ?? 0) === generation) {
77
+ this.entries.set(key, entry);
78
+ this.notify(key, entry.summary);
79
+ }
68
80
  return entry;
69
81
  })().finally(() => {
70
- this.inflight.delete(provider.key);
82
+ if (this.inflight.get(key) === job) this.inflight.delete(key);
71
83
  });
72
84
 
73
- this.inflight.set(provider.key, job);
85
+ this.inflight.set(key, job);
74
86
  return job;
75
87
  }
76
88
 
package/core/registry.ts CHANGED
@@ -112,9 +112,13 @@ export class ProviderRegistry {
112
112
  matchModel(model?: { provider?: string }): UsageProvider | null {
113
113
  const current = model?.provider;
114
114
  if (!current) return null;
115
- return this.detectActive().find(p =>
116
- p.key === current || (p.matchProviders?.includes(current) ?? false),
117
- ) ?? null;
115
+ const matches = (p: UsageProvider) =>
116
+ p.key === current || (p.matchProviders?.includes(current) ?? false);
117
+ // Match by name first: detect() may read credentials synchronously (Chrome cookie DB),
118
+ // and this runs on every footer update.
119
+ const direct = this.list().find(p => !p.hidden && matches(p));
120
+ if (direct) return direct;
121
+ return this.detectActive().find(matches) ?? null;
118
122
  }
119
123
 
120
124
  loadFromConfig(providers: ProviderConfig[]): void {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-usage-hub",
3
- "version": "1.1.3",
3
+ "version": "1.1.5",
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",
@@ -19,9 +19,20 @@
19
19
  "bugs": {
20
20
  "url": "https://github.com/ouzhenkun/pi-usage-hub/issues"
21
21
  },
22
+ "files": [
23
+ "index.ts",
24
+ "core/",
25
+ "session/",
26
+ "providers/",
27
+ "ui/",
28
+ "utils/",
29
+ "types.ts",
30
+ "assets/",
31
+ "examples/"
32
+ ],
22
33
  "peerDependencies": {
23
- "@earendil-works/pi-coding-agent": "*",
24
- "@earendil-works/pi-tui": "*"
34
+ "@earendil-works/pi-coding-agent": ">=1.2.0",
35
+ "@earendil-works/pi-tui": ">=1.2.0"
25
36
  },
26
37
  "pi": {
27
38
  "extensions": [
package/providers/ark.ts CHANGED
@@ -117,7 +117,7 @@ export function makeArkProvider(name: string, cfg: ArkConfig = {}): UsageProvide
117
117
  return {
118
118
  error: manual
119
119
  ? "invalid cookie in config"
120
- : "not logged in — set cookie in config or /usage-hub login ark",
120
+ : `not logged in — set cookie in config or /usage-hub login ${name}`,
121
121
  };
122
122
  }
123
123
  const result = await callApi(auth.cookieHeader, auth.csrf);
@@ -125,7 +125,7 @@ export function makeArkProvider(name: string, cfg: ArkConfig = {}): UsageProvide
125
125
  return {
126
126
  error: manual
127
127
  ? "session expired — refresh cookie in config"
128
- : "session expired — run /usage-hub login ark",
128
+ : `session expired — run /usage-hub login ${name}`,
129
129
  };
130
130
  }
131
131
  return result;
@@ -36,6 +36,33 @@ function toWindow(
36
36
  return { pct: (used / limit) * 100, resetsIn: formatDurationSeconds(resetsInSec) };
37
37
  }
38
38
 
39
+ async function fetchStatus(session: string, workspaceId: string): Promise<Response> {
40
+ const controller = new AbortController();
41
+ const timer = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
42
+ try {
43
+ return await fetch(STATUS_URL, {
44
+ headers: {
45
+ "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) Gecko/20100101 Firefox/148.0",
46
+ Accept: "application/json",
47
+ "x-org-id": workspaceId,
48
+ Cookie: `${SESSION_COOKIE}=${session}`,
49
+ },
50
+ signal: controller.signal,
51
+ });
52
+ } finally {
53
+ clearTimeout(timer);
54
+ }
55
+ }
56
+
57
+ /** A cookie that exists locally may still be revoked server-side. */
58
+ async function sessionWorks(session: string, workspaceId: string): Promise<boolean> {
59
+ try {
60
+ return (await fetchStatus(session, workspaceId)).ok;
61
+ } catch {
62
+ return false;
63
+ }
64
+ }
65
+
39
66
  export function makeOpencodeGoProvider(name: string, cfg: OpencodeGoConfig): UsageProvider {
40
67
  const workspaceId = cfg.workspaceId;
41
68
  const manual = !!cfg.auth?.trim();
@@ -56,26 +83,15 @@ export function makeOpencodeGoProvider(name: string, cfg: OpencodeGoConfig): Usa
56
83
  return {
57
84
  error: manual
58
85
  ? "invalid auth in config"
59
- : "not logged in — set auth in config or /usage-hub login ocg",
86
+ : `not logged in — set auth in config or /usage-hub login ${name}`,
60
87
  };
61
88
  }
62
89
 
63
- const controller = new AbortController();
64
- const timer = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
65
-
66
90
  try {
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}`,
73
- },
74
- signal: controller.signal,
75
- });
91
+ const res = await fetchStatus(session, workspaceId);
76
92
 
77
93
  if (res.status === 401 || res.status === 403) {
78
- return { error: "session expired — /usage-hub login ocg" };
94
+ return { error: `session expired — /usage-hub login ${name}` };
79
95
  }
80
96
  if (!res.ok) return { error: `HTTP ${res.status}` };
81
97
 
@@ -100,8 +116,6 @@ export function makeOpencodeGoProvider(name: string, cfg: OpencodeGoConfig): Usa
100
116
  } catch (err: any) {
101
117
  if (err?.name === "AbortError") return { error: "timeout" };
102
118
  return { error: err?.message ?? String(err) };
103
- } finally {
104
- clearTimeout(timer);
105
119
  }
106
120
  },
107
121
 
@@ -109,11 +123,21 @@ export function makeOpencodeGoProvider(name: string, cfg: OpencodeGoConfig): Usa
109
123
  ? undefined
110
124
  : async (): Promise<boolean> => {
111
125
  if (!workspaceId) return false;
126
+ const before = readChromeSessionCookie();
127
+ if (before && await sessionWorks(before, workspaceId)) return true;
112
128
  execFile("open", ["-a", "Google Chrome", `https://opencode.ai/console/${workspaceId}/go`]);
113
129
  const deadline = Date.now() + 300_000;
130
+ let probed: string | null = null;
131
+ let probeCount = 0;
114
132
  while (Date.now() < deadline) {
115
133
  await new Promise(r => setTimeout(r, 2000));
116
- if (readChromeSessionCookie()) return true;
134
+ const current = readChromeSessionCookie();
135
+ if (!current || current === before) continue;
136
+ // Probe a new cookie value at most twice, so a stuck session cannot spin requests.
137
+ if (current === probed && probeCount >= 2) continue;
138
+ probeCount = current === probed ? probeCount + 1 : 1;
139
+ probed = current;
140
+ if (await sessionWorks(current, workspaceId)) return true;
117
141
  }
118
142
  return false;
119
143
  },
package/providers/xai.ts CHANGED
@@ -98,14 +98,14 @@ function isFresh(credentials: XaiCredentials): boolean {
98
98
  function validateTokenEndpoint(url: string): string {
99
99
  const normalized = url.replace(/\/$/, "");
100
100
  if (normalized !== DEFAULT_TOKEN_ENDPOINT) {
101
- throw new Error("unexpected xAI token endpoint — run /login xai-auth");
101
+ throw new Error("unexpected xAI token endpoint — run /login xai");
102
102
  }
103
103
  return DEFAULT_TOKEN_ENDPOINT;
104
104
  }
105
105
 
106
106
  async function refreshCredentials(credentials: XaiCredentials): Promise<XaiCredentials> {
107
107
  if (!credentials.refresh) {
108
- throw new Error("session expired — run /login xai-auth");
108
+ throw new Error("session expired — run /login xai");
109
109
  }
110
110
 
111
111
  const tokenEndpoint = validateTokenEndpoint(credentials.tokenEndpoint || DEFAULT_TOKEN_ENDPOINT);
@@ -283,13 +283,13 @@ export function makeXaiProvider(name: string, cfg: XaiConfig = {}): UsageProvide
283
283
  fetchUsage: async (): Promise<UsageReport> => {
284
284
  try {
285
285
  const credentials = await getCredentials(false);
286
- if (!credentials) return { error: "not logged in — run /login xai-auth" };
286
+ if (!credentials) return { error: "not logged in — run /login xai" };
287
287
  try {
288
288
  return mapUsage(await fetchBillingUsage(credentials.access));
289
289
  } catch (err) {
290
290
  if (!isUnauthorized(err)) throw err;
291
291
  const refreshed = await getCredentials(true);
292
- if (!refreshed) return { error: "session expired — run /login xai-auth" };
292
+ if (!refreshed) return { error: "session expired — run /login xai" };
293
293
  return mapUsage(await fetchBillingUsage(refreshed.access));
294
294
  }
295
295
  } catch (err: any) {
@@ -1,20 +0,0 @@
1
- name: Publish to npm
2
-
3
- on:
4
- release:
5
- types: [published]
6
-
7
- jobs:
8
- publish:
9
- runs-on: ubuntu-latest
10
- permissions:
11
- contents: read
12
- id-token: write
13
- steps:
14
- - uses: actions/checkout@v6
15
- - uses: actions/setup-node@v6
16
- with:
17
- node-version: 24
18
- registry-url: https://registry.npmjs.org
19
- package-manager-cache: false
20
- - run: npm publish --access public