Skip to content

Commit eafcf76

Browse files
feat: scope statusline quota bar to subscription providers
- Add subscription-provider registry (quota.ts): only registered providers render a quota bar; third-party API/pay-per-use providers show none. - Both Codex accounts share the 'CODEX WEEK' label; the rendered balance follows whichever account is active via its own cache file. - opencode-go stays unregistered: opencode exposes no official usage/balance API (anomalyco/opencode#31084 closed without implementation), so it shows no quota until an official endpoint ships. - Add test-quota.mjs covering registry lookup, per-account caches, corrupt cache fallback, and non-subscription providers.
1 parent 13ecdf5 commit eafcf76

3 files changed

Lines changed: 163 additions & 45 deletions

File tree

‎extensions/custom-statusline/index.ts‎

Lines changed: 15 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -11,8 +11,8 @@ import { truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
1111
import { readFileSync } from "node:fs";
1212
import { homedir } from "node:os";
1313
import { join } from "node:path";
14-
import { getCodexCachePath, getCodexProviderId } from "../weekly-usage-status/codex-provider.ts";
1514
import { createActiveModelState, getRoutingProviderForStatusline } from "./model-state.ts";
15+
import { formatResetCountdown, readSubscriptionQuota, SUBSCRIPTION_PROVIDERS } from "./quota.ts";
1616

1717
const AGENT_DIR = process.env.PI_CODING_AGENT_DIR || join(homedir(), ".pi", "agent");
1818
const ROUTING_PATH = join(AGENT_DIR, "provider-routing.json");
@@ -29,44 +29,6 @@ function readProxyMode(provider: string): string {
2929
}
3030
}
3131

32-
interface CodexQuota {
33-
remaining: number | null;
34-
/** Unix timestamp in seconds. */
35-
resetsAt?: number;
36-
}
37-
38-
function readCodexQuota(provider: unknown): CodexQuota {
39-
const codexProvider = getCodexProviderId(provider);
40-
if (!codexProvider) return { remaining: null };
41-
try {
42-
const data = JSON.parse(readFileSync(getCodexCachePath(AGENT_DIR, codexProvider), "utf8")) as {
43-
remainingPercent?: unknown;
44-
resetsAt?: unknown;
45-
};
46-
return {
47-
remaining: typeof data.remainingPercent === "number" && Number.isFinite(data.remainingPercent)
48-
? Math.max(0, Math.min(100, data.remainingPercent))
49-
: null,
50-
resetsAt: typeof data.resetsAt === "number" && Number.isFinite(data.resetsAt)
51-
? data.resetsAt
52-
: undefined,
53-
};
54-
} catch {
55-
return { remaining: null };
56-
}
57-
}
58-
59-
function formatResetCountdown(resetsAt: number | undefined, nowMs = Date.now()): string | null {
60-
if (!resetsAt) return null;
61-
const seconds = Math.max(0, Math.floor(resetsAt - nowMs / 1000));
62-
if (seconds === 0) return "now";
63-
const days = Math.floor(seconds / 86_400);
64-
const hours = Math.floor((seconds % 86_400) / 3_600);
65-
const minutes = Math.floor((seconds % 3_600) / 60);
66-
if (days > 0) return `${days}d ${hours}h`;
67-
if (hours > 0) return `${hours}h ${minutes}m`;
68-
return `${Math.max(1, minutes)}m`;
69-
}
7032

7133
export default function (pi: ExtensionAPI) {
7234
let streaming = false;
@@ -124,9 +86,10 @@ export default function (pi: ExtensionAPI) {
12486
const contextRemainingTokens = contextUsage?.tokens == null || contextTotal == null
12587
? null
12688
: Math.max(0, contextTotal - contextUsage.tokens);
127-
const codexQuota = readCodexQuota(providerId);
128-
const codexRemaining = codexQuota.remaining;
129-
const codexReset = formatResetCountdown(codexQuota.resetsAt);
89+
// --- Subscription quota bar (only for subscription providers) ---
90+
// Third-party API / pay-per-use providers are not in the registry and
91+
// render no quota bar at all; the balance follows the active provider.
92+
const subscriptionProvider = SUBSCRIPTION_PROVIDERS[providerId];
13093
const barWidth = Math.min(10, Math.max(4, Math.floor(width * 0.055)));
13194
const capacity = (label: string, remaining: number | null) => {
13295
const valueColor = remaining == null
@@ -141,8 +104,14 @@ export default function (pi: ExtensionAPI) {
141104
const value = remaining == null ? "N/A" : `${Math.round(remaining)}%`;
142105
return `${theme.fg("muted", label)} ${theme.fg(valueColor, value)} ${cells}`;
143106
};
144-
const quotaBar = capacity("CODEX WEEK", codexRemaining) +
145-
(codexReset ? ` ${theme.fg("dim", `RESET ${codexReset}`)}` : "");
107+
let quotaBar = "";
108+
if (subscriptionProvider) {
109+
const quota = readSubscriptionQuota(AGENT_DIR, providerId);
110+
if (quota) {
111+
quotaBar = capacity(subscriptionProvider.label, quota.remaining) +
112+
(quota.resetsAt ? ` ${theme.fg("dim", `RESET ${formatResetCountdown(quota.resetsAt)}`)}` : "");
113+
}
114+
}
146115
const contextBar = capacity("CTX", contextRemaining);
147116
const contextAmounts = contextTotal == null
148117
? theme.fg("dim", "N/A")
@@ -173,7 +142,8 @@ export default function (pi: ExtensionAPI) {
173142
const firstGap = Math.max(1, width - visibleWidth(firstLeft) - visibleWidth(firstRight));
174143
const firstLine = firstLeft + " ".repeat(firstGap) + firstRight;
175144

176-
const secondLine = `${quotaBar} ${contextBar} ${contextAmounts}`;
145+
const secondSegments = [quotaBar, `${contextBar} ${contextAmounts}`].filter(Boolean);
146+
const secondLine = secondSegments.join(" ");
177147
return [truncateToWidth(firstLine, width), truncateToWidth(secondLine, width)];
178148
},
179149
};
Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
/**
2+
* Subscription-provider quota registry for the custom status line.
3+
*
4+
* Only providers listed here render a quota bar. Third-party API / pay-per-use
5+
* providers (e.g. claude-relay, big-data-claude) are intentionally absent and
6+
* never show quota.
7+
*
8+
* OpenCode Go (`opencode-go`) is also absent: opencode does not expose an
9+
* official usage/balance API (anomalyco/opencode#31084 was closed without an
10+
* implementation, and the docs confirm the API-key surface exposes no
11+
* spend/balance data). Add it here with its own cache reader once
12+
* `GET /zen/go/v1/usage` (or equivalent) ships — no dashboard scraping by
13+
* design.
14+
*/
15+
16+
import { readFileSync } from "node:fs";
17+
import { getCodexCachePath } from "../weekly-usage-status/codex-provider.ts";
18+
19+
export interface SubscriptionQuota {
20+
remaining: number | null;
21+
/** Unix timestamp in seconds. */
22+
resetsAt?: number;
23+
}
24+
25+
export interface SubscriptionProvider {
26+
label: string;
27+
cacheFile: (agentDir: string) => string;
28+
}
29+
30+
export const SUBSCRIPTION_PROVIDERS: Record<string, SubscriptionProvider> = {
31+
// Both Codex accounts share the same label; the rendered balance follows
32+
// whichever account is active (each reads its own cache file).
33+
"openai-codex": {
34+
label: "CODEX WEEK",
35+
cacheFile: (agentDir) => getCodexCachePath(agentDir, "openai-codex"),
36+
},
37+
"openai-codex-second": {
38+
label: "CODEX WEEK",
39+
cacheFile: (agentDir) => getCodexCachePath(agentDir, "openai-codex-second"),
40+
},
41+
};
42+
43+
/**
44+
* Read the cached quota for a provider.
45+
*
46+
* Returns `undefined` when the provider is not a subscription provider (the
47+
* status line must not render a quota bar for it), and `{ remaining: null }`
48+
* when it is a subscription provider but no usable cache exists yet.
49+
*/
50+
export function readSubscriptionQuota(agentDir: string, provider: unknown): SubscriptionQuota | undefined {
51+
const entry = SUBSCRIPTION_PROVIDERS[String(provider)];
52+
if (!entry) return undefined;
53+
try {
54+
const data = JSON.parse(readFileSync(entry.cacheFile(agentDir), "utf8")) as {
55+
remainingPercent?: unknown;
56+
resetsAt?: unknown;
57+
};
58+
return {
59+
remaining: typeof data.remainingPercent === "number" && Number.isFinite(data.remainingPercent)
60+
? Math.max(0, Math.min(100, data.remainingPercent))
61+
: null,
62+
resetsAt: typeof data.resetsAt === "number" && Number.isFinite(data.resetsAt)
63+
? data.resetsAt
64+
: undefined,
65+
};
66+
} catch {
67+
return { remaining: null };
68+
}
69+
}
70+
71+
export function formatResetCountdown(resetsAt: number | undefined, nowMs = Date.now()): string | null {
72+
if (!resetsAt) return null;
73+
const seconds = Math.max(0, Math.floor(resetsAt - nowMs / 1000));
74+
if (seconds === 0) return "now";
75+
const days = Math.floor(seconds / 86_400);
76+
const hours = Math.floor((seconds % 86_400) / 3_600);
77+
const minutes = Math.floor((seconds % 3_600) / 60);
78+
if (days > 0) return `${days}d ${hours}h`;
79+
if (hours > 0) return `${hours}h ${minutes}m`;
80+
return `${Math.max(1, minutes)}m`;
81+
}
Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
import assert from "node:assert/strict";
2+
import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
3+
import { tmpdir } from "node:os";
4+
import { join } from "node:path";
5+
import { getCodexCachePath } from "../weekly-usage-status/codex-provider.ts";
6+
import { formatResetCountdown, readSubscriptionQuota, SUBSCRIPTION_PROVIDERS } from "./quota.ts";
7+
8+
const agentDir = mkdtempSync(join(tmpdir(), "pi-quota-"));
9+
try {
10+
mkdirSync(join(agentDir, "cache"), { recursive: true });
11+
writeFileSync(
12+
getCodexCachePath(agentDir, "openai-codex"),
13+
JSON.stringify({ remainingPercent: 76.4, resetsAt: 1_700_000_100 }),
14+
);
15+
writeFileSync(
16+
getCodexCachePath(agentDir, "openai-codex-second"),
17+
JSON.stringify({ remainingPercent: 98, resetsAt: 1_700_000_200 }),
18+
);
19+
20+
// Both Codex accounts share one label; the balance follows the active provider.
21+
assert.equal(SUBSCRIPTION_PROVIDERS["openai-codex"].label, "CODEX WEEK");
22+
assert.equal(SUBSCRIPTION_PROVIDERS["openai-codex-second"].label, "CODEX WEEK");
23+
24+
const first = readSubscriptionQuota(agentDir, "openai-codex");
25+
assert.ok(first);
26+
assert.equal(first.remaining, 76.4);
27+
assert.equal(first.resetsAt, 1_700_000_100);
28+
29+
const second = readSubscriptionQuota(agentDir, "openai-codex-second");
30+
assert.ok(second);
31+
assert.equal(second.remaining, 98);
32+
assert.equal(second.resetsAt, 1_700_000_200);
33+
console.log("✓ both Codex accounts share label 'CODEX WEEK' and read their own cache");
34+
35+
// Third-party API / pay-per-use providers render no quota bar at all.
36+
assert.equal(readSubscriptionQuota(agentDir, "claude-relay"), undefined);
37+
assert.equal(readSubscriptionQuota(agentDir, "claude-relay-alibaba"), undefined);
38+
assert.equal(readSubscriptionQuota(agentDir, "big-data-claude"), undefined);
39+
assert.equal(
40+
SUBSCRIPTION_PROVIDERS["opencode-go"],
41+
undefined,
42+
"opencode-go waits for an official usage API (anomalyco/opencode#31084)",
43+
);
44+
console.log("✓ non-subscription providers (API/pay-per-use, opencode-go) yield no quota");
45+
46+
// Corrupt cache degrades to unknown remaining instead of crashing the footer.
47+
writeFileSync(getCodexCachePath(agentDir, "openai-codex-second"), "not-json{");
48+
assert.deepEqual(readSubscriptionQuota(agentDir, "openai-codex-second"), { remaining: null });
49+
console.log("✓ corrupt cache degrades to { remaining: null }");
50+
51+
// Reset countdown formatting matches the existing weekly-usage formatter.
52+
assert.equal(formatResetCountdown(undefined), null);
53+
assert.equal(formatResetCountdown(1_700_000_000 / 1000, 1_700_000_000), "now");
54+
assert.equal(formatResetCountdown(1_700_000_000 / 1000 + 65 * 60, 1_700_000_000), "1h 5m");
55+
assert.equal(formatResetCountdown(1_700_000_000 / 1000 + 2 * 86_400 + 3 * 3600, 1_700_000_000), "2d 3h");
56+
console.log("✓ reset countdown formatting");
57+
} finally {
58+
rmSync(agentDir, { recursive: true, force: true });
59+
}
60+
61+
const source = readFileSync(new URL("./index.ts", import.meta.url), "utf8");
62+
assert.match(source, /SUBSCRIPTION_PROVIDERS\[providerId\]/);
63+
assert.match(source, /readSubscriptionQuota\(AGENT_DIR, providerId\)/);
64+
assert.match(source, /secondSegments\.join\(" "\)/);
65+
assert.doesNotMatch(source, /function readCodexQuota/);
66+
assert.doesNotMatch(source, /function formatResetCountdown/);
67+
console.log("✓ statusline renders quota only for registered subscription providers");

0 commit comments

Comments
 (0)