@0xkahi/pi-qol 1.1.2 → 1.2.0
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 +12 -3
- package/assets/config.schema.json +2 -18
- package/package.json +4 -4
- package/src/extensions/custom-footer/codemap.md +5 -6
- package/src/extensions/custom-footer/constants.ts +0 -1
- package/src/extensions/custom-footer/footer-component.ts +19 -9
- package/src/extensions/custom-footer/index.ts +3 -1
- package/src/extensions/custom-footer/token-stats.ts +25 -17
- package/src/extensions/custom-footer/types.ts +3 -1
- package/src/extensions/model-select/codemap.md +8 -4
- package/src/extensions/model-select/index.ts +35 -29
- package/src/extensions/model-select/model-select-dialog.ts +9 -25
- package/src/extensions/model-select/model-select-modal.ts +66 -0
- package/src/extensions/model-select/usage-section/codemap.md +14 -0
- package/src/extensions/model-select/usage-section/index.ts +37 -0
- package/src/extensions/model-select/usage-section/usage-provider-tab.ts +166 -0
- package/src/index.ts +7 -3
- package/src/libs/modal/README.md +46 -2
- package/src/libs/modal/codemap.md +4 -1
- package/src/libs/modal/index.ts +2 -0
- package/src/libs/modal/label-window.ts +32 -0
- package/src/libs/modal/modal-dialog.ts +16 -2
- package/src/libs/modal/section-strip.ts +33 -0
- package/src/libs/modal/sectioned-modal.ts +105 -0
- package/src/libs/modal/tab-strip.ts +2 -26
- package/src/libs/subscription-usage/codemap.md +10 -21
- package/src/libs/subscription-usage/credential-resolver.ts +44 -0
- package/src/libs/subscription-usage/index.ts +8 -0
- package/src/libs/subscription-usage/pace.ts +28 -0
- package/src/libs/subscription-usage/progress-bar.ts +13 -0
- package/src/libs/subscription-usage/provider-color.ts +10 -0
- package/src/libs/subscription-usage/strategy/anthropic-oauth-usage.strategy.ts +5 -5
- package/src/libs/subscription-usage/strategy/codemap.md +5 -41
- package/src/libs/subscription-usage/strategy/openai-codex-usage.strategy.ts +7 -8
- package/src/libs/subscription-usage/subscription-usage-api.util.ts +45 -66
- package/src/libs/subscription-usage/subscription-usage-cache.ts +89 -0
- package/src/schemas/codemap.md +1 -1
- package/src/schemas/custom-footer-config.schema.ts +0 -4
- package/src/extensions/custom-footer/progress-bar.ts +0 -16
- package/src/extensions/custom-footer/subscription-usage-manager.ts +0 -91
|
@@ -2,27 +2,16 @@
|
|
|
2
2
|
|
|
3
3
|
## Responsibility
|
|
4
4
|
|
|
5
|
-
|
|
5
|
+
Shared subscription data pipeline for Claude and Codex, exported through `index.ts`.
|
|
6
6
|
|
|
7
|
-
|
|
7
|
+
- `subscription-usage-api.util.ts`: provider/auth/window types, supported-provider labels derived from strategies, shared fetch timeout and TTL constants, status-discriminated `UsageResult`, injectable API. Classifies no-auth, expired, HTTP errors, network/timeout, unavailable and ok; owns fetch timeout and error catching. Malformed JSON is unavailable; fetch and abort failures remain network.
|
|
8
|
+
- `credential-resolver.ts`: verifies stored OAuth auth through PathUtil and RawDataParser, asks the latest host context for refreshed tokens, falls back to stored access. Codex account id comes from stored accountId or defensive JWT decoding.
|
|
9
|
+
- `subscription-usage-cache.ts`: shared injected cache with TTL, per-provider in-flight deduplication, forced refresh, retained last-success windows/timestamp, and completion subscribers. Includes provider aliases and soonest-reset window selection.
|
|
10
|
+
- `pace.ts`: pure elapsed-window pace and relative reset formatting.
|
|
11
|
+
- `progress-bar.ts`: pure percentage clamp and glyph-configurable bar (defaults █/░).
|
|
12
|
+
- `provider-color.ts`: fixed shared provider colors (Claude #D97706, Codex #10B981), exported as PROVIDER_USAGE_COLORS and providerUsageColor; no configuration dependency.
|
|
13
|
+
- `strategy/`: pure request construction and JSON normalization; no network I/O.
|
|
8
14
|
|
|
9
|
-
|
|
10
|
-
- **Adapter / Normalization**: each strategy adapts a provider response to the shared `RateWindow[]` model (`label`, `usedPercent`, `resetAt`).
|
|
11
|
-
- **Safe parsing**: `RawDataParser` guards against unexpected JSON shapes and missing fields.
|
|
12
|
-
- **Utility API class**: `SubscriptionUsageApi` wraps auth loading, fetching, and formatting in one injectable-style class.
|
|
15
|
+
## Flow
|
|
13
16
|
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
1. A caller invokes `SubscriptionUsageApi.fetchUsage(strategy)`.
|
|
17
|
-
2. The API loads provider OAuth credentials from the local auth config via `PathUtil.findPiAuthConfig()`.
|
|
18
|
-
3. It calls `strategy.fetchUsage(auth)`.
|
|
19
|
-
4. The strategy performs a provider HTTP request, parses JSON, and maps relevant fields to `RateWindow[]`.
|
|
20
|
-
5. The API wraps the result in `FetchUsageResponse` (`label`, `rateWindow`).
|
|
21
|
-
6. `formatResetDescription(resetAt)` converts reset timestamps to human-readable relative strings (`5m`, `2h30m`, `1d`, etc.).
|
|
22
|
-
|
|
23
|
-
## Integration Points
|
|
24
|
-
|
|
25
|
-
- **Local auth config**: `PathUtil.findPiAuthConfig()` supplies `SubscriptionAuthconfig`, which maps providers to `{ access, accountId }` objects.
|
|
26
|
-
- **Anthropic API**: `AnthropicOauthUsageStrategy` calls `https://api.anthropic.com/api/oauth/usage` with `Authorization: Bearer <token>` and `anthropic-beta: oauth-2025-04-20`.
|
|
27
|
-
- **OpenAI Codex API**: `OpenAiCodexUsageStrategy` calls `https://chatgpt.com/backend-api/wham/usage` with bearer token and optional `ChatGPT-Account-Id` header.
|
|
28
|
-
- **Shared utilities**: depends on `src/utils/path.util` for config discovery and `src/utils/raw-data-parser.util` for defensive JSON parsing.
|
|
17
|
+
Consumers ensure freshness or force refresh → cache picks strategy → API resolves credentials and fetches → strategy parses windows with durations → cache stores status and last success, then notifies subscribers. Footer shows ok windows or last-success windows for network/http-error/unavailable; no-auth/expired hide usage. Other consumers can retain earlier windows alongside failure status.
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { readFileSync } from 'node:fs';
|
|
2
|
+
import type { ExtensionContext } from '@earendil-works/pi-coding-agent';
|
|
3
|
+
import { PathUtil } from '../../utils/path.util';
|
|
4
|
+
import { RawDataParser } from '../../utils/raw-data-parser.util';
|
|
5
|
+
import type { CredentialResolver } from './subscription-usage-api.util';
|
|
6
|
+
|
|
7
|
+
function jwtAccountId(token: string): string | undefined {
|
|
8
|
+
try {
|
|
9
|
+
const payload = token.split('.')[1];
|
|
10
|
+
if (!payload) return undefined;
|
|
11
|
+
const claims = RawDataParser.asRecord(JSON.parse(Buffer.from(payload, 'base64url').toString('utf8')));
|
|
12
|
+
const auth = RawDataParser.asRecord(claims?.['https://api.openai.com/auth']);
|
|
13
|
+
return RawDataParser.stringValue(auth?.chatgpt_account_id);
|
|
14
|
+
} catch {
|
|
15
|
+
return undefined;
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export function createHostCredentialResolver(getCtx: () => ExtensionContext | undefined): CredentialResolver {
|
|
20
|
+
return async provider => {
|
|
21
|
+
try {
|
|
22
|
+
const path = PathUtil.findPiAuthConfig();
|
|
23
|
+
if (!path.exists) return undefined;
|
|
24
|
+
const config = RawDataParser.asRecord(JSON.parse(readFileSync(path.path, 'utf8')));
|
|
25
|
+
const stored = RawDataParser.asRecord(config?.[provider]);
|
|
26
|
+
if (!stored || (stored.type !== undefined && stored.type !== 'oauth')) return undefined;
|
|
27
|
+
let token: string | undefined;
|
|
28
|
+
try {
|
|
29
|
+
const resolved = await getCtx()?.modelRegistry.getProviderAuth(provider);
|
|
30
|
+
token = RawDataParser.stringValue(resolved?.auth?.apiKey);
|
|
31
|
+
} catch {
|
|
32
|
+
// Stored access is the verified fallback when host refresh fails.
|
|
33
|
+
}
|
|
34
|
+
token ||= RawDataParser.stringValue(stored.access);
|
|
35
|
+
if (!token) return undefined;
|
|
36
|
+
return {
|
|
37
|
+
token,
|
|
38
|
+
accountId: provider === 'openai-codex' ? RawDataParser.stringValue(stored.accountId) || jwtAccountId(token) : undefined,
|
|
39
|
+
};
|
|
40
|
+
} catch {
|
|
41
|
+
return undefined;
|
|
42
|
+
}
|
|
43
|
+
};
|
|
44
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export * from './credential-resolver';
|
|
2
|
+
export * from './pace';
|
|
3
|
+
export * from './progress-bar';
|
|
4
|
+
export * from './provider-color';
|
|
5
|
+
export * from './strategy/anthropic-oauth-usage.strategy';
|
|
6
|
+
export * from './strategy/openai-codex-usage.strategy';
|
|
7
|
+
export * from './subscription-usage-api.util';
|
|
8
|
+
export * from './subscription-usage-cache';
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { clampPercent } from './progress-bar';
|
|
2
|
+
import type { RateWindow } from './subscription-usage-api.util';
|
|
3
|
+
|
|
4
|
+
export function computePace(window: RateWindow, now = Date.now()): { elapsedPercent: number; pace: 'limit' | 'ahead' | 'on-pace' } | undefined {
|
|
5
|
+
if (
|
|
6
|
+
!window.resetAt ||
|
|
7
|
+
!window.windowSeconds ||
|
|
8
|
+
window.windowSeconds <= 0 ||
|
|
9
|
+
!Number.isFinite(window.windowSeconds) ||
|
|
10
|
+
!Number.isFinite(window.resetAt.getTime())
|
|
11
|
+
)
|
|
12
|
+
return undefined;
|
|
13
|
+
const elapsedPercent = clampPercent(100 * (1 - (window.resetAt.getTime() - now) / (window.windowSeconds * 1000)));
|
|
14
|
+
return { elapsedPercent, pace: window.usedPercent >= 100 ? 'limit' : window.usedPercent > elapsedPercent ? 'ahead' : 'on-pace' };
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export function formatResetDescription(date: Date, now = Date.now()): string {
|
|
18
|
+
const diffMs = date.getTime() - now;
|
|
19
|
+
if (diffMs <= 0) return 'now';
|
|
20
|
+
const minutes = Math.floor(diffMs / 60000);
|
|
21
|
+
if (minutes < 60) return `${minutes}m`;
|
|
22
|
+
const hours = Math.floor(minutes / 60);
|
|
23
|
+
const remainingMinutes = minutes % 60;
|
|
24
|
+
if (hours < 24) return remainingMinutes > 0 ? `${hours}h${remainingMinutes}m` : `${hours}h`;
|
|
25
|
+
const days = Math.floor(hours / 24);
|
|
26
|
+
const remainingHours = hours % 24;
|
|
27
|
+
return remainingHours > 0 ? `${days}d${remainingHours}h` : `${days}d`;
|
|
28
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
export function clampPercent(n: number): number {
|
|
2
|
+
return Number.isFinite(n) ? Math.max(0, Math.min(100, n)) : 0;
|
|
3
|
+
}
|
|
4
|
+
|
|
5
|
+
export function renderProgressBar(
|
|
6
|
+
usedPercent: number,
|
|
7
|
+
width = 10,
|
|
8
|
+
glyphs: { filled: string; empty: string } = { filled: '█', empty: '░' },
|
|
9
|
+
): { filled: string; empty: string } {
|
|
10
|
+
const barWidth = Number.isFinite(width) ? Math.max(0, Math.floor(width)) : 0;
|
|
11
|
+
const filledCount = Math.round((clampPercent(usedPercent) / 100) * barWidth);
|
|
12
|
+
return { filled: glyphs.filled.repeat(filledCount), empty: glyphs.empty.repeat(barWidth - filledCount) };
|
|
13
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { SubscriptionProvider } from './subscription-usage-api.util';
|
|
2
|
+
|
|
3
|
+
export const PROVIDER_USAGE_COLORS: Readonly<Record<SubscriptionProvider, string>> = {
|
|
4
|
+
anthropic: '#D97706',
|
|
5
|
+
'openai-codex': '#10B981',
|
|
6
|
+
};
|
|
7
|
+
|
|
8
|
+
export function providerUsageColor(provider: SubscriptionProvider): string {
|
|
9
|
+
return PROVIDER_USAGE_COLORS[provider];
|
|
10
|
+
}
|
|
@@ -5,10 +5,9 @@ export class AnthropicOauthUsageStrategy implements SubscriptionUsageStrategy {
|
|
|
5
5
|
readonly provider = 'anthropic';
|
|
6
6
|
readonly label = 'Claude';
|
|
7
7
|
|
|
8
|
-
|
|
9
|
-
const
|
|
10
|
-
|
|
11
|
-
if (!data) return;
|
|
8
|
+
parse(json: unknown): RateWindow[] {
|
|
9
|
+
const data = RawDataParser.asRecord(json);
|
|
10
|
+
if (!data) return [];
|
|
12
11
|
|
|
13
12
|
const windows: RateWindow[] = [];
|
|
14
13
|
for (const [key, label] of [
|
|
@@ -23,13 +22,14 @@ export class AnthropicOauthUsageStrategy implements SubscriptionUsageStrategy {
|
|
|
23
22
|
windows.push({
|
|
24
23
|
label,
|
|
25
24
|
usedPercent,
|
|
25
|
+
windowSeconds: key === 'five_hour' ? 18000 : 604800,
|
|
26
26
|
resetAt: resetDate && Number.isFinite(resetDate.getTime()) ? resetDate : undefined,
|
|
27
27
|
});
|
|
28
28
|
}
|
|
29
29
|
return windows;
|
|
30
30
|
}
|
|
31
31
|
|
|
32
|
-
|
|
32
|
+
request(opts: ProviderAuth): Request {
|
|
33
33
|
return new Request('https://api.anthropic.com/api/oauth/usage', {
|
|
34
34
|
method: 'GET',
|
|
35
35
|
headers: {
|
|
@@ -1,44 +1,8 @@
|
|
|
1
|
-
# subscription-usage
|
|
1
|
+
# subscription-usage strategies
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Pure `SubscriptionUsageStrategy` implementations expose `provider`, `label`, `request(auth): Request`, and `parse(json: unknown): RateWindow[]`. Network I/O, timeout and status classification belong to SubscriptionUsageApi, not strategies. Unknown shapes return an empty array.
|
|
4
4
|
|
|
5
|
-
|
|
6
|
-
|
|
5
|
+
- `anthropic-oauth-usage.strategy.ts`: bearer-authenticated Anthropic OAuth usage request with beta header. Parses five_hour (5h, 18000 seconds) and seven_day (Week, 604800 seconds), utilization and optional valid reset dates.
|
|
6
|
+
- `openai-codex-usage.strategy.ts`: bearer-authenticated wham usage request with optional ChatGPT-Account-Id. Keeps primary, secondary and named additional limits. Uses reported limit_window_seconds, falling back to 10800 / 86400 seconds; normalizes used percentage and reset epoch seconds.
|
|
7
7
|
|
|
8
|
-
|
|
9
|
-
- Fetching usage data from that provider's API.
|
|
10
|
-
- Parsing the raw JSON response into a normalized `RateWindow[]`.
|
|
11
|
-
- Returning `undefined` when no usable usage data is available.
|
|
12
|
-
|
|
13
|
-
Current strategies:
|
|
14
|
-
|
|
15
|
-
- `AnthropicOauthUsageStrategy` — fetches Anthropic OAuth usage and exposes the `five_hour` and `seven_day` windows.
|
|
16
|
-
- `OpenAiCodexUsageStrategy` — fetches OpenAI Codex usage and exposes the main `rate_limit` windows plus any `additional_rate_limits`.
|
|
17
|
-
|
|
18
|
-
## Design Patterns
|
|
19
|
-
|
|
20
|
-
- **Strategy pattern** — both classes implement the common `SubscriptionUsageStrategy` interface, so the caller (`SubscriptionUsageApi`) can treat them uniformly.
|
|
21
|
-
- **Encapsulation of provider details** — request construction, response parsing, and window labeling are kept private to each strategy.
|
|
22
|
-
- **Defensive parsing** — unknown API responses are coerced safely through `RawDataParser` before being used.
|
|
23
|
-
- **Helper decomposition** — the OpenAI strategy splits parsing into small private helpers (`pushRateLimitWindows`, `pushRateWindow`, `getResetDate`, `getWindowLabel`) to keep the main flow readable.
|
|
24
|
-
|
|
25
|
-
## Data & Control Flow
|
|
26
|
-
|
|
27
|
-
1. `SubscriptionUsageApi.fetchUsage(strategy)` loads provider credentials and calls `strategy.fetchUsage(auth)`.
|
|
28
|
-
2. Each strategy builds a provider-specific `Request` and calls `fetch`.
|
|
29
|
-
3. The JSON response is converted to a `Record<string, unknown>` via `RawDataParser.asRecord`.
|
|
30
|
-
4. Relevant fields are extracted:
|
|
31
|
-
- **Anthropic**: iterates over `five_hour` and `seven_day`, reads `utilization` as `usedPercent`, and parses `resets_at` into a `Date`.
|
|
32
|
-
- **OpenAI**: reads `rate_limit.primary_window` and `rate_limit.secondary_window`, then loops over `additional_rate_limits`.
|
|
33
|
-
5. Each discovered window is pushed as a `RateWindow` object with `label`, `usedPercent`, and optional `resetAt`.
|
|
34
|
-
6. The array is returned to `SubscriptionUsageApi`, which wraps it in a `FetchUsageResponse` keyed by the strategy's `label`.
|
|
35
|
-
|
|
36
|
-
## Integration Points
|
|
37
|
-
|
|
38
|
-
- **Interface contract**: strategies implement `SubscriptionUsageStrategy` and use the `ProviderAuth`, `RateWindow`, and `SubscriptionProvider` types from `../subscription-usage-api.util`.
|
|
39
|
-
- **Shared utility**: all parsing helpers come from `../../../utils/raw-data-parser.util` (`RawDataParser`).
|
|
40
|
-
- **Network layer**: strategies use the global `fetch` API directly.
|
|
41
|
-
- **Provider endpoints**:
|
|
42
|
-
- Anthropic: `https://api.anthropic.com/api/oauth/usage` — authenticated with a `Bearer` token and the `anthropic-beta: oauth-2025-04-20` header.
|
|
43
|
-
- OpenAI Codex: `https://chatgpt.com/backend-api/wham/usage` — authenticated with a `Bearer` token and an optional `ChatGPT-Account-Id` header.
|
|
44
|
-
- **Consumer**: `SubscriptionUsageApi` orchestrates strategies, loads auth config via `PathUtil.findPiAuthConfig`, and formats results for downstream display.
|
|
8
|
+
Both use RawDataParser for defensive parsing and the shared auth/window contracts. Their requests have no timeout side effects; the API adds its abort signal.
|
|
@@ -8,12 +8,9 @@ export class OpenAiCodexUsageStrategy implements SubscriptionUsageStrategy {
|
|
|
8
8
|
readonly provider = 'openai-codex';
|
|
9
9
|
readonly label = 'Codex';
|
|
10
10
|
|
|
11
|
-
|
|
12
|
-
const
|
|
13
|
-
if (!
|
|
14
|
-
|
|
15
|
-
const data = RawDataParser.asRecord(await response.json());
|
|
16
|
-
if (!data) return;
|
|
11
|
+
parse(json: unknown): RateWindow[] {
|
|
12
|
+
const data = RawDataParser.asRecord(json);
|
|
13
|
+
if (!data) return [];
|
|
17
14
|
|
|
18
15
|
const windows: RateWindow[] = [];
|
|
19
16
|
this.pushRateLimitWindows(windows, RawDataParser.asRecord(data.rate_limit));
|
|
@@ -27,7 +24,7 @@ export class OpenAiCodexUsageStrategy implements SubscriptionUsageStrategy {
|
|
|
27
24
|
this.pushRateLimitWindows(windows, RawDataParser.asRecord(entry.rate_limit), prefix);
|
|
28
25
|
}
|
|
29
26
|
|
|
30
|
-
return windows
|
|
27
|
+
return windows;
|
|
31
28
|
}
|
|
32
29
|
|
|
33
30
|
private pushRateLimitWindows(windows: RateWindow[], rateLimit: Record<string, unknown> | undefined, prefix?: string): void {
|
|
@@ -39,10 +36,12 @@ export class OpenAiCodexUsageStrategy implements SubscriptionUsageStrategy {
|
|
|
39
36
|
if (!window) return;
|
|
40
37
|
|
|
41
38
|
const resetDate = this.getResetDate(window);
|
|
39
|
+
const seconds = RawDataParser.numberValue(window.limit_window_seconds);
|
|
42
40
|
windows.push({
|
|
43
41
|
label: this.getWindowLabel(RawDataParser.numberValue(window.limit_window_seconds), fallbackWindowSeconds, prefix),
|
|
44
42
|
usedPercent: RawDataParser.numberValue(window.used_percent) ?? 0,
|
|
45
43
|
resetAt: resetDate,
|
|
44
|
+
windowSeconds: seconds && seconds > 0 ? seconds : fallbackWindowSeconds,
|
|
46
45
|
});
|
|
47
46
|
}
|
|
48
47
|
|
|
@@ -62,7 +61,7 @@ export class OpenAiCodexUsageStrategy implements SubscriptionUsageStrategy {
|
|
|
62
61
|
return prefix ? `${prefix} ${label}` : label;
|
|
63
62
|
}
|
|
64
63
|
|
|
65
|
-
|
|
64
|
+
request(opts: ProviderAuth): Request {
|
|
66
65
|
return new Request('https://chatgpt.com/backend-api/wham/usage', {
|
|
67
66
|
method: 'GET',
|
|
68
67
|
headers: {
|
|
@@ -1,78 +1,57 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import { RawDataParser } from '../../utils/raw-data-parser.util';
|
|
1
|
+
import { AnthropicOauthUsageStrategy } from './strategy/anthropic-oauth-usage.strategy';
|
|
2
|
+
import { OpenAiCodexUsageStrategy } from './strategy/openai-codex-usage.strategy';
|
|
4
3
|
|
|
5
|
-
export
|
|
6
|
-
|
|
7
|
-
accountId?: string;
|
|
8
|
-
};
|
|
4
|
+
export const SUBSCRIPTION_USAGE_FETCH_TIMEOUT_MS = 10_000;
|
|
5
|
+
export const SUBSCRIPTION_USAGE_TTL_MS = 60_000;
|
|
9
6
|
|
|
10
7
|
export type SubscriptionProvider = 'anthropic' | 'openai-codex';
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
};
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
label: string
|
|
21
|
-
|
|
22
|
-
};
|
|
8
|
+
export const SUBSCRIPTION_PROVIDERS: readonly { provider: SubscriptionProvider; label: string }[] = [
|
|
9
|
+
{ provider: 'anthropic', label: new AnthropicOauthUsageStrategy().label },
|
|
10
|
+
{ provider: 'openai-codex', label: new OpenAiCodexUsageStrategy().label },
|
|
11
|
+
];
|
|
12
|
+
export type ProviderAuth = { token: string; accountId?: string };
|
|
13
|
+
export type CredentialResolver = (provider: SubscriptionProvider) => Promise<ProviderAuth | undefined>;
|
|
14
|
+
export type RateWindow = { label: string; usedPercent: number; resetAt?: Date; windowSeconds?: number };
|
|
15
|
+
export type UsageResult =
|
|
16
|
+
| { status: 'ok'; label: string; windows: RateWindow[] }
|
|
17
|
+
| { status: 'no-auth' | 'expired' | 'network' | 'unavailable'; label: string }
|
|
18
|
+
| { status: 'http-error'; label: string; httpStatus: number };
|
|
23
19
|
|
|
24
20
|
export interface SubscriptionUsageStrategy {
|
|
25
21
|
readonly provider: SubscriptionProvider;
|
|
26
22
|
readonly label: string;
|
|
27
|
-
|
|
23
|
+
request(auth: ProviderAuth): Request;
|
|
24
|
+
parse(json: unknown): RateWindow[];
|
|
28
25
|
}
|
|
29
26
|
|
|
30
|
-
export
|
|
31
|
-
async fetchUsage(strategy: SubscriptionUsageStrategy): Promise<FetchUsageResponse | undefined> {
|
|
32
|
-
const auth = this.getOauthProviderAuth(strategy.provider);
|
|
33
|
-
if (!auth) return;
|
|
34
|
-
const rateWindow = await strategy.fetchUsage(auth);
|
|
35
|
-
if (!rateWindow) return;
|
|
36
|
-
return {
|
|
37
|
-
label: strategy.label,
|
|
38
|
-
rateWindow,
|
|
39
|
-
};
|
|
40
|
-
}
|
|
41
|
-
|
|
42
|
-
formatResetDescription(date: Date): string {
|
|
43
|
-
const diffMs = date.getTime() - Date.now();
|
|
44
|
-
if (diffMs <= 0) return 'now';
|
|
45
|
-
|
|
46
|
-
const minutes = Math.floor(diffMs / 60000);
|
|
47
|
-
if (minutes < 60) return `${minutes}m`;
|
|
27
|
+
export type SubscriptionUsageApiLike = Pick<SubscriptionUsageApi, 'fetchUsage'>;
|
|
48
28
|
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
return RawDataParser.asRecord(JSON.parse(readFileSync(authJson.path, 'utf-8'))) as SubscriptionAuthconfig | undefined;
|
|
29
|
+
export class SubscriptionUsageApi {
|
|
30
|
+
constructor(
|
|
31
|
+
private readonly resolveCredentials: CredentialResolver,
|
|
32
|
+
private readonly fetchFn: (request: Request) => Promise<Response> = fetch,
|
|
33
|
+
) {}
|
|
34
|
+
|
|
35
|
+
async fetchUsage(strategy: SubscriptionUsageStrategy): Promise<UsageResult> {
|
|
36
|
+
const label = strategy.label;
|
|
37
|
+
try {
|
|
38
|
+
const auth = await this.resolveCredentials(strategy.provider);
|
|
39
|
+
if (!auth) return { status: 'no-auth', label };
|
|
40
|
+
const request = new Request(strategy.request(auth), { signal: AbortSignal.timeout(SUBSCRIPTION_USAGE_FETCH_TIMEOUT_MS) });
|
|
41
|
+
const response = await this.fetchFn(request);
|
|
42
|
+
if (response.status === 401 || response.status === 403) return { status: 'expired', label };
|
|
43
|
+
if (!response.ok) return { status: 'http-error', label, httpStatus: response.status };
|
|
44
|
+
let json: unknown;
|
|
45
|
+
try {
|
|
46
|
+
json = await response.json();
|
|
47
|
+
} catch (error) {
|
|
48
|
+
if (request.signal.aborted || (error instanceof DOMException && error.name === 'AbortError')) throw error;
|
|
49
|
+
return { status: 'unavailable', label };
|
|
50
|
+
}
|
|
51
|
+
const windows = strategy.parse(json);
|
|
52
|
+
return windows.length ? { status: 'ok', label, windows } : { status: 'unavailable', label };
|
|
53
|
+
} catch {
|
|
54
|
+
return { status: 'network', label };
|
|
55
|
+
}
|
|
77
56
|
}
|
|
78
57
|
}
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
import { formatResetDescription } from './pace';
|
|
2
|
+
import { AnthropicOauthUsageStrategy } from './strategy/anthropic-oauth-usage.strategy';
|
|
3
|
+
import { OpenAiCodexUsageStrategy } from './strategy/openai-codex-usage.strategy';
|
|
4
|
+
import {
|
|
5
|
+
type RateWindow,
|
|
6
|
+
SUBSCRIPTION_USAGE_TTL_MS,
|
|
7
|
+
type SubscriptionProvider,
|
|
8
|
+
SubscriptionUsageApi,
|
|
9
|
+
type SubscriptionUsageApiLike,
|
|
10
|
+
type UsageResult,
|
|
11
|
+
} from './subscription-usage-api.util';
|
|
12
|
+
|
|
13
|
+
export type UsageCacheEntry = { result?: UsageResult; lastSuccess?: { windows: RateWindow[]; fetchedAt: number }; inFlight: boolean };
|
|
14
|
+
|
|
15
|
+
export function resolveSupportedProvider(provider?: string): SubscriptionProvider | undefined {
|
|
16
|
+
switch (provider?.toLowerCase()) {
|
|
17
|
+
case 'anthropic':
|
|
18
|
+
return 'anthropic';
|
|
19
|
+
case 'openai-codex':
|
|
20
|
+
case 'codex':
|
|
21
|
+
case 'openai':
|
|
22
|
+
case 'chatgpt':
|
|
23
|
+
return 'openai-codex';
|
|
24
|
+
default:
|
|
25
|
+
return undefined;
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export function pickSubscriptionUsageWindow(windows: readonly RateWindow[]): RateWindow | undefined {
|
|
30
|
+
let earliest: RateWindow | undefined;
|
|
31
|
+
for (const window of windows) {
|
|
32
|
+
if (!window.resetAt || !Number.isFinite(window.resetAt.getTime())) continue;
|
|
33
|
+
if (!earliest?.resetAt || window.resetAt.getTime() <= earliest.resetAt.getTime()) earliest = window;
|
|
34
|
+
}
|
|
35
|
+
return earliest ?? windows[0];
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export class SubscriptionUsageCache {
|
|
39
|
+
private readonly entries = new Map<SubscriptionProvider, UsageCacheEntry>();
|
|
40
|
+
private readonly lastAttemptAt = new Map<SubscriptionProvider, number>();
|
|
41
|
+
private readonly listeners = new Set<() => void>();
|
|
42
|
+
private readonly api: SubscriptionUsageApiLike;
|
|
43
|
+
private readonly ttlMs: number;
|
|
44
|
+
private readonly now: () => number;
|
|
45
|
+
|
|
46
|
+
constructor(opts: { api?: SubscriptionUsageApiLike; ttlMs?: number; now?: () => number } = {}) {
|
|
47
|
+
this.api = opts.api ?? new SubscriptionUsageApi(async () => undefined);
|
|
48
|
+
this.ttlMs = opts.ttlMs ?? SUBSCRIPTION_USAGE_TTL_MS;
|
|
49
|
+
this.now = opts.now ?? Date.now;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
get(provider: SubscriptionProvider): UsageCacheEntry | undefined {
|
|
53
|
+
return this.entries.get(provider);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
ensureFresh(provider: SubscriptionProvider): UsageCacheEntry | undefined {
|
|
57
|
+
const last = this.lastAttemptAt.get(provider);
|
|
58
|
+
if (last === undefined || this.now() - last > this.ttlMs) this.refresh(provider);
|
|
59
|
+
return this.get(provider);
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
refresh(provider: SubscriptionProvider): void {
|
|
63
|
+
if (this.get(provider)?.inFlight) return;
|
|
64
|
+
const entry: UsageCacheEntry = { ...this.get(provider), inFlight: true };
|
|
65
|
+
this.entries.set(provider, entry);
|
|
66
|
+
this.lastAttemptAt.set(provider, this.now());
|
|
67
|
+
const strategy = provider === 'anthropic' ? new AnthropicOauthUsageStrategy() : new OpenAiCodexUsageStrategy();
|
|
68
|
+
void Promise.resolve()
|
|
69
|
+
.then(() => this.api.fetchUsage(strategy))
|
|
70
|
+
.catch((): UsageResult => ({ status: 'network', label: strategy.label }))
|
|
71
|
+
.then(result => {
|
|
72
|
+
entry.result = result;
|
|
73
|
+
if (result.status === 'ok') entry.lastSuccess = { windows: result.windows, fetchedAt: this.now() };
|
|
74
|
+
entry.inFlight = false;
|
|
75
|
+
for (const listener of this.listeners) listener();
|
|
76
|
+
});
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
subscribe(listener: () => void): () => void {
|
|
80
|
+
this.listeners.add(listener);
|
|
81
|
+
return () => {
|
|
82
|
+
this.listeners.delete(listener);
|
|
83
|
+
};
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
formatResetDescription(date: Date): string {
|
|
87
|
+
return formatResetDescription(date, this.now());
|
|
88
|
+
}
|
|
89
|
+
}
|
package/src/schemas/codemap.md
CHANGED
|
@@ -34,7 +34,7 @@ This directory defines the Zod-based configuration schemas for the `pi-qol` plug
|
|
|
34
34
|
- `layout: 'inline' | 'overlay'` (default `'inline'`)
|
|
35
35
|
- `CustomFooterConfigSchema` contains:
|
|
36
36
|
- `enabled: boolean`
|
|
37
|
-
- `colors: { directory?, modelName?,
|
|
37
|
+
- `colors: { directory?, modelName?, agentName? }`; subscription usage colors are fixed in the usage library, not configurable. Full and partial Zod objects strip former usage-color keys without validation errors.
|
|
38
38
|
- `icons: { directory?: ' ', refresh?: ' ', cache?: ' ', cacheRead?: ' ', cacheWrite?: ' ' }`
|
|
39
39
|
- `display: { tokens?: true, cache?: true }`
|
|
40
40
|
- `ContextViewConfigSchema` contains `enabled: boolean` and `layout: 'inline' | 'overlay'`.
|
|
@@ -10,8 +10,6 @@ const CustomFooterColorsSchema = z.object({
|
|
|
10
10
|
directory: ColorHexSchema.optional(),
|
|
11
11
|
modelName: ColorHexSchema.optional(),
|
|
12
12
|
agentName: ColorHexSchema.optional(),
|
|
13
|
-
anthropicUsage: ColorHexSchema.optional().default('#D97706'),
|
|
14
|
-
codexUsage: ColorHexSchema.optional().default('#10B981'),
|
|
15
13
|
});
|
|
16
14
|
|
|
17
15
|
const CustomFooterIconsSchema = z.object({
|
|
@@ -50,8 +48,6 @@ export const PartialCustomFooterConfigSchema = z.object({
|
|
|
50
48
|
directory: ColorHexSchema.optional(),
|
|
51
49
|
modelName: ColorHexSchema.optional(),
|
|
52
50
|
agentName: ColorHexSchema.optional(),
|
|
53
|
-
anthropicUsage: ColorHexSchema.optional(),
|
|
54
|
-
codexUsage: ColorHexSchema.optional(),
|
|
55
51
|
})
|
|
56
52
|
.optional(),
|
|
57
53
|
icons: z
|
|
@@ -1,16 +0,0 @@
|
|
|
1
|
-
import { EMPTY_BAR_ICON, FILLED_BAR_ICON, SUBSCRIPTION_BAR_WIDTH } from './constants';
|
|
2
|
-
|
|
3
|
-
export function clampPercent(usedPercent: number): number {
|
|
4
|
-
return Number.isFinite(usedPercent) ? Math.max(0, Math.min(100, usedPercent)) : 0;
|
|
5
|
-
}
|
|
6
|
-
|
|
7
|
-
export function renderProgressBar(usedPercent: number, width = SUBSCRIPTION_BAR_WIDTH): { filled: string; empty: string } {
|
|
8
|
-
const barWidth = Math.max(0, Math.floor(width));
|
|
9
|
-
const pct = clampPercent(usedPercent);
|
|
10
|
-
const filledCount = Math.round((pct / 100) * barWidth);
|
|
11
|
-
|
|
12
|
-
return {
|
|
13
|
-
filled: FILLED_BAR_ICON.repeat(filledCount),
|
|
14
|
-
empty: EMPTY_BAR_ICON.repeat(barWidth - filledCount),
|
|
15
|
-
};
|
|
16
|
-
}
|
|
@@ -1,91 +0,0 @@
|
|
|
1
|
-
import { AnthropicOauthUsageStrategy } from '../../libs/subscription-usage/strategy/anthropic-oauth-usage.strategy';
|
|
2
|
-
import { OpenAiCodexUsageStrategy } from '../../libs/subscription-usage/strategy/openai-codex-usage.strategy';
|
|
3
|
-
import {
|
|
4
|
-
type FetchUsageResponse,
|
|
5
|
-
type RateWindow,
|
|
6
|
-
SubscriptionUsageApi,
|
|
7
|
-
type SubscriptionUsageStrategy,
|
|
8
|
-
} from '../../libs/subscription-usage/subscription-usage-api.util';
|
|
9
|
-
import { SUBSCRIPTION_USAGE_TTL_MS } from './constants';
|
|
10
|
-
import type { SupportedProvider } from './types';
|
|
11
|
-
|
|
12
|
-
export type SubscriptionUsageApiLike = Pick<SubscriptionUsageApi, 'fetchUsage' | 'formatResetDescription'>;
|
|
13
|
-
|
|
14
|
-
export function resolveSupportedProvider(provider: string | undefined): SupportedProvider | undefined {
|
|
15
|
-
switch (provider?.toLowerCase()) {
|
|
16
|
-
case 'anthropic':
|
|
17
|
-
return 'anthropic';
|
|
18
|
-
case 'openai-codex':
|
|
19
|
-
case 'codex':
|
|
20
|
-
case 'openai':
|
|
21
|
-
case 'chatgpt':
|
|
22
|
-
return 'openai-codex';
|
|
23
|
-
default:
|
|
24
|
-
return undefined;
|
|
25
|
-
}
|
|
26
|
-
}
|
|
27
|
-
|
|
28
|
-
export function pickSubscriptionUsageWindow(windows: readonly RateWindow[]): RateWindow | undefined {
|
|
29
|
-
let earliestWithReset: RateWindow | undefined;
|
|
30
|
-
|
|
31
|
-
for (const window of windows) {
|
|
32
|
-
if (!window.resetAt) continue;
|
|
33
|
-
if (!earliestWithReset?.resetAt || window.resetAt.getTime() <= earliestWithReset.resetAt.getTime()) {
|
|
34
|
-
earliestWithReset = window;
|
|
35
|
-
}
|
|
36
|
-
}
|
|
37
|
-
|
|
38
|
-
return earliestWithReset ?? windows[0];
|
|
39
|
-
}
|
|
40
|
-
|
|
41
|
-
export class SubscriptionUsageManager {
|
|
42
|
-
private cache = new Map<SupportedProvider, FetchUsageResponse>();
|
|
43
|
-
private inFlight = new Set<SupportedProvider>();
|
|
44
|
-
private lastFetchAt = new Map<SupportedProvider, number>();
|
|
45
|
-
|
|
46
|
-
constructor(
|
|
47
|
-
private api: SubscriptionUsageApiLike = new SubscriptionUsageApi(),
|
|
48
|
-
private onUpdate?: () => void,
|
|
49
|
-
private ttlMs = SUBSCRIPTION_USAGE_TTL_MS,
|
|
50
|
-
) {}
|
|
51
|
-
|
|
52
|
-
get(provider: SupportedProvider): FetchUsageResponse | undefined {
|
|
53
|
-
return this.cache.get(provider);
|
|
54
|
-
}
|
|
55
|
-
|
|
56
|
-
ensureFresh(provider: SupportedProvider): FetchUsageResponse | undefined {
|
|
57
|
-
const last = this.lastFetchAt.get(provider) ?? 0;
|
|
58
|
-
if (!this.inFlight.has(provider) && Date.now() - last > this.ttlMs) {
|
|
59
|
-
this.refresh(provider);
|
|
60
|
-
}
|
|
61
|
-
|
|
62
|
-
return this.cache.get(provider);
|
|
63
|
-
}
|
|
64
|
-
|
|
65
|
-
formatResetDescription(date: Date): string {
|
|
66
|
-
return this.api.formatResetDescription(date);
|
|
67
|
-
}
|
|
68
|
-
|
|
69
|
-
private refresh(provider: SupportedProvider): void {
|
|
70
|
-
this.inFlight.add(provider);
|
|
71
|
-
this.lastFetchAt.set(provider, Date.now());
|
|
72
|
-
|
|
73
|
-
void this.api
|
|
74
|
-
.fetchUsage(this.strategyFor(provider))
|
|
75
|
-
.then(response => {
|
|
76
|
-
if (!response) return;
|
|
77
|
-
this.cache.set(provider, response);
|
|
78
|
-
this.onUpdate?.();
|
|
79
|
-
})
|
|
80
|
-
.catch(() => {
|
|
81
|
-
// Best-effort status: auth/network failures simply hide the segment.
|
|
82
|
-
})
|
|
83
|
-
.finally(() => {
|
|
84
|
-
this.inFlight.delete(provider);
|
|
85
|
-
});
|
|
86
|
-
}
|
|
87
|
-
|
|
88
|
-
private strategyFor(provider: SupportedProvider): SubscriptionUsageStrategy {
|
|
89
|
-
return provider === 'anthropic' ? new AnthropicOauthUsageStrategy() : new OpenAiCodexUsageStrategy();
|
|
90
|
-
}
|
|
91
|
-
}
|