@0xkahi/pi-qol 1.1.3 → 1.3.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.
Files changed (46) hide show
  1. package/README.md +36 -14
  2. package/assets/config.schema.json +12 -19
  3. package/package.json +5 -5
  4. package/src/extensions/auto-session-name/codemap.md +5 -5
  5. package/src/extensions/auto-session-name/guards.ts +9 -18
  6. package/src/extensions/auto-session-name/index.ts +8 -32
  7. package/src/extensions/auto-session-name/naming-text.ts +17 -0
  8. package/src/extensions/custom-footer/codemap.md +5 -6
  9. package/src/extensions/custom-footer/constants.ts +0 -1
  10. package/src/extensions/custom-footer/footer-component.ts +10 -8
  11. package/src/extensions/custom-footer/index.ts +3 -1
  12. package/src/extensions/custom-footer/token-stats.ts +5 -6
  13. package/src/extensions/custom-footer/types.ts +3 -1
  14. package/src/extensions/model-select/codemap.md +8 -4
  15. package/src/extensions/model-select/index.ts +35 -29
  16. package/src/extensions/model-select/model-select-dialog.ts +9 -25
  17. package/src/extensions/model-select/model-select-modal.ts +66 -0
  18. package/src/extensions/model-select/usage-section/codemap.md +14 -0
  19. package/src/extensions/model-select/usage-section/index.ts +37 -0
  20. package/src/extensions/model-select/usage-section/usage-provider-tab.ts +166 -0
  21. package/src/index.ts +7 -3
  22. package/src/libs/modal/README.md +46 -2
  23. package/src/libs/modal/codemap.md +4 -1
  24. package/src/libs/modal/index.ts +2 -0
  25. package/src/libs/modal/label-window.ts +32 -0
  26. package/src/libs/modal/modal-dialog.ts +16 -2
  27. package/src/libs/modal/section-strip.ts +33 -0
  28. package/src/libs/modal/sectioned-modal.ts +105 -0
  29. package/src/libs/modal/tab-strip.ts +2 -26
  30. package/src/libs/subscription-usage/codemap.md +10 -21
  31. package/src/libs/subscription-usage/credential-resolver.ts +44 -0
  32. package/src/libs/subscription-usage/index.ts +8 -0
  33. package/src/libs/subscription-usage/pace.ts +28 -0
  34. package/src/libs/subscription-usage/progress-bar.ts +13 -0
  35. package/src/libs/subscription-usage/provider-color.ts +10 -0
  36. package/src/libs/subscription-usage/strategy/anthropic-oauth-usage.strategy.ts +7 -15
  37. package/src/libs/subscription-usage/strategy/codemap.md +5 -41
  38. package/src/libs/subscription-usage/strategy/openai-codex-usage.strategy.ts +8 -15
  39. package/src/libs/subscription-usage/subscription-usage-api.util.ts +44 -67
  40. package/src/libs/subscription-usage/subscription-usage-cache.ts +89 -0
  41. package/src/schemas/auto-session-name.config.schema.ts +9 -2
  42. package/src/schemas/codemap.md +1 -1
  43. package/src/schemas/config.schema.ts +1 -1
  44. package/src/schemas/custom-footer-config.schema.ts +0 -4
  45. package/src/extensions/custom-footer/progress-bar.ts +0 -16
  46. package/src/extensions/custom-footer/subscription-usage-manager.ts +0 -91
@@ -1,80 +1,57 @@
1
- import { readFileSync } from 'node:fs';
2
- import { PathUtil } from '../../utils/path.util';
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
4
  export const SUBSCRIPTION_USAGE_FETCH_TIMEOUT_MS = 10_000;
6
-
7
- export type ProviderAuth = {
8
- token: string;
9
- accountId?: string;
10
- };
5
+ export const SUBSCRIPTION_USAGE_TTL_MS = 60_000;
11
6
 
12
7
  export type SubscriptionProvider = 'anthropic' | 'openai-codex';
13
- type SubscriptionAuthconfig = Partial<Record<SubscriptionProvider, Record<string, unknown>>>;
14
-
15
- export type RateWindow = {
16
- label: string;
17
- usedPercent: number;
18
- resetAt?: Date;
19
- };
20
-
21
- export type FetchUsageResponse = {
22
- label: string;
23
- rateWindow: RateWindow[];
24
- };
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 };
25
19
 
