@fenlyin/pi-subscription-usage 0.0.0-stage → 2.0.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/LICENSE +24 -0
- package/README.md +156 -3
- package/README.zh-CN.md +156 -0
- package/THIRD_PARTY_NOTICES.md +28 -0
- package/index.ts +1 -0
- package/package.json +52 -6
- package/src/codex-reset-core.ts +249 -0
- package/src/codex-resets.ts +145 -0
- package/src/config-core.ts +43 -0
- package/src/config.ts +48 -0
- package/src/core.ts +182 -0
- package/src/display.ts +55 -0
- package/src/format.ts +225 -0
- package/src/providers/claude-bridge.ts +118 -0
- package/src/providers/codex-constants.ts +2 -0
- package/src/providers/codex.ts +227 -0
- package/src/providers/grok.ts +358 -0
- package/src/providers/kimi.ts +155 -0
- package/src/providers/openai.ts +145 -0
- package/src/providers/opencode-go.ts +88 -0
- package/src/query.ts +511 -0
- package/src/status.ts +255 -0
- package/src/types.ts +90 -0
- package/src/usage.ts +679 -0
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
// Adapted from @narumitw/pi-usage@0.53.0 (MIT).
|
|
2
|
+
import {
|
|
3
|
+
readStoredCredential,
|
|
4
|
+
type ExtensionContext,
|
|
5
|
+
} from "@earendil-works/pi-coding-agent";
|
|
6
|
+
import { fingerprintResolvedAuth } from "./core.ts";
|
|
7
|
+
import {
|
|
8
|
+
normalizeCodexResetCreditsPayload,
|
|
9
|
+
parseCodexResetOutcome,
|
|
10
|
+
verifyCodexStoredOAuthCredential,
|
|
11
|
+
type CodexResetAvailability,
|
|
12
|
+
type CodexResetOption,
|
|
13
|
+
type CodexResetOutcome,
|
|
14
|
+
} from "./codex-reset-core.ts";
|
|
15
|
+
import {
|
|
16
|
+
adapterForProvider,
|
|
17
|
+
AUTH_FINGERPRINT_SALT,
|
|
18
|
+
fetchProviderJson,
|
|
19
|
+
resolveUsageAuth,
|
|
20
|
+
} from "./query.ts";
|
|
21
|
+
import type { ResolvedUsageAuth } from "./types.ts";
|
|
22
|
+
import { CODEX_PROVIDER_ID } from "./providers/codex-constants.ts";
|
|
23
|
+
import { OPENAI_PROVIDER_ID } from "./providers/openai.ts";
|
|
24
|
+
|
|
25
|
+
const RESET_CREDITS_URL =
|
|
26
|
+
"https://chatgpt.com/backend-api/wham/rate-limit-reset-credits";
|
|
27
|
+
const RESET_CONSUME_URL = `${RESET_CREDITS_URL}/consume`;
|
|
28
|
+
|
|
29
|
+
type StoredCredentialReader = (providerId: string) => unknown;
|
|
30
|
+
|
|
31
|
+
export async function resolveCodexResetAuth(
|
|
32
|
+
ctx: ExtensionContext,
|
|
33
|
+
salt: Uint8Array = AUTH_FINGERPRINT_SALT,
|
|
34
|
+
credentialReader: StoredCredentialReader = readStoredCredential,
|
|
35
|
+
): Promise<ResolvedUsageAuth> {
|
|
36
|
+
const model = ctx.model;
|
|
37
|
+
if (model?.provider !== CODEX_PROVIDER_ID && model?.provider !== OPENAI_PROVIDER_ID) {
|
|
38
|
+
throw new Error(
|
|
39
|
+
"Account resets require the current model to use OpenAI or OpenAI Codex.",
|
|
40
|
+
);
|
|
41
|
+
}
|
|
42
|
+
const expectedModel = `${model.provider}/${model.id}`;
|
|
43
|
+
const adapter = adapterForProvider(model.provider);
|
|
44
|
+
if (!adapter) throw new Error(`Usage support for ${model.provider} is unavailable.`);
|
|
45
|
+
const auth = await resolveUsageAuth(ctx, adapter, salt);
|
|
46
|
+
if (`${ctx.model?.provider}/${ctx.model?.id}` !== expectedModel) {
|
|
47
|
+
throw new Error(
|
|
48
|
+
"The current model changed while resolving reset authentication.",
|
|
49
|
+
);
|
|
50
|
+
}
|
|
51
|
+
if (!auth)
|
|
52
|
+
throw new Error(`No runtime credential is configured for ${adapter.displayName}.`);
|
|
53
|
+
|
|
54
|
+
const resolvedAccess =
|
|
55
|
+
bearerToken(headerValue(auth.headers, "Authorization")) ?? auth.apiKey;
|
|
56
|
+
if (!resolvedAccess)
|
|
57
|
+
throw new Error("OpenAI Codex OAuth credentials were incomplete.");
|
|
58
|
+
const accountId = verifyCodexStoredOAuthCredential(
|
|
59
|
+
resolvedAccess,
|
|
60
|
+
credentialReader(CODEX_PROVIDER_ID),
|
|
61
|
+
);
|
|
62
|
+
if (model.provider === OPENAI_PROVIDER_ID) {
|
|
63
|
+
const stored = credentialReader(OPENAI_PROVIDER_ID) as { type?: string; access?: string; refresh?: string } | undefined;
|
|
64
|
+
if (!stored || stored.type !== "oauth" || typeof stored.access !== "string" ||
|
|
65
|
+
typeof stored.refresh !== "string" || !stored.refresh || fingerprintResolvedAuth({ apiKey: `Bearer ${stored.access}`, headers: auth.headers }, salt) !== auth.fingerprint) {
|
|
66
|
+
throw new Error("The active OpenAI runtime account does not match Pi\'s stored OAuth account.");
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
const authorization = `Bearer ${resolvedAccess}`;
|
|
70
|
+
const headers = {
|
|
71
|
+
Authorization: authorization,
|
|
72
|
+
"chatgpt-account-id": accountId,
|
|
73
|
+
};
|
|
74
|
+
return {
|
|
75
|
+
actualProviderId: model.provider,
|
|
76
|
+
openaiClientId: auth.openaiClientId,
|
|
77
|
+
usageFingerprint: auth.fingerprint,
|
|
78
|
+
apiKey: resolvedAccess,
|
|
79
|
+
headers,
|
|
80
|
+
fingerprint: fingerprintResolvedAuth({ apiKey: auth.fingerprint, headers }, salt),
|
|
81
|
+
secrets: [
|
|
82
|
+
...new Set([...auth.secrets, resolvedAccess, authorization, accountId]),
|
|
83
|
+
],
|
|
84
|
+
model: auth.model,
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
export async function listCodexResetCredits(
|
|
89
|
+
auth: ResolvedUsageAuth,
|
|
90
|
+
signal: AbortSignal,
|
|
91
|
+
timeoutMs: number,
|
|
92
|
+
): Promise<CodexResetAvailability> {
|
|
93
|
+
return normalizeCodexResetCreditsPayload(
|
|
94
|
+
await fetchProviderJson(
|
|
95
|
+
RESET_CREDITS_URL,
|
|
96
|
+
auth,
|
|
97
|
+
signal,
|
|
98
|
+
timeoutMs,
|
|
99
|
+
"Codex reset endpoint",
|
|
100
|
+
),
|
|
101
|
+
);
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
export async function consumeCodexResetCredit(
|
|
105
|
+
auth: ResolvedUsageAuth,
|
|
106
|
+
option: CodexResetOption,
|
|
107
|
+
redeemRequestId: string,
|
|
108
|
+
signal: AbortSignal,
|
|
109
|
+
timeoutMs: number,
|
|
110
|
+
): Promise<CodexResetOutcome> {
|
|
111
|
+
if (!redeemRequestId)
|
|
112
|
+
throw new Error("Codex reset request ID must not be empty.");
|
|
113
|
+
if (!option.creditId) {
|
|
114
|
+
throw new Error("Account resets require an explicitly selected credit.");
|
|
115
|
+
}
|
|
116
|
+
return parseCodexResetOutcome(
|
|
117
|
+
await fetchProviderJson(
|
|
118
|
+
RESET_CONSUME_URL,
|
|
119
|
+
auth,
|
|
120
|
+
signal,
|
|
121
|
+
timeoutMs,
|
|
122
|
+
"Codex reset consume endpoint",
|
|
123
|
+
{
|
|
124
|
+
method: "POST",
|
|
125
|
+
body: {
|
|
126
|
+
redeem_request_id: redeemRequestId,
|
|
127
|
+
credit_id: option.creditId,
|
|
128
|
+
},
|
|
129
|
+
},
|
|
130
|
+
),
|
|
131
|
+
);
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
function bearerToken(authorization: string | undefined): string | undefined {
|
|
135
|
+
return /^Bearer\s+(.+)$/iu.exec(authorization ?? "")?.[1];
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
function headerValue(
|
|
139
|
+
headers: Record<string, string>,
|
|
140
|
+
name: string,
|
|
141
|
+
): string | undefined {
|
|
142
|
+
return Object.entries(headers).find(
|
|
143
|
+
([candidate]) => candidate.toLowerCase() === name.toLowerCase(),
|
|
144
|
+
)?.[1];
|
|
145
|
+
}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import {
|
|
2
|
+
DEFAULT_USAGE_DISPLAY_MODE,
|
|
3
|
+
type UsageDisplayMode,
|
|
4
|
+
} from "./display.ts";
|
|
5
|
+
|
|
6
|
+
export interface UsageConfig {
|
|
7
|
+
displayMode: UsageDisplayMode;
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
export interface ParsedUsageConfig {
|
|
11
|
+
displayMode?: UsageDisplayMode;
|
|
12
|
+
warning?: string;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export const DEFAULT_USAGE_CONFIG: UsageConfig = {
|
|
16
|
+
displayMode: DEFAULT_USAGE_DISPLAY_MODE,
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
export function resolveUsageConfig(
|
|
20
|
+
globalConfig?: ParsedUsageConfig,
|
|
21
|
+
projectConfig?: ParsedUsageConfig,
|
|
22
|
+
): UsageConfig {
|
|
23
|
+
return {
|
|
24
|
+
displayMode:
|
|
25
|
+
projectConfig?.displayMode ??
|
|
26
|
+
globalConfig?.displayMode ??
|
|
27
|
+
DEFAULT_USAGE_CONFIG.displayMode,
|
|
28
|
+
};
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export function parseUsageConfig(value: unknown): ParsedUsageConfig {
|
|
32
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
|
33
|
+
return { warning: "configuration must be a JSON object" };
|
|
34
|
+
}
|
|
35
|
+
const displayMode = (value as Record<string, unknown>).displayMode;
|
|
36
|
+
if (displayMode === undefined) return {};
|
|
37
|
+
if (displayMode !== "remaining" && displayMode !== "used") {
|
|
38
|
+
return {
|
|
39
|
+
warning: 'displayMode must be either "remaining" or "used"',
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
return { displayMode };
|
|
43
|
+
}
|
package/src/config.ts
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import { CONFIG_DIR_NAME, getAgentDir } from "@earendil-works/pi-coding-agent";
|
|
4
|
+
import {
|
|
5
|
+
parseUsageConfig,
|
|
6
|
+
resolveUsageConfig,
|
|
7
|
+
type UsageConfig,
|
|
8
|
+
} from "./config-core.ts";
|
|
9
|
+
|
|
10
|
+
const CONFIG_FILE_NAME = "subscription-usage.json";
|
|
11
|
+
|
|
12
|
+
export interface LoadedUsageConfig extends UsageConfig {
|
|
13
|
+
warnings: string[];
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export function loadUsageConfig(
|
|
17
|
+
cwd: string,
|
|
18
|
+
includeProjectConfig: boolean,
|
|
19
|
+
): LoadedUsageConfig {
|
|
20
|
+
const warnings: string[] = [];
|
|
21
|
+
const globalConfig = readConfigFile(
|
|
22
|
+
join(getAgentDir(), CONFIG_FILE_NAME),
|
|
23
|
+
warnings,
|
|
24
|
+
);
|
|
25
|
+
const projectConfig = includeProjectConfig
|
|
26
|
+
? readConfigFile(join(cwd, CONFIG_DIR_NAME, CONFIG_FILE_NAME), warnings)
|
|
27
|
+
: undefined;
|
|
28
|
+
return {
|
|
29
|
+
...resolveUsageConfig(globalConfig, projectConfig),
|
|
30
|
+
warnings,
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function readConfigFile(
|
|
35
|
+
path: string,
|
|
36
|
+
warnings: string[],
|
|
37
|
+
): ReturnType<typeof parseUsageConfig> | undefined {
|
|
38
|
+
if (!existsSync(path)) return undefined;
|
|
39
|
+
try {
|
|
40
|
+
const parsed = parseUsageConfig(JSON.parse(readFileSync(path, "utf8")));
|
|
41
|
+
if (parsed.warning) warnings.push(`${path}: ${parsed.warning}`);
|
|
42
|
+
return parsed;
|
|
43
|
+
} catch (error) {
|
|
44
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
45
|
+
warnings.push(`${path}: ${message}`);
|
|
46
|
+
return undefined;
|
|
47
|
+
}
|
|
48
|
+
}
|
package/src/core.ts
ADDED
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
// Adapted from @narumitw/pi-usage@0.53.0 (MIT).
|
|
2
|
+
import { createHmac } from "node:crypto";
|
|
3
|
+
import type { UsageReport } from "./types.ts";
|
|
4
|
+
|
|
5
|
+
export class UsageCache {
|
|
6
|
+
private readonly entries = new Map<
|
|
7
|
+
string,
|
|
8
|
+
{ createdAt: number; report: UsageReport }
|
|
9
|
+
>();
|
|
10
|
+
private readonly ttlMs: number;
|
|
11
|
+
private readonly maxEntries: number;
|
|
12
|
+
|
|
13
|
+
constructor(ttlMs: number, maxEntries = 32) {
|
|
14
|
+
if (!Number.isFinite(ttlMs) || ttlMs <= 0) {
|
|
15
|
+
throw new Error("Cache TTL must be positive.");
|
|
16
|
+
}
|
|
17
|
+
if (!Number.isSafeInteger(maxEntries) || maxEntries < 1) {
|
|
18
|
+
throw new Error("Cache entry limit must be a positive integer.");
|
|
19
|
+
}
|
|
20
|
+
this.ttlMs = ttlMs;
|
|
21
|
+
this.maxEntries = maxEntries;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
get(
|
|
25
|
+
providerId: string,
|
|
26
|
+
fingerprint: string,
|
|
27
|
+
now = Date.now(),
|
|
28
|
+
): UsageReport | undefined {
|
|
29
|
+
this.sweepExpired(now);
|
|
30
|
+
return this.entries.get(cacheKey(providerId, fingerprint))?.report;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
set(
|
|
34
|
+
providerId: string,
|
|
35
|
+
fingerprint: string,
|
|
36
|
+
report: UsageReport,
|
|
37
|
+
now = Date.now(),
|
|
38
|
+
): void {
|
|
39
|
+
this.sweepExpired(now);
|
|
40
|
+
const key = cacheKey(providerId, fingerprint);
|
|
41
|
+
this.entries.delete(key);
|
|
42
|
+
while (this.entries.size >= this.maxEntries) {
|
|
43
|
+
const oldest = this.entries.keys().next().value;
|
|
44
|
+
if (oldest === undefined) break;
|
|
45
|
+
this.entries.delete(oldest);
|
|
46
|
+
}
|
|
47
|
+
this.entries.set(key, { createdAt: now, report });
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
clearProvider(providerId: string): void {
|
|
51
|
+
for (const key of this.entries.keys()) {
|
|
52
|
+
if (key.startsWith(`${providerId}:`)) this.entries.delete(key);
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
clear(): void {
|
|
57
|
+
this.entries.clear();
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
private sweepExpired(now: number): void {
|
|
61
|
+
for (const [key, entry] of this.entries) {
|
|
62
|
+
if (now - entry.createdAt >= this.ttlMs) this.entries.delete(key);
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export function fingerprintResolvedAuth(
|
|
68
|
+
auth: { apiKey?: string; headers?: Record<string, string> },
|
|
69
|
+
salt: Uint8Array,
|
|
70
|
+
): string {
|
|
71
|
+
const headers = Object.entries(auth.headers ?? {})
|
|
72
|
+
.map(([name, value]) => [name.toLowerCase(), value] as const)
|
|
73
|
+
.sort(([left], [right]) => left.localeCompare(right));
|
|
74
|
+
return createHmac("sha256", salt)
|
|
75
|
+
.update(JSON.stringify({ apiKey: auth.apiKey ?? "", headers }))
|
|
76
|
+
.digest("hex");
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export async function awaitWithDeadline<T>(
|
|
80
|
+
operation: () => Promise<T>,
|
|
81
|
+
signal: AbortSignal,
|
|
82
|
+
timeoutMs: number,
|
|
83
|
+
description: string,
|
|
84
|
+
): Promise<T> {
|
|
85
|
+
if (signal.aborted) throw abortError();
|
|
86
|
+
let timeout: ReturnType<typeof setTimeout> | undefined;
|
|
87
|
+
let abortListener: (() => void) | undefined;
|
|
88
|
+
try {
|
|
89
|
+
const result = Promise.resolve().then(() => {
|
|
90
|
+
if (signal.aborted) throw abortError();
|
|
91
|
+
return operation();
|
|
92
|
+
});
|
|
93
|
+
return await Promise.race([
|
|
94
|
+
result,
|
|
95
|
+
new Promise<never>((_resolve, reject) => {
|
|
96
|
+
timeout = setTimeout(() => {
|
|
97
|
+
reject(
|
|
98
|
+
Object.assign(
|
|
99
|
+
new Error(
|
|
100
|
+
`Timed out after ${Math.round(timeoutMs / 1_000)}s ${description}.`,
|
|
101
|
+
),
|
|
102
|
+
{ name: "TimeoutError" },
|
|
103
|
+
),
|
|
104
|
+
);
|
|
105
|
+
}, timeoutMs);
|
|
106
|
+
abortListener = () => reject(abortError());
|
|
107
|
+
signal.addEventListener("abort", abortListener, { once: true });
|
|
108
|
+
}),
|
|
109
|
+
]);
|
|
110
|
+
} finally {
|
|
111
|
+
if (timeout) clearTimeout(timeout);
|
|
112
|
+
if (abortListener) signal.removeEventListener("abort", abortListener);
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
export function sanitizeDisplayText(value: string, maxChars = 160): string {
|
|
117
|
+
const plain = value
|
|
118
|
+
.replace(/\x1b(?:\[[0-?]*[ -/]*[@-~]|\][^\x07]*(?:\x07|\x1b\\)?)/gu, "")
|
|
119
|
+
.replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f-\u009f]/gu, "")
|
|
120
|
+
.replace(/[\t\r\n]+/gu, " ")
|
|
121
|
+
.replace(/\s+/gu, " ")
|
|
122
|
+
.trim();
|
|
123
|
+
return plain.length <= maxChars
|
|
124
|
+
? plain
|
|
125
|
+
: `${plain.slice(0, Math.max(0, maxChars - 1))}…`;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
export function redactUsageError(
|
|
129
|
+
value: string,
|
|
130
|
+
secrets: readonly string[] = [],
|
|
131
|
+
): string {
|
|
132
|
+
let redacted = value;
|
|
133
|
+
for (const secret of [...new Set(secrets)]
|
|
134
|
+
.filter(Boolean)
|
|
135
|
+
.sort((a, b) => b.length - a.length)) {
|
|
136
|
+
redacted = redacted.replace(
|
|
137
|
+
new RegExp(escapeRegExp(secret), "gu"),
|
|
138
|
+
"<redacted>",
|
|
139
|
+
);
|
|
140
|
+
}
|
|
141
|
+
redacted = redacted
|
|
142
|
+
.replace(/Bearer\s+[A-Za-z0-9._~+/=-]+/giu, "Bearer <redacted>")
|
|
143
|
+
.replace(
|
|
144
|
+
/"(?:access_token|refresh_token|api_key)"\s*:\s*"[^"]+"/giu,
|
|
145
|
+
(match) => {
|
|
146
|
+
const separator = match.indexOf(":");
|
|
147
|
+
return `${match.slice(0, separator + 1)}"<redacted>"`;
|
|
148
|
+
},
|
|
149
|
+
);
|
|
150
|
+
return sanitizeDisplayText(redacted, 600);
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
export function errorMessage(error: unknown): string {
|
|
154
|
+
return sanitizeDisplayText(
|
|
155
|
+
error instanceof Error ? error.message : String(error),
|
|
156
|
+
600,
|
|
157
|
+
);
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
export function abortError(): Error {
|
|
161
|
+
return Object.assign(new Error("Usage query aborted."), {
|
|
162
|
+
name: "AbortError",
|
|
163
|
+
});
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
export function isAbortError(error: unknown): boolean {
|
|
167
|
+
return error instanceof Error && error.name === "AbortError";
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
export function modelIdentity(
|
|
171
|
+
model: { provider: string; id: string } | undefined,
|
|
172
|
+
): string | undefined {
|
|
173
|
+
return model ? `${model.provider}/${model.id}` : undefined;
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
function cacheKey(providerId: string, fingerprint: string): string {
|
|
177
|
+
return `${providerId}:${fingerprint}`;
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
function escapeRegExp(value: string): string {
|
|
181
|
+
return value.replace(/[.*+?^${}()|[\]\\]/gu, "\\$&");
|
|
182
|
+
}
|
package/src/display.ts
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import type { UsageBucket } from "./types.ts";
|
|
2
|
+
|
|
3
|
+
export type UsageDisplayMode = "remaining" | "used";
|
|
4
|
+
|
|
5
|
+
export const DEFAULT_USAGE_DISPLAY_MODE: UsageDisplayMode = "remaining";
|
|
6
|
+
|
|
7
|
+
export function usagePercentRemaining(bucket: UsageBucket): number | undefined {
|
|
8
|
+
if (bucket.unit === "percent" && bucket.remaining !== undefined) {
|
|
9
|
+
return clampPercent(bucket.remaining);
|
|
10
|
+
}
|
|
11
|
+
if (!bucket.limit || bucket.remaining === undefined) return undefined;
|
|
12
|
+
return clampPercent((bucket.remaining / bucket.limit) * 100);
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export function usagePercentUsed(bucket: UsageBucket): number | undefined {
|
|
16
|
+
if (bucket.unit === "percent" && bucket.used !== undefined) {
|
|
17
|
+
return clampPercent(bucket.used);
|
|
18
|
+
}
|
|
19
|
+
if (bucket.limit && bucket.used !== undefined) {
|
|
20
|
+
return clampPercent((bucket.used / bucket.limit) * 100);
|
|
21
|
+
}
|
|
22
|
+
const remaining = usagePercentRemaining(bucket);
|
|
23
|
+
return remaining === undefined ? undefined : 100 - remaining;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export function usagePercent(
|
|
27
|
+
bucket: UsageBucket,
|
|
28
|
+
mode: UsageDisplayMode,
|
|
29
|
+
): number | undefined {
|
|
30
|
+
return mode === "used"
|
|
31
|
+
? usagePercentUsed(bucket)
|
|
32
|
+
: usagePercentRemaining(bucket);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export function usageAmount(
|
|
36
|
+
bucket: UsageBucket,
|
|
37
|
+
mode: UsageDisplayMode,
|
|
38
|
+
): number | undefined {
|
|
39
|
+
const direct = mode === "used" ? bucket.used : bucket.remaining;
|
|
40
|
+
if (direct !== undefined) return direct;
|
|
41
|
+
if (bucket.limit === undefined) return undefined;
|
|
42
|
+
const opposite = mode === "used" ? bucket.remaining : bucket.used;
|
|
43
|
+
return opposite === undefined
|
|
44
|
+
? undefined
|
|
45
|
+
: Math.max(0, bucket.limit - opposite);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** Integer presentation only; keep the original number for semantic decisions. */
|
|
49
|
+
export function formatUsagePercent(value: number): string {
|
|
50
|
+
return String(Math.round(clampPercent(value)));
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function clampPercent(value: number): number {
|
|
54
|
+
return Math.min(100, Math.max(0, value));
|
|
55
|
+
}
|
package/src/format.ts
ADDED
|
@@ -0,0 +1,225 @@
|
|
|
1
|
+
// Formatting model adapted from @narumitw/pi-usage@0.53.0 (MIT).
|
|
2
|
+
import {
|
|
3
|
+
DEFAULT_USAGE_DISPLAY_MODE,
|
|
4
|
+
formatUsagePercent,
|
|
5
|
+
usageAmount,
|
|
6
|
+
usagePercent,
|
|
7
|
+
type UsageDisplayMode,
|
|
8
|
+
} from "./display.ts";
|
|
9
|
+
import { sortUsageBuckets, usageWindowLabel } from "./status.ts";
|
|
10
|
+
import type {
|
|
11
|
+
ProviderUsageState,
|
|
12
|
+
UsageBucket,
|
|
13
|
+
UsageMetric,
|
|
14
|
+
UsageReport,
|
|
15
|
+
} from "./types.ts";
|
|
16
|
+
|
|
17
|
+
export { formatUsageStatusline } from "./status.ts";
|
|
18
|
+
|
|
19
|
+
const BAR_SEGMENTS = 12;
|
|
20
|
+
|
|
21
|
+
interface PanelRow {
|
|
22
|
+
label: string;
|
|
23
|
+
detail: string;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
interface PanelSection {
|
|
27
|
+
heading?: string;
|
|
28
|
+
rows: PanelRow[];
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export function formatUsageReport(
|
|
32
|
+
report: UsageReport,
|
|
33
|
+
displayMode: UsageDisplayMode = DEFAULT_USAGE_DISPLAY_MODE,
|
|
34
|
+
): string {
|
|
35
|
+
const sections = bucketSections(report, displayMode);
|
|
36
|
+
const accountRows: PanelRow[] = report.metrics.map((metric) => ({
|
|
37
|
+
label: metric.label,
|
|
38
|
+
detail: formatMetric(metric),
|
|
39
|
+
}));
|
|
40
|
+
for (const note of report.notes ?? []) accountRows.push(noteRow(note));
|
|
41
|
+
const allRows = [
|
|
42
|
+
...sections.flatMap((section) => section.rows),
|
|
43
|
+
...accountRows,
|
|
44
|
+
];
|
|
45
|
+
const labelWidth = allRows.reduce(
|
|
46
|
+
(width, row) => Math.max(width, displayWidth(row.label)),
|
|
47
|
+
0,
|
|
48
|
+
);
|
|
49
|
+
const grouped = sections.some((section) => Boolean(section.heading));
|
|
50
|
+
const lines = [report.providerName];
|
|
51
|
+
if (!grouped) {
|
|
52
|
+
const rows = sections.flatMap((section) => section.rows);
|
|
53
|
+
lines.push(...formatPanelRows(rows, labelWidth, 2));
|
|
54
|
+
if (accountRows.length > 0) {
|
|
55
|
+
lines.push("", " Account:");
|
|
56
|
+
lines.push(...formatPanelRows(accountRows, labelWidth, 4));
|
|
57
|
+
}
|
|
58
|
+
return lines.join("\n");
|
|
59
|
+
}
|
|
60
|
+
for (const section of sections) {
|
|
61
|
+
if (lines.length > 1) lines.push("");
|
|
62
|
+
if (section.heading) lines.push(` ${section.heading}:`);
|
|
63
|
+
lines.push(...formatPanelRows(section.rows, labelWidth, 4));
|
|
64
|
+
}
|
|
65
|
+
if (accountRows.length > 0) {
|
|
66
|
+
lines.push("", " Account:");
|
|
67
|
+
lines.push(...formatPanelRows(accountRows, labelWidth, 4));
|
|
68
|
+
}
|
|
69
|
+
return lines.join("\n");
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export function formatProviderState(
|
|
73
|
+
state: ProviderUsageState,
|
|
74
|
+
displayMode: UsageDisplayMode = DEFAULT_USAGE_DISPLAY_MODE,
|
|
75
|
+
): string {
|
|
76
|
+
if (state.status === "ready") {
|
|
77
|
+
return formatUsageReport(state.report, displayMode);
|
|
78
|
+
}
|
|
79
|
+
let status = "Query Failed";
|
|
80
|
+
if (state.status === "auth-unavailable") status = "Auth Unavailable";
|
|
81
|
+
else if (state.status === "unsupported") status = "Unsupported";
|
|
82
|
+
else if (state.status === "pending") status = "Waiting";
|
|
83
|
+
return `${state.providerName}\n ${status}: ${state.message}`;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
function formatBucket(
|
|
87
|
+
bucket: UsageBucket,
|
|
88
|
+
displayMode: UsageDisplayMode,
|
|
89
|
+
): string {
|
|
90
|
+
const selectedPercent = usagePercent(bucket, displayMode);
|
|
91
|
+
const selectedAmount = usageAmount(bucket, displayMode);
|
|
92
|
+
const qualifier = displayMode === "used" ? "used" : "left";
|
|
93
|
+
const reset = bucket.resetsAt
|
|
94
|
+
? ` · resets ${formatReset(bucket.resetsAt)}`
|
|
95
|
+
: "";
|
|
96
|
+
if (selectedPercent !== undefined) {
|
|
97
|
+
const filled = Math.round((selectedPercent / 100) * BAR_SEGMENTS);
|
|
98
|
+
const bar = `${"█".repeat(filled)}${"░".repeat(BAR_SEGMENTS - filled)}`;
|
|
99
|
+
const percent = `${formatUsagePercent(selectedPercent).padStart(3)}%`;
|
|
100
|
+
if (
|
|
101
|
+
bucket.unit !== "percent" &&
|
|
102
|
+
bucket.limit !== undefined &&
|
|
103
|
+
bucket.limit !== 100 && // x/100 duplicates the percent exactly
|
|
104
|
+
selectedAmount !== undefined
|
|
105
|
+
) {
|
|
106
|
+
return `${bar} ${percent} ${qualifier} · ${formatNumber(selectedAmount)}/${formatNumber(bucket.limit)}${reset}`;
|
|
107
|
+
}
|
|
108
|
+
return `${bar} ${percent} ${qualifier}${reset}`;
|
|
109
|
+
}
|
|
110
|
+
const indent = " ".repeat(BAR_SEGMENTS + 2);
|
|
111
|
+
return `${indent}${formatValue(selectedAmount ?? "n/a", bucket.unit)} ${qualifier}${reset}`;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
function bucketSections(
|
|
115
|
+
report: UsageReport,
|
|
116
|
+
displayMode: UsageDisplayMode,
|
|
117
|
+
): PanelSection[] {
|
|
118
|
+
if (!report.buckets.some((bucket) => bucket.groupId)) {
|
|
119
|
+
return [
|
|
120
|
+
{
|
|
121
|
+
rows: sortUsageBuckets(report.buckets).map((bucket) => ({
|
|
122
|
+
label: usageWindowLabel(bucket),
|
|
123
|
+
detail: formatBucket(bucket, displayMode),
|
|
124
|
+
})),
|
|
125
|
+
},
|
|
126
|
+
];
|
|
127
|
+
}
|
|
128
|
+
const groups = new Map<string, { heading: string; buckets: UsageBucket[] }>();
|
|
129
|
+
for (const bucket of report.buckets) {
|
|
130
|
+
const key = bucket.groupId ?? "other";
|
|
131
|
+
let group = groups.get(key);
|
|
132
|
+
if (!group) {
|
|
133
|
+
group = {
|
|
134
|
+
heading: bucket.groupLabel ?? bucket.groupId ?? "Other Quota",
|
|
135
|
+
buckets: [],
|
|
136
|
+
};
|
|
137
|
+
groups.set(key, group);
|
|
138
|
+
}
|
|
139
|
+
group.buckets.push(bucket);
|
|
140
|
+
}
|
|
141
|
+
return [...groups.entries()]
|
|
142
|
+
.sort(([leftKey, left], [rightKey, right]) => {
|
|
143
|
+
if (leftKey === report.defaultGroupId) return -1;
|
|
144
|
+
if (rightKey === report.defaultGroupId) return 1;
|
|
145
|
+
return left.heading.localeCompare(right.heading);
|
|
146
|
+
})
|
|
147
|
+
.map(([, group]) => ({
|
|
148
|
+
heading: group.heading,
|
|
149
|
+
rows: sortUsageBuckets(group.buckets).map((bucket) => ({
|
|
150
|
+
label: usageWindowLabel(bucket),
|
|
151
|
+
detail: formatBucket(bucket, displayMode),
|
|
152
|
+
})),
|
|
153
|
+
}));
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
function formatPanelRows(
|
|
157
|
+
rows: readonly PanelRow[],
|
|
158
|
+
labelWidth: number,
|
|
159
|
+
indent: number,
|
|
160
|
+
): string[] {
|
|
161
|
+
const prefix = " ".repeat(indent);
|
|
162
|
+
return rows.map(
|
|
163
|
+
(row) => `${prefix}${padDisplayEnd(row.label, labelWidth)} ${row.detail}`,
|
|
164
|
+
);
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
function formatMetric(metric: UsageMetric): string {
|
|
168
|
+
return formatValue(metric.value, metric.unit);
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
function noteRow(note: string): PanelRow {
|
|
172
|
+
return { label: "Note", detail: note };
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
function formatValue(
|
|
176
|
+
value: number | string,
|
|
177
|
+
unit: UsageBucket["unit"] | undefined,
|
|
178
|
+
): string {
|
|
179
|
+
if (unit === "usd" && typeof value === "number") return `$${value.toFixed(2)}`;
|
|
180
|
+
return typeof value === "number" ? formatNumber(value) : value;
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
function formatNumber(value: number): string {
|
|
184
|
+
return Number.isInteger(value) ? String(value) : value.toFixed(2);
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
function formatReset(epochSeconds: number): string {
|
|
188
|
+
const reset = new Date(epochSeconds * 1_000);
|
|
189
|
+
if (Number.isNaN(reset.getTime())) return "unknown";
|
|
190
|
+
const month = (reset.getMonth() + 1).toString().padStart(2, "0");
|
|
191
|
+
const day = reset.getDate().toString().padStart(2, "0");
|
|
192
|
+
const hour = reset.getHours().toString().padStart(2, "0");
|
|
193
|
+
const minute = reset.getMinutes().toString().padStart(2, "0");
|
|
194
|
+
return `${month}/${day} ${hour}:${minute}`;
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
// East Asian display width so CJK labels can be padded into a real grid.
|
|
198
|
+
function displayWidth(value: string): number {
|
|
199
|
+
let width = 0;
|
|
200
|
+
for (const char of value) {
|
|
201
|
+
width += isWideCodePoint(char.codePointAt(0) ?? 0) ? 2 : 1;
|
|
202
|
+
}
|
|
203
|
+
return width;
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
function isWideCodePoint(code: number): boolean {
|
|
207
|
+
return (
|
|
208
|
+
code >= 0x1100 &&
|
|
209
|
+
(code <= 0x115f ||
|
|
210
|
+
code === 0x2329 ||
|
|
211
|
+
code === 0x232a ||
|
|
212
|
+
(code >= 0x2e80 && code <= 0xa4cf && code !== 0x303f) ||
|
|
213
|
+
(code >= 0xac00 && code <= 0xd7a3) ||
|
|
214
|
+
(code >= 0xf900 && code <= 0xfaff) ||
|
|
215
|
+
(code >= 0xfe30 && code <= 0xfe6f) ||
|
|
216
|
+
(code >= 0xff00 && code <= 0xff60) ||
|
|
217
|
+
(code >= 0xffe0 && code <= 0xffe6) ||
|
|
218
|
+
(code >= 0x20000 && code <= 0x3fffd))
|
|
219
|
+
);
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
function padDisplayEnd(value: string, width: number): string {
|
|
223
|
+
const padding = width - displayWidth(value);
|
|
224
|
+
return padding > 0 ? value + " ".repeat(padding) : value;
|
|
225
|
+
}
|