@specode/pi-subscription-usage 0.1.1 → 0.2.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/README.md +18 -1
- package/README.zh-CN.md +18 -1
- package/package.json +1 -1
- package/src/codex-resets.ts +5 -4
- package/src/config-core.ts +43 -0
- package/src/config.ts +48 -0
- package/src/display.ts +50 -0
- package/src/format.ts +45 -56
- package/src/providers/codex-constants.ts +2 -0
- package/src/providers/codex.ts +25 -9
- package/src/providers/grok.ts +29 -16
- package/src/providers/opencode-go.ts +3 -2
- package/src/query.ts +22 -33
- package/src/status.ts +55 -40
- package/src/types.ts +2 -0
- package/src/usage.ts +53 -15
package/README.md
CHANGED
|
@@ -55,6 +55,23 @@ Windows from different domains are never interleaved. Run `/usage` again wheneve
|
|
|
55
55
|
|
|
56
56
|
The reset menu appears only when Codex reports redeemable reset credits. Grok's current API exposes quota windows and natural reset times, but no verified manual-reset endpoint or reset-credit count, so the extension never invents a reset action.
|
|
57
57
|
|
|
58
|
+
## Configuration
|
|
59
|
+
|
|
60
|
+
Create `~/.pi/agent/subscription-usage.json` for a global setting, or `.pi/subscription-usage.json` in a trusted project to override it:
|
|
61
|
+
|
|
62
|
+
```json
|
|
63
|
+
{
|
|
64
|
+
"displayMode": "used"
|
|
65
|
+
}
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
`displayMode` accepts:
|
|
69
|
+
|
|
70
|
+
- `"remaining"` — show quota remaining (default, preserving the existing behavior).
|
|
71
|
+
- `"used"` — show quota consumed.
|
|
72
|
+
|
|
73
|
+
The setting applies to the footer status, `/usage` quota bars, and the structured status event. Run `/reload` after editing the file.
|
|
74
|
+
|
|
58
75
|
## Codex reset safety
|
|
59
76
|
|
|
60
77
|
Before redeeming a Codex reset credit, the extension:
|
|
@@ -71,7 +88,7 @@ The extension publishes two status layers:
|
|
|
71
88
|
- A plain `setStatus` string without provider names or icons, such as `5h 99% · 1w 85% · 1m 60%`.
|
|
72
89
|
- Structured window data through the `subscription-usage/status/v1` event.
|
|
73
90
|
|
|
74
|
-
Windows are always ordered as `5h / 1w / 1m / other`. Other extensions can consume the structured event to provide their own icons, colors, and layout without parsing display text.
|
|
91
|
+
Windows are always ordered as `5h / 1w / 1m / other`. Other extensions can consume the structured event to provide their own icons, colors, and layout without parsing display text. Ready events include `displayMode`; each window includes `displayPercent`, `remainingPercent`, and `usedPercent`. Consumers should render `displayPercent` while using the explicit remaining/used fields for semantic decisions such as colors or alerts.
|
|
75
92
|
|
|
76
93
|
## Security boundaries
|
|
77
94
|
|
package/README.zh-CN.md
CHANGED
|
@@ -55,6 +55,23 @@ Codex 结果会按以下额度域分组:
|
|
|
55
55
|
|
|
56
56
|
只有当 Codex 返回可兑换的重置次数时,才会显示重置菜单。Grok 当前 API 只公开额度窗口和自然重置时间,没有经过验证的手动重置端点或重置次数,因此本扩展不会虚构重置操作。
|
|
57
57
|
|
|
58
|
+
## 配置
|
|
59
|
+
|
|
60
|
+
可创建 `~/.pi/agent/subscription-usage.json` 作为全局配置,或在受信任项目中创建 `.pi/subscription-usage.json` 覆盖全局配置:
|
|
61
|
+
|
|
62
|
+
```json
|
|
63
|
+
{
|
|
64
|
+
"displayMode": "used"
|
|
65
|
+
}
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
`displayMode` 支持:
|
|
69
|
+
|
|
70
|
+
- `"remaining"`:显示剩余额度(默认值,保持当前行为)。
|
|
71
|
+
- `"used"`:显示已使用额度。
|
|
72
|
+
|
|
73
|
+
该配置同时作用于底部状态、`/usage` 额度条和结构化状态事件。修改配置文件后运行 `/reload`。
|
|
74
|
+
|
|
58
75
|
## Codex 重置安全措施
|
|
59
76
|
|
|
60
77
|
兑换 Codex 重置次数前,本扩展会:
|
|
@@ -71,7 +88,7 @@ Codex 结果会按以下额度域分组:
|
|
|
71
88
|
- 不含提供商名称或图标的普通 `setStatus` 文本,例如 `5h 99% · 1w 85% · 1m 60%`。
|
|
72
89
|
- 通过 `subscription-usage/status/v1` 事件发布的结构化窗口数据。
|
|
73
90
|
|
|
74
|
-
窗口始终按 `5h / 1w / 1m / other`
|
|
91
|
+
窗口始终按 `5h / 1w / 1m / other` 排序。其他扩展可以直接消费结构化事件,自定义图标、颜色和布局,而不必解析显示文本。就绪事件包含 `displayMode`,每个窗口包含 `displayPercent`、`remainingPercent` 和 `usedPercent`;消费者应展示 `displayPercent`,并在颜色或告警等语义判断中使用明确的剩余/已用字段。
|
|
75
92
|
|
|
76
93
|
## 安全边界
|
|
77
94
|
|
package/package.json
CHANGED
package/src/codex-resets.ts
CHANGED
|
@@ -19,6 +19,7 @@ import {
|
|
|
19
19
|
resolveUsageAuth,
|
|
20
20
|
} from "./query.ts";
|
|
21
21
|
import type { ResolvedUsageAuth } from "./types.ts";
|
|
22
|
+
import { CODEX_PROVIDER_ID } from "./providers/codex-constants.ts";
|
|
22
23
|
|
|
23
24
|
const RESET_CREDITS_URL =
|
|
24
25
|
"https://chatgpt.com/backend-api/wham/rate-limit-reset-credits";
|
|
@@ -32,13 +33,13 @@ export async function resolveCodexResetAuth(
|
|
|
32
33
|
credentialReader: StoredCredentialReader = readStoredCredential,
|
|
33
34
|
): Promise<ResolvedUsageAuth> {
|
|
34
35
|
const model = ctx.model;
|
|
35
|
-
if (model?.provider !==
|
|
36
|
+
if (model?.provider !== CODEX_PROVIDER_ID) {
|
|
36
37
|
throw new Error(
|
|
37
38
|
"Codex resets require the current model to use OpenAI Codex.",
|
|
38
39
|
);
|
|
39
40
|
}
|
|
40
41
|
const expectedModel = `${model.provider}/${model.id}`;
|
|
41
|
-
const adapter = adapterForProvider(
|
|
42
|
+
const adapter = adapterForProvider(CODEX_PROVIDER_ID);
|
|
42
43
|
if (!adapter) throw new Error("OpenAI Codex usage support is unavailable.");
|
|
43
44
|
const auth = await resolveUsageAuth(ctx, adapter, salt);
|
|
44
45
|
if (`${ctx.model?.provider}/${ctx.model?.id}` !== expectedModel) {
|
|
@@ -55,7 +56,7 @@ export async function resolveCodexResetAuth(
|
|
|
55
56
|
throw new Error("OpenAI Codex OAuth credentials were incomplete.");
|
|
56
57
|
const accountId = verifyCodexStoredOAuthCredential(
|
|
57
58
|
resolvedAccess,
|
|
58
|
-
credentialReader(
|
|
59
|
+
credentialReader(CODEX_PROVIDER_ID),
|
|
59
60
|
);
|
|
60
61
|
const authorization = `Bearer ${resolvedAccess}`;
|
|
61
62
|
const headers = {
|
|
@@ -63,7 +64,7 @@ export async function resolveCodexResetAuth(
|
|
|
63
64
|
"chatgpt-account-id": accountId,
|
|
64
65
|
};
|
|
65
66
|
return {
|
|
66
|
-
actualProviderId:
|
|
67
|
+
actualProviderId: CODEX_PROVIDER_ID,
|
|
67
68
|
apiKey: resolvedAccess,
|
|
68
69
|
headers,
|
|
69
70
|
fingerprint: fingerprintResolvedAuth({ headers }, salt),
|
|
@@ -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/display.ts
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
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
|
+
function clampPercent(value: number): number {
|
|
49
|
+
return Math.min(100, Math.max(0, value));
|
|
50
|
+
}
|
package/src/format.ts
CHANGED
|
@@ -1,9 +1,11 @@
|
|
|
1
1
|
// Formatting model adapted from @narumitw/pi-usage@0.53.0 (MIT).
|
|
2
2
|
import {
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
3
|
+
DEFAULT_USAGE_DISPLAY_MODE,
|
|
4
|
+
usageAmount,
|
|
5
|
+
usagePercent,
|
|
6
|
+
type UsageDisplayMode,
|
|
7
|
+
} from "./display.ts";
|
|
8
|
+
import { sortUsageBuckets, usageWindowLabel } from "./status.ts";
|
|
7
9
|
import type {
|
|
8
10
|
ProviderUsageState,
|
|
9
11
|
UsageBucket,
|
|
@@ -25,10 +27,13 @@ interface PanelSection {
|
|
|
25
27
|
rows: PanelRow[];
|
|
26
28
|
}
|
|
27
29
|
|
|
28
|
-
export function formatUsageReport(
|
|
29
|
-
|
|
30
|
+
export function formatUsageReport(
|
|
31
|
+
report: UsageReport,
|
|
32
|
+
displayMode: UsageDisplayMode = DEFAULT_USAGE_DISPLAY_MODE,
|
|
33
|
+
): string {
|
|
34
|
+
const sections = bucketSections(report, displayMode);
|
|
30
35
|
const accountRows: PanelRow[] = report.metrics.map((metric) => ({
|
|
31
|
-
label:
|
|
36
|
+
label: metric.label,
|
|
32
37
|
detail: formatMetric(metric),
|
|
33
38
|
}));
|
|
34
39
|
for (const note of report.notes ?? []) accountRows.push(noteRow(note));
|
|
@@ -59,61 +64,68 @@ export function formatUsageReport(report: UsageReport): string {
|
|
|
59
64
|
return lines.join("\n");
|
|
60
65
|
}
|
|
61
66
|
|
|
62
|
-
export function formatProviderState(
|
|
63
|
-
|
|
67
|
+
export function formatProviderState(
|
|
68
|
+
state: ProviderUsageState,
|
|
69
|
+
displayMode: UsageDisplayMode = DEFAULT_USAGE_DISPLAY_MODE,
|
|
70
|
+
): string {
|
|
71
|
+
if (state.status === "ready") {
|
|
72
|
+
return formatUsageReport(state.report, displayMode);
|
|
73
|
+
}
|
|
64
74
|
let status = "Query Failed";
|
|
65
75
|
if (state.status === "auth-unavailable") status = "Auth Unavailable";
|
|
66
76
|
else if (state.status === "unsupported") status = "Unsupported";
|
|
67
77
|
return `${state.providerName}\n ${status}: ${state.message}`;
|
|
68
78
|
}
|
|
69
79
|
|
|
70
|
-
function formatBucket(
|
|
71
|
-
|
|
80
|
+
function formatBucket(
|
|
81
|
+
bucket: UsageBucket,
|
|
82
|
+
displayMode: UsageDisplayMode,
|
|
83
|
+
): string {
|
|
84
|
+
const selectedPercent = usagePercent(bucket, displayMode);
|
|
85
|
+
const selectedAmount = usageAmount(bucket, displayMode);
|
|
86
|
+
const qualifier = displayMode === "used" ? "used" : "left";
|
|
72
87
|
const reset = bucket.resetsAt
|
|
73
88
|
? ` · resets ${formatReset(bucket.resetsAt)}`
|
|
74
89
|
: "";
|
|
75
|
-
if (
|
|
76
|
-
const filled = Math.round((
|
|
90
|
+
if (selectedPercent !== undefined) {
|
|
91
|
+
const filled = Math.round((selectedPercent / 100) * BAR_SEGMENTS);
|
|
77
92
|
const bar = `${"█".repeat(filled)}${"░".repeat(BAR_SEGMENTS - filled)}`;
|
|
78
|
-
const percent = `${String(Math.round(
|
|
93
|
+
const percent = `${String(Math.round(selectedPercent)).padStart(3)}%`;
|
|
79
94
|
if (
|
|
80
95
|
bucket.unit !== "percent" &&
|
|
81
96
|
bucket.limit !== undefined &&
|
|
82
97
|
bucket.limit !== 100 && // x/100 duplicates the percent exactly
|
|
83
|
-
|
|
98
|
+
selectedAmount !== undefined
|
|
84
99
|
) {
|
|
85
|
-
return `${bar} ${percent}
|
|
100
|
+
return `${bar} ${percent} ${qualifier} · ${formatNumber(selectedAmount)}/${formatNumber(bucket.limit)}${reset}`;
|
|
86
101
|
}
|
|
87
|
-
return `${bar} ${percent}
|
|
102
|
+
return `${bar} ${percent} ${qualifier}${reset}`;
|
|
88
103
|
}
|
|
89
104
|
const indent = " ".repeat(BAR_SEGMENTS + 2);
|
|
90
|
-
|
|
91
|
-
return `${indent}${formatValue(bucket.remaining, bucket.unit)} left${reset}`;
|
|
92
|
-
}
|
|
93
|
-
return `${indent}${formatValue(bucket.used ?? "n/a", bucket.unit)} used${reset}`;
|
|
105
|
+
return `${indent}${formatValue(selectedAmount ?? "n/a", bucket.unit)} ${qualifier}${reset}`;
|
|
94
106
|
}
|
|
95
107
|
|
|
96
|
-
function bucketSections(
|
|
97
|
-
|
|
108
|
+
function bucketSections(
|
|
109
|
+
report: UsageReport,
|
|
110
|
+
displayMode: UsageDisplayMode,
|
|
111
|
+
): PanelSection[] {
|
|
112
|
+
if (!report.buckets.some((bucket) => bucket.groupId)) {
|
|
98
113
|
return [
|
|
99
114
|
{
|
|
100
|
-
rows: sortUsageBuckets(buckets).map((bucket) => ({
|
|
115
|
+
rows: sortUsageBuckets(report.buckets).map((bucket) => ({
|
|
101
116
|
label: usageWindowLabel(bucket),
|
|
102
|
-
detail: formatBucket(bucket),
|
|
117
|
+
detail: formatBucket(bucket, displayMode),
|
|
103
118
|
})),
|
|
104
119
|
},
|
|
105
120
|
];
|
|
106
121
|
}
|
|
107
122
|
const groups = new Map<string, { heading: string; buckets: UsageBucket[] }>();
|
|
108
|
-
for (const bucket of buckets) {
|
|
123
|
+
for (const bucket of report.buckets) {
|
|
109
124
|
const key = bucket.groupId ?? "other";
|
|
110
125
|
let group = groups.get(key);
|
|
111
126
|
if (!group) {
|
|
112
127
|
group = {
|
|
113
|
-
heading:
|
|
114
|
-
key === "codex"
|
|
115
|
-
? "Shared Across Models"
|
|
116
|
-
: (bucket.groupLabel ?? bucket.groupId ?? "Other Quota"),
|
|
128
|
+
heading: bucket.groupLabel ?? bucket.groupId ?? "Other Quota",
|
|
117
129
|
buckets: [],
|
|
118
130
|
};
|
|
119
131
|
groups.set(key, group);
|
|
@@ -122,15 +134,15 @@ function bucketSections(buckets: readonly UsageBucket[]): PanelSection[] {
|
|
|
122
134
|
}
|
|
123
135
|
return [...groups.entries()]
|
|
124
136
|
.sort(([leftKey, left], [rightKey, right]) => {
|
|
125
|
-
if (leftKey ===
|
|
126
|
-
if (rightKey ===
|
|
137
|
+
if (leftKey === report.defaultGroupId) return -1;
|
|
138
|
+
if (rightKey === report.defaultGroupId) return 1;
|
|
127
139
|
return left.heading.localeCompare(right.heading);
|
|
128
140
|
})
|
|
129
141
|
.map(([, group]) => ({
|
|
130
142
|
heading: group.heading,
|
|
131
143
|
rows: sortUsageBuckets(group.buckets).map((bucket) => ({
|
|
132
144
|
label: usageWindowLabel(bucket),
|
|
133
|
-
detail: formatBucket(bucket),
|
|
145
|
+
detail: formatBucket(bucket, displayMode),
|
|
134
146
|
})),
|
|
135
147
|
}));
|
|
136
148
|
}
|
|
@@ -146,34 +158,11 @@ function formatPanelRows(
|
|
|
146
158
|
);
|
|
147
159
|
}
|
|
148
160
|
|
|
149
|
-
function metricLabel(metric: UsageMetric): string {
|
|
150
|
-
if (metric.id === "reset-credits") return "Resets Left";
|
|
151
|
-
if (metric.id === "credits") return "Extra Credit";
|
|
152
|
-
if (metric.id === "included-used") return "Included Used";
|
|
153
|
-
if (metric.id === "included-limit") return "Included Total";
|
|
154
|
-
if (metric.id === "on-demand-used") return "On-Demand Used";
|
|
155
|
-
if (metric.id === "on-demand-cap") return "On-Demand Cap";
|
|
156
|
-
if (metric.id === "prepaid-balance") return "Prepaid Balance";
|
|
157
|
-
return metric.label;
|
|
158
|
-
}
|
|
159
|
-
|
|
160
161
|
function formatMetric(metric: UsageMetric): string {
|
|
161
|
-
if (metric.id === "reset-credits" && typeof metric.value === "number") {
|
|
162
|
-
return formatNumber(metric.value);
|
|
163
|
-
}
|
|
164
162
|
return formatValue(metric.value, metric.unit);
|
|
165
163
|
}
|
|
166
164
|
|
|
167
165
|
function noteRow(note: string): PanelRow {
|
|
168
|
-
if (note.startsWith("Plan: ")) {
|
|
169
|
-
return { label: "Plan", detail: note.slice("Plan: ".length) };
|
|
170
|
-
}
|
|
171
|
-
if (note === "On-demand billing: enabled") {
|
|
172
|
-
return { label: "On-Demand", detail: "on" };
|
|
173
|
-
}
|
|
174
|
-
if (note === "On-demand billing: disabled") {
|
|
175
|
-
return { label: "On-Demand", detail: "off" };
|
|
176
|
-
}
|
|
177
166
|
return { label: "Note", detail: note };
|
|
178
167
|
}
|
|
179
168
|
|
package/src/providers/codex.ts
CHANGED
|
@@ -1,6 +1,10 @@
|
|
|
1
1
|
// Adapted from @narumitw/pi-usage@0.53.0 (MIT).
|
|
2
2
|
import { sanitizeDisplayText } from "../core.ts";
|
|
3
3
|
import type { UsageBucket, UsageMetric, UsageReport } from "../types.ts";
|
|
4
|
+
import {
|
|
5
|
+
CODEX_DEFAULT_GROUP_ID,
|
|
6
|
+
CODEX_PROVIDER_ID,
|
|
7
|
+
} from "./codex-constants.ts";
|
|
4
8
|
|
|
5
9
|
export function normalizeCodexUsage(
|
|
6
10
|
payload: unknown,
|
|
@@ -9,7 +13,13 @@ export function normalizeCodexUsage(
|
|
|
9
13
|
const root = asObject(payload);
|
|
10
14
|
if (!root) throw new Error("Codex usage response was not an object.");
|
|
11
15
|
const buckets: UsageBucket[] = [];
|
|
12
|
-
normalizeRateLimitGroup(
|
|
16
|
+
normalizeRateLimitGroup(
|
|
17
|
+
buckets,
|
|
18
|
+
CODEX_DEFAULT_GROUP_ID,
|
|
19
|
+
"Shared Across Models",
|
|
20
|
+
root.rate_limit,
|
|
21
|
+
false,
|
|
22
|
+
);
|
|
13
23
|
const additional = Array.isArray(root.additional_rate_limits)
|
|
14
24
|
? root.additional_rate_limits
|
|
15
25
|
: [];
|
|
@@ -34,25 +44,29 @@ export function normalizeCodexUsage(
|
|
|
34
44
|
const credits = asObject(root.credits);
|
|
35
45
|
if (credits?.has_credits === true) {
|
|
36
46
|
if (credits.unlimited === true) {
|
|
37
|
-
metrics.push({
|
|
47
|
+
metrics.push({
|
|
48
|
+
id: "credits",
|
|
49
|
+
label: "Extra Credit",
|
|
50
|
+
value: "unlimited",
|
|
51
|
+
});
|
|
38
52
|
} else {
|
|
39
53
|
const balance = asNumber(credits.balance);
|
|
40
54
|
metrics.push({
|
|
41
55
|
id: "credits",
|
|
42
|
-
label: "
|
|
56
|
+
label: "Extra Credit",
|
|
43
57
|
value: balance ?? "available",
|
|
44
58
|
...(balance === undefined ? {} : { unit: "count" as const }),
|
|
45
59
|
});
|
|
46
60
|
}
|
|
47
61
|
} else if (credits?.has_credits === false) {
|
|
48
|
-
metrics.push({ id: "credits", label: "
|
|
62
|
+
metrics.push({ id: "credits", label: "Extra Credit", value: "none" });
|
|
49
63
|
}
|
|
50
64
|
const resetCredits = asObject(root.rate_limit_reset_credits);
|
|
51
65
|
const resetCount = asNonnegativeInteger(resetCredits?.available_count);
|
|
52
66
|
if (resetCount !== undefined) {
|
|
53
67
|
metrics.push({
|
|
54
68
|
id: "reset-credits",
|
|
55
|
-
label: "
|
|
69
|
+
label: "Resets Left",
|
|
56
70
|
value: resetCount,
|
|
57
71
|
unit: "count",
|
|
58
72
|
});
|
|
@@ -61,8 +75,9 @@ export function normalizeCodexUsage(
|
|
|
61
75
|
throw new Error("Codex usage endpoint returned no displayable usage data.");
|
|
62
76
|
}
|
|
63
77
|
const planType = asString(root.plan_type);
|
|
78
|
+
if (planType) metrics.push({ id: "plan", label: "Plan", value: planType });
|
|
64
79
|
return {
|
|
65
|
-
providerId:
|
|
80
|
+
providerId: CODEX_PROVIDER_ID,
|
|
66
81
|
providerName: "OpenAI Codex",
|
|
67
82
|
capturedAt,
|
|
68
83
|
source: "codex-pi-auth",
|
|
@@ -71,8 +86,8 @@ export function normalizeCodexUsage(
|
|
|
71
86
|
label: "ChatGPT subscription limits",
|
|
72
87
|
},
|
|
73
88
|
buckets,
|
|
89
|
+
defaultGroupId: CODEX_DEFAULT_GROUP_ID,
|
|
74
90
|
metrics,
|
|
75
|
-
...(planType ? { notes: [`Plan: ${planType}`] } : {}),
|
|
76
91
|
};
|
|
77
92
|
}
|
|
78
93
|
|
|
@@ -105,6 +120,7 @@ function addWindow(
|
|
|
105
120
|
if (!value) throw new Error("Codex rate-limit window was not an object.");
|
|
106
121
|
const used = asNumber(value.used_percent);
|
|
107
122
|
if (used === undefined) return;
|
|
123
|
+
const clampedUsed = clampPercent(used);
|
|
108
124
|
const seconds = asNumber(value.limit_window_seconds);
|
|
109
125
|
const resetsAt = asNumber(value.reset_at);
|
|
110
126
|
buckets.push({
|
|
@@ -113,8 +129,8 @@ function addWindow(
|
|
|
113
129
|
groupId,
|
|
114
130
|
groupLabel,
|
|
115
131
|
modelKeys: [groupId, groupLabel],
|
|
116
|
-
used,
|
|
117
|
-
remaining: 100 -
|
|
132
|
+
used: clampedUsed,
|
|
133
|
+
remaining: 100 - clampedUsed,
|
|
118
134
|
limit: 100,
|
|
119
135
|
unit: "percent",
|
|
120
136
|
...(seconds !== undefined && seconds > 0
|
package/src/providers/grok.ts
CHANGED
|
@@ -6,6 +6,18 @@ const MAX_USER_ID_LENGTH = 256;
|
|
|
6
6
|
const MAX_LABEL_LENGTH = 80;
|
|
7
7
|
const MAX_CENTS = 1_000_000_000_000;
|
|
8
8
|
const USER_ID_PATTERN = /^[\x21-\x7e]+$/u;
|
|
9
|
+
// Grok CLI proxy protocol version; independent of this extension's package version.
|
|
10
|
+
const GROK_CLIENT_VERSION = "0.1.0";
|
|
11
|
+
|
|
12
|
+
export function grokRequestHeaders(userId?: string): Record<string, string> {
|
|
13
|
+
return {
|
|
14
|
+
"X-XAI-Token-Auth": "xai-grok-cli",
|
|
15
|
+
"x-grok-client-version": GROK_CLIENT_VERSION,
|
|
16
|
+
"x-grok-client-mode":
|
|
17
|
+
process.stdin.isTTY && process.stdout.isTTY ? "interactive" : "headless",
|
|
18
|
+
...(userId ? { "x-userid": userId } : {}),
|
|
19
|
+
};
|
|
20
|
+
}
|
|
9
21
|
|
|
10
22
|
export function normalizeGrokIdentity(payload: unknown): string {
|
|
11
23
|
const userId = asObject(payload)?.userId;
|
|
@@ -38,8 +50,8 @@ export function normalizeGrokBilling(
|
|
|
38
50
|
if (buckets.length === 0 && metrics.length === 0) {
|
|
39
51
|
throw new Error("Grok billing endpoint returned no displayable usage data.");
|
|
40
52
|
}
|
|
41
|
-
|
|
42
|
-
|
|
53
|
+
addAccountMetrics(metrics, root);
|
|
54
|
+
return {
|
|
43
55
|
providerId: "xai",
|
|
44
56
|
providerName: "Grok",
|
|
45
57
|
capturedAt,
|
|
@@ -51,8 +63,6 @@ export function normalizeGrokBilling(
|
|
|
51
63
|
buckets,
|
|
52
64
|
metrics,
|
|
53
65
|
};
|
|
54
|
-
if (notes.length > 0) report.notes = notes;
|
|
55
|
-
return report;
|
|
56
66
|
}
|
|
57
67
|
|
|
58
68
|
function createIncludedBucket(
|
|
@@ -122,46 +132,49 @@ function collectMetrics(
|
|
|
122
132
|
addUsdMetric(
|
|
123
133
|
metrics,
|
|
124
134
|
"included-used",
|
|
125
|
-
"Included
|
|
135
|
+
"Included Used",
|
|
126
136
|
boundedCents(config?.used),
|
|
127
137
|
);
|
|
128
138
|
addUsdMetric(
|
|
129
139
|
metrics,
|
|
130
140
|
"included-limit",
|
|
131
|
-
"Included
|
|
141
|
+
"Included Total",
|
|
132
142
|
boundedCents(config?.monthlyLimit),
|
|
133
143
|
);
|
|
134
144
|
addUsdMetric(
|
|
135
145
|
metrics,
|
|
136
146
|
"on-demand-used",
|
|
137
|
-
"On-
|
|
147
|
+
"On-Demand Used",
|
|
138
148
|
boundedCents(config?.onDemandUsed),
|
|
139
149
|
);
|
|
140
150
|
addUsdMetric(
|
|
141
151
|
metrics,
|
|
142
152
|
"on-demand-cap",
|
|
143
|
-
"On-
|
|
153
|
+
"On-Demand Cap",
|
|
144
154
|
boundedCents(config?.onDemandCap),
|
|
145
155
|
);
|
|
146
156
|
addUsdMetric(
|
|
147
157
|
metrics,
|
|
148
158
|
"prepaid-balance",
|
|
149
|
-
"Prepaid
|
|
159
|
+
"Prepaid Balance",
|
|
150
160
|
boundedCents(config?.prepaidBalance),
|
|
151
161
|
);
|
|
152
162
|
return metrics;
|
|
153
163
|
}
|
|
154
164
|
|
|
155
|
-
function
|
|
156
|
-
|
|
165
|
+
function addAccountMetrics(
|
|
166
|
+
metrics: UsageMetric[],
|
|
167
|
+
root: Record<string, unknown>,
|
|
168
|
+
): void {
|
|
157
169
|
const tier = boundedLabel(root.subscriptionTier);
|
|
158
|
-
if (tier)
|
|
170
|
+
if (tier) metrics.push({ id: "plan", label: "Plan", value: tier });
|
|
159
171
|
if (typeof root.onDemandEnabled === "boolean") {
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
172
|
+
metrics.push({
|
|
173
|
+
id: "on-demand",
|
|
174
|
+
label: "On-Demand",
|
|
175
|
+
value: root.onDemandEnabled ? "on" : "off",
|
|
176
|
+
});
|
|
163
177
|
}
|
|
164
|
-
return notes;
|
|
165
178
|
}
|
|
166
179
|
|
|
167
180
|
function addUsdMetric(
|
|
@@ -29,12 +29,13 @@ export function normalizeOpenCodeGoUsage(
|
|
|
29
29
|
}
|
|
30
30
|
const used = asNonnegativeNumber(raw.percent);
|
|
31
31
|
if (used === undefined) continue;
|
|
32
|
+
const clampedUsed = clampPercent(used);
|
|
32
33
|
const resetsAt = asEpochSeconds(raw.resetsAt);
|
|
33
34
|
buckets.push({
|
|
34
35
|
id: window.key,
|
|
35
36
|
label: `${window.label} window`,
|
|
36
|
-
used,
|
|
37
|
-
remaining: 100 -
|
|
37
|
+
used: clampedUsed,
|
|
38
|
+
remaining: 100 - clampedUsed,
|
|
38
39
|
limit: 100,
|
|
39
40
|
unit: "percent",
|
|
40
41
|
windowMinutes: window.windowMinutes,
|
package/src/query.ts
CHANGED
|
@@ -1,13 +1,16 @@
|
|
|
1
1
|
// Runtime-auth and origin checks adapted from @narumitw/pi-usage@0.53.0 (MIT).
|
|
2
2
|
import { randomBytes } from "node:crypto";
|
|
3
|
+
import { createRequire } from "node:module";
|
|
3
4
|
import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
4
5
|
import {
|
|
5
6
|
errorMessage,
|
|
6
7
|
fingerprintResolvedAuth,
|
|
7
8
|
redactUsageError,
|
|
8
9
|
} from "./core.ts";
|
|
10
|
+
import { CODEX_PROVIDER_ID } from "./providers/codex-constants.ts";
|
|
9
11
|
import { normalizeCodexUsage } from "./providers/codex.ts";
|
|
10
12
|
import {
|
|
13
|
+
grokRequestHeaders,
|
|
11
14
|
normalizeGrokBilling,
|
|
12
15
|
normalizeGrokIdentity,
|
|
13
16
|
} from "./providers/grok.ts";
|
|
@@ -27,6 +30,11 @@ const GROK_BILLING_URL =
|
|
|
27
30
|
"https://cli-chat-proxy.grok.com/v1/billing?format=credits";
|
|
28
31
|
const MAX_SUCCESS_BODY_BYTES = 64 * 1024;
|
|
29
32
|
const MAX_ERROR_BODY_BYTES = 4 * 1024;
|
|
33
|
+
const PACKAGE_METADATA = createRequire(import.meta.url)("../package.json") as {
|
|
34
|
+
name: string;
|
|
35
|
+
version: string;
|
|
36
|
+
};
|
|
37
|
+
const USER_AGENT = `${PACKAGE_METADATA.name}/${PACKAGE_METADATA.version}`;
|
|
30
38
|
|
|
31
39
|
type PiModel = NonNullable<ExtensionContext["model"]>;
|
|
32
40
|
|
|
@@ -34,9 +42,10 @@ export const AUTH_FINGERPRINT_SALT = randomBytes(32);
|
|
|
34
42
|
|
|
35
43
|
export const SUPPORTED_ADAPTERS: readonly UsageProviderAdapter[] = [
|
|
36
44
|
{
|
|
37
|
-
id:
|
|
45
|
+
id: CODEX_PROVIDER_ID,
|
|
38
46
|
displayName: "OpenAI Codex",
|
|
39
|
-
providerIds: [
|
|
47
|
+
providerIds: [CODEX_PROVIDER_ID],
|
|
48
|
+
officialOrigins: ["https://chatgpt.com"],
|
|
40
49
|
semantics: {
|
|
41
50
|
kind: "consumer-subscription",
|
|
42
51
|
label: "ChatGPT subscription limits",
|
|
@@ -58,6 +67,7 @@ export const SUPPORTED_ADAPTERS: readonly UsageProviderAdapter[] = [
|
|
|
58
67
|
id: "opencode-go",
|
|
59
68
|
displayName: "OpenCode Go",
|
|
60
69
|
providerIds: ["opencode-go"],
|
|
70
|
+
officialOrigins: ["https://opencode.ai"],
|
|
61
71
|
semantics: { kind: "consumer-subscription", label: "OpenCode Go plan usage" },
|
|
62
72
|
async query(auth, signal, timeoutMs) {
|
|
63
73
|
return normalizeOpenCodeGoUsage(
|
|
@@ -76,6 +86,7 @@ export const SUPPORTED_ADAPTERS: readonly UsageProviderAdapter[] = [
|
|
|
76
86
|
id: "kimi-coding",
|
|
77
87
|
displayName: "Kimi Coding",
|
|
78
88
|
providerIds: ["kimi-coding"],
|
|
89
|
+
officialOrigins: ["https://api.kimi.com"],
|
|
79
90
|
semantics: { kind: "consumer-subscription", label: "Kimi Coding plan usage" },
|
|
80
91
|
async query(auth, signal, timeoutMs) {
|
|
81
92
|
return normalizeKimiUsage(
|
|
@@ -94,6 +105,7 @@ export const SUPPORTED_ADAPTERS: readonly UsageProviderAdapter[] = [
|
|
|
94
105
|
id: "xai",
|
|
95
106
|
displayName: "Grok",
|
|
96
107
|
providerIds: ["xai", "xai-auth"],
|
|
108
|
+
officialOrigins: ["https://api.x.ai", "https://cli-chat-proxy.grok.com"],
|
|
97
109
|
semantics: {
|
|
98
110
|
kind: "consumer-subscription",
|
|
99
111
|
label: "SuperGrok subscription usage",
|
|
@@ -106,7 +118,7 @@ export const SUPPORTED_ADAPTERS: readonly UsageProviderAdapter[] = [
|
|
|
106
118
|
signal,
|
|
107
119
|
timeoutMs,
|
|
108
120
|
"Grok identity endpoint",
|
|
109
|
-
{ headers:
|
|
121
|
+
{ headers: grokRequestHeaders() },
|
|
110
122
|
);
|
|
111
123
|
const userId = normalizeGrokIdentity(identity);
|
|
112
124
|
const billing = await fetchProviderJson(
|
|
@@ -115,7 +127,7 @@ export const SUPPORTED_ADAPTERS: readonly UsageProviderAdapter[] = [
|
|
|
115
127
|
signal,
|
|
116
128
|
timeoutMs,
|
|
117
129
|
"Grok billing endpoint",
|
|
118
|
-
{ headers:
|
|
130
|
+
{ headers: grokRequestHeaders(userId) },
|
|
119
131
|
);
|
|
120
132
|
return normalizeGrokBilling(billing, Date.now());
|
|
121
133
|
},
|
|
@@ -139,14 +151,14 @@ export async function resolveUsageAuth(
|
|
|
139
151
|
if (
|
|
140
152
|
current &&
|
|
141
153
|
adapter.providerIds.includes(current.provider) &&
|
|
142
|
-
!hasOfficialOrigin(current.baseUrl,
|
|
154
|
+
!hasOfficialOrigin(current.baseUrl, adapter)
|
|
143
155
|
) {
|
|
144
156
|
throw new Error(
|
|
145
157
|
`${adapter.displayName} usage cannot send a custom provider credential to an official usage endpoint.`,
|
|
146
158
|
);
|
|
147
159
|
}
|
|
148
160
|
const candidates = candidateModels(ctx, adapter.providerIds).filter(
|
|
149
|
-
(candidate) => hasOfficialOrigin(candidate.baseUrl,
|
|
161
|
+
(candidate) => hasOfficialOrigin(candidate.baseUrl, adapter),
|
|
150
162
|
);
|
|
151
163
|
const currentModel =
|
|
152
164
|
current && adapter.providerIds.includes(current.provider)
|
|
@@ -166,10 +178,7 @@ export async function resolveUsageAuth(
|
|
|
166
178
|
}
|
|
167
179
|
const result = await ctx.modelRegistry.getProviderAuth(model.provider);
|
|
168
180
|
if (!result) return undefined;
|
|
169
|
-
if (
|
|
170
|
-
result.auth.baseUrl &&
|
|
171
|
-
!hasOfficialOrigin(result.auth.baseUrl, model.provider)
|
|
172
|
-
) {
|
|
181
|
+
if (result.auth.baseUrl && !hasOfficialOrigin(result.auth.baseUrl, adapter)) {
|
|
173
182
|
throw new Error(
|
|
174
183
|
`${adapter.displayName} usage cannot send a proxy-resolved credential to an official usage endpoint.`,
|
|
175
184
|
);
|
|
@@ -232,7 +241,7 @@ export async function fetchProviderJson(
|
|
|
232
241
|
try {
|
|
233
242
|
const headers: Record<string, string> = {
|
|
234
243
|
Accept: "application/json",
|
|
235
|
-
"User-Agent":
|
|
244
|
+
"User-Agent": USER_AGENT,
|
|
236
245
|
...auth.headers,
|
|
237
246
|
...request.headers,
|
|
238
247
|
};
|
|
@@ -348,21 +357,11 @@ function candidateModels(
|
|
|
348
357
|
|
|
349
358
|
function hasOfficialOrigin(
|
|
350
359
|
value: string | undefined,
|
|
351
|
-
|
|
360
|
+
adapter: UsageProviderAdapter,
|
|
352
361
|
): boolean {
|
|
353
362
|
if (!value) return false;
|
|
354
363
|
try {
|
|
355
|
-
|
|
356
|
-
if (providerId === "openai-codex") return origin === "https://chatgpt.com";
|
|
357
|
-
if (providerId === "opencode-go") return origin === "https://opencode.ai";
|
|
358
|
-
if (providerId === "kimi-coding") return origin === "https://api.kimi.com";
|
|
359
|
-
if (providerId === "xai" || providerId === "xai-auth") {
|
|
360
|
-
return (
|
|
361
|
-
origin === "https://api.x.ai" ||
|
|
362
|
-
origin === "https://cli-chat-proxy.grok.com"
|
|
363
|
-
);
|
|
364
|
-
}
|
|
365
|
-
return false;
|
|
364
|
+
return adapter.officialOrigins.includes(new URL(value).origin);
|
|
366
365
|
} catch {
|
|
367
366
|
return false;
|
|
368
367
|
}
|
|
@@ -378,13 +377,3 @@ function headerValue(
|
|
|
378
377
|
)?.[1] ?? undefined
|
|
379
378
|
);
|
|
380
379
|
}
|
|
381
|
-
|
|
382
|
-
function grokHeaders(userId?: string): Record<string, string> {
|
|
383
|
-
return {
|
|
384
|
-
"X-XAI-Token-Auth": "xai-grok-cli",
|
|
385
|
-
"x-grok-client-version": "0.1.0",
|
|
386
|
-
"x-grok-client-mode":
|
|
387
|
-
process.stdin.isTTY && process.stdout.isTTY ? "interactive" : "headless",
|
|
388
|
-
...(userId ? { "x-userid": userId } : {}),
|
|
389
|
-
};
|
|
390
|
-
}
|
package/src/status.ts
CHANGED
|
@@ -1,5 +1,14 @@
|
|
|
1
|
+
import {
|
|
2
|
+
DEFAULT_USAGE_DISPLAY_MODE,
|
|
3
|
+
usagePercent,
|
|
4
|
+
usagePercentRemaining,
|
|
5
|
+
usagePercentUsed,
|
|
6
|
+
type UsageDisplayMode,
|
|
7
|
+
} from "./display.ts";
|
|
1
8
|
import type { UsageBucket, UsageModel, UsageReport } from "./types.ts";
|
|
2
9
|
|
|
10
|
+
export { usagePercentRemaining, usagePercentUsed } from "./display.ts";
|
|
11
|
+
|
|
3
12
|
export const USAGE_STATUS_EVENT = "subscription-usage/status/v1";
|
|
4
13
|
|
|
5
14
|
export type UsageStatusWindowKind =
|
|
@@ -13,6 +22,8 @@ export interface UsageStatusWindow {
|
|
|
13
22
|
kind: UsageStatusWindowKind;
|
|
14
23
|
label: string;
|
|
15
24
|
remainingPercent: number;
|
|
25
|
+
usedPercent: number;
|
|
26
|
+
displayPercent: number;
|
|
16
27
|
windowMinutes?: number;
|
|
17
28
|
resetsAt?: number;
|
|
18
29
|
}
|
|
@@ -23,6 +34,7 @@ export type UsageStatusEvent =
|
|
|
23
34
|
status: "ready";
|
|
24
35
|
providerId: string;
|
|
25
36
|
capturedAt: number;
|
|
37
|
+
displayMode: UsageDisplayMode;
|
|
26
38
|
windows: UsageStatusWindow[];
|
|
27
39
|
}
|
|
28
40
|
| {
|
|
@@ -37,19 +49,27 @@ export function unavailableUsageStatusEvent(): UsageStatusEvent {
|
|
|
37
49
|
export function buildUsageStatusEvent(
|
|
38
50
|
report: UsageReport,
|
|
39
51
|
model?: UsageModel,
|
|
52
|
+
displayMode: UsageDisplayMode = DEFAULT_USAGE_DISPLAY_MODE,
|
|
40
53
|
): UsageStatusEvent {
|
|
41
|
-
const buckets =
|
|
42
|
-
report.providerId === "openai-codex"
|
|
43
|
-
? bucketsForCodexModel(report, model)
|
|
44
|
-
: report.buckets;
|
|
54
|
+
const buckets = bucketsForModel(report, model);
|
|
45
55
|
const windows = sortUsageBuckets(buckets).flatMap((bucket) => {
|
|
46
56
|
const remainingPercent = usagePercentRemaining(bucket);
|
|
47
|
-
|
|
57
|
+
const usedPercent = usagePercentUsed(bucket);
|
|
58
|
+
const displayPercent = usagePercent(bucket, displayMode);
|
|
59
|
+
if (
|
|
60
|
+
remainingPercent === undefined ||
|
|
61
|
+
usedPercent === undefined ||
|
|
62
|
+
displayPercent === undefined
|
|
63
|
+
) {
|
|
64
|
+
return [];
|
|
65
|
+
}
|
|
48
66
|
return [
|
|
49
67
|
{
|
|
50
68
|
kind: usageWindowKind(bucket),
|
|
51
69
|
label: compactUsageWindowLabel(bucket),
|
|
52
70
|
remainingPercent,
|
|
71
|
+
usedPercent,
|
|
72
|
+
displayPercent,
|
|
53
73
|
...(bucket.windowMinutes === undefined
|
|
54
74
|
? {}
|
|
55
75
|
: { windowMinutes: bucket.windowMinutes }),
|
|
@@ -62,6 +82,7 @@ export function buildUsageStatusEvent(
|
|
|
62
82
|
status: "ready",
|
|
63
83
|
providerId: report.providerId,
|
|
64
84
|
capturedAt: report.capturedAt,
|
|
85
|
+
displayMode,
|
|
65
86
|
windows,
|
|
66
87
|
};
|
|
67
88
|
}
|
|
@@ -70,13 +91,14 @@ export function buildUsageStatusEvent(
|
|
|
70
91
|
export function formatUsageStatusline(
|
|
71
92
|
report: UsageReport,
|
|
72
93
|
model?: UsageModel,
|
|
94
|
+
displayMode: UsageDisplayMode = DEFAULT_USAGE_DISPLAY_MODE,
|
|
73
95
|
): string | undefined {
|
|
74
|
-
const event = buildUsageStatusEvent(report, model);
|
|
96
|
+
const event = buildUsageStatusEvent(report, model, displayMode);
|
|
75
97
|
if (event.status !== "ready" || event.windows.length === 0) return undefined;
|
|
76
98
|
return event.windows
|
|
77
99
|
.map(
|
|
78
100
|
(window) =>
|
|
79
|
-
`${window.label} ${Math.round(window.
|
|
101
|
+
`${window.label} ${Math.round(window.displayPercent).toString()}%`,
|
|
80
102
|
)
|
|
81
103
|
.join(" · ");
|
|
82
104
|
}
|
|
@@ -142,14 +164,6 @@ export function sortUsageBuckets(
|
|
|
142
164
|
});
|
|
143
165
|
}
|
|
144
166
|
|
|
145
|
-
export function usagePercentRemaining(bucket: UsageBucket): number | undefined {
|
|
146
|
-
if (bucket.unit === "percent" && bucket.remaining !== undefined) {
|
|
147
|
-
return clampPercent(bucket.remaining);
|
|
148
|
-
}
|
|
149
|
-
if (!bucket.limit || bucket.remaining === undefined) return undefined;
|
|
150
|
-
return clampPercent((bucket.remaining / bucket.limit) * 100);
|
|
151
|
-
}
|
|
152
|
-
|
|
153
167
|
function usageWindowRank(bucket: UsageBucket): number {
|
|
154
168
|
const kind = usageWindowKind(bucket);
|
|
155
169
|
if (kind === "hourly" || kind === "rolling") return 0;
|
|
@@ -158,45 +172,50 @@ function usageWindowRank(bucket: UsageBucket): number {
|
|
|
158
172
|
return 3;
|
|
159
173
|
}
|
|
160
174
|
|
|
161
|
-
function
|
|
175
|
+
function bucketsForModel(
|
|
162
176
|
report: UsageReport,
|
|
163
177
|
model?: UsageModel,
|
|
164
178
|
): UsageBucket[] {
|
|
165
|
-
const
|
|
179
|
+
const hasGroups = report.buckets.some((bucket) => bucket.groupId);
|
|
180
|
+
const hasModelGroups = report.buckets.some(
|
|
181
|
+
(bucket) => bucket.modelKeys && bucket.modelKeys.length > 0,
|
|
182
|
+
);
|
|
183
|
+
if (!hasGroups || (!report.defaultGroupId && !hasModelGroups)) {
|
|
184
|
+
return report.buckets;
|
|
185
|
+
}
|
|
186
|
+
const group = selectUsageGroup(report, model);
|
|
166
187
|
return report.buckets.filter(
|
|
167
188
|
(bucket) => (bucket.groupId ?? bucket.id) === group,
|
|
168
189
|
);
|
|
169
190
|
}
|
|
170
191
|
|
|
171
|
-
function
|
|
192
|
+
function selectUsageGroup(
|
|
172
193
|
report: UsageReport,
|
|
173
194
|
model?: UsageModel,
|
|
174
195
|
): string | undefined {
|
|
175
196
|
const groups = [
|
|
176
197
|
...new Set(report.buckets.map((bucket) => bucket.groupId ?? bucket.id)),
|
|
177
198
|
];
|
|
178
|
-
|
|
179
|
-
|
|
199
|
+
const keys = [model?.id, model?.name]
|
|
200
|
+
.map(normalizeKey)
|
|
201
|
+
.filter((value): value is string => Boolean(value));
|
|
202
|
+
const specificGroups = groups
|
|
203
|
+
.filter((group) => group !== report.defaultGroupId)
|
|
204
|
+
.sort((left, right) => right.length - left.length);
|
|
205
|
+
for (const group of specificGroups) {
|
|
206
|
+
const bucket = report.buckets.find(
|
|
207
|
+
(candidate) => (candidate.groupId ?? candidate.id) === group,
|
|
208
|
+
);
|
|
209
|
+
const candidates = [group, bucket?.groupLabel, ...(bucket?.modelKeys ?? [])]
|
|
180
210
|
.map(normalizeKey)
|
|
181
211
|
.filter((value): value is string => Boolean(value));
|
|
182
|
-
|
|
183
|
-
.
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
const bucket = report.buckets.find(
|
|
187
|
-
(candidate) => (candidate.groupId ?? candidate.id) === group,
|
|
188
|
-
);
|
|
189
|
-
const candidates = [group, bucket?.groupLabel, ...(bucket?.modelKeys ?? [])]
|
|
190
|
-
.map(normalizeKey)
|
|
191
|
-
.filter((value): value is string => Boolean(value));
|
|
192
|
-
if (
|
|
193
|
-
candidates.some((candidate) => keys.some((key) => key.includes(candidate)))
|
|
194
|
-
) {
|
|
195
|
-
return group;
|
|
196
|
-
}
|
|
212
|
+
if (
|
|
213
|
+
candidates.some((candidate) => keys.some((key) => key.includes(candidate)))
|
|
214
|
+
) {
|
|
215
|
+
return group;
|
|
197
216
|
}
|
|
198
217
|
}
|
|
199
|
-
return groups.
|
|
218
|
+
return groups.find((group) => group === report.defaultGroupId) ?? groups[0];
|
|
200
219
|
}
|
|
201
220
|
|
|
202
221
|
function normalizeKey(value: string | undefined): string | undefined {
|
|
@@ -207,7 +226,3 @@ function normalizeKey(value: string | undefined): string | undefined {
|
|
|
207
226
|
.replace(/^-+|-+$/gu, "") || undefined
|
|
208
227
|
);
|
|
209
228
|
}
|
|
210
|
-
|
|
211
|
-
function clampPercent(value: number): number {
|
|
212
|
-
return Math.min(100, Math.max(0, value));
|
|
213
|
-
}
|
package/src/types.ts
CHANGED
|
@@ -42,6 +42,7 @@ export interface UsageReport {
|
|
|
42
42
|
source: string;
|
|
43
43
|
semantics: UsageSemantics;
|
|
44
44
|
buckets: UsageBucket[];
|
|
45
|
+
defaultGroupId?: string;
|
|
45
46
|
metrics: UsageMetric[];
|
|
46
47
|
notes?: string[];
|
|
47
48
|
}
|
|
@@ -59,6 +60,7 @@ export interface UsageProviderAdapter {
|
|
|
59
60
|
id: string;
|
|
60
61
|
displayName: string;
|
|
61
62
|
providerIds: readonly string[];
|
|
63
|
+
officialOrigins: readonly string[];
|
|
62
64
|
semantics: UsageSemantics;
|
|
63
65
|
requiresOAuth?: boolean;
|
|
64
66
|
query(
|
package/src/usage.ts
CHANGED
|
@@ -4,6 +4,7 @@ import type {
|
|
|
4
4
|
ExtensionCommandContext,
|
|
5
5
|
ExtensionContext,
|
|
6
6
|
} from "@earendil-works/pi-coding-agent";
|
|
7
|
+
import { loadUsageConfig } from "./config.ts";
|
|
7
8
|
import {
|
|
8
9
|
awaitWithDeadline,
|
|
9
10
|
errorMessage,
|
|
@@ -11,6 +12,10 @@ import {
|
|
|
11
12
|
modelIdentity,
|
|
12
13
|
UsageCache,
|
|
13
14
|
} from "./core.ts";
|
|
15
|
+
import {
|
|
16
|
+
DEFAULT_USAGE_DISPLAY_MODE,
|
|
17
|
+
type UsageDisplayMode,
|
|
18
|
+
} from "./display.ts";
|
|
14
19
|
import {
|
|
15
20
|
CODEX_RESET_CONFIRMATION_OPTIONS,
|
|
16
21
|
codexResetCount,
|
|
@@ -26,6 +31,7 @@ import {
|
|
|
26
31
|
resolveCodexResetAuth,
|
|
27
32
|
} from "./codex-resets.ts";
|
|
28
33
|
import { formatProviderState } from "./format.ts";
|
|
34
|
+
import { CODEX_PROVIDER_ID } from "./providers/codex-constants.ts";
|
|
29
35
|
import {
|
|
30
36
|
buildUsageStatusEvent,
|
|
31
37
|
formatUsageStatusline,
|
|
@@ -65,6 +71,7 @@ export default function subscriptionUsage(pi: ExtensionAPI): void {
|
|
|
65
71
|
const failureBackoff = new Map<string, { until: number; message: string }>();
|
|
66
72
|
const activeControllers = new Set<AbortController>();
|
|
67
73
|
let sessionActive = false;
|
|
74
|
+
let displayMode: UsageDisplayMode = DEFAULT_USAGE_DISPLAY_MODE;
|
|
68
75
|
let statusGeneration = 0;
|
|
69
76
|
let statusController: AbortController | undefined;
|
|
70
77
|
let statusTimer: ReturnType<typeof setTimeout> | undefined;
|
|
@@ -107,6 +114,7 @@ export default function subscriptionUsage(pi: ExtensionAPI): void {
|
|
|
107
114
|
function scheduleStatusRefresh(
|
|
108
115
|
ctx: ExtensionContext,
|
|
109
116
|
model: UsageModel,
|
|
117
|
+
delayMs = CACHE_TTL_MS,
|
|
110
118
|
): void {
|
|
111
119
|
clearStatusTimer();
|
|
112
120
|
const generation = statusGeneration;
|
|
@@ -114,7 +122,7 @@ export default function subscriptionUsage(pi: ExtensionAPI): void {
|
|
|
114
122
|
statusTimer = undefined;
|
|
115
123
|
if (!sessionActive || generation !== statusGeneration) return;
|
|
116
124
|
startStatusRefresh(ctx, model, true);
|
|
117
|
-
},
|
|
125
|
+
}, delayMs);
|
|
118
126
|
}
|
|
119
127
|
|
|
120
128
|
function publishStatus(
|
|
@@ -145,8 +153,10 @@ export default function subscriptionUsage(pi: ExtensionAPI): void {
|
|
|
145
153
|
}
|
|
146
154
|
return;
|
|
147
155
|
}
|
|
148
|
-
emitUsageStatus(
|
|
149
|
-
|
|
156
|
+
emitUsageStatus(
|
|
157
|
+
buildUsageStatusEvent(outcome.state.report, model, displayMode),
|
|
158
|
+
);
|
|
159
|
+
const value = formatUsageStatusline(outcome.state.report, model, displayMode);
|
|
150
160
|
if (!safeSetStatus(ctx, value)) return;
|
|
151
161
|
if (schedule && sessionActive) scheduleStatusRefresh(ctx, model);
|
|
152
162
|
}
|
|
@@ -328,6 +338,11 @@ export default function subscriptionUsage(pi: ExtensionAPI): void {
|
|
|
328
338
|
const controller = new AbortController();
|
|
329
339
|
statusController = controller;
|
|
330
340
|
activeControllers.add(controller);
|
|
341
|
+
const refreshIsCurrent = (): boolean =>
|
|
342
|
+
sessionActive &&
|
|
343
|
+
generation === statusGeneration &&
|
|
344
|
+
!controller.signal.aborted &&
|
|
345
|
+
modelIdentity(ctx.model) === modelIdentity(model);
|
|
331
346
|
try {
|
|
332
347
|
safeSetStatus(ctx, "usage …");
|
|
333
348
|
const outcome = await queryCurrentState(
|
|
@@ -337,14 +352,28 @@ export default function subscriptionUsage(pi: ExtensionAPI): void {
|
|
|
337
352
|
controller.signal,
|
|
338
353
|
);
|
|
339
354
|
if (
|
|
340
|
-
!
|
|
341
|
-
generation !== statusGeneration ||
|
|
342
|
-
controller.signal.aborted ||
|
|
355
|
+
!refreshIsCurrent() ||
|
|
343
356
|
!(await outcomeStillCurrent(ctx, model, outcome, controller.signal))
|
|
344
357
|
) {
|
|
345
358
|
return;
|
|
346
359
|
}
|
|
347
360
|
publishStatus(ctx, outcome, model, true);
|
|
361
|
+
} catch (error) {
|
|
362
|
+
if (isAbortError(error) || !refreshIsCurrent()) return;
|
|
363
|
+
try {
|
|
364
|
+
emitUnavailableUsage();
|
|
365
|
+
} catch {
|
|
366
|
+
// A status consumer must not stop future refreshes.
|
|
367
|
+
}
|
|
368
|
+
if (!refreshIsCurrent()) return;
|
|
369
|
+
try {
|
|
370
|
+
safeSetStatus(ctx, "usage error");
|
|
371
|
+
} catch {
|
|
372
|
+
// Error reporting must not stop future refreshes.
|
|
373
|
+
}
|
|
374
|
+
if (refreshIsCurrent()) {
|
|
375
|
+
scheduleStatusRefresh(ctx, model, FAILURE_BACKOFF_MS);
|
|
376
|
+
}
|
|
348
377
|
} finally {
|
|
349
378
|
activeControllers.delete(controller);
|
|
350
379
|
if (statusController === controller) statusController = undefined;
|
|
@@ -356,10 +385,8 @@ export default function subscriptionUsage(pi: ExtensionAPI): void {
|
|
|
356
385
|
model: UsageModel | undefined,
|
|
357
386
|
force: boolean,
|
|
358
387
|
): void {
|
|
359
|
-
void refreshCurrentStatus(ctx, model, force).catch((
|
|
360
|
-
|
|
361
|
-
emitUnavailableUsage();
|
|
362
|
-
safeSetStatus(ctx, "usage error");
|
|
388
|
+
void refreshCurrentStatus(ctx, model, force).catch(() => {
|
|
389
|
+
// Unsupported-model cleanup is best effort during UI teardown.
|
|
363
390
|
});
|
|
364
391
|
}
|
|
365
392
|
|
|
@@ -369,7 +396,7 @@ export default function subscriptionUsage(pi: ExtensionAPI): void {
|
|
|
369
396
|
controller: AbortController,
|
|
370
397
|
): Promise<StableCurrent | undefined> {
|
|
371
398
|
if (
|
|
372
|
-
ctx.model?.provider !==
|
|
399
|
+
ctx.model?.provider !== CODEX_PROVIDER_ID ||
|
|
373
400
|
current.outcome.state.status !== "ready"
|
|
374
401
|
) {
|
|
375
402
|
ctx.ui.notify(
|
|
@@ -441,7 +468,7 @@ export default function subscriptionUsage(pi: ExtensionAPI): void {
|
|
|
441
468
|
controller.signal,
|
|
442
469
|
QUERY_TIMEOUT_MS,
|
|
443
470
|
);
|
|
444
|
-
cache.clearProvider(
|
|
471
|
+
cache.clearProvider(CODEX_PROVIDER_ID);
|
|
445
472
|
failureBackoff.clear();
|
|
446
473
|
const refreshed = await queryStableCurrent(ctx, true, controller.signal);
|
|
447
474
|
if (refreshed?.model) {
|
|
@@ -482,12 +509,15 @@ export default function subscriptionUsage(pi: ExtensionAPI): void {
|
|
|
482
509
|
);
|
|
483
510
|
return;
|
|
484
511
|
}
|
|
485
|
-
ctx.ui.notify(
|
|
512
|
+
ctx.ui.notify(
|
|
513
|
+
formatProviderState(current.outcome.state, displayMode),
|
|
514
|
+
"info",
|
|
515
|
+
);
|
|
486
516
|
if (current.model) {
|
|
487
517
|
publishStatus(ctx, current.outcome, current.model, sessionActive);
|
|
488
518
|
}
|
|
489
519
|
if (
|
|
490
|
-
ctx.model?.provider !==
|
|
520
|
+
ctx.model?.provider !== CODEX_PROVIDER_ID ||
|
|
491
521
|
current.outcome.state.status !== "ready"
|
|
492
522
|
) {
|
|
493
523
|
return;
|
|
@@ -501,7 +531,10 @@ export default function subscriptionUsage(pi: ExtensionAPI): void {
|
|
|
501
531
|
if (!action) return;
|
|
502
532
|
const refreshed = await redeemCodexReset(ctx, current, controller);
|
|
503
533
|
if (refreshed?.outcome.state.status === "ready") {
|
|
504
|
-
ctx.ui.notify(
|
|
534
|
+
ctx.ui.notify(
|
|
535
|
+
formatProviderState(refreshed.outcome.state, displayMode),
|
|
536
|
+
"info",
|
|
537
|
+
);
|
|
505
538
|
}
|
|
506
539
|
} finally {
|
|
507
540
|
controller.abort();
|
|
@@ -527,6 +560,11 @@ export default function subscriptionUsage(pi: ExtensionAPI): void {
|
|
|
527
560
|
|
|
528
561
|
pi.on("session_start", (_event, ctx) => {
|
|
529
562
|
sessionActive = ctx.hasUI;
|
|
563
|
+
const config = loadUsageConfig(ctx.cwd, ctx.isProjectTrusted());
|
|
564
|
+
displayMode = config.displayMode;
|
|
565
|
+
for (const warning of config.warnings) {
|
|
566
|
+
ctx.ui.notify(`Usage config ignored: ${warning}`, "warning");
|
|
567
|
+
}
|
|
530
568
|
if (ctx.hasUI) startStatusRefresh(ctx, ctx.model, false);
|
|
531
569
|
});
|
|
532
570
|
pi.on("session_tree", (_event, ctx) => {
|