26
20
  export interface SubscriptionUsageStrategy {
27
21
  readonly provider: SubscriptionProvider;
28
22
  readonly label: string;
29
- fetchUsage(auth: ProviderAuth): Promise<RateWindow[] | undefined>;
23
+ request(auth: ProviderAuth): Request;
24
+ parse(json: unknown): RateWindow[];
30
25
  }
31
26
 
32
- export class SubscriptionUsageApi {
33
- async fetchUsage(strategy: SubscriptionUsageStrategy): Promise<FetchUsageResponse | undefined> {
34
- const auth = this.getOauthProviderAuth(strategy.provider);
35
- if (!auth) return;
36
- const rateWindow = await strategy.fetchUsage(auth);
37
- if (!rateWindow) return;
38
- return {
39
- label: strategy.label,
40
- rateWindow,
41
- };
42
- }
43
-
44
- formatResetDescription(date: Date): string {
45
- const diffMs = date.getTime() - Date.now();
46
- if (diffMs <= 0) return 'now';
47
-
48
- const minutes = Math.floor(diffMs / 60000);
49
- if (minutes < 60) return `${minutes}m`;
50
-
51
- const hours = Math.floor(minutes / 60);
52
- const remainingMinutes = minutes % 60;
53
- if (hours < 24) return remainingMinutes > 0 ? `${hours}h${remainingMinutes}m` : `${hours}h`;
27
+ export type SubscriptionUsageApiLike = Pick<SubscriptionUsageApi, 'fetchUsage'>;
54
28
 
55
- const days = Math.floor(hours / 24);
56
- const remainingHours = hours % 24;
57
- return remainingHours > 0 ? `${days}d${remainingHours}h` : `${days}d`;
58
- }
59
-
60
- private getOauthProviderAuth(provider: SubscriptionProvider): ProviderAuth | undefined {
61
- const auth = this.loadAuthConfig();
62
- if (!auth) return;
63
-
64
- const providerAuth = auth[provider];
65
- const access = RawDataParser.stringValue(providerAuth?.access);
66
- if (!access) return;
67
-
68
- return {
69
- token: access,
70
- accountId: RawDataParser.stringValue(providerAuth?.accountId),
71
- };
72
- }
73
-
74
- private loadAuthConfig(): SubscriptionAuthconfig | undefined {
75
- const authJson = PathUtil.findPiAuthConfig();
76
- if (!authJson.exists) return undefined;
77
-
78
- 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
+ }
79
56
  }
80
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
+ }
@@ -4,9 +4,16 @@ import { ModelConfigSchema } from './shared-config.schema';
4
4
  export const AutoSessionNameConfigSchema = z.object({
5
5
  enabled: z.boolean().default(false),
6
6
  model: ModelConfigSchema.optional(),
7
- // customMessageWhitelist: z.array(z.string()).describe('a list of pi custom_messages, customType to be used to trigger auto session name'),
7
+ custom_message_whitelist: z
8
+ .array(z.string())
9
+ .default([])
10
+ .describe('customType values of pi custom messages (sent with triggerTurn) that may trigger auto session naming. Empty = only user prompts.'),
8
11
  });
9
12
  export type AutoSessionNameConfig = z.infer<typeof AutoSessionNameConfigSchema>;
10
13
 
11
- export const PartialAutoSessionNameConfigSchema = AutoSessionNameConfigSchema.partial();
14
+ export const PartialAutoSessionNameConfigSchema = z.object({
15
+ enabled: z.boolean().optional(),
16
+ model: ModelConfigSchema.optional(),
17
+ custom_message_whitelist: z.array(z.string()).optional(),
18
+ });
12
19
  export type PartialAutoSessionNameConfig = z.infer<typeof PartialAutoSessionNameConfigSchema>;
@@ -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?, anthropicUsage?: '#D97706', codexUsage?: '#10B981' }`
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'`.
@@ -9,7 +9,7 @@ export const ConfigSchema = z.object({
9
9
  $schema: z.string().optional(),
10
10
  auto_session_name: AutoSessionNameConfigSchema.default({
11
11
  enabled: false,
12
- // customMessageWhitelist: [],
12
+ custom_message_whitelist: [],
13
13
  }),
14
14
  model_select: ModelSelectConfigSchema.default({
15
15
  enabled: false,
@@ -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
- }