ceulen 0.1.0 → 0.5.1
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/CHANGELOG.md +150 -0
- package/README.md +103 -14
- package/extensions/index.ts +113 -0
- package/extensions/lib/env.ts +75 -0
- package/extensions/lib/panel.ts +1720 -0
- package/extensions/lib/registry.ts +182 -0
- package/extensions/modules/composer/index.ts +128 -0
- package/extensions/modules/composer/lib/settings.ts +55 -0
- package/extensions/modules/composer/lib/shapes.ts +436 -0
- package/extensions/modules/composer/test/editor.test.ts +138 -0
- package/extensions/modules/composer/test/module.test.ts +218 -0
- package/extensions/modules/composer/test/screen.test.ts +195 -0
- package/extensions/modules/composer/test/shapes.test.ts +175 -0
- package/extensions/modules/config/index.ts +298 -0
- package/extensions/modules/config/piSettings.ts +467 -0
- package/extensions/modules/config/plugins.ts +290 -0
- package/extensions/modules/config/test/kernel.test.ts +523 -0
- package/extensions/modules/config/test/kernelV4.test.ts +196 -0
- package/extensions/modules/config/test/menu.test.ts +226 -0
- package/extensions/modules/config/test/panel.test.ts +395 -0
- package/extensions/modules/config/test/piSettings.test.ts +185 -0
- package/extensions/modules/config/test/plugins.test.ts +181 -0
- package/extensions/modules/config/test/preview-block.test.ts +88 -0
- package/extensions/modules/ponytail/UPSTREAM +26 -0
- package/extensions/modules/ponytail/index.ts +336 -0
- package/extensions/modules/ponytail/lib/config.ts +149 -0
- package/extensions/modules/ponytail/lib/instructions.ts +98 -0
- package/extensions/modules/ponytail/lib/subagent.ts +31 -0
- package/extensions/modules/ponytail/test/extension.test.ts +422 -0
- package/extensions/modules/ponytail/test/helpers.test.ts +163 -0
- package/extensions/modules/ponytail/test/subagent.test.ts +33 -0
- package/extensions/modules/router/commands/commands.ts +99 -0
- package/extensions/modules/router/configPanel.ts +89 -0
- package/extensions/modules/router/index.ts +75 -0
- package/extensions/modules/router/lib/client.ts +390 -0
- package/extensions/modules/router/lib/config.ts +142 -0
- package/extensions/modules/router/lib/migrate.ts +92 -0
- package/extensions/modules/router/lib/provider.ts +138 -0
- package/extensions/modules/router/lib/refresh.ts +19 -0
- package/extensions/modules/router/test/guard.test.ts +77 -0
- package/extensions/modules/router/test/unit.test.ts +1126 -0
- package/extensions/modules/usage/index.ts +1975 -0
- package/extensions/modules/usage/test/context.test.ts +387 -0
- package/extensions/modules/usage/test/env-gating.test.ts +113 -0
- package/extensions/modules/usage/test/opencode-go-usage.test.ts +139 -0
- package/extensions/modules/usage/test/parsers.test.ts +244 -0
- package/extensions/modules/usage/test/stale-ctx-regression.test.ts +294 -0
- package/extensions/modules/usage/test/zai-anthropic-adapter.test.ts +40 -0
- package/package.json +15 -3
- package/skills/ponytail/SKILL.md +124 -0
- package/skills/ponytail-audit/SKILL.md +41 -0
- package/skills/ponytail-debt/SKILL.md +44 -0
- package/skills/ponytail-gain/SKILL.md +51 -0
- package/skills/ponytail-help/SKILL.md +73 -0
- package/skills/ponytail-review/SKILL.md +57 -0
- package/extensions/index.js +0 -42
|
@@ -0,0 +1,1975 @@
|
|
|
1
|
+
import { DEFAULT_COMPACTION_SETTINGS, estimateTokens, readStoredCredential, type ExtensionAPI, type ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import { createHash } from "node:crypto";
|
|
3
|
+
import fs from "node:fs";
|
|
4
|
+
import os from "node:os";
|
|
5
|
+
import path from "node:path";
|
|
6
|
+
import { loadCwdEnvFilesIfTrusted, parseEnvText } from "../../lib/env.js";
|
|
7
|
+
|
|
8
|
+
/** Single source of truth for User-Agent strings — matches package.json version. */
|
|
9
|
+
const CEULEN_VERSION: string = (() => {
|
|
10
|
+
try {
|
|
11
|
+
return JSON.parse(fs.readFileSync(new URL("../../../package.json", import.meta.url), "utf8")).version; // ceulen bundle root
|
|
12
|
+
} catch {
|
|
13
|
+
return "unknown"; // ponytail: partial installs must not kill extension load
|
|
14
|
+
}
|
|
15
|
+
})();
|
|
16
|
+
|
|
17
|
+
const STATUS_KEY = "ceulen-usage";
|
|
18
|
+
const MESSAGE_TYPE = "ceulen-usage-status";
|
|
19
|
+
/** /context panel message type — rendered inline in the transcript (OMP-style). */
|
|
20
|
+
const MESSAGE_TYPE_CONTEXT = "ceulen-usage-context";
|
|
21
|
+
const USAGE_ENDPOINT = "https://chatgpt.com/backend-api/wham/usage";
|
|
22
|
+
export const REFRESH_INTERVAL_MS = 60_000;
|
|
23
|
+
const REFRESH_TTL_MS = 30_000;
|
|
24
|
+
export const REFRESH_DEBOUNCE_MS = 2_000;
|
|
25
|
+
const CODEX_PROVIDER = "openai-codex";
|
|
26
|
+
const OPC_PROVIDER = "opencode-go";
|
|
27
|
+
const OPC_USAGE_URL = "https://opencode.ai/zen/go/v1/usage";
|
|
28
|
+
const ZAI_PROVIDER = "zai";
|
|
29
|
+
const ZAI_USAGE_URL = "https://api.z.ai/api/monitor/usage/quota/limit";
|
|
30
|
+
const ZAI_CODING_CN_PROVIDER = "zai-coding-cn";
|
|
31
|
+
const ZAI_CODING_CN_USAGE_URL = "https://open.bigmodel.cn/api/monitor/usage/quota/limit";
|
|
32
|
+
// GLM via the Anthropic-compatible endpoint (pi-model-tools `zai-anthropic`
|
|
33
|
+
// provider). Same api.z.ai host and quota monitor as the `zai` provider.
|
|
34
|
+
// ponytail: usage URL is fixed to api.z.ai — if ZAI_ANTHROPIC_BASE_URL is
|
|
35
|
+
// overridden to BigModel/zcode-plan, quota still reads from api.z.ai (correct
|
|
36
|
+
// for the z.ai coding-plan key; BigModel-plan keys should use zai-coding-cn).
|
|
37
|
+
const ZAI_ANTHROPIC_PROVIDER = "zai-anthropic";
|
|
38
|
+
const ZAI_ANTHROPIC_USAGE_URL = ZAI_USAGE_URL;
|
|
39
|
+
const ROUTER_PROVIDER = "router";
|
|
40
|
+
const LEGACY_9ROUTER_PROVIDER = "9router";
|
|
41
|
+
// pi-router (formerly pi-9router): URL lives in settings.json `router.baseUrl`
|
|
42
|
+
// (env override ROUTER_BASE_URL), key in auth.json `router` credential.
|
|
43
|
+
const ROUTER_SETTINGS_PATH = path.join(os.homedir(), ".pi", "agent", "settings.json");
|
|
44
|
+
const COMMAND_CODE_PROVIDER = "commandcode";
|
|
45
|
+
const COMMAND_CODE_USAGE_URL = "https://api.commandcode.ai/alpha/billing/credits";
|
|
46
|
+
|
|
47
|
+
type ModelLike = { provider?: string; id?: string } | undefined;
|
|
48
|
+
|
|
49
|
+
type UsageApiWindow = {
|
|
50
|
+
used_percent?: number;
|
|
51
|
+
reset_at?: number;
|
|
52
|
+
};
|
|
53
|
+
|
|
54
|
+
type UsageApiSnapshot = {
|
|
55
|
+
primary?: UsageApiWindow;
|
|
56
|
+
secondary?: UsageApiWindow;
|
|
57
|
+
plan_type?: string;
|
|
58
|
+
};
|
|
59
|
+
|
|
60
|
+
type OpcUsageWindowApi = {
|
|
61
|
+
status?: string;
|
|
62
|
+
percent?: number;
|
|
63
|
+
resetsAt?: string;
|
|
64
|
+
};
|
|
65
|
+
|
|
66
|
+
type OpcUsageApiResponse = {
|
|
67
|
+
usage?: {
|
|
68
|
+
rolling?: OpcUsageWindowApi;
|
|
69
|
+
weekly?: OpcUsageWindowApi;
|
|
70
|
+
monthly?: OpcUsageWindowApi;
|
|
71
|
+
};
|
|
72
|
+
};
|
|
73
|
+
|
|
74
|
+
type PiAuthEntry = {
|
|
75
|
+
type?: string;
|
|
76
|
+
access?: string;
|
|
77
|
+
refresh?: string;
|
|
78
|
+
expires?: number;
|
|
79
|
+
accountId?: string;
|
|
80
|
+
key?: string;
|
|
81
|
+
email?: string;
|
|
82
|
+
label?: string;
|
|
83
|
+
name?: string;
|
|
84
|
+
env?: Record<string, string>;
|
|
85
|
+
};
|
|
86
|
+
|
|
87
|
+
interface UsageWindow {
|
|
88
|
+
percent?: number;
|
|
89
|
+
remaining?: number;
|
|
90
|
+
remainingLabel?: string;
|
|
91
|
+
resetLabel?: string;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
interface SubscriptionAccountSnapshot {
|
|
95
|
+
id?: string;
|
|
96
|
+
isActive?: boolean;
|
|
97
|
+
accountLabel?: string;
|
|
98
|
+
plan?: string;
|
|
99
|
+
fiveHour?: UsageWindow;
|
|
100
|
+
weekly?: UsageWindow;
|
|
101
|
+
monthly?: UsageWindow; // OpenCode Go 30d window
|
|
102
|
+
// Command Code-only: monthly credit balance (not a rolling window).
|
|
103
|
+
monthlyCredits?: number;
|
|
104
|
+
// Balance currency — only "CNY" is special-cased (¥); undefined = USD ($).
|
|
105
|
+
creditsCurrency?: string;
|
|
106
|
+
// Z.ai-only extras surfaced in the /usage detail view.
|
|
107
|
+
mcpMonthly?: UsageWindow; // from TIME_LIMIT already present in the quota response
|
|
108
|
+
usageBreakdown?: string; // per-model / per-tool summary line(s)
|
|
109
|
+
lastActivity?: string;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
interface SubscriptionUsageSnapshot {
|
|
113
|
+
providerDisplayName: string;
|
|
114
|
+
accounts: SubscriptionAccountSnapshot[];
|
|
115
|
+
activeAccount?: SubscriptionAccountSnapshot;
|
|
116
|
+
fetchedAt: number;
|
|
117
|
+
error?: string;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
type SubscriptionProviderAdapter = {
|
|
121
|
+
id: string;
|
|
122
|
+
displayName: string;
|
|
123
|
+
fetchUsage(signal?: AbortSignal): Promise<SubscriptionUsageSnapshot>;
|
|
124
|
+
};
|
|
125
|
+
|
|
126
|
+
export interface State {
|
|
127
|
+
model?: ModelLike;
|
|
128
|
+
adapter?: SubscriptionProviderAdapter;
|
|
129
|
+
adapterId?: string;
|
|
130
|
+
ctx?: ExtensionContext;
|
|
131
|
+
snapshot?: SubscriptionUsageSnapshot;
|
|
132
|
+
lastRefreshAt: number;
|
|
133
|
+
refreshGeneration: number;
|
|
134
|
+
inFlight?: Promise<SubscriptionUsageSnapshot>;
|
|
135
|
+
refreshTimer?: NodeJS.Timeout;
|
|
136
|
+
debounceTimer?: NodeJS.Timeout;
|
|
137
|
+
responseStartTime?: number;
|
|
138
|
+
lastTokPerSec?: number;
|
|
139
|
+
lastTokPerSecLabel?: string;
|
|
140
|
+
cumulativeOutput: number;
|
|
141
|
+
cumulativeDurationMs: number;
|
|
142
|
+
cumulativeCost: number;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
function isCodexModel(model: ModelLike): boolean {
|
|
146
|
+
const provider = model?.provider?.toLowerCase() ?? "";
|
|
147
|
+
return provider === CODEX_PROVIDER || provider.includes(CODEX_PROVIDER);
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
function isOpenCodeGoModel(model: ModelLike): boolean {
|
|
151
|
+
return (model?.provider?.toLowerCase() ?? "") === OPC_PROVIDER;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
function isZaiModel(model: ModelLike): boolean {
|
|
155
|
+
return (model?.provider?.toLowerCase() ?? "") === ZAI_PROVIDER;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
function isZaiCodingCnModel(model: ModelLike): boolean {
|
|
159
|
+
return (model?.provider?.toLowerCase() ?? "") === ZAI_CODING_CN_PROVIDER;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
function isZaiAnthropicModel(model: ModelLike): boolean {
|
|
163
|
+
return (model?.provider?.toLowerCase() ?? "") === ZAI_ANTHROPIC_PROVIDER;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
function isRouterModel(model: ModelLike, provider: string = ROUTER_PROVIDER): boolean {
|
|
167
|
+
return (model?.provider?.toLowerCase() ?? "") === provider;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
function isCommandCodeModel(model: ModelLike): boolean {
|
|
171
|
+
return (model?.provider?.toLowerCase() ?? "") === COMMAND_CODE_PROVIDER;
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
function piAuthPath(): string {
|
|
175
|
+
const configDir = process.env.PI_CODING_AGENT_DIR?.trim() || path.join(os.homedir(), ".pi", "agent");
|
|
176
|
+
return path.join(configDir, "auth.json");
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
function decodeJwtPayload(token: string | undefined): Record<string, any> | undefined {
|
|
180
|
+
if (!token) return undefined;
|
|
181
|
+
const parts = token.split(".");
|
|
182
|
+
if (parts.length < 2) return undefined;
|
|
183
|
+
try {
|
|
184
|
+
return JSON.parse(Buffer.from(parts[1], "base64url").toString("utf8")) as Record<string, any>;
|
|
185
|
+
} catch {
|
|
186
|
+
return undefined;
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
/** True when the token's `exp` claim (epoch seconds) has passed. Missing exp
|
|
191
|
+
* or unparseable token → false (the server still arbitrates auth). */
|
|
192
|
+
export function jwtExpired(payload: Record<string, any> | undefined): boolean {
|
|
193
|
+
return typeof payload?.exp === "number" && Date.now() / 1000 >= payload.exp;
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
// Exported for tests: the JWT exp → "expired" plan path.
|
|
197
|
+
export function accountFromPiAuth(entry: PiAuthEntry): SubscriptionAccountSnapshot {
|
|
198
|
+
const claims = decodeJwtPayload(entry.access);
|
|
199
|
+
const profile = claims?.["https://api.openai.com/profile"];
|
|
200
|
+
const auth = claims?.["https://api.openai.com/auth"];
|
|
201
|
+
const email = typeof profile?.email === "string" ? profile.email : undefined;
|
|
202
|
+
const plan = jwtExpired(claims) ? "expired" : typeof auth?.chatgpt_plan_type === "string" ? planLabel(auth.chatgpt_plan_type) : undefined;
|
|
203
|
+
const accountId = typeof entry.accountId === "string" ? entry.accountId : typeof auth?.chatgpt_account_id === "string" ? auth.chatgpt_account_id : undefined;
|
|
204
|
+
return {
|
|
205
|
+
id: accountId,
|
|
206
|
+
isActive: true,
|
|
207
|
+
accountLabel: email ?? accountId ?? "openai-codex account",
|
|
208
|
+
plan,
|
|
209
|
+
lastActivity: "Now",
|
|
210
|
+
};
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
function firstString(...values: unknown[]): string | undefined {
|
|
214
|
+
for (const value of values) {
|
|
215
|
+
if (typeof value !== "string") continue;
|
|
216
|
+
const trimmed = value.trim();
|
|
217
|
+
if (trimmed.length > 0) return trimmed;
|
|
218
|
+
}
|
|
219
|
+
return undefined;
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
function authEntryLabel(entry: PiAuthEntry | undefined): string | undefined {
|
|
223
|
+
return firstString(entry?.email, entry?.label, entry?.name, entry?.accountId);
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
function keyFingerprint(key: string | undefined): string | undefined {
|
|
227
|
+
if (!key) return undefined;
|
|
228
|
+
return createHash("sha256").update(key).digest("hex").slice(0, 8);
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
function authAccountLabel(providerLabel: string, entry: PiAuthEntry | undefined): string {
|
|
232
|
+
const label = authEntryLabel(entry);
|
|
233
|
+
if (label) return label;
|
|
234
|
+
const fingerprint = keyFingerprint(entry?.key);
|
|
235
|
+
return fingerprint ? `${providerLabel} key#${fingerprint}` : `${providerLabel} account`;
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
function authAccountSnapshot(providerLabel: string, entry: PiAuthEntry | undefined, defaults: Partial<SubscriptionAccountSnapshot> = {}): SubscriptionAccountSnapshot {
|
|
239
|
+
return {
|
|
240
|
+
id: firstString(entry?.accountId),
|
|
241
|
+
isActive: true,
|
|
242
|
+
accountLabel: authAccountLabel(providerLabel, entry),
|
|
243
|
+
lastActivity: "Now",
|
|
244
|
+
...defaults,
|
|
245
|
+
};
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
function formatFooterAccount(account: SubscriptionAccountSnapshot | undefined): string | undefined {
|
|
249
|
+
const label = firstString(account?.accountLabel);
|
|
250
|
+
return label ? `(${label})` : undefined;
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
function getCodexAccountId(entry: PiAuthEntry | undefined): string | undefined {
|
|
254
|
+
if (!entry) return undefined;
|
|
255
|
+
if (typeof entry.accountId === "string" && entry.accountId.length > 0) return entry.accountId;
|
|
256
|
+
const claims = decodeJwtPayload(entry.access);
|
|
257
|
+
const auth = claims?.["https://api.openai.com/auth"];
|
|
258
|
+
return typeof auth?.chatgpt_account_id === "string" ? auth.chatgpt_account_id : undefined;
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
function planLabel(plan: string | undefined): string | undefined {
|
|
262
|
+
if (!plan) return undefined;
|
|
263
|
+
const normalized = plan.toLowerCase().replace(/[_-]+/g, " ");
|
|
264
|
+
const labels: Record<string, string> = {
|
|
265
|
+
free: "Free",
|
|
266
|
+
plus: "Plus",
|
|
267
|
+
prolite: "Pro Lite",
|
|
268
|
+
"pro lite": "Pro Lite",
|
|
269
|
+
pro: "Pro",
|
|
270
|
+
team: "Business",
|
|
271
|
+
business: "Business",
|
|
272
|
+
enterprise: "Enterprise",
|
|
273
|
+
edu: "Edu",
|
|
274
|
+
unknown: "Unknown",
|
|
275
|
+
};
|
|
276
|
+
return labels[normalized] ?? plan;
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
function formatRemainingTime(resetAtSec: number | undefined): string | undefined {
|
|
280
|
+
if (!resetAtSec) return undefined;
|
|
281
|
+
const nowSec = Date.now() / 1000;
|
|
282
|
+
const remainingSec = resetAtSec - nowSec;
|
|
283
|
+
if (remainingSec <= 0) return "0M";
|
|
284
|
+
const remainingMin = Math.ceil(remainingSec / 60);
|
|
285
|
+
if (remainingMin < 60) return `${remainingMin}M`;
|
|
286
|
+
const remainingH = Math.ceil(remainingSec / 3600);
|
|
287
|
+
if (remainingH < 24) return `${remainingH}H`;
|
|
288
|
+
const remainingD = Math.ceil(remainingSec / 86400);
|
|
289
|
+
return `${remainingD}D`;
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
function formatReset(timestampSeconds: number | undefined): string | undefined {
|
|
293
|
+
if (!timestampSeconds) return undefined;
|
|
294
|
+
const date = new Date(timestampSeconds * 1000);
|
|
295
|
+
const now = new Date();
|
|
296
|
+
const time = date.toLocaleTimeString(undefined, { hour: "2-digit", minute: "2-digit", hour12: false });
|
|
297
|
+
if (date.toDateString() === now.toDateString()) return time;
|
|
298
|
+
const day = date.toLocaleDateString(undefined, { day: "numeric" });
|
|
299
|
+
const month = date.toLocaleDateString(undefined, { month: "short" });
|
|
300
|
+
return `${time} on ${day} ${month}`;
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
function usageWindowFromApi(window: UsageApiWindow | undefined): UsageWindow | undefined {
|
|
304
|
+
if (!window || typeof window.used_percent !== "number") return undefined;
|
|
305
|
+
const percent = Math.round(window.used_percent);
|
|
306
|
+
const remaining = Math.max(0, 100 - percent);
|
|
307
|
+
const resetLabel = formatReset(window.reset_at);
|
|
308
|
+
const remainingLabel = formatRemainingTime(window.reset_at);
|
|
309
|
+
return {
|
|
310
|
+
percent,
|
|
311
|
+
remaining,
|
|
312
|
+
remainingLabel,
|
|
313
|
+
resetLabel,
|
|
314
|
+
};
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
function mergeUsageIntoAccount(account: SubscriptionAccountSnapshot, usage: UsageApiSnapshot | undefined): SubscriptionAccountSnapshot {
|
|
318
|
+
if (!usage) return account;
|
|
319
|
+
return {
|
|
320
|
+
...account,
|
|
321
|
+
plan: planLabel(usage.plan_type) ?? account.plan,
|
|
322
|
+
fiveHour: usageWindowFromApi(usage.primary) ?? account.fiveHour,
|
|
323
|
+
weekly: usageWindowFromApi(usage.secondary) ?? account.weekly,
|
|
324
|
+
};
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
function parseUsageResponse(body: unknown): UsageApiSnapshot | undefined {
|
|
328
|
+
if (!body || typeof body !== "object") return undefined;
|
|
329
|
+
const root = body as any;
|
|
330
|
+
const rateLimit = root.rate_limit;
|
|
331
|
+
if (!rateLimit || typeof rateLimit !== "object") return undefined;
|
|
332
|
+
const parseWindow = (window: any): UsageApiWindow | undefined => {
|
|
333
|
+
if (!window || typeof window !== "object" || typeof window.used_percent !== "number") return undefined;
|
|
334
|
+
return {
|
|
335
|
+
used_percent: window.used_percent,
|
|
336
|
+
reset_at: typeof window.reset_at === "number" ? window.reset_at : undefined,
|
|
337
|
+
};
|
|
338
|
+
};
|
|
339
|
+
return {
|
|
340
|
+
primary: parseWindow(rateLimit.primary_window),
|
|
341
|
+
secondary: parseWindow(rateLimit.secondary_window),
|
|
342
|
+
plan_type: typeof root.plan_type === "string" ? root.plan_type : undefined,
|
|
343
|
+
};
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
async function readPiCodexAuth(): Promise<PiAuthEntry & { accountId: string }> {
|
|
347
|
+
const entry = readStoredCredential(CODEX_PROVIDER, piAuthPath()) as PiAuthEntry | undefined;
|
|
348
|
+
const accountId = getCodexAccountId(entry);
|
|
349
|
+
if (!entry?.access || !accountId) throw new Error("Missing openai-codex OAuth entry in Pi auth");
|
|
350
|
+
return { ...entry, accountId };
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
async function readOpenCodeGoAuth(): Promise<{ key?: string; account: SubscriptionAccountSnapshot }> {
|
|
354
|
+
const entry = readStoredCredential(OPC_PROVIDER, piAuthPath()) as PiAuthEntry | undefined;
|
|
355
|
+
if (!entry?.key && !entry?.accountId) throw new Error("Missing opencode-go API key or accountId in Pi auth");
|
|
356
|
+
return { key: entry.key, account: authAccountSnapshot("OpenCode Go", entry, { plan: "Go" }) };
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
// Zen Go returns percent (0-100, used) per window; resetsAt is ISO 8601
|
|
360
|
+
// (fractional seconds fine for Date.parse). Helpers expect epoch seconds.
|
|
361
|
+
// Undocumented API: percent is clamped to 0-100 both raw and post-derivation.
|
|
362
|
+
export function opcWindowToUsageWindow(w: OpcUsageWindowApi | undefined): UsageWindow | undefined {
|
|
363
|
+
if (!w || typeof w.percent !== "number") return undefined;
|
|
364
|
+
const percent = Math.min(100, Math.max(0, Math.round(w.percent)));
|
|
365
|
+
const resetAtSec = w.resetsAt ? Date.parse(w.resetsAt) / 1000 : undefined;
|
|
366
|
+
return {
|
|
367
|
+
percent,
|
|
368
|
+
remaining: 100 - percent,
|
|
369
|
+
remainingLabel: formatRemainingTime(resetAtSec),
|
|
370
|
+
resetLabel: formatReset(resetAtSec),
|
|
371
|
+
};
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
async function readZaiAuth(providerId: string, label: string): Promise<{ key: string; account: SubscriptionAccountSnapshot }> {
|
|
375
|
+
const entry = readStoredCredential(providerId, piAuthPath()) as PiAuthEntry | undefined;
|
|
376
|
+
if (!entry?.key) throw new Error(`Missing ${providerId} API key in Pi auth`);
|
|
377
|
+
return { key: entry.key, account: authAccountSnapshot(label, entry) };
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
// ponytail: duplicated from pi-router — no shared config lib, ~12 lines, acceptable
|
|
381
|
+
function readRouterConfig(): { baseUrl: string } | null {
|
|
382
|
+
try {
|
|
383
|
+
let baseUrl = process.env.ROUTER_BASE_URL || process.env.NINE_ROUTER_BASE_URL;
|
|
384
|
+
if (!baseUrl && fs.statSync(ROUTER_SETTINGS_PATH).isFile()) {
|
|
385
|
+
const settings = JSON.parse(fs.readFileSync(ROUTER_SETTINGS_PATH, "utf8")) as Record<string, unknown>;
|
|
386
|
+
const router = settings.router as { baseUrl?: unknown } | undefined;
|
|
387
|
+
if (typeof router?.baseUrl === "string" && router.baseUrl) baseUrl = router.baseUrl;
|
|
388
|
+
}
|
|
389
|
+
return baseUrl ? { baseUrl } : null;
|
|
390
|
+
} catch {
|
|
391
|
+
return null;
|
|
392
|
+
}
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
/** Router API key: auth.json `router` credential (via /login), then env. */
|
|
396
|
+
function readRouterApiKey(): string | undefined {
|
|
397
|
+
const stored = readStoredCredential(ROUTER_PROVIDER, piAuthPath()) as PiAuthEntry | undefined;
|
|
398
|
+
if (stored?.key) return stored.key;
|
|
399
|
+
return process.env.ROUTER_API_KEY || process.env.NINE_ROUTER_API_KEY || undefined;
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
/** Strip a `/v1` suffix so management routes (under the origin) can be
|
|
403
|
+
* derived from the OpenAI-compatible baseUrl. */
|
|
404
|
+
function routerOrigin(baseUrl: string): string {
|
|
405
|
+
return baseUrl.replace(/\/v1\/?$/, "");
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
/** OmniRoute management credential (manage-scope key or oma_ CLI token) from
|
|
409
|
+
* env — optional override. The router key itself works when it holds the
|
|
410
|
+
* `manage` scope (API Keys dashboard), which unlocks
|
|
411
|
+
* /api/usage/<connectionId> carrying the raw USD balance for credit-based
|
|
412
|
+
* upstreams (deepseek) that the key-authable endpoints normalize away. */
|
|
413
|
+
function readRouterMgmtToken(apiKey: string | undefined): string | undefined {
|
|
414
|
+
return process.env.ROUTER_MGMT_TOKEN || process.env.OMNIROUTE_MGMT_TOKEN || apiKey;
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
/** Parse OmniRoute's `/api/usage/om-usage` plain-text report into windows.
|
|
418
|
+
* Sections: "Personal quota" (per-key USD budgets: Daily/Weekly) and
|
|
419
|
+
* "Provider quota" (connection session/weekly). Lines: `<Label>`,
|
|
420
|
+
* `NN% left`, `⏱ reset in <countdown>`. Robust to missing/unknown blocks. */
|
|
421
|
+
/** Convert OmniRoute's "reset in 2h 55m" countdown into the compact footer
|
|
422
|
+
* label (e.g. 3H), matching the direct Z.ai display (R:99%/4H). */
|
|
423
|
+
function countdownToLabel(text: string): string | undefined {
|
|
424
|
+
const m = text.match(/(?:(\d+)\s*d)?\s*(?:(\d+)\s*h)?\s*(?:(\d+)\s*m)?/);
|
|
425
|
+
if (!m || (!m[1] && !m[2] && !m[3])) return undefined;
|
|
426
|
+
const secs = Number(m[1] || 0) * 86400 + Number(m[2] || 0) * 3600 + Number(m[3] || 0) * 60;
|
|
427
|
+
return secs ? formatRemainingTime(Date.now() / 1000 + secs) : undefined;
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
/** Human countdown from an epoch-ms reset timestamp: "2h 55m" / "1d 4h". */
|
|
431
|
+
export function msCountdown(resetAtMs: number | undefined): string | undefined {
|
|
432
|
+
if (!resetAtMs) return undefined;
|
|
433
|
+
const s = Math.round((resetAtMs - Date.now()) / 1000);
|
|
434
|
+
if (s <= 0) return undefined;
|
|
435
|
+
const d = Math.floor(s / 86400);
|
|
436
|
+
const h = Math.floor((s % 86400) / 3600);
|
|
437
|
+
const m = Math.floor((s % 3600) / 60);
|
|
438
|
+
const parts = [d ? `${d}d` : "", h ? `${h}h` : "", m ? `${m}m` : ""].filter(Boolean);
|
|
439
|
+
return parts.length ? parts.join(" ") : "0m";
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
interface GenericUsage {
|
|
443
|
+
fiveHour?: UsageWindow;
|
|
444
|
+
weekly?: UsageWindow;
|
|
445
|
+
monthly?: UsageWindow; // OpenCode Go 30d pct window (router /v1/usage windows.monthly)
|
|
446
|
+
monthlyCredits?: number;
|
|
447
|
+
creditsCurrency?: string;
|
|
448
|
+
breakdown?: string;
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
/** Parse the general router usage API (GET <baseUrl>/usage, JSON —
|
|
452
|
+
* yardmaster) into windows + credits: `{windows: {session, weekly, monthly}:
|
|
453
|
+
* {remaining_pct, reset_at}, credits: {currency, balance}, providers: []}`.
|
|
454
|
+
* Robust to missing sections; `{}` when nothing usable is present. */
|
|
455
|
+
export function parseGenericUsage(data: unknown): GenericUsage {
|
|
456
|
+
const body = data as {
|
|
457
|
+
windows?: Record<string, { remaining_pct?: number; reset_at?: number }>;
|
|
458
|
+
credits?: { currency?: string; balance?: number };
|
|
459
|
+
} | null;
|
|
460
|
+
if (!body || typeof body !== "object") return {};
|
|
461
|
+
const toWindow = (w: { remaining_pct?: number; reset_at?: number } | undefined): UsageWindow | undefined => {
|
|
462
|
+
if (!w || typeof w.remaining_pct !== "number" || !Number.isFinite(w.remaining_pct)) return undefined;
|
|
463
|
+
const out: UsageWindow = { remaining: Math.max(0, Math.min(100, Math.round(w.remaining_pct))) };
|
|
464
|
+
if (w.reset_at) {
|
|
465
|
+
out.remainingLabel = formatRemainingTime(w.reset_at / 1000);
|
|
466
|
+
out.resetLabel = `⏱ reset in ${msCountdown(w.reset_at) ?? "unknown"}`;
|
|
467
|
+
}
|
|
468
|
+
return out;
|
|
469
|
+
};
|
|
470
|
+
const fiveHour = toWindow(body.windows?.session);
|
|
471
|
+
const weekly = toWindow(body.windows?.weekly);
|
|
472
|
+
const monthly = toWindow(body.windows?.monthly);
|
|
473
|
+
const monthlyCredits = typeof body.credits?.balance === "number" && Number.isFinite(body.credits.balance)
|
|
474
|
+
? body.credits.balance : undefined;
|
|
475
|
+
const creditsCurrency = body.credits?.currency ?? "USD";
|
|
476
|
+
const lines: string[] = [];
|
|
477
|
+
if (fiveHour) lines.push(`Session ${fiveHour.remaining}% left${fiveHour.resetLabel ? ` ${fiveHour.resetLabel}` : ""}`);
|
|
478
|
+
if (weekly) lines.push(`Weekly ${weekly.remaining}% left${weekly.resetLabel ? ` ${weekly.resetLabel}` : ""}`);
|
|
479
|
+
if (monthly) lines.push(`Monthly ${monthly.remaining}% left${monthly.resetLabel ? ` ${monthly.resetLabel}` : ""}`);
|
|
480
|
+
if (monthlyCredits !== undefined) {
|
|
481
|
+
const amt = creditsCurrency === "CNY" ? `¥${monthlyCredits.toFixed(2)} CNY` : `$${monthlyCredits.toFixed(2)}`;
|
|
482
|
+
lines.push(`🪙 Balance (${creditsCurrency}) ${amt}`);
|
|
483
|
+
}
|
|
484
|
+
const out: GenericUsage = {};
|
|
485
|
+
if (fiveHour) out.fiveHour = fiveHour;
|
|
486
|
+
if (weekly) out.weekly = weekly;
|
|
487
|
+
if (monthly) out.monthly = monthly;
|
|
488
|
+
if (monthlyCredits !== undefined) {
|
|
489
|
+
out.monthlyCredits = monthlyCredits;
|
|
490
|
+
out.creditsCurrency = creditsCurrency;
|
|
491
|
+
}
|
|
492
|
+
if (lines.length) out.breakdown = lines.join("\n");
|
|
493
|
+
return out;
|
|
494
|
+
}
|
|
495
|
+
|
|
496
|
+
export function parseOmniUsageText(text: string): {
|
|
497
|
+
personalDaily?: UsageWindow;
|
|
498
|
+
personalWeekly?: UsageWindow;
|
|
499
|
+
session?: UsageWindow;
|
|
500
|
+
providerWeekly?: UsageWindow;
|
|
501
|
+
} {
|
|
502
|
+
const out: {
|
|
503
|
+
personalDaily?: UsageWindow;
|
|
504
|
+
personalWeekly?: UsageWindow;
|
|
505
|
+
session?: UsageWindow;
|
|
506
|
+
providerWeekly?: UsageWindow;
|
|
507
|
+
} = {};
|
|
508
|
+
const lines = text.split(/\r?\n/).map((l) => l.trim()).filter(Boolean);
|
|
509
|
+
let inPersonal = false;
|
|
510
|
+
for (let i = 0; i < lines.length; i++) {
|
|
511
|
+
const line = lines[i];
|
|
512
|
+
if (line.toLowerCase() === "personal quota") { inPersonal = true; continue; }
|
|
513
|
+
if (line.toLowerCase() === "provider quota") { inPersonal = false; continue; }
|
|
514
|
+
const usedMatch = line.match(/^(\d+)%\s*left$/);
|
|
515
|
+
if (!usedMatch) continue;
|
|
516
|
+
const label = (lines[i - 1] ?? "").toLowerCase();
|
|
517
|
+
const resetMatch = lines[i + 1]?.match(/reset in (.+)$/);
|
|
518
|
+
const remaining = Number(usedMatch[1]);
|
|
519
|
+
if (remaining < 0 || remaining > 100) continue;
|
|
520
|
+
const window: UsageWindow = { remaining };
|
|
521
|
+
if (resetMatch) {
|
|
522
|
+
window.resetLabel = `⏱ ${resetMatch[1].trim()}`;
|
|
523
|
+
window.remainingLabel = countdownToLabel(resetMatch[1]);
|
|
524
|
+
}
|
|
525
|
+
if (inPersonal) {
|
|
526
|
+
if (label.includes("daily")) out.personalDaily = window;
|
|
527
|
+
else if (label.includes("weekly")) out.personalWeekly = window;
|
|
528
|
+
} else {
|
|
529
|
+
if (label.includes("session")) out.session = window;
|
|
530
|
+
else if (label.includes("weekly")) out.providerWeekly = window;
|
|
531
|
+
}
|
|
532
|
+
}
|
|
533
|
+
return out;
|
|
534
|
+
}
|
|
535
|
+
|
|
536
|
+
// ponytail: parser assertions live in extensions/test/parsers.test.ts
|
|
537
|
+
|
|
538
|
+
async function fetchUsageFromPiAuth(entry: PiAuthEntry, signal?: AbortSignal): Promise<UsageApiSnapshot | undefined> {
|
|
539
|
+
const accountId = getCodexAccountId(entry) ?? entry.accountId;
|
|
540
|
+
if (!accountId) throw new Error("Missing openai-codex OAuth entry in Pi auth");
|
|
541
|
+
const timeoutSignal = AbortSignal.timeout(7_000);
|
|
542
|
+
const combinedSignal = signal ? AbortSignal.any([signal, timeoutSignal]) : timeoutSignal;
|
|
543
|
+
const response = await fetch(USAGE_ENDPOINT, {
|
|
544
|
+
headers: {
|
|
545
|
+
Accept: "application/json",
|
|
546
|
+
Authorization: `Bearer ${entry.access}`,
|
|
547
|
+
"ChatGPT-Account-Id": accountId,
|
|
548
|
+
"User-Agent": `ceulen/${CEULEN_VERSION}`,
|
|
549
|
+
},
|
|
550
|
+
signal: combinedSignal,
|
|
551
|
+
});
|
|
552
|
+
if (!response.ok) throw new Error(`usage request failed with HTTP ${response.status}`);
|
|
553
|
+
return parseUsageResponse(await response.json());
|
|
554
|
+
}
|
|
555
|
+
|
|
556
|
+
// ponytail: shared redaction — show provider + failure class, never leak keys.
|
|
557
|
+
// Structured API errors carry the server's own message (e.g. Z.ai's
|
|
558
|
+
// "Internal service error" outage); auth-looking messages were already
|
|
559
|
+
// redacted above, so surface the rest verbatim for diagnosability.
|
|
560
|
+
export function redactedError(error: unknown, provider = "Codex"): string {
|
|
561
|
+
const message = error instanceof Error ? error.message : String(error || "Unknown error");
|
|
562
|
+
if (/ENOENT|no such file/i.test(message)) return "Pi auth not found";
|
|
563
|
+
if (/missing openai-codex/i.test(message)) return "openai-codex auth not found";
|
|
564
|
+
if (/missing opencode-go/i.test(message)) return "opencode-go auth not found";
|
|
565
|
+
if (/missing zai/i.test(message)) return "zai auth not found";
|
|
566
|
+
if (/missing commandcode/i.test(message)) return "commandcode auth not found";
|
|
567
|
+
if (/timed out|timeout|aborted/i.test(message)) return `${provider} usage refresh timed out`;
|
|
568
|
+
if (/401|403|auth|token|unauthorized|forbidden/i.test(message)) return `${provider} auth unavailable`;
|
|
569
|
+
const apiMatch = / API error: (.+)$/.exec(message);
|
|
570
|
+
if (!apiMatch) return `${provider} usage unavailable`;
|
|
571
|
+
// Trust boundary: the msg is remote-controlled — scrub credential-shaped
|
|
572
|
+
// material and cap length before it reaches the status bar.
|
|
573
|
+
const scrubbed = apiMatch[1]
|
|
574
|
+
.replace(/sk-[A-Za-z0-9_-]+|Bearer\s+\S+|eyJ[A-Za-z0-9._-]+/g, "[REDACTED]")
|
|
575
|
+
.slice(0, 120);
|
|
576
|
+
return scrubbed ? `${provider} API error: ${scrubbed}` : `${provider} usage unavailable`;
|
|
577
|
+
}
|
|
578
|
+
|
|
579
|
+
async function fetchCodexUsage(signal?: AbortSignal): Promise<SubscriptionUsageSnapshot> {
|
|
580
|
+
try {
|
|
581
|
+
const entry = await readPiCodexAuth();
|
|
582
|
+
let activeAccount = accountFromPiAuth(entry);
|
|
583
|
+
const usage = await fetchUsageFromPiAuth(entry, signal);
|
|
584
|
+
activeAccount = mergeUsageIntoAccount(activeAccount, usage);
|
|
585
|
+
return {
|
|
586
|
+
providerDisplayName: "Codex",
|
|
587
|
+
accounts: [activeAccount],
|
|
588
|
+
activeAccount,
|
|
589
|
+
fetchedAt: Date.now(),
|
|
590
|
+
};
|
|
591
|
+
} catch (error) {
|
|
592
|
+
return {
|
|
593
|
+
providerDisplayName: "Codex",
|
|
594
|
+
accounts: [],
|
|
595
|
+
fetchedAt: Date.now(),
|
|
596
|
+
error: redactedError(error),
|
|
597
|
+
};
|
|
598
|
+
}
|
|
599
|
+
}
|
|
600
|
+
|
|
601
|
+
export async function fetchOpenCodeGoUsage(signal?: AbortSignal): Promise<SubscriptionUsageSnapshot> {
|
|
602
|
+
try {
|
|
603
|
+
const { key, account } = await readOpenCodeGoAuth();
|
|
604
|
+
let windows: Pick<SubscriptionAccountSnapshot, "fiveHour" | "weekly" | "monthly"> = {};
|
|
605
|
+
if (key) {
|
|
606
|
+
let shapeError: Error | undefined;
|
|
607
|
+
try {
|
|
608
|
+
const timeoutSignal = AbortSignal.timeout(7_000);
|
|
609
|
+
const combinedSignal = signal ? AbortSignal.any([signal, timeoutSignal]) : timeoutSignal;
|
|
610
|
+
const response = await fetch(OPC_USAGE_URL, {
|
|
611
|
+
headers: {
|
|
612
|
+
Accept: "application/json",
|
|
613
|
+
Authorization: `Bearer ${key}`,
|
|
614
|
+
"User-Agent": `ceulen/${CEULEN_VERSION}`,
|
|
615
|
+
},
|
|
616
|
+
signal: combinedSignal,
|
|
617
|
+
});
|
|
618
|
+
if (!response.ok) throw new Error(`usage request failed with HTTP ${response.status}`);
|
|
619
|
+
const body = (await response.json()) as OpcUsageApiResponse;
|
|
620
|
+
const fiveHour = opcWindowToUsageWindow(body.usage?.rolling);
|
|
621
|
+
const weekly = opcWindowToUsageWindow(body.usage?.weekly);
|
|
622
|
+
const monthly = opcWindowToUsageWindow(body.usage?.monthly);
|
|
623
|
+
if (!fiveHour && !weekly && !monthly) {
|
|
624
|
+
// HTTP 200 but nothing parsed: structural (shape drift), not
|
|
625
|
+
// transient — surface it so the parser gets fixed.
|
|
626
|
+
shapeError = new Error("No usage windows in OpenCode Go response");
|
|
627
|
+
} else {
|
|
628
|
+
windows = { fiveHour, weekly, monthly };
|
|
629
|
+
}
|
|
630
|
+
} catch {
|
|
631
|
+
// ponytail: transport/API failures (offline, timeout, HTTP error) are
|
|
632
|
+
// transient — never degrade to the empty-error footer, the label,
|
|
633
|
+
// session cost, and tok/s would vanish (0.1.46 regression). Keep the
|
|
634
|
+
// 0.1.44 always-renders behavior and just skip the windows.
|
|
635
|
+
}
|
|
636
|
+
if (shapeError) throw shapeError;
|
|
637
|
+
}
|
|
638
|
+
// ponytail: keyless (accountId-only) setups keep the auth-only snapshot —
|
|
639
|
+
// session cost still renders, no usage API to call.
|
|
640
|
+
return {
|
|
641
|
+
providerDisplayName: "OpenCode Go",
|
|
642
|
+
accounts: [{ ...account, ...windows }],
|
|
643
|
+
activeAccount: { ...account, ...windows },
|
|
644
|
+
fetchedAt: Date.now(),
|
|
645
|
+
};
|
|
646
|
+
} catch (error) {
|
|
647
|
+
return {
|
|
648
|
+
providerDisplayName: "OpenCode Go",
|
|
649
|
+
accounts: [],
|
|
650
|
+
fetchedAt: Date.now(),
|
|
651
|
+
error: redactedError(error, "OpenCode Go"),
|
|
652
|
+
};
|
|
653
|
+
}
|
|
654
|
+
}
|
|
655
|
+
|
|
656
|
+
async function fetchRouterUsage(signal?: AbortSignal, provider?: string): Promise<SubscriptionUsageSnapshot> {
|
|
657
|
+
const cfg = readRouterConfig();
|
|
658
|
+
const now = Date.now();
|
|
659
|
+
if (!cfg) {
|
|
660
|
+
return {
|
|
661
|
+
providerDisplayName: "Router",
|
|
662
|
+
accounts: [],
|
|
663
|
+
fetchedAt: now,
|
|
664
|
+
error: "router not configured — set router.baseUrl in ~/.pi/agent/settings.json",
|
|
665
|
+
};
|
|
666
|
+
}
|
|
667
|
+
const apiKey = readRouterApiKey();
|
|
668
|
+
const baseAccount: SubscriptionAccountSnapshot = {
|
|
669
|
+
id: cfg.baseUrl,
|
|
670
|
+
isActive: true,
|
|
671
|
+
accountLabel: cfg.baseUrl.replace(/^https?:\/\//, ""),
|
|
672
|
+
lastActivity: "Now",
|
|
673
|
+
};
|
|
674
|
+
|
|
675
|
+
// General usage API (yardmaster): GET <baseUrl>/usage?provider=<prefix> —
|
|
676
|
+
// JSON with windows (session/weekly remaining_pct + reset_at) and credits.
|
|
677
|
+
// baseUrl already ends in /v1 so no origin derivation is needed. Unknown
|
|
678
|
+
// provider slugs 404 → retry the aggregate (no query). Routers without this
|
|
679
|
+
// endpoint (OmniRoute) 404/return HTML → fall through to the om-usage text
|
|
680
|
+
// flow below. A 200 JSON without windows/credits also falls through.
|
|
681
|
+
if (apiKey) {
|
|
682
|
+
try {
|
|
683
|
+
const timeoutSignal = AbortSignal.timeout(7_000);
|
|
684
|
+
const combined = signal ? AbortSignal.any([signal, timeoutSignal]) : timeoutSignal;
|
|
685
|
+
const usageUrl = (q: string) => `${cfg.baseUrl.replace(/\/$/, "")}/usage${q}`;
|
|
686
|
+
let response = await fetch(usageUrl(provider ? `?provider=${encodeURIComponent(provider)}` : ""), {
|
|
687
|
+
headers: { Accept: "application/json", Authorization: `Bearer ${apiKey}` },
|
|
688
|
+
signal: combined,
|
|
689
|
+
});
|
|
690
|
+
if (response.status === 404 && provider) {
|
|
691
|
+
response = await fetch(usageUrl(""), {
|
|
692
|
+
headers: { Accept: "application/json", Authorization: `Bearer ${apiKey}` },
|
|
693
|
+
signal: combined,
|
|
694
|
+
});
|
|
695
|
+
}
|
|
696
|
+
const ct = response.headers.get("content-type") ?? "";
|
|
697
|
+
if (response.ok && ct.includes("application/json")) {
|
|
698
|
+
const g = parseGenericUsage(await response.json());
|
|
699
|
+
if (g.fiveHour || g.weekly || g.monthly || g.monthlyCredits !== undefined) {
|
|
700
|
+
const account: SubscriptionAccountSnapshot = {
|
|
701
|
+
...baseAccount,
|
|
702
|
+
plan: provider ? `Router · ${provider}` : "Router usage",
|
|
703
|
+
fiveHour: g.fiveHour,
|
|
704
|
+
weekly: g.weekly,
|
|
705
|
+
monthly: g.monthly,
|
|
706
|
+
monthlyCredits: g.monthlyCredits,
|
|
707
|
+
creditsCurrency: g.creditsCurrency,
|
|
708
|
+
usageBreakdown: g.breakdown,
|
|
709
|
+
};
|
|
710
|
+
return {
|
|
711
|
+
providerDisplayName: "Router",
|
|
712
|
+
accounts: [account],
|
|
713
|
+
activeAccount: account,
|
|
714
|
+
fetchedAt: Date.now(),
|
|
715
|
+
};
|
|
716
|
+
}
|
|
717
|
+
}
|
|
718
|
+
} catch { /* no general usage endpoint / transient — fall through */ }
|
|
719
|
+
}
|
|
720
|
+
|
|
721
|
+
// OmniRoute exposes per-key usage at GET <origin>/api/usage/om-usage
|
|
722
|
+
// (Bearer = the router API key). `?provider=` selects that upstream's quota
|
|
723
|
+
// (e.g. command-code/deepseek/deepseek-v4-flash → provider=command-code);
|
|
724
|
+
// without it the report shows the best/all snapshot. Plain text: Personal
|
|
725
|
+
// quota (Daily/Weekly USD budgets) + Provider quota (Session/Weekly).
|
|
726
|
+
// Non-OmniRoute routers 404 here — fall back to endpoint-only display.
|
|
727
|
+
if (apiKey) {
|
|
728
|
+
try {
|
|
729
|
+
const timeoutSignal = AbortSignal.timeout(7_000);
|
|
730
|
+
const combined = signal ? AbortSignal.any([signal, timeoutSignal]) : timeoutSignal;
|
|
731
|
+
const url = `${routerOrigin(cfg.baseUrl)}/api/usage/om-usage` +
|
|
732
|
+
(provider ? `?provider=${encodeURIComponent(provider)}` : "");
|
|
733
|
+
const response = await fetch(url, {
|
|
734
|
+
headers: { Accept: "text/plain", Authorization: `Bearer ${apiKey}` },
|
|
735
|
+
signal: combined,
|
|
736
|
+
});
|
|
737
|
+
if (response.ok) {
|
|
738
|
+
let text = await response.text();
|
|
739
|
+
if (text && !text.includes("disabled")) {
|
|
740
|
+
let w = parseOmniUsageText(text);
|
|
741
|
+
// "No cached usage data" = unknown/wrong slug — retry without
|
|
742
|
+
// ?provider= for the best/all snapshot. "Unavailable" windows mean a
|
|
743
|
+
// known credit-based upstream (deepseek) — keep them empty so the
|
|
744
|
+
// USD-balance path below takes over instead of showing the aggregate.
|
|
745
|
+
if (provider && !w.session && !w.providerWeekly && text.includes("No cached usage data")) {
|
|
746
|
+
const plain = await fetch(url.replace(/\?provider=.*$/, ""), {
|
|
747
|
+
headers: { Accept: "text/plain", Authorization: `Bearer ${apiKey}` },
|
|
748
|
+
signal: combined,
|
|
749
|
+
});
|
|
750
|
+
if (plain.ok) {
|
|
751
|
+
const plainText = await plain.text();
|
|
752
|
+
if (plainText && !plainText.includes("disabled")) {
|
|
753
|
+
w = parseOmniUsageText(plainText);
|
|
754
|
+
text = plainText;
|
|
755
|
+
}
|
|
756
|
+
}
|
|
757
|
+
}
|
|
758
|
+
// Credit-based upstreams (deepseek): the usage text prints "Unavailable"
|
|
759
|
+
// windows — pull the real USD balance from the management API instead.
|
|
760
|
+
const credits = await fetchRouterCredits(provider, w);
|
|
761
|
+
if (credits) {
|
|
762
|
+
const account: SubscriptionAccountSnapshot = {
|
|
763
|
+
...baseAccount,
|
|
764
|
+
plan: `Router · ${provider}`,
|
|
765
|
+
monthlyCredits: credits.balanceUsd,
|
|
766
|
+
usageBreakdown: credits.breakdown,
|
|
767
|
+
};
|
|
768
|
+
return {
|
|
769
|
+
providerDisplayName: "Router",
|
|
770
|
+
accounts: [account],
|
|
771
|
+
activeAccount: account,
|
|
772
|
+
fetchedAt: Date.now(),
|
|
773
|
+
};
|
|
774
|
+
}
|
|
775
|
+
// personalDaily = per-key budget (nearest reset → R slot),
|
|
776
|
+
// provider weekly/session = upstream quota (W slot). Fall back sensibly.
|
|
777
|
+
const account: SubscriptionAccountSnapshot = {
|
|
778
|
+
...baseAccount,
|
|
779
|
+
plan: provider ? `Router · ${provider}` : "Router usage",
|
|
780
|
+
fiveHour: w.personalDaily ?? w.session,
|
|
781
|
+
weekly: w.providerWeekly ?? w.personalWeekly,
|
|
782
|
+
// breakdown keeps only the provider-quota section — the raw text can
|
|
783
|
+
// include personal USD budget lines (privacy) and is noisy.
|
|
784
|
+
usageBreakdown: providerQuotaSection(text),
|
|
785
|
+
};
|
|
786
|
+
return {
|
|
787
|
+
providerDisplayName: "Router",
|
|
788
|
+
accounts: [account],
|
|
789
|
+
activeAccount: account,
|
|
790
|
+
fetchedAt: Date.now(),
|
|
791
|
+
};
|
|
792
|
+
}
|
|
793
|
+
// Usage command exists but is disabled for this key — keep the footer
|
|
794
|
+
// clean (endpoint display) and surface the hint in /usage detail only.
|
|
795
|
+
const hintAccount: SubscriptionAccountSnapshot = {
|
|
796
|
+
...baseAccount,
|
|
797
|
+
usageBreakdown: `OmniRoute usage command is disabled for this router key — ` +
|
|
798
|
+
`enable it in the dashboard (API Keys → the key ending ${apiKey?.slice(-4)} → usage command).`,
|
|
799
|
+
};
|
|
800
|
+
return {
|
|
801
|
+
providerDisplayName: "Router",
|
|
802
|
+
accounts: [hintAccount],
|
|
803
|
+
activeAccount: hintAccount,
|
|
804
|
+
fetchedAt: Date.now(),
|
|
805
|
+
};
|
|
806
|
+
}
|
|
807
|
+
} catch { /* non-OmniRoute or transient — fall through to endpoint display */ }
|
|
808
|
+
}
|
|
809
|
+
|
|
810
|
+
return {
|
|
811
|
+
providerDisplayName: "Router",
|
|
812
|
+
accounts: [baseAccount],
|
|
813
|
+
activeAccount: baseAccount,
|
|
814
|
+
fetchedAt: now,
|
|
815
|
+
};
|
|
816
|
+
}
|
|
817
|
+
|
|
818
|
+
interface RouterCredits {
|
|
819
|
+
balanceUsd: number;
|
|
820
|
+
breakdown: string;
|
|
821
|
+
}
|
|
822
|
+
|
|
823
|
+
/** Fetch the raw USD balance for credit-based upstreams (deepseek: `credits_usd`)
|
|
824
|
+
* via OmniRoute's management usage API. Only called when the key-authable
|
|
825
|
+
* om-usage text reports no usable windows — that surface normalizes credits
|
|
826
|
+
* to meaningless percentages. Needs the router key to hold the `manage`
|
|
827
|
+
* scope (or ROUTER_MGMT_TOKEN as override). Connection discovery comes from
|
|
828
|
+
* /api/v1/me/status (key-authable); the balance from /api/usage/<id>. */
|
|
829
|
+
async function fetchRouterCredits(provider: string | undefined, w: ReturnType<typeof parseOmniUsageText>): Promise<RouterCredits | undefined> {
|
|
830
|
+
if (!provider || w.session || w.providerWeekly) return undefined;
|
|
831
|
+
const cfg = readRouterConfig();
|
|
832
|
+
const apiKey = readRouterApiKey();
|
|
833
|
+
const mgmtToken = readRouterMgmtToken(apiKey);
|
|
834
|
+
if (!cfg || !apiKey || !mgmtToken) return undefined;
|
|
835
|
+
const origin = routerOrigin(cfg.baseUrl);
|
|
836
|
+
try {
|
|
837
|
+
const combined = AbortSignal.timeout(7_000);
|
|
838
|
+
// 1. Connection id for this upstream via the key-authable status endpoint.
|
|
839
|
+
const statusRes = await fetch(`${origin}/api/v1/me/status`, {
|
|
840
|
+
headers: { Authorization: `Bearer ${apiKey}` },
|
|
841
|
+
signal: combined,
|
|
842
|
+
});
|
|
843
|
+
if (!statusRes.ok) return undefined;
|
|
844
|
+
const status = (await statusRes.json()) as { accountQuotas?: Array<{ provider?: string; connectionId?: string }> };
|
|
845
|
+
const connectionId = status.accountQuotas?.find((q) => q.provider === provider)?.connectionId;
|
|
846
|
+
if (!connectionId) return undefined;
|
|
847
|
+
// 2. Raw usage (management token) — quotas.credits_usd.remaining is the USD balance.
|
|
848
|
+
const usageRes = await fetch(`${origin}/api/usage/${connectionId}`, {
|
|
849
|
+
headers: { Authorization: `Bearer ${mgmtToken}` },
|
|
850
|
+
signal: combined,
|
|
851
|
+
});
|
|
852
|
+
if (!usageRes.ok) return undefined;
|
|
853
|
+
const usage = (await usageRes.json()) as { quotas?: Record<string, { remaining?: number }> };
|
|
854
|
+
const credits = usage.quotas?.credits_usd ?? usage.quotas?.credits;
|
|
855
|
+
const remaining = credits?.remaining;
|
|
856
|
+
if (typeof remaining !== "number" || !Number.isFinite(remaining)) return undefined;
|
|
857
|
+
const cny = usage.quotas?.credits_cny?.remaining;
|
|
858
|
+
return {
|
|
859
|
+
balanceUsd: remaining,
|
|
860
|
+
breakdown: `🪙 Balance (USD) $${remaining.toFixed(2)}` +
|
|
861
|
+
(typeof cny === "number" ? ` · ¥${cny.toFixed(2)} CNY` : ""),
|
|
862
|
+
};
|
|
863
|
+
} catch {
|
|
864
|
+
return undefined; // no mgmt token / upstream down — fall back to endpoint display
|
|
865
|
+
}
|
|
866
|
+
}
|
|
867
|
+
|
|
868
|
+
// Command Code's /alpha/billing/credits endpoint (auth: same Provider API key
|
|
869
|
+
// as /provider/v1 models) returns live 5-hour and weekly rolling windows plus
|
|
870
|
+
// the monthly credit balance — the same data as the cmd /usage CLI.
|
|
871
|
+
async function fetchCommandCodeUsage(signal?: AbortSignal): Promise<SubscriptionUsageSnapshot> {
|
|
872
|
+
try {
|
|
873
|
+
const { key: apiKey, account: authAccount } = await readZaiAuth(COMMAND_CODE_PROVIDER, "Command Code");
|
|
874
|
+
const timeoutSignal = AbortSignal.timeout(7_000);
|
|
875
|
+
const combinedSignal = signal ? AbortSignal.any([signal, timeoutSignal]) : timeoutSignal;
|
|
876
|
+
|
|
877
|
+
const headers = {
|
|
878
|
+
Accept: "application/json",
|
|
879
|
+
Authorization: `Bearer ${apiKey}`,
|
|
880
|
+
"User-Agent": `ceulen/${CEULEN_VERSION}`,
|
|
881
|
+
};
|
|
882
|
+
const response = await fetch(COMMAND_CODE_USAGE_URL, { headers, signal: combinedSignal });
|
|
883
|
+
if (!response.ok) {
|
|
884
|
+
throw new Error(`Command Code usage request failed with HTTP ${response.status}`);
|
|
885
|
+
}
|
|
886
|
+
const body = (await response.json()) as CommandCodeCreditsApiResponse;
|
|
887
|
+
|
|
888
|
+
const credits = body.credits;
|
|
889
|
+
const windowLimits = body.windowLimits;
|
|
890
|
+
const fiveHour = commandCodeWindowToUsageWindow(windowLimits?.fiveHour);
|
|
891
|
+
const weekly = commandCodeWindowToUsageWindow(windowLimits?.weekly);
|
|
892
|
+
|
|
893
|
+
// Monthly allowance is an absolute USD balance, not a rolling window.
|
|
894
|
+
const monthlyCredits = typeof credits?.monthlyCredits === "number" ? credits.monthlyCredits : undefined;
|
|
895
|
+
const monthlyLine = monthlyCredits !== undefined ? `Monthly: $${monthlyCredits.toFixed(2)} remaining` : undefined;
|
|
896
|
+
const breakdown = [monthlyLine].filter((s): s is string => !!s);
|
|
897
|
+
|
|
898
|
+
const account: SubscriptionAccountSnapshot = {
|
|
899
|
+
...authAccount,
|
|
900
|
+
fiveHour,
|
|
901
|
+
weekly,
|
|
902
|
+
monthlyCredits,
|
|
903
|
+
usageBreakdown: breakdown.length > 0 ? breakdown.join("\n") : undefined,
|
|
904
|
+
};
|
|
905
|
+
|
|
906
|
+
return {
|
|
907
|
+
providerDisplayName: "Command Code",
|
|
908
|
+
accounts: [account],
|
|
909
|
+
activeAccount: account,
|
|
910
|
+
fetchedAt: Date.now(),
|
|
911
|
+
};
|
|
912
|
+
} catch (error) {
|
|
913
|
+
return {
|
|
914
|
+
providerDisplayName: "Command Code",
|
|
915
|
+
accounts: [],
|
|
916
|
+
fetchedAt: Date.now(),
|
|
917
|
+
error: redactedError(error, "Command Code"),
|
|
918
|
+
};
|
|
919
|
+
}
|
|
920
|
+
}
|
|
921
|
+
|
|
922
|
+
// ---------------------------------------------------------------------------
|
|
923
|
+
// Z.ai adapter
|
|
924
|
+
// ---------------------------------------------------------------------------
|
|
925
|
+
|
|
926
|
+
interface ZaiLimitEntry {
|
|
927
|
+
type: string;
|
|
928
|
+
percentage: number;
|
|
929
|
+
nextResetTime?: number;
|
|
930
|
+
}
|
|
931
|
+
|
|
932
|
+
interface ZaiUsageApiResponse {
|
|
933
|
+
data?: {
|
|
934
|
+
limits?: ZaiLimitEntry[];
|
|
935
|
+
planName?: string;
|
|
936
|
+
plan?: string;
|
|
937
|
+
plan_type?: string;
|
|
938
|
+
packageName?: string;
|
|
939
|
+
level?: string;
|
|
940
|
+
};
|
|
941
|
+
}
|
|
942
|
+
|
|
943
|
+
interface ZaiUsageApiError {
|
|
944
|
+
code: number;
|
|
945
|
+
msg: string;
|
|
946
|
+
success?: boolean;
|
|
947
|
+
}
|
|
948
|
+
|
|
949
|
+
// ---------------------------------------------------------------------------
|
|
950
|
+
// Command Code adapter
|
|
951
|
+
// ---------------------------------------------------------------------------
|
|
952
|
+
// Live-verified 2026-08-09: GET https://api.commandcode.ai/alpha/billing/credits
|
|
953
|
+
// with the Provider API key (same user_... key as /provider/v1 models) returns
|
|
954
|
+
// USD windows + monthly credit balance. resetAt is epoch milliseconds.
|
|
955
|
+
|
|
956
|
+
interface CommandCodeWindowApi {
|
|
957
|
+
used: number;
|
|
958
|
+
cap: number;
|
|
959
|
+
exceeded?: boolean | null;
|
|
960
|
+
resetAt?: number;
|
|
961
|
+
}
|
|
962
|
+
|
|
963
|
+
interface CommandCodeCreditsApiResponse {
|
|
964
|
+
credits?: {
|
|
965
|
+
monthlyCredits?: number;
|
|
966
|
+
purchasedCredits?: number;
|
|
967
|
+
freeCredits?: number;
|
|
968
|
+
belowThreshold?: boolean;
|
|
969
|
+
};
|
|
970
|
+
windowLimits?: {
|
|
971
|
+
limited?: boolean;
|
|
972
|
+
fiveHour?: CommandCodeWindowApi;
|
|
973
|
+
weekly?: CommandCodeWindowApi;
|
|
974
|
+
};
|
|
975
|
+
}
|
|
976
|
+
|
|
977
|
+
/** Map a Command Code USD window (used/cap in dollars, resetAt in ms) into
|
|
978
|
+
* the shared UsageWindow shape (remaining%, reset labels). */
|
|
979
|
+
export function commandCodeWindowToUsageWindow(window: CommandCodeWindowApi | undefined): UsageWindow | undefined {
|
|
980
|
+
if (!window || typeof window.used !== "number" || typeof window.cap !== "number" || window.cap <= 0) return undefined;
|
|
981
|
+
const usedPct = Math.round((window.used / window.cap) * 100);
|
|
982
|
+
const percent = Math.min(100, usedPct);
|
|
983
|
+
const remaining = Math.max(0, 100 - percent);
|
|
984
|
+
// resetAt is epoch ms; format helpers expect seconds.
|
|
985
|
+
const resetAtSec = window.resetAt ? window.resetAt / 1000 : undefined;
|
|
986
|
+
const resetLabel = formatReset(resetAtSec);
|
|
987
|
+
const remainingLabel = formatRemainingTime(resetAtSec);
|
|
988
|
+
return { percent, remaining, remainingLabel, resetLabel };
|
|
989
|
+
}
|
|
990
|
+
|
|
991
|
+
function zaiLimitToUsageWindow(limit: ZaiLimitEntry): UsageWindow | undefined {
|
|
992
|
+
if (typeof limit.percentage !== "number") return undefined;
|
|
993
|
+
const percent = Math.round(limit.percentage);
|
|
994
|
+
const remaining = Math.max(0, 100 - percent);
|
|
995
|
+
// Z.ai returns nextResetTime in epoch milliseconds; format helpers expect seconds.
|
|
996
|
+
const resetAtSec = limit.nextResetTime ? limit.nextResetTime / 1000 : undefined;
|
|
997
|
+
const resetLabel = formatReset(resetAtSec);
|
|
998
|
+
const remainingLabel = formatRemainingTime(resetAtSec);
|
|
999
|
+
return {
|
|
1000
|
+
percent,
|
|
1001
|
+
remaining,
|
|
1002
|
+
remainingLabel,
|
|
1003
|
+
resetLabel,
|
|
1004
|
+
};
|
|
1005
|
+
}
|
|
1006
|
+
|
|
1007
|
+
function zaiPlanLabel(response: ZaiUsageApiResponse): string | undefined {
|
|
1008
|
+
const data = response.data;
|
|
1009
|
+
return planLabel(firstString(data?.planName, data?.plan, data?.plan_type, data?.packageName, data?.level));
|
|
1010
|
+
}
|
|
1011
|
+
|
|
1012
|
+
function compactCount(n: number): string {
|
|
1013
|
+
if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(1)}M`;
|
|
1014
|
+
if (n >= 1_000) return `${Math.round(n / 1_000)}K`;
|
|
1015
|
+
return String(n);
|
|
1016
|
+
}
|
|
1017
|
+
|
|
1018
|
+
// ponytail: trailing-24h window matches Z.ai dashboard intent (chelper uses ~48h).
|
|
1019
|
+
function zaiUsageTimeWindow(): string {
|
|
1020
|
+
const fmt = (d: Date) => {
|
|
1021
|
+
const p = (n: number) => String(n).padStart(2, "0");
|
|
1022
|
+
return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}:${p(d.getSeconds())}`;
|
|
1023
|
+
};
|
|
1024
|
+
const now = new Date();
|
|
1025
|
+
return `?startTime=${encodeURIComponent(fmt(new Date(now.getTime() - 86_400_000)))}&endTime=${encodeURIComponent(fmt(now))}`;
|
|
1026
|
+
}
|
|
1027
|
+
|
|
1028
|
+
// Z.ai model-usage / tool-usage are time-series responses (verified live, CN host).
|
|
1029
|
+
// Per-model totals live in data.totalUsage.modelSummaryList[]; tool totals are
|
|
1030
|
+
// named scalars in data.totalUsage. Return undefined on any mismatch so the
|
|
1031
|
+
// quota table is never affected.
|
|
1032
|
+
function parseZaiModelUsage(body: unknown): string | undefined {
|
|
1033
|
+
const tu = (body as any)?.data?.totalUsage;
|
|
1034
|
+
const list = tu?.modelSummaryList;
|
|
1035
|
+
if (!Array.isArray(list)) return undefined;
|
|
1036
|
+
const entries = list
|
|
1037
|
+
.map((m: any) => ({ name: m?.modelName, count: m?.totalTokens }))
|
|
1038
|
+
.filter((e: { name: string; count: number }) => typeof e.name === "string" && e.name && typeof e.count === "number" && e.count > 0)
|
|
1039
|
+
.sort((a, b) => b.count - a.count);
|
|
1040
|
+
if (entries.length === 0) return undefined;
|
|
1041
|
+
const calls = typeof tu.totalModelCallCount === "number" && tu.totalModelCallCount > 0 ? ` (${tu.totalModelCallCount} calls)` : "";
|
|
1042
|
+
return `Models: ${entries.map((e) => `${e.name} ${compactCount(e.count)}`).join(" · ")}${calls}`;
|
|
1043
|
+
}
|
|
1044
|
+
|
|
1045
|
+
function parseZaiToolUsage(body: unknown): string | undefined {
|
|
1046
|
+
const u = (body as any)?.data?.totalUsage;
|
|
1047
|
+
if (!u || typeof u !== "object") return undefined;
|
|
1048
|
+
// ponytail: fixed label map — Z.ai returns named scalar counts, not a list.
|
|
1049
|
+
const labels: Record<string, string> = {
|
|
1050
|
+
totalNetworkSearchCount: "search",
|
|
1051
|
+
totalWebReadMcpCount: "web-read",
|
|
1052
|
+
totalZreadMcpCount: "zread",
|
|
1053
|
+
totalSearchMcpCount: "search-mcp",
|
|
1054
|
+
};
|
|
1055
|
+
const entries = Object.entries(labels)
|
|
1056
|
+
.map(([field, label]) => ({ label, count: u[field] }))
|
|
1057
|
+
.filter((e: { label: string; count: number }) => typeof e.count === "number" && e.count > 0);
|
|
1058
|
+
if (entries.length === 0) return undefined;
|
|
1059
|
+
return `Tools: ${entries.map((e) => `${e.label} ${e.count}`).join(" · ")}`;
|
|
1060
|
+
}
|
|
1061
|
+
|
|
1062
|
+
// Factory: the international `zai` and China `zai-coding-cn` endpoints share an
|
|
1063
|
+
// identical quota response; only the provider id, host, and label differ.
|
|
1064
|
+
function zaiUsageAdapter(providerId: string, usageUrl: string, displayName: string): { fetchUsage(signal?: AbortSignal): Promise<SubscriptionUsageSnapshot> } {
|
|
1065
|
+
async function fetchUsage(signal?: AbortSignal): Promise<SubscriptionUsageSnapshot> {
|
|
1066
|
+
try {
|
|
1067
|
+
const { key: apiKey, account: authAccount } = await readZaiAuth(providerId, displayName);
|
|
1068
|
+
const timeoutSignal = AbortSignal.timeout(7_000);
|
|
1069
|
+
const combinedSignal = signal ? AbortSignal.any([signal, timeoutSignal]) : timeoutSignal;
|
|
1070
|
+
|
|
1071
|
+
const headers = {
|
|
1072
|
+
Accept: "application/json",
|
|
1073
|
+
Authorization: `Bearer ${apiKey}`,
|
|
1074
|
+
"User-Agent": `ceulen/${CEULEN_VERSION}`,
|
|
1075
|
+
};
|
|
1076
|
+
const response = await fetch(usageUrl, { headers, signal: combinedSignal });
|
|
1077
|
+
|
|
1078
|
+
const body = await response.json();
|
|
1079
|
+
|
|
1080
|
+
// Z.ai / BigModel return HTTP 200 even on auth errors: {"code":401,"msg":"...","success":false}
|
|
1081
|
+
// Also handle missing success field, empty msg, or presence of code.
|
|
1082
|
+
const apiError = body as ZaiUsageApiError;
|
|
1083
|
+
if (apiError.code >= 400 || (typeof apiError.success === "boolean" && !apiError.success) || (apiError.msg && apiError.msg.length > 0 && apiError.success === undefined)) {
|
|
1084
|
+
const message = apiError.msg || `HTTP status ${apiError.code}`;
|
|
1085
|
+
throw new Error(`${displayName} API error: ${message}`);
|
|
1086
|
+
}
|
|
1087
|
+
|
|
1088
|
+
const parsed = body as ZaiUsageApiResponse;
|
|
1089
|
+
const limits = parsed.data?.limits ?? [];
|
|
1090
|
+
const tokenLimits = limits
|
|
1091
|
+
.filter((l) => l.type === "TOKENS_LIMIT")
|
|
1092
|
+
.sort((a, b) => (a.nextResetTime ?? 0) - (b.nextResetTime ?? 0));
|
|
1093
|
+
// TIME_LIMIT is the MCP/month allowance already present in this response.
|
|
1094
|
+
const timeLimit = limits.find((l) => l.type === "TIME_LIMIT");
|
|
1095
|
+
|
|
1096
|
+
if (tokenLimits.length === 0) {
|
|
1097
|
+
throw new Error(`No TOKENS_LIMIT entries in ${displayName} usage response`);
|
|
1098
|
+
}
|
|
1099
|
+
|
|
1100
|
+
// The limit with the nearest reset is the 5-hour rolling window;
|
|
1101
|
+
// the next one (if present) is the weekly window.
|
|
1102
|
+
const fiveHour = zaiLimitToUsageWindow(tokenLimits[0]);
|
|
1103
|
+
const weekly = tokenLimits.length >= 2 ? zaiLimitToUsageWindow(tokenLimits[1]) : undefined;
|
|
1104
|
+
const mcpMonthly = timeLimit ? zaiLimitToUsageWindow(timeLimit) : undefined;
|
|
1105
|
+
|
|
1106
|
+
// Best-effort: per-model tokens + per-tool calls. Any failure is silent; the
|
|
1107
|
+
// quota table above is the source of truth and never depends on these.
|
|
1108
|
+
const window = zaiUsageTimeWindow();
|
|
1109
|
+
const modelUrl = usageUrl.replace(/\/quota\/limit$/, "/model-usage") + window;
|
|
1110
|
+
const toolUrl = usageUrl.replace(/\/quota\/limit$/, "/tool-usage") + window;
|
|
1111
|
+
const [modelRes, toolRes] = await Promise.allSettled([
|
|
1112
|
+
fetch(modelUrl, { headers, signal: combinedSignal }).then((r) => r.json()),
|
|
1113
|
+
fetch(toolUrl, { headers, signal: combinedSignal }).then((r) => r.json()),
|
|
1114
|
+
]);
|
|
1115
|
+
const breakdowns = [
|
|
1116
|
+
modelRes.status === "fulfilled" ? parseZaiModelUsage(modelRes.value) : undefined,
|
|
1117
|
+
toolRes.status === "fulfilled" ? parseZaiToolUsage(toolRes.value) : undefined,
|
|
1118
|
+
].filter((s): s is string => !!s);
|
|
1119
|
+
|
|
1120
|
+
const account: SubscriptionAccountSnapshot = {
|
|
1121
|
+
...authAccount,
|
|
1122
|
+
plan: zaiPlanLabel(parsed) ?? authAccount.plan,
|
|
1123
|
+
fiveHour,
|
|
1124
|
+
weekly,
|
|
1125
|
+
mcpMonthly,
|
|
1126
|
+
usageBreakdown: breakdowns.length > 0 ? breakdowns.join("\n") : undefined,
|
|
1127
|
+
};
|
|
1128
|
+
|
|
1129
|
+
return {
|
|
1130
|
+
providerDisplayName: displayName,
|
|
1131
|
+
accounts: [account],
|
|
1132
|
+
activeAccount: account,
|
|
1133
|
+
fetchedAt: Date.now(),
|
|
1134
|
+
};
|
|
1135
|
+
} catch (error) {
|
|
1136
|
+
return {
|
|
1137
|
+
providerDisplayName: displayName,
|
|
1138
|
+
accounts: [],
|
|
1139
|
+
fetchedAt: Date.now(),
|
|
1140
|
+
error: redactedError(error, displayName),
|
|
1141
|
+
};
|
|
1142
|
+
}
|
|
1143
|
+
}
|
|
1144
|
+
return { fetchUsage };
|
|
1145
|
+
}
|
|
1146
|
+
|
|
1147
|
+
// Exported for the adapter-wiring regression test (provider-id string ↔
|
|
1148
|
+
// adapter id ↔ usage URL are exactly what a typo silently breaks).
|
|
1149
|
+
export function supportedAdapter(model: ModelLike): SubscriptionProviderAdapter | undefined {
|
|
1150
|
+
if (isCodexModel(model)) return { id: CODEX_PROVIDER, displayName: "Codex", fetchUsage: fetchCodexUsage };
|
|
1151
|
+
if (isOpenCodeGoModel(model)) return { id: OPC_PROVIDER, displayName: "OpenCode Go", fetchUsage: fetchOpenCodeGoUsage };
|
|
1152
|
+
if (isZaiModel(model)) return { id: ZAI_PROVIDER, displayName: "Z.ai", ...zaiUsageAdapter(ZAI_PROVIDER, ZAI_USAGE_URL, "Z.ai") };
|
|
1153
|
+
if (isZaiCodingCnModel(model)) return { id: ZAI_CODING_CN_PROVIDER, displayName: "Z.ai (CN)", ...zaiUsageAdapter(ZAI_CODING_CN_PROVIDER, ZAI_CODING_CN_USAGE_URL, "Z.ai (CN)") };
|
|
1154
|
+
if (isZaiAnthropicModel(model)) return { id: ZAI_ANTHROPIC_PROVIDER, displayName: "Z.ai (Anthropic)", ...zaiUsageAdapter(ZAI_ANTHROPIC_PROVIDER, ZAI_ANTHROPIC_USAGE_URL, "Z.ai (Anthropic)") };
|
|
1155
|
+
if (isRouterModel(model)) {
|
|
1156
|
+
const prefix = routerUpstreamPrefix(model);
|
|
1157
|
+
return {
|
|
1158
|
+
// Prefix in the id makes adapterChanged fire when switching upstreams
|
|
1159
|
+
// (e.g. opencode-go → command-code), so the in-flight fetch from the
|
|
1160
|
+
// previous model is discarded via the refreshGeneration guard.
|
|
1161
|
+
id: prefix ? `${ROUTER_PROVIDER}:${prefix}` : ROUTER_PROVIDER,
|
|
1162
|
+
displayName: "Router",
|
|
1163
|
+
// ponytail: capture the upstream provider prefix so fetchRouterUsage can
|
|
1164
|
+
// request that provider's quota from the OmniRoute usage API.
|
|
1165
|
+
fetchUsage: (signal) => fetchRouterUsage(signal, prefix),
|
|
1166
|
+
};
|
|
1167
|
+
}
|
|
1168
|
+
if (isRouterModel(model, LEGACY_9ROUTER_PROVIDER)) return { id: LEGACY_9ROUTER_PROVIDER, displayName: "9router (legacy)", fetchUsage: fetchRouterUsage };
|
|
1169
|
+
if (isCommandCodeModel(model)) return { id: COMMAND_CODE_PROVIDER, displayName: "Command Code", fetchUsage: fetchCommandCodeUsage };
|
|
1170
|
+
return undefined;
|
|
1171
|
+
}
|
|
1172
|
+
|
|
1173
|
+
/** Strip everything up to and including the "Provider quota" section header
|
|
1174
|
+
* so /usage breakdown never shows personal USD budget lines. */
|
|
1175
|
+
function providerQuotaSection(text: string): string | undefined {
|
|
1176
|
+
const idx = text.indexOf("Provider quota");
|
|
1177
|
+
if (idx < 0) return undefined;
|
|
1178
|
+
const section = text.slice(idx);
|
|
1179
|
+
return section.trim().length > 0 ? section : undefined;
|
|
1180
|
+
}
|
|
1181
|
+
|
|
1182
|
+
/** First path segment of a router model id = the upstream provider OmniRoute
|
|
1183
|
+
* routes to (e.g. `command-code/deepseek/deepseek-v4-flash` → `command-code`).
|
|
1184
|
+
* `router/provider/model` in pi flattens to id `provider/model`, so the prefix
|
|
1185
|
+
* is the first segment. Aliases normalize to the canonical provider id
|
|
1186
|
+
* (`cmd` → `command-code`); generic router aliases carry no provider info —
|
|
1187
|
+
* return undefined so the usage API picks the best snapshot. */
|
|
1188
|
+
export function routerUpstreamPrefix(model: ModelLike): string | undefined {
|
|
1189
|
+
const id = model?.id ?? "";
|
|
1190
|
+
const first = id.split("/")[0]?.toLowerCase();
|
|
1191
|
+
if (!first) return undefined;
|
|
1192
|
+
// Alias normalization: OmniRoute exposes the same upstream under several ids.
|
|
1193
|
+
if (first === "cmd") return "command-code";
|
|
1194
|
+
if (first === "oc") return "opencode-go";
|
|
1195
|
+
if (first === "ds") return "deepseek";
|
|
1196
|
+
if (first === "glmcn") return "glm-cn"; // OmniRoute connection slug (not the Pi provider id zai-coding-cn)
|
|
1197
|
+
// Generic router aliases / upstreams without cached quota data — no provider
|
|
1198
|
+
// selection; the usage API returns the best snapshot instead.
|
|
1199
|
+
const generic = new Set(["auto", "aug", "no-think", "tllm", "combo", "openrouter", "nvidia", "felo", "pepper", "mcode", "ddgw", "veoaifree-web", "veo-free"]);
|
|
1200
|
+
return generic.has(first) ? undefined : first;
|
|
1201
|
+
}
|
|
1202
|
+
|
|
1203
|
+
/** Currency-aware monthly-balance figure for footer/detail segments:
|
|
1204
|
+
* CNY → ¥88.00 CNY, anything else (incl. undefined) → $88.00. Mirrors the
|
|
1205
|
+
* breakdown formatting in parseGenericUsage. */
|
|
1206
|
+
export function formatMonthlyCredits(amount: number, currency?: string): string {
|
|
1207
|
+
return currency === "CNY" ? `¥${amount.toFixed(2)} CNY` : `$${amount.toFixed(2)}`;
|
|
1208
|
+
}
|
|
1209
|
+
|
|
1210
|
+
function formatRemaining(window: UsageWindow | undefined): string {
|
|
1211
|
+
if (!window) return "?";
|
|
1212
|
+
if (window.remainingLabel) return `${window.remaining}%/${window.remainingLabel}`;
|
|
1213
|
+
if (window.remaining !== undefined) return `${window.remaining}%`;
|
|
1214
|
+
return "?";
|
|
1215
|
+
}
|
|
1216
|
+
|
|
1217
|
+
function minRemaining(account: SubscriptionAccountSnapshot | undefined): number {
|
|
1218
|
+
const values: number[] = [];
|
|
1219
|
+
if (account?.fiveHour?.remaining !== undefined) values.push(account.fiveHour.remaining);
|
|
1220
|
+
if (account?.weekly?.remaining !== undefined) values.push(account.weekly.remaining);
|
|
1221
|
+
if (account?.monthly?.remaining !== undefined) values.push(account.monthly.remaining);
|
|
1222
|
+
if (values.length === 0) return 100;
|
|
1223
|
+
return Math.min(...values);
|
|
1224
|
+
}
|
|
1225
|
+
|
|
1226
|
+
function windowSegments(account: SubscriptionAccountSnapshot | undefined): string[] {
|
|
1227
|
+
if (!account) return [];
|
|
1228
|
+
const segments: string[] = [];
|
|
1229
|
+
if (account.fiveHour) segments.push(`R:${formatRemaining(account.fiveHour)}`);
|
|
1230
|
+
if (account.weekly) segments.push(`W:${formatRemaining(account.weekly)}`);
|
|
1231
|
+
if (account.monthly) segments.push(`M:${formatRemaining(account.monthly)}`);
|
|
1232
|
+
return segments;
|
|
1233
|
+
}
|
|
1234
|
+
|
|
1235
|
+
export function renderSubscriptionLine(state: State): void {
|
|
1236
|
+
// ponytail: resolve ctx at render time — any captured ctx goes stale on
|
|
1237
|
+
// session replacement (new/fork/switch/reload) and ctx.ui then throws.
|
|
1238
|
+
const ctx = state.ctx;
|
|
1239
|
+
if (!ctx) return;
|
|
1240
|
+
const theme = ctx.ui.theme;
|
|
1241
|
+
// pi-budget parity: the theme proxy may not be initialized yet — dereferencing
|
|
1242
|
+
// theme.fg throws (unhandledRejection → pi exits). Best-effort footer: skip.
|
|
1243
|
+
if (!theme?.fg) return;
|
|
1244
|
+
if (!state.adapter) {
|
|
1245
|
+
// Unsupported provider (e.g. Ollama): still show the last response speed.
|
|
1246
|
+
ctx.ui.setStatus(STATUS_KEY, state.lastTokPerSec !== undefined ? theme.fg("dim", `${state.lastTokPerSec} tok/s`) : undefined);
|
|
1247
|
+
return;
|
|
1248
|
+
}
|
|
1249
|
+
const snapshot = state.snapshot;
|
|
1250
|
+
let line: string;
|
|
1251
|
+
let color: "dim" | "warning" | "error" = "dim";
|
|
1252
|
+
if (!snapshot) {
|
|
1253
|
+
line = `Sub ${state.adapter.displayName} loading`;
|
|
1254
|
+
} else if (snapshot.error) {
|
|
1255
|
+
line = `Sub ${snapshot.error}`;
|
|
1256
|
+
color = "warning";
|
|
1257
|
+
} else {
|
|
1258
|
+
const account = snapshot.activeAccount;
|
|
1259
|
+
const windowParts = windowSegments(account);
|
|
1260
|
+
const accountPart = formatFooterAccount(account);
|
|
1261
|
+
const segments = accountPart ? [accountPart, ...windowParts] : [...windowParts];
|
|
1262
|
+
const cost = state.cumulativeCost;
|
|
1263
|
+
const hasWindows = windowParts.length > 0;
|
|
1264
|
+
// Monthly balance (Command Code credits, router-reported balances):
|
|
1265
|
+
// currency-aware compact figure — e.g. M:$69.99 / M:¥88.00 CNY.
|
|
1266
|
+
if (typeof account?.monthlyCredits === "number") {
|
|
1267
|
+
segments.push(`M:${formatMonthlyCredits(account.monthlyCredits, account.creditsCurrency)}`);
|
|
1268
|
+
}
|
|
1269
|
+
if (cost > 0) segments.push(`$${cost.toFixed(2)}`);
|
|
1270
|
+
if (state.lastTokPerSec !== undefined) segments.push(`${state.lastTokPerSec} tok/s`);
|
|
1271
|
+
if (segments.length === 0) {
|
|
1272
|
+
line = `Sub ${state.adapter.displayName}`;
|
|
1273
|
+
} else if (!hasWindows) {
|
|
1274
|
+
line = `${state.adapter.displayName} ${segments.join(" ")}`;
|
|
1275
|
+
} else {
|
|
1276
|
+
line = segments.join(" ");
|
|
1277
|
+
}
|
|
1278
|
+
const remaining = minRemaining(account);
|
|
1279
|
+
color = remaining <= 10 ? "error" : remaining <= 20 ? "warning" : "dim";
|
|
1280
|
+
}
|
|
1281
|
+
ctx.ui.setStatus(STATUS_KEY, theme.fg(color, line));
|
|
1282
|
+
}
|
|
1283
|
+
|
|
1284
|
+
function isStaleCtxError(error: unknown): boolean {
|
|
1285
|
+
// pi 0.85.1's wording is "This extension ctx is stale after session
|
|
1286
|
+
// replacement or reload." (verified in the host bundle); "invalidated" is
|
|
1287
|
+
// matched too so wording drift degrades to a harmless extra disarm instead
|
|
1288
|
+
// of silently disabling recovery.
|
|
1289
|
+
return error instanceof Error && /\bctx is stale\b|invalidated/i.test(error.message);
|
|
1290
|
+
}
|
|
1291
|
+
|
|
1292
|
+
function selfDisarm(state: State): void {
|
|
1293
|
+
stopTimer(state);
|
|
1294
|
+
state.inFlight = undefined;
|
|
1295
|
+
state.refreshGeneration++;
|
|
1296
|
+
state.ctx = undefined;
|
|
1297
|
+
}
|
|
1298
|
+
|
|
1299
|
+
/** pi can invalidate state.ctx without ever delivering a matching
|
|
1300
|
+
* session_shutdown (pi 0.85.1 orphaned-runtime teardown; instances are shared
|
|
1301
|
+
* across sessions), so a deferred refresh can hit a stale ctx. refreshUsage
|
|
1302
|
+
* is async — its throw becomes a rejected promise, and a void-discarded
|
|
1303
|
+
* rejection exits pi (unhandledRejection -> uncaughtException). Catch it and
|
|
1304
|
+
* self-disarm; session_start re-arms with the fresh ctx. Non-stale
|
|
1305
|
+
* rejections are swallowed: adapters already resolve error snapshots. */
|
|
1306
|
+
function deferRefresh(state: State, force: boolean): void {
|
|
1307
|
+
refreshUsage(state, force).catch((error) => {
|
|
1308
|
+
if (isStaleCtxError(error)) selfDisarm(state);
|
|
1309
|
+
});
|
|
1310
|
+
}
|
|
1311
|
+
|
|
1312
|
+
function startTimer(state: State): void {
|
|
1313
|
+
if (state.refreshTimer || !state.adapter) return;
|
|
1314
|
+
state.refreshTimer = setInterval(() => {
|
|
1315
|
+
deferRefresh(state, false);
|
|
1316
|
+
}, REFRESH_INTERVAL_MS);
|
|
1317
|
+
}
|
|
1318
|
+
|
|
1319
|
+
function stopTimer(state: State): void {
|
|
1320
|
+
if (state.refreshTimer) clearInterval(state.refreshTimer);
|
|
1321
|
+
if (state.debounceTimer) clearTimeout(state.debounceTimer);
|
|
1322
|
+
state.refreshTimer = undefined;
|
|
1323
|
+
state.debounceTimer = undefined;
|
|
1324
|
+
}
|
|
1325
|
+
|
|
1326
|
+
function updateActiveAdapter(state: State, model: ModelLike): void {
|
|
1327
|
+
const nextAdapter = supportedAdapter(model);
|
|
1328
|
+
const adapterChanged = state.adapterId !== nextAdapter?.id;
|
|
1329
|
+
|
|
1330
|
+
state.model = model;
|
|
1331
|
+
state.adapter = nextAdapter;
|
|
1332
|
+
state.adapterId = nextAdapter?.id;
|
|
1333
|
+
|
|
1334
|
+
if (adapterChanged) {
|
|
1335
|
+
state.snapshot = undefined;
|
|
1336
|
+
state.lastRefreshAt = 0;
|
|
1337
|
+
state.inFlight = undefined;
|
|
1338
|
+
state.refreshGeneration++;
|
|
1339
|
+
}
|
|
1340
|
+
|
|
1341
|
+
if (!state.adapter) {
|
|
1342
|
+
stopTimer(state);
|
|
1343
|
+
}
|
|
1344
|
+
renderSubscriptionLine(state);
|
|
1345
|
+
if (state.adapter) startTimer(state);
|
|
1346
|
+
}
|
|
1347
|
+
|
|
1348
|
+
async function refreshUsage(state: State, force: boolean): Promise<SubscriptionUsageSnapshot | undefined> {
|
|
1349
|
+
const adapter = state.adapter;
|
|
1350
|
+
// ponytail: resolve ctx at call time, never capture it across the fetch —
|
|
1351
|
+
// the session can be replaced while the promise is in flight.
|
|
1352
|
+
const ctx = state.ctx;
|
|
1353
|
+
if (!adapter || !ctx) {
|
|
1354
|
+
renderSubscriptionLine(state);
|
|
1355
|
+
return undefined;
|
|
1356
|
+
}
|
|
1357
|
+
if (!force && state.snapshot && Date.now() - state.lastRefreshAt < REFRESH_TTL_MS) return state.snapshot;
|
|
1358
|
+
if (state.inFlight) return state.inFlight;
|
|
1359
|
+
const generation = state.refreshGeneration;
|
|
1360
|
+
renderSubscriptionLine(state);
|
|
1361
|
+
state.inFlight = adapter.fetchUsage(ctx.signal).then((snapshot) => {
|
|
1362
|
+
if (state.refreshGeneration !== generation) return snapshot;
|
|
1363
|
+
state.snapshot = snapshot;
|
|
1364
|
+
state.lastRefreshAt = Date.now();
|
|
1365
|
+
renderSubscriptionLine(state);
|
|
1366
|
+
return snapshot;
|
|
1367
|
+
}).finally(() => {
|
|
1368
|
+
if (state.refreshGeneration === generation) {
|
|
1369
|
+
state.inFlight = undefined;
|
|
1370
|
+
}
|
|
1371
|
+
});
|
|
1372
|
+
return state.inFlight;
|
|
1373
|
+
}
|
|
1374
|
+
|
|
1375
|
+
export function scheduleRefresh(state: State): void {
|
|
1376
|
+
if (!state.adapter) return;
|
|
1377
|
+
if (state.debounceTimer) clearTimeout(state.debounceTimer);
|
|
1378
|
+
state.debounceTimer = setTimeout(() => {
|
|
1379
|
+
state.debounceTimer = undefined;
|
|
1380
|
+
deferRefresh(state, true);
|
|
1381
|
+
}, REFRESH_DEBOUNCE_MS);
|
|
1382
|
+
}
|
|
1383
|
+
|
|
1384
|
+
function pad(value: string, width: number): string {
|
|
1385
|
+
return value.length >= width ? value : value + " ".repeat(width - value.length);
|
|
1386
|
+
}
|
|
1387
|
+
|
|
1388
|
+
/** "46 tok/s (36 think + 10 answer)" — split shown only when the model
|
|
1389
|
+
* reasoned. usage.reasoning is a subset of usage.output (Pi SDK contract),
|
|
1390
|
+
* so answer speed = (output − reasoning)/s, never output + reasoning. */
|
|
1391
|
+
export function tokPerSecLabel(output: number, thinking: number, elapsedMs: number): string {
|
|
1392
|
+
const total = Math.round(output / (elapsedMs / 1000));
|
|
1393
|
+
if (thinking <= 0) return `${total} tok/s`;
|
|
1394
|
+
const secs = elapsedMs / 1000;
|
|
1395
|
+
return `${total} tok/s (${Math.round(thinking / secs)} think + ${Math.round((output - thinking) / secs)} answer)`;
|
|
1396
|
+
}
|
|
1397
|
+
|
|
1398
|
+
function buildDetails(snapshot: SubscriptionUsageSnapshot | undefined, state: State): string {
|
|
1399
|
+
if (!state.adapter) {
|
|
1400
|
+
const header = `Provider: ${state.model?.provider ?? "unknown"}${state.model?.id ? ` · Model: ${state.model.id}` : ""}`;
|
|
1401
|
+
if (state.lastTokPerSec === undefined) return `${header}\nSubscription tracking inactive for this provider.`;
|
|
1402
|
+
const tokPerSecLine = `Last response: ${state.lastTokPerSecLabel}` +
|
|
1403
|
+
(state.cumulativeDurationMs > 0
|
|
1404
|
+
? ` · Session avg: ${Math.round(state.cumulativeOutput / (state.cumulativeDurationMs / 1000))} tok/s`
|
|
1405
|
+
: "");
|
|
1406
|
+
return `${header}\n${tokPerSecLine}`;
|
|
1407
|
+
}
|
|
1408
|
+
if (!snapshot) return "Subscription usage has not been loaded yet.";
|
|
1409
|
+
if (snapshot.error) return `${snapshot.providerDisplayName}: ${snapshot.error}`;
|
|
1410
|
+
if (snapshot.accounts.length === 0) {
|
|
1411
|
+
const costLine = state.cumulativeCost > 0 ? `\nSession cost: $${state.cumulativeCost.toFixed(2)}` : "";
|
|
1412
|
+
const modelInfo = state.model?.id ? ` · Model: ${state.model.id}` : "";
|
|
1413
|
+
return `Provider: ${snapshot.providerDisplayName}${modelInfo} · Fetched: ${new Date(snapshot.fetchedAt).toLocaleTimeString()}\n${snapshot.providerDisplayName} does not expose usage windows.${costLine}`;
|
|
1414
|
+
}
|
|
1415
|
+
|
|
1416
|
+
const columns: { key: string; label: string; get: (a: SubscriptionAccountSnapshot) => string }[] = [
|
|
1417
|
+
{ key: "account", label: "ACCOUNT", get: (a) => a.accountLabel ?? "unknown" },
|
|
1418
|
+
{ key: "plan", label: "PLAN", get: (a) => a.plan ?? "?" },
|
|
1419
|
+
];
|
|
1420
|
+
|
|
1421
|
+
const hasFiveHour = snapshot.accounts.some((a) => a.fiveHour);
|
|
1422
|
+
const hasWeekly = snapshot.accounts.some((a) => a.weekly);
|
|
1423
|
+
if (hasFiveHour) columns.push({ key: "five", label: "ROLLING", get: (a) => formatRemaining(a.fiveHour) });
|
|
1424
|
+
if (hasWeekly) columns.push({ key: "weekly", label: "WEEKLY", get: (a) => formatRemaining(a.weekly) });
|
|
1425
|
+
const hasMonthly = snapshot.accounts.some((a) => a.monthly);
|
|
1426
|
+
if (hasMonthly) columns.push({ key: "monthly", label: "MONTHLY", get: (a) => formatRemaining(a.monthly) });
|
|
1427
|
+
const rows = snapshot.accounts.map((account) => ({
|
|
1428
|
+
active: account.isActive ? "*" : " ",
|
|
1429
|
+
snapshot: account,
|
|
1430
|
+
}));
|
|
1431
|
+
|
|
1432
|
+
const widths: Record<string, number> = {};
|
|
1433
|
+
for (const col of columns) {
|
|
1434
|
+
widths[col.key] = Math.max(col.label.length, ...snapshot.accounts.map((a) => col.get(a).length));
|
|
1435
|
+
}
|
|
1436
|
+
|
|
1437
|
+
const headerCols = columns.map((c) => pad(c.label, widths[c.key]));
|
|
1438
|
+
const header = ` ${headerCols.join(" ")} LAST ACTIVITY`;
|
|
1439
|
+
const sep = "-".repeat(header.length);
|
|
1440
|
+
const body = rows.map((row) => {
|
|
1441
|
+
const cols = columns.map((c) => pad(c.get(row.snapshot), widths[c.key]));
|
|
1442
|
+
return `${row.active} ${cols.join(" ")} ${row.snapshot.lastActivity ?? ""}`;
|
|
1443
|
+
});
|
|
1444
|
+
|
|
1445
|
+
const costLine = state.cumulativeCost > 0 ? `\nSession cost: $${state.cumulativeCost.toFixed(2)}` : "";
|
|
1446
|
+
const tokPerSecLine = state.lastTokPerSec !== undefined
|
|
1447
|
+
? `\nLast response: ${state.lastTokPerSecLabel}` +
|
|
1448
|
+
(state.cumulativeDurationMs > 0
|
|
1449
|
+
? ` · Session avg: ${Math.round(state.cumulativeOutput / (state.cumulativeDurationMs / 1000))} tok/s`
|
|
1450
|
+
: "")
|
|
1451
|
+
: "";
|
|
1452
|
+
const lines = [`Provider: ${snapshot.providerDisplayName} · Model: ${state.model?.id ?? "unknown-model"} · Fetched: ${new Date(snapshot.fetchedAt).toLocaleTimeString()}${costLine}${tokPerSecLine}`, "", header, sep, ...body];
|
|
1453
|
+
if (!hasFiveHour && !hasWeekly && !hasMonthly) {
|
|
1454
|
+
lines.push("", `${snapshot.providerDisplayName} does not expose usage windows.`);
|
|
1455
|
+
}
|
|
1456
|
+
// Z.ai extras: MCP/month allowance (from TIME_LIMIT) + per-model/per-tool breakdown.
|
|
1457
|
+
const mcpAcct = snapshot.accounts.find((a) => a.mcpMonthly);
|
|
1458
|
+
if (mcpAcct && mcpAcct.mcpMonthly) lines.push("", `MCP/month: ${formatRemaining(mcpAcct.mcpMonthly)}`);
|
|
1459
|
+
for (const a of snapshot.accounts) if (a.usageBreakdown) lines.push("", a.usageBreakdown);
|
|
1460
|
+
return lines.join("\n");
|
|
1461
|
+
}
|
|
1462
|
+
|
|
1463
|
+
// ============================================================================
|
|
1464
|
+
// /context — context-window breakdown (Claude Code style panel)
|
|
1465
|
+
// ============================================================================
|
|
1466
|
+
|
|
1467
|
+
/** Formatting helpers for the /context panel (OMP house style: 5.3K, 21K, 1m). */
|
|
1468
|
+
export function formatCtxTokens(n: number): string {
|
|
1469
|
+
if (n < 1000) return String(n);
|
|
1470
|
+
if (n < 1_000_000) return `${(n / 1000).toFixed(n < 10_000 ? 1 : 0)}K`;
|
|
1471
|
+
return `${(n / 1_000_000).toFixed(1).replace(/\.0$/, "")}m`;
|
|
1472
|
+
}
|
|
1473
|
+
|
|
1474
|
+
/** OMP-style percentage: `<0.1%` for non-zero slivers, one decimal otherwise. */
|
|
1475
|
+
export function formatCtxPercent(tokens: number, contextWindow: number): string {
|
|
1476
|
+
if (!(contextWindow > 0)) return "?";
|
|
1477
|
+
const pct = (tokens / contextWindow) * 100;
|
|
1478
|
+
if (pct > 0 && pct < 0.1) return "<0.1%";
|
|
1479
|
+
return `${pct.toFixed(1)}%`;
|
|
1480
|
+
}
|
|
1481
|
+
|
|
1482
|
+
/** Waffle-chart glyphs, matching OMP's vocabulary. */
|
|
1483
|
+
const WAFFLE_FILLED = "⛁";
|
|
1484
|
+
const WAFFLE_FREE = "⛶";
|
|
1485
|
+
const WAFFLE_BUFFER = "⛝";
|
|
1486
|
+
|
|
1487
|
+
/** OMP's signature waffle grid: `rows × cols` cells over the window, painted in
|
|
1488
|
+
* slice order (used categories → free → autocompact buffer).
|
|
1489
|
+
*
|
|
1490
|
+
* Cells are allocated by share of the window, with a **minimum of one cell per
|
|
1491
|
+
* slice worth ≥0.5%** — deliberate visibility scaling, the same choice OMP
|
|
1492
|
+
* makes (their 2%-used grid still lights up a third of the cells). Any
|
|
1493
|
+
* shortfall or overflow is absorbed by the largest slice, so the grid always
|
|
1494
|
+
* fills exactly `rows × cols` cells. */
|
|
1495
|
+
export function ctxWaffle(
|
|
1496
|
+
slices: { tokens: number; glyph: string }[],
|
|
1497
|
+
contextWindow: number,
|
|
1498
|
+
cols = 10,
|
|
1499
|
+
rows = 4,
|
|
1500
|
+
): string[] {
|
|
1501
|
+
const cells = cols * rows;
|
|
1502
|
+
if (!(contextWindow > 0)) return Array.from({ length: rows }, () => WAFFLE_FREE.repeat(cols));
|
|
1503
|
+
const MIN_SHARE = 0.005;
|
|
1504
|
+
const alloc = slices.map((s) => {
|
|
1505
|
+
const tokens = Math.max(0, s.tokens);
|
|
1506
|
+
if (tokens <= 0) return 0;
|
|
1507
|
+
const share = tokens / contextWindow;
|
|
1508
|
+
return share < MIN_SHARE ? 1 : Math.max(1, Math.round(share * cells));
|
|
1509
|
+
});
|
|
1510
|
+
// Overflow swallows from the largest slice first (never below one cell).
|
|
1511
|
+
let total = alloc.reduce((a, b) => a + b, 0);
|
|
1512
|
+
while (total > cells) {
|
|
1513
|
+
const biggest = alloc.indexOf(Math.max(...alloc));
|
|
1514
|
+
if (alloc[biggest] <= 1) break;
|
|
1515
|
+
alloc[biggest] -= 1;
|
|
1516
|
+
total -= 1;
|
|
1517
|
+
}
|
|
1518
|
+
// Underflow pads the LARGEST slice — with a well-formed breakdown that is free
|
|
1519
|
+
// space. Never the last slice: that would inflate the autocompact buffer (a
|
|
1520
|
+
// fixed reserve) whenever a category figure is underestimated.
|
|
1521
|
+
if (total < cells && alloc.length > 0) {
|
|
1522
|
+
const biggest = alloc.indexOf(Math.max(...alloc));
|
|
1523
|
+
alloc[biggest] += cells - total;
|
|
1524
|
+
}
|
|
1525
|
+
const glyphs = alloc.flatMap((count, i) => Array.from({ length: count }, () => slices[i].glyph));
|
|
1526
|
+
const out: string[] = [];
|
|
1527
|
+
for (let r = 0; r < rows; r++) out.push(glyphs.slice(r * cols, (r + 1) * cols).join(""));
|
|
1528
|
+
return out;
|
|
1529
|
+
}
|
|
1530
|
+
|
|
1531
|
+
/** Token cost of one tool as the prompt carries it: description + JSON
|
|
1532
|
+
* parameter schema + guidelines, chars/4 (same heuristic as estimateTokens). */
|
|
1533
|
+
function toolTokens(t: { description: string; parameters: unknown; promptGuidelines?: string[] }): number {
|
|
1534
|
+
let chars = t.description.length + JSON.stringify(t.parameters ?? {}).length;
|
|
1535
|
+
if (t.promptGuidelines) chars += t.promptGuidelines.join("\n").length;
|
|
1536
|
+
return Math.ceil(chars / 4);
|
|
1537
|
+
}
|
|
1538
|
+
|
|
1539
|
+
/** Short, readable source label: `sourceInfo.source` is a filesystem path for
|
|
1540
|
+
* locally-linked packages and a package spec for installed ones — both reduce
|
|
1541
|
+
* to the last segment (`../../pi-web` and `@bacnh85/pi-web` → `pi-web`),
|
|
1542
|
+
* leaving built-in single-segment names untouched. */
|
|
1543
|
+
export function shortSource(source: string): string {
|
|
1544
|
+
const parts = source.split("/").filter((p) => p && p !== "." && p !== "..");
|
|
1545
|
+
return parts[parts.length - 1] ?? source;
|
|
1546
|
+
}
|
|
1547
|
+
|
|
1548
|
+
/** Parse `<name>…</name>` skill entries out of the skills prompt section. */
|
|
1549
|
+
function countSkills(skillsSection: string): number {
|
|
1550
|
+
const matches = skillsSection.match(/<skill>[\s\S]*?<\/skill>/g);
|
|
1551
|
+
return matches ? matches.length : 0;
|
|
1552
|
+
}
|
|
1553
|
+
|
|
1554
|
+
/** Effective compaction reserve for the active model: pi resolves
|
|
1555
|
+
* `compaction.modelOverrides["provider/id"].reserveTokens` → `compaction.reserveTokens`
|
|
1556
|
+
* → default 16384 (settings-manager getCompactionReserveTokens). Mirrors that
|
|
1557
|
+
* order so the panel shows the number pi will actually use. */
|
|
1558
|
+
export function resolveReserveTokens(settings: unknown, model?: { provider?: string; id?: string }): number {
|
|
1559
|
+
const compaction = (settings as { compaction?: { reserveTokens?: unknown; modelOverrides?: Record<string, unknown> } } | undefined)?.compaction;
|
|
1560
|
+
const override = model?.provider && model?.id
|
|
1561
|
+
? (compaction?.modelOverrides?.[`${model.provider}/${model.id}`] as { reserveTokens?: unknown } | undefined)?.reserveTokens
|
|
1562
|
+
: undefined;
|
|
1563
|
+
for (const candidate of [override, compaction?.reserveTokens]) {
|
|
1564
|
+
if (typeof candidate === "number" && Number.isSafeInteger(candidate) && candidate >= 0) return candidate;
|
|
1565
|
+
}
|
|
1566
|
+
return DEFAULT_COMPACTION_SETTINGS.reserveTokens;
|
|
1567
|
+
}
|
|
1568
|
+
|
|
1569
|
+
function readCompactionSettings(): unknown {
|
|
1570
|
+
try {
|
|
1571
|
+
const dir = process.env.PI_CODING_AGENT_DIR?.trim() || path.join(os.homedir(), ".pi", "agent");
|
|
1572
|
+
return JSON.parse(fs.readFileSync(path.join(dir, "settings.json"), "utf8"));
|
|
1573
|
+
} catch {
|
|
1574
|
+
return undefined; // no settings file → defaults
|
|
1575
|
+
}
|
|
1576
|
+
}
|
|
1577
|
+
|
|
1578
|
+
export interface ContextBreakdownInput {
|
|
1579
|
+
ctx: {
|
|
1580
|
+
getContextUsage(): { tokens: number | null; contextWindow: number; percent: number | null } | undefined;
|
|
1581
|
+
getSystemPrompt(): string;
|
|
1582
|
+
sessionManager: { buildSessionProjection(): { messages: unknown[] } };
|
|
1583
|
+
};
|
|
1584
|
+
/** From pi.getAllTools() — command contexts do not expose it; the closure does. */
|
|
1585
|
+
allTools: { name: string; description: string; parameters: unknown; promptGuidelines?: string[]; sourceInfo: { source: string } }[];
|
|
1586
|
+
/** From pi.getActiveTools(). */
|
|
1587
|
+
activeTools: string[];
|
|
1588
|
+
model?: { provider?: string; id?: string; name?: string; maxTokens?: number; contextWindow?: number };
|
|
1589
|
+
/** Parsed ~/.pi/agent/settings.json — resolves the effective compaction reserve. */
|
|
1590
|
+
settings?: unknown;
|
|
1591
|
+
}
|
|
1592
|
+
|
|
1593
|
+
export interface ContextBreakdown {
|
|
1594
|
+
contextWindow: number;
|
|
1595
|
+
usedTokens: number | null;
|
|
1596
|
+
percent: number | null;
|
|
1597
|
+
/** `provider/id` of the active model, for the header line. */
|
|
1598
|
+
modelLabel?: string;
|
|
1599
|
+
/** Human-readable model name, e.g. "GLM-5.3". */
|
|
1600
|
+
modelName?: string;
|
|
1601
|
+
systemPrompt: { total: number; sections: Record<string, number> };
|
|
1602
|
+
tools: { total: number; activeCount: number; registeredCount: number; bySource: Record<string, { tokens: number; count: number }> };
|
|
1603
|
+
/** Per-tool costs, descending — powers the "top tools" list. */
|
|
1604
|
+
toolCosts: { name: string; tokens: number; source: string }[];
|
|
1605
|
+
skills: { total: number; count: number };
|
|
1606
|
+
memoryFiles: { total: number; files: { name: string; tokens: number }[] };
|
|
1607
|
+
messages: { total: number; count: number };
|
|
1608
|
+
/** Disjoint category totals for the panel (no overlap, sum ≤ window):
|
|
1609
|
+
* system prompt/context split out of the sections, plus tools, messages,
|
|
1610
|
+
* autocompact buffer, free space. */
|
|
1611
|
+
categories: { label: string; tokens: number; glyph: string }[];
|
|
1612
|
+
/** Compaction reserve — pi triggers at `tokens > window - compaction`. A hard
|
|
1613
|
+
* slice of the window (the "autocompact buffer" in Claude/OMP terms), NOT
|
|
1614
|
+
* additive with free space. */
|
|
1615
|
+
reserved: { compaction: number };
|
|
1616
|
+
/** Window left before compaction triggers: `window - used - reserve`. */
|
|
1617
|
+
freeSpace: number;
|
|
1618
|
+
/** True when compaction is disabled in settings (reserve is not enforced). */
|
|
1619
|
+
compactionDisabled: boolean;
|
|
1620
|
+
}
|
|
1621
|
+
|
|
1622
|
+
/** Build the full context-window breakdown for /context. Pure over ctx getters.
|
|
1623
|
+
* Exported for tests. Token figures are chars/4 estimates except usedTokens,
|
|
1624
|
+
* which is the authoritative ctx.getContextUsage() total when known. */
|
|
1625
|
+
export function computeContextBreakdown(input: ContextBreakdownInput): ContextBreakdown {
|
|
1626
|
+
const { ctx, allTools, activeTools, model } = input;
|
|
1627
|
+
const usage = ctx.getContextUsage();
|
|
1628
|
+
const contextWindow = model?.contextWindow ?? usage?.contextWindow ?? 0;
|
|
1629
|
+
const usedTokens = usage?.tokens ?? null;
|
|
1630
|
+
const percent = usage?.percent ?? null;
|
|
1631
|
+
|
|
1632
|
+
// System prompt: prefer the structured sections replayed on the transcript's
|
|
1633
|
+
// leading system message (exactly what the model sees); fall back to the
|
|
1634
|
+
// whole-prompt blob before the first turn records sections.
|
|
1635
|
+
const sections: Record<string, number> = {};
|
|
1636
|
+
let systemTotal = 0;
|
|
1637
|
+
let haveSections = false;
|
|
1638
|
+
let sysRawSkills = "";
|
|
1639
|
+
try {
|
|
1640
|
+
const messages = ctx.sessionManager.buildSessionProjection().messages as Array<{ role?: string; sections?: Record<string, string | null> }>;
|
|
1641
|
+
const sys = messages.find((m) => m.role === "system");
|
|
1642
|
+
if (sys?.sections) {
|
|
1643
|
+
haveSections = true;
|
|
1644
|
+
for (const [name, content] of Object.entries(sys.sections)) {
|
|
1645
|
+
if (!content) continue;
|
|
1646
|
+
if (name === "skills") sysRawSkills = content;
|
|
1647
|
+
const tokens = Math.ceil(content.length / 4);
|
|
1648
|
+
sections[name] = (sections[name] ?? 0) + tokens;
|
|
1649
|
+
systemTotal += tokens;
|
|
1650
|
+
}
|
|
1651
|
+
}
|
|
1652
|
+
} catch { /* projection unavailable — fall back to blob */ }
|
|
1653
|
+
if (!haveSections) {
|
|
1654
|
+
// No transcript system message yet (nothing has been sent). The rendered
|
|
1655
|
+
// prompt is the only source; keep it as one bucket and let the tool/skill
|
|
1656
|
+
// figures below still populate, so a first-turn /context is still useful.
|
|
1657
|
+
systemTotal = Math.ceil(ctx.getSystemPrompt().length / 4);
|
|
1658
|
+
}
|
|
1659
|
+
|
|
1660
|
+
const tools = allTools;
|
|
1661
|
+
const activeSet = new Set(activeTools);
|
|
1662
|
+
const bySource: Record<string, { tokens: number; count: number }> = {};
|
|
1663
|
+
const toolCosts: { name: string; tokens: number; source: string }[] = [];
|
|
1664
|
+
let toolsTotal = 0;
|
|
1665
|
+
for (const t of tools) {
|
|
1666
|
+
const cost = toolTokens(t);
|
|
1667
|
+
toolsTotal += cost;
|
|
1668
|
+
const src = t.sourceInfo?.source ?? "unknown";
|
|
1669
|
+
const bucket = (bySource[src] ??= { tokens: 0, count: 0 });
|
|
1670
|
+
bucket.tokens += cost;
|
|
1671
|
+
bucket.count += 1;
|
|
1672
|
+
toolCosts.push({ name: t.name, tokens: cost, source: src });
|
|
1673
|
+
}
|
|
1674
|
+
toolCosts.sort((a, b) => b.tokens - a.tokens);
|
|
1675
|
+
|
|
1676
|
+
const skillsRaw = sysRawSkills;
|
|
1677
|
+
const memorySectionTokens = (sections.project_context ?? 0) + (sections.addendum ?? 0);
|
|
1678
|
+
|
|
1679
|
+
let messagesTotal = 0;
|
|
1680
|
+
let messagesCount = 0;
|
|
1681
|
+
try {
|
|
1682
|
+
for (const m of ctx.sessionManager.buildSessionProjection().messages as Array<{ role?: string }>) {
|
|
1683
|
+
if (m.role === "system") continue; // counted above as systemPrompt
|
|
1684
|
+
messagesTotal += estimateTokens(m as Parameters<typeof estimateTokens>[0]);
|
|
1685
|
+
messagesCount += 1;
|
|
1686
|
+
}
|
|
1687
|
+
} catch { /* no projection */ }
|
|
1688
|
+
|
|
1689
|
+
// pi's trigger: shouldCompact → tokens > contextWindow - reserveTokens. The
|
|
1690
|
+
// reserve is a hard slice of the window, not a cost added on top; model output
|
|
1691
|
+
// is NOT reserved (pi only caps it inside summarization).
|
|
1692
|
+
const compactionDisabled = (input.settings as { compaction?: { enabled?: unknown } } | undefined)?.compaction?.enabled === false;
|
|
1693
|
+
const reserved = { compaction: resolveReserveTokens(input.settings, model) };
|
|
1694
|
+
const withheld = compactionDisabled ? 0 : reserved.compaction;
|
|
1695
|
+
|
|
1696
|
+
// Disjoint partition for the waffle + category lines (OMP model). Sections
|
|
1697
|
+
// count each once: context files and skills leave the system-prompt bucket so
|
|
1698
|
+
// nothing is double-counted against the window.
|
|
1699
|
+
//
|
|
1700
|
+
// The prompt-side rows are near-exact character counts of text we can see
|
|
1701
|
+
// (sections, tool schemas), so they are reported as measured. The Messages row
|
|
1702
|
+
// is the weak estimate: chars/4 also reads thinking blocks and cache-unwritten
|
|
1703
|
+
// content, so on real sessions it lands tens of percent ABOVE the provider's
|
|
1704
|
+
// authoritative input count. Messages is therefore reported as the RESIDUAL
|
|
1705
|
+
// (`used − prompt rows`), which absorbs both that over-count and any tokens we
|
|
1706
|
+
// cannot attribute at all — and keeps every row ≤ the headline total.
|
|
1707
|
+
const contextTokens = memorySectionTokens;
|
|
1708
|
+
const skillsTokens = sections.skills ?? 0;
|
|
1709
|
+
const corePromptTokens = Math.max(0, systemTotal - contextTokens - skillsTokens);
|
|
1710
|
+
const promptTokens = corePromptTokens + toolsTotal + contextTokens + skillsTokens;
|
|
1711
|
+
const messagesRow = usedTokens !== null
|
|
1712
|
+
// Capped so a stale figure reporting more tokens than the window can hold
|
|
1713
|
+
// still yields a partition that fits.
|
|
1714
|
+
? Math.min(Math.max(0, usedTokens - promptTokens), Math.max(0, contextWindow - withheld - promptTokens))
|
|
1715
|
+
: messagesTotal;
|
|
1716
|
+
// Occupancy basis: the authoritative count when known, estimates otherwise.
|
|
1717
|
+
// `max` guards the post-compaction case where prompt estimates alone exceed a
|
|
1718
|
+
// momentarily tiny measured total.
|
|
1719
|
+
const occupied = Math.max(usedTokens ?? 0, promptTokens + messagesRow);
|
|
1720
|
+
const freeSpace = Math.max(0, contextWindow - Math.min(occupied, contextWindow - withheld) - withheld);
|
|
1721
|
+
const categories = [
|
|
1722
|
+
{ label: "System prompt", tokens: corePromptTokens, glyph: "⛁" },
|
|
1723
|
+
{ label: "System tools", tokens: toolsTotal, glyph: "⛁" },
|
|
1724
|
+
{ label: "System context", tokens: contextTokens, glyph: "⛁" },
|
|
1725
|
+
{ label: "Skills", tokens: skillsTokens, glyph: "⛁" },
|
|
1726
|
+
{ label: "Messages", tokens: messagesRow, glyph: WAFFLE_FILLED },
|
|
1727
|
+
{ label: "Free space", tokens: freeSpace, glyph: WAFFLE_FREE },
|
|
1728
|
+
// The reserve is the LAST slice of the window (pi compacts at
|
|
1729
|
+
// `tokens > window - reserve`), so it renders after free space.
|
|
1730
|
+
...(compactionDisabled ? [] : [{ label: "Autocompact buffer", tokens: reserved.compaction, glyph: WAFFLE_BUFFER }]),
|
|
1731
|
+
];
|
|
1732
|
+
|
|
1733
|
+
return {
|
|
1734
|
+
contextWindow,
|
|
1735
|
+
usedTokens,
|
|
1736
|
+
percent,
|
|
1737
|
+
modelLabel: model && "provider" in model && model.provider ? `${model.provider}/${model.id ?? "?"}` : undefined,
|
|
1738
|
+
modelName: model && "name" in model ? model.name : undefined,
|
|
1739
|
+
systemPrompt: { total: systemTotal, sections },
|
|
1740
|
+
tools: { total: toolsTotal, activeCount: activeSet.size, registeredCount: tools.length, bySource },
|
|
1741
|
+
toolCosts,
|
|
1742
|
+
skills: { total: sections.skills ?? 0, count: countSkills(skillsRaw) },
|
|
1743
|
+
memoryFiles: {
|
|
1744
|
+
total: memorySectionTokens,
|
|
1745
|
+
files: Object.entries(sections)
|
|
1746
|
+
.filter(([name]) => name === "project_context" || name === "addendum")
|
|
1747
|
+
.map(([name, tokens]) => ({ name, tokens })),
|
|
1748
|
+
},
|
|
1749
|
+
messages: { total: messagesTotal, count: messagesCount },
|
|
1750
|
+
categories,
|
|
1751
|
+
reserved,
|
|
1752
|
+
freeSpace,
|
|
1753
|
+
compactionDisabled,
|
|
1754
|
+
};
|
|
1755
|
+
}
|
|
1756
|
+
|
|
1757
|
+
/** Render the /context panel in OMP's layout: waffle grid + model info to its
|
|
1758
|
+
* right, then a disjoint "Estimated usage by category" block, then detail
|
|
1759
|
+
* lists and pruning recommendations. */
|
|
1760
|
+
export function renderContextPanel(b: ContextBreakdown): string[] {
|
|
1761
|
+
const k = formatCtxTokens;
|
|
1762
|
+
const pct = (n: number) => ` (${formatCtxPercent(n, b.contextWindow)})`;
|
|
1763
|
+
const lines: string[] = ["Context Usage", ""];
|
|
1764
|
+
|
|
1765
|
+
if (b.usedTokens === null) {
|
|
1766
|
+
lines.push(
|
|
1767
|
+
"Context usage: exact totals unknown (right after compaction or before the first model response).",
|
|
1768
|
+
"Run /context again after the next reply for authoritative numbers. Category splits are estimates.",
|
|
1769
|
+
"",
|
|
1770
|
+
);
|
|
1771
|
+
}
|
|
1772
|
+
const used = b.usedTokens ?? b.systemPrompt.total + b.tools.total + b.messages.total;
|
|
1773
|
+
|
|
1774
|
+
// ── Header: waffle on the left (10 cols), model + totals on the right ──
|
|
1775
|
+
// Painted in window order: used categories → free → autocompact buffer.
|
|
1776
|
+
const waffleSlices = b.categories.map((c) => ({ tokens: c.tokens, glyph: c.glyph }));
|
|
1777
|
+
const grid = ctxWaffle(waffleSlices, b.contextWindow, 10, 4);
|
|
1778
|
+
const right = [
|
|
1779
|
+
b.modelName ? `${b.modelName}${b.contextWindow > 0 ? ` (${k(b.contextWindow)} context)` : ""}` : undefined,
|
|
1780
|
+
// OMP shows the bare model id with the window bracketed: `glm-5.3[1m]`.
|
|
1781
|
+
b.modelLabel ? `${b.modelLabel.split("/").pop()}${b.contextWindow > 0 ? `[${k(b.contextWindow)}]` : ""}` : undefined,
|
|
1782
|
+
`${k(used)}/${k(b.contextWindow)} tokens (${formatCtxPercent(used, b.contextWindow)})`,
|
|
1783
|
+
"Estimated usage by category",
|
|
1784
|
+
];
|
|
1785
|
+
for (let r = 0; r < grid.length; r++) {
|
|
1786
|
+
const rightText = right[r];
|
|
1787
|
+
lines.push(rightText ? `${grid[r]} ${rightText}` : grid[r]);
|
|
1788
|
+
}
|
|
1789
|
+
for (const extra of right.slice(grid.length)) if (extra) lines.push(" " + extra);
|
|
1790
|
+
lines.push("");
|
|
1791
|
+
|
|
1792
|
+
// ── Disjoint category block (glyph-prefixed, OMP style) ──
|
|
1793
|
+
for (const c of b.categories) {
|
|
1794
|
+
lines.push(` ${c.glyph} ${c.label}: ${k(c.tokens)} token${c.tokens === 1 ? "" : "s"}${pct(c.tokens)}`);
|
|
1795
|
+
}
|
|
1796
|
+
if (b.compactionDisabled) lines.push(" ⛶ Autocompact buffer: disabled (compaction.enabled=false)");
|
|
1797
|
+
|
|
1798
|
+
// ── Detail: system-prompt sections, top tools, per-package attribution ──
|
|
1799
|
+
const sectionNames = Object.keys(b.systemPrompt.sections).sort((x, y) => b.systemPrompt.sections[y] - b.systemPrompt.sections[x]);
|
|
1800
|
+
if (sectionNames.length > 1) {
|
|
1801
|
+
lines.push("", `Prompt sections (${k(b.systemPrompt.total)}):`);
|
|
1802
|
+
for (const name of sectionNames) lines.push(` ${name}: ${k(b.systemPrompt.sections[name])}`);
|
|
1803
|
+
}
|
|
1804
|
+
if (b.toolCosts.length > 0) {
|
|
1805
|
+
lines.push("", `Tools (${b.tools.registeredCount}${b.tools.activeCount !== b.tools.registeredCount ? ` · ${b.tools.activeCount} active` : ""}):`);
|
|
1806
|
+
for (const t of b.toolCosts.slice(0, 5)) lines.push(` ${t.name}: ${k(t.tokens)}`);
|
|
1807
|
+
const top = Object.entries(b.tools.bySource).sort((x, y) => y[1].tokens - x[1].tokens).slice(0, 3);
|
|
1808
|
+
for (const [src, s] of top) lines.push(` ${shortSource(src)}: ${k(s.tokens)} · ${s.count} tool${s.count === 1 ? "" : "s"}`);
|
|
1809
|
+
}
|
|
1810
|
+
|
|
1811
|
+
const recs: string[] = [];
|
|
1812
|
+
if (b.tools.total > b.contextWindow * 0.4) {
|
|
1813
|
+
recs.push(`Tool schemas are ${k(b.tools.total)} tokens (${formatCtxPercent(b.tools.total, b.contextWindow)} of window) — consider setActiveTools pruning.`);
|
|
1814
|
+
}
|
|
1815
|
+
if (b.memoryFiles.total > 3000) {
|
|
1816
|
+
recs.push(`Context files are ${k(b.memoryFiles.total)} tokens — consider trimming AGENTS.md.`);
|
|
1817
|
+
}
|
|
1818
|
+
if (b.skills.total > 2000) {
|
|
1819
|
+
recs.push(`Skills section is ${k(b.skills.total)} tokens — disable-model-invocation on reference-only skills.`);
|
|
1820
|
+
}
|
|
1821
|
+
if (recs.length > 0) lines.push("", "Recommendations:", ...recs.map((r) => `- ${r}`));
|
|
1822
|
+
return lines;
|
|
1823
|
+
}
|
|
1824
|
+
|
|
1825
|
+
export default function (pi: ExtensionAPI) {
|
|
1826
|
+
const state: State = { lastRefreshAt: 0, refreshGeneration: 0, cumulativeOutput: 0, cumulativeDurationMs: 0, cumulativeCost: 0 };
|
|
1827
|
+
|
|
1828
|
+
pi.on("session_start", async (_event, ctx) => {
|
|
1829
|
+
// Cwd .env files are untrusted repo content — ingest only for trusted
|
|
1830
|
+
// projects (idempotent; first trusted session wins).
|
|
1831
|
+
loadCwdEnvFilesIfTrusted(ctx);
|
|
1832
|
+
// Only session_start installs state.ctx: it fires (startup/new/fork/switch/
|
|
1833
|
+
// reload) before the session's other events, so mid-session handlers never
|
|
1834
|
+
// need to — and a late old-session event must not reinstall a stale ctx.
|
|
1835
|
+
state.ctx = ctx;
|
|
1836
|
+
updateActiveAdapter(state, ctx.model);
|
|
1837
|
+
if (state.adapter) deferRefresh(state, true);
|
|
1838
|
+
});
|
|
1839
|
+
|
|
1840
|
+
pi.on("model_select", async (event, _ctx) => {
|
|
1841
|
+
updateActiveAdapter(state, event.model);
|
|
1842
|
+
if (state.adapter) deferRefresh(state, true);
|
|
1843
|
+
});
|
|
1844
|
+
|
|
1845
|
+
pi.on("before_provider_request", async (_event, _ctx) => {
|
|
1846
|
+
state.responseStartTime = Date.now();
|
|
1847
|
+
});
|
|
1848
|
+
|
|
1849
|
+
pi.on("message_end", async (event, _ctx) => {
|
|
1850
|
+
if (event.message.role === "assistant") {
|
|
1851
|
+
// pi-budget parity: coerce + finite guard so a string/NaN cost.total can
|
|
1852
|
+
// never poison the accumulator (string concat garbles every subsequent
|
|
1853
|
+
// footer).
|
|
1854
|
+
const cost = Number((event.message.usage as any)?.cost?.total);
|
|
1855
|
+
if (Number.isFinite(cost) && cost > 0) state.cumulativeCost += cost;
|
|
1856
|
+
if (state.responseStartTime) {
|
|
1857
|
+
// usage.output already includes reasoning tokens (Pi SDK contract) —
|
|
1858
|
+
// this is total tok/s in both thinking and normal mode.
|
|
1859
|
+
const output = (event.message.usage as any)?.output ?? 0;
|
|
1860
|
+
const reasoning = (event.message.usage as any)?.reasoning ?? 0;
|
|
1861
|
+
const elapsed = Date.now() - state.responseStartTime;
|
|
1862
|
+
state.responseStartTime = undefined;
|
|
1863
|
+
if (elapsed > 0 && output > 0) {
|
|
1864
|
+
state.lastTokPerSec = Math.round(output / (elapsed / 1000));
|
|
1865
|
+
state.lastTokPerSecLabel = tokPerSecLabel(output, reasoning, elapsed);
|
|
1866
|
+
state.cumulativeOutput += output;
|
|
1867
|
+
state.cumulativeDurationMs += elapsed;
|
|
1868
|
+
}
|
|
1869
|
+
}
|
|
1870
|
+
renderSubscriptionLine(state);
|
|
1871
|
+
}
|
|
1872
|
+
});
|
|
1873
|
+
|
|
1874
|
+
pi.on("after_provider_response", async (event, _ctx) => {
|
|
1875
|
+
if (event.status >= 400) {
|
|
1876
|
+
state.responseStartTime = undefined;
|
|
1877
|
+
}
|
|
1878
|
+
if (state.adapter) scheduleRefresh(state);
|
|
1879
|
+
});
|
|
1880
|
+
|
|
1881
|
+
pi.on("session_shutdown", async (_event, ctx) => {
|
|
1882
|
+
// Only tear down if this shutdown belongs to the installed session: a late
|
|
1883
|
+
// old-session shutdown (delivered after the next session_start) must not
|
|
1884
|
+
// stop the live refresh timer, drop the live in-flight fetch, or touch a
|
|
1885
|
+
// ctx that may already be invalidated. Normal flow: session_start installed
|
|
1886
|
+
// this ctx, so the identity always matches for the session being torn down.
|
|
1887
|
+
if (state.ctx !== ctx) return;
|
|
1888
|
+
stopTimer(state);
|
|
1889
|
+
// ponytail: session is being torn down (new/fork/switch/reload). Pi invalidates
|
|
1890
|
+
// this ctx next; no-op any in-flight fetch .then that captured it, and drop the
|
|
1891
|
+
// stale promise so the next session fetches fresh instead of returning it.
|
|
1892
|
+
state.inFlight = undefined;
|
|
1893
|
+
state.refreshGeneration++;
|
|
1894
|
+
ctx.ui.setStatus(STATUS_KEY, undefined);
|
|
1895
|
+
state.ctx = undefined;
|
|
1896
|
+
});
|
|
1897
|
+
|
|
1898
|
+
pi.registerCommand("usage", {
|
|
1899
|
+
description: "Show subscription usage for the current supported model provider (use /usage refresh to force refresh).",
|
|
1900
|
+
getArgumentCompletions: (prefix) => {
|
|
1901
|
+
const items = ["refresh"]
|
|
1902
|
+
.filter((k) => k.startsWith(String(prefix || "").trim().toLowerCase()))
|
|
1903
|
+
.map((k) => ({ value: k, label: k, description: "force refresh" }));
|
|
1904
|
+
return items.length > 0 ? items : null;
|
|
1905
|
+
},
|
|
1906
|
+
handler: async (args, ctx) => {
|
|
1907
|
+
try {
|
|
1908
|
+
updateActiveAdapter(state, ctx.model);
|
|
1909
|
+
const command = args.trim().toLowerCase();
|
|
1910
|
+
const force = command === "refresh";
|
|
1911
|
+
const snapshot = state.adapter ? await refreshUsage(state, force || !state.snapshot) : undefined;
|
|
1912
|
+
const details = buildDetails(snapshot ?? state.snapshot, state);
|
|
1913
|
+
pi.sendMessage({ customType: MESSAGE_TYPE, content: details, display: true });
|
|
1914
|
+
// state.ctx (not captured ctx): the session could be replaced during the
|
|
1915
|
+
// await above; if it was, skip the notification instead of touching a
|
|
1916
|
+
// stale ctx.
|
|
1917
|
+
if (force) state.ctx?.ui.notify("Subscription usage refreshed", "info");
|
|
1918
|
+
} catch (error) {
|
|
1919
|
+
// Orphaned stale ctx (invalidated without shutdown): disarm like the
|
|
1920
|
+
// deferred paths instead of throwing into pi's dispatcher.
|
|
1921
|
+
if (!isStaleCtxError(error)) throw error;
|
|
1922
|
+
selfDisarm(state);
|
|
1923
|
+
}
|
|
1924
|
+
},
|
|
1925
|
+
});
|
|
1926
|
+
|
|
1927
|
+
// Transcript renderer for /context: pi renders this inline in the scrollback
|
|
1928
|
+
// (above the editor), like OMP's panel, instead of a dismissable overlay. The
|
|
1929
|
+
// renderer receives the live theme, so the category glyphs keep their colors
|
|
1930
|
+
// and the panel stays visible while you keep working.
|
|
1931
|
+
// Optional-call guard: matches pi-a2a/pi-subagent/pi-advisor, and keeps older
|
|
1932
|
+
// SDK builds (and minimal test harnesses) loadable.
|
|
1933
|
+
pi.registerMessageRenderer?.<{ lines: string[] }>(MESSAGE_TYPE_CONTEXT, (message, _opts, theme) => {
|
|
1934
|
+
try {
|
|
1935
|
+
const fg = theme?.fg ? (c: string, s: string) => theme.fg(c as never, s) : (s: string) => s;
|
|
1936
|
+
const body = (message.details as { lines?: string[] } | undefined)?.lines
|
|
1937
|
+
?? (typeof message.content === "string" ? message.content.split("\n") : []);
|
|
1938
|
+
const clamp = (line: string, width: number) => {
|
|
1939
|
+
if (width <= 0 || [...line].length <= width) return line;
|
|
1940
|
+
// Ellipsis rather than a mid-word slice — this is a display clamp, not data loss.
|
|
1941
|
+
const chars = [...line];
|
|
1942
|
+
return chars.length <= width ? line : chars.slice(0, Math.max(0, width - 1)).join("") + "…";
|
|
1943
|
+
};
|
|
1944
|
+
return {
|
|
1945
|
+
render: (width: number) => body.map((l) => clamp(l, width)).map((line) => {
|
|
1946
|
+
// Tint the category glyph; keep the numeric body plain for contrast.
|
|
1947
|
+
const m = line.match(/^(\s*)([⛁⛶⛝])( .*)$/);
|
|
1948
|
+
if (!m) return fg("customMessageText", line);
|
|
1949
|
+
const tint = m[2] === "⛶" ? "dim" : m[2] === "⛝" ? "warning" : "accent";
|
|
1950
|
+
return `${m[1]}${fg(tint, m[2])}${fg("customMessageText", m[3])}`;
|
|
1951
|
+
}),
|
|
1952
|
+
invalidate: () => {},
|
|
1953
|
+
};
|
|
1954
|
+
} catch {
|
|
1955
|
+
return undefined; // pi-tui unavailable → fall back to default rendering
|
|
1956
|
+
}
|
|
1957
|
+
});
|
|
1958
|
+
|
|
1959
|
+
pi.registerCommand("context", {
|
|
1960
|
+
description: "Show a context-window breakdown: system prompt, tools, memory files, skills, messages, reserved, free space.",
|
|
1961
|
+
handler: async (_args, ctx) => {
|
|
1962
|
+
// getAllTools/getActiveTools live on the ExtensionAPI closure — command
|
|
1963
|
+
// contexts (ExtensionCommandContext) do not expose them.
|
|
1964
|
+
const b = computeContextBreakdown({ ctx, allTools: pi.getAllTools(), activeTools: pi.getActiveTools(), model: ctx.model as ContextBreakdownInput["model"], settings: readCompactionSettings() });
|
|
1965
|
+
const lines = renderContextPanel(b);
|
|
1966
|
+
// display:true → shown in the transcript (above the editor, like OMP).
|
|
1967
|
+
// `content` is the plain-text fallback for renderer-less builds and
|
|
1968
|
+
// non-TUI modes; `details.lines` feeds the themed transcript renderer.
|
|
1969
|
+
pi.sendMessage({ customType: MESSAGE_TYPE_CONTEXT, content: lines.join("\n"), display: true, details: { lines } });
|
|
1970
|
+
},
|
|
1971
|
+
});
|
|
1972
|
+
|
|
1973
|
+
// Returned for tests only — Pi ignores the extension setup return value.
|
|
1974
|
+
return state;
|
|
1975
|
+
}
|