@0xkahi/pi-qol 1.3.0 → 1.4.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 CHANGED
@@ -48,10 +48,11 @@ Favourites, ordered custom group tabs, provider filtering, and inline or overlay
48
48
  - **shared filtering** across Favourites, group, and Search tabs
49
49
  - **bidirectional tab navigation** with Tab and Shift+Tab
50
50
  - **provider filtering** for Search without removing models from favourite tabs
51
- - **sections**: opens on Select Model; `Ctrl+]` switches to the next section and
52
- `Ctrl+[` to the previous (both wrap). Without the Kitty keyboard protocol,
53
- `Ctrl+[` acts as Esc instead. Tab/Shift+Tab stay within the active section.
54
- - **Usage**: `[Claude]` and `[Codex]` tabs show every subscription rate window,
51
+ - **sections**: opens on Select Model; `Ctrl+L` switches to the next section and
52
+ `Ctrl+H` to the previous (both wrap). `Ctrl+H` needs a terminal that reports it
53
+ distinctly (Kitty, CSI-u, or modifyOtherKeys); otherwise it acts as Backspace.
54
+ `Ctrl+L` works everywhere. Tab/Shift+Tab stay within the active section.
55
+ - **Usage**: `[Claude]` `[Codex]` `[OC-GO]` tabs show every subscription rate window,
55
56
  separated by blank lines, with a progress bar, used percentage, reset time,
56
57
  pace, and data freshness. Fixed provider colors match the custom footer. Missing
57
58
  credentials and request failures are shown explicitly. Usage shares the footer
@@ -65,9 +66,13 @@ allow keybindings with [pi-vim-keys](https://github.com/0xKahi/pi-vim-keys) with
65
66
 
66
67
  Replaces pi's built-in interactive footer with the same three-line layout, but
67
68
  shows the current directory as an icon plus basename, supports hex color overrides,
68
- can hide token/cache clusters, and adds an OAuth subscription-usage progress bar
69
- for supported providers (Anthropic and OpenAI Codex). Usage colors are fixed:
70
- Claude `#D97706` and Codex `#10B981`; former usage-color overrides are ignored.
69
+ can hide token/cache clusters, and adds a subscription-usage progress bar
70
+ for supported providers (Anthropic, OpenAI Codex, and OpenCode Go via model provider
71
+ `opencode-go`, not OpenCode Zen `opencode`). Usage colors are fixed: Claude
72
+ `#D97706`, Codex `#10B981`, and OC-GO `#00ADD8`; former usage-color overrides are ignored.
73
+ OpenCode Go shows `5h`, `Week`, and `Month` windows and requires an `opencode-go`
74
+ entry of type `api_key` in `~/.pi/agent/auth.json`, with the secret in `key`;
75
+ `OPENCODE_API_KEY` alone is not used. Claude and Codex require OAuth entries.
71
76
 
72
77
  - **Directory line** — optional inverse-styled agent badge followed by the
73
78
  directory icon + basename, with optional git branch and session name. The badge
@@ -77,7 +82,7 @@ Claude `#D97706` and Codex `#10B981`; former usage-color overrides are ignored.
77
82
  right-aligned model name (with provider prefix when multiple providers are
78
83
  available).
79
84
  - **Subscription usage** — a colored progress bar plus percentage and reset time
80
- for the active OAuth provider. Usage is fetched lazily and cached, refreshing
85
+ for the active subscription provider. Usage is fetched lazily and cached, refreshing
81
86
  at most once every 60 seconds per provider; auth/network failures simply hide
82
87
  the segment.
83
88
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@0xkahi/pi-qol",
3
- "version": "1.3.0",
3
+ "version": "1.4.0",
4
4
  "description": "quality of life pi extensions",
5
5
  "type": "module",
6
6
  "keywords": [
@@ -160,7 +160,7 @@ export class CustomFooterComponent implements Component {
160
160
  }
161
161
 
162
162
  private isUsingSubscription(model: NonNullable<CustomFooterComponentDeps['ctx']['model']>): boolean {
163
- if (model.provider === 'kimi-coding') return true;
163
+ if (model.provider === 'kimi-coding' || model.provider === 'opencode-go') return true;
164
164
 
165
165
  return (
166
166
  this.deps.ctx.modelRegistry.isUsingOAuth(model) && this.deps.ctx.modelRegistry.getProvider(model.provider)?.auth?.oauth?.isSubscription === true
@@ -18,7 +18,7 @@ This extension implements the `/select-model` command and its interactive picker
18
18
  - `usage-section/`: [usage section map](usage-section/codemap.md); Claude/Codex provider tabs, explicit status and freshness, all window rows with progress/reset/pace, retained Vim row navigation, and `r` refresh.
19
19
  - `constants.ts`: command name, cross-extension event ID, and dialog rendering limits.
20
20
  - `types.ts`: shared item, list, tab, and dialog option types.
21
- - **Modal library delegation**: `ModelSelectModal` extends `SectionedModal` from `src/libs/modal/`, containing retained embedded dialogs; Ctrl+] and disambiguated Ctrl+[ wrap sections, bare Esc stays dismissal, and Tab stays inside the active section. Each dialog shell owns the tab strip, tab cycling, keybinding-driven navigation (wrap-around selection via `ListTab`), the shared filter `Input`, and the help footer.
21
+ - **Modal library delegation**: `ModelSelectModal` extends `SectionedModal` from `src/libs/modal/`, containing retained embedded dialogs; Ctrl+L and disambiguated Ctrl+H wrap sections, bare Esc stays dismissal, and Tab stays inside the active section. Each dialog shell owns the tab strip, tab cycling, keybinding-driven navigation (wrap-around selection via `ListTab`), the shared filter `Input`, and the help footer.
22
22
  - **Layout-aware presentation**: `showModelSelector` passes `model_select.layout` to the shared modal presenter, which coordinates the dialog's inline/bordered frame with normal or centered overlay mounting.
23
23
  - **Defensive guards**: checks feature enablement, UI availability, idle state (`waitForIdle`), exact-match short-circuit, and auth availability before applying a model.
24
24
 
@@ -86,9 +86,10 @@ Wire every dialog's `onComplete` to the same host `done` callback and choose its
86
86
  `cancelValue`. Section state survives switches, and natural height follows the
87
87
  active section. `onActivate` runs once per section, including the initial section.
88
88
 
89
- Input routing: `Ctrl+]` goes forward and disambiguated `Ctrl+[` goes backward
90
- (both wrap); all other input goes to the active dialog. Bare Esc always dismisses
91
- through that dialog (layers close first). In non-Kitty terminals, `Ctrl+[` is Esc.
89
+ Input routing: `Ctrl+L` goes forward and disambiguated `Ctrl+H` goes backward
90
+ (both wrap); all other input goes to the active dialog. A raw `0x08` byte is always
91
+ Backspace for the active dialog, so `Ctrl+H` needs a terminal that reports it
92
+ distinctly. Bare Esc always dismisses through that dialog (layers close first).
92
93
  Tab/Shift+Tab stay inside the section. Switching clears pending navigation chords.
93
94
  Only the active dialog receives focus. Multiple sections add a footer hint.
94
95
 
@@ -16,7 +16,7 @@ The library is self-contained: it imports only from Pi host packages (`@earendil
16
16
  - `tabs/list-tab.ts` — `ListTab<T>` generic picker tab: items + row renderer + confirm callback, optional fuzzy filtering (`filterText`) wired to the dialog filter, dynamic count labels, filter captions, footer hook (rendered below the list in all states), empty/no-match messages, fixed or height-driven window, clamp (default) or wrap selection.
17
17
  - `preview-layer.ts` — `PreviewLayer`: title + right-aligned meta header, `PreviewScroller`-windowed body, overflow counter, optional pinned description; dismissal is shell-owned (pops the layer).
18
18
  - `list-navigator.ts` — `ListNavigator` (selection + scroll window; clamp default, `wrap` option; `setRowCount` for filtered lists) and `PreviewScroller` (scroll-only window over wrapped lines). Forked from `pi-context-view`.
19
- - `sectioned-modal.ts` — Exports `SectionFrame` (`inline` | `bordered`) for section host framing. `SectionedModal<TResult>` hosts retained `ModalSection` dialogs with `frame: 'none'`, draws the frame, routes Ctrl+]/disambiguated Ctrl+[ before dialog input, resets outgoing navigation, propagates active-only focus, and runs first-activation callbacks. Callers wire every dialog completion to the same host sink and own resource cleanup (for example an idempotent `dispose()` on a consumer subclass). Bare Esc stays dialog input; Tab stays within sections; natural height follows the active dialog.
19
+ - `sectioned-modal.ts` — Exports `SectionFrame` (`inline` | `bordered`) for section host framing. `SectionedModal<TResult>` hosts retained `ModalSection` dialogs with `frame: 'none'`, draws the frame, routes Ctrl+L/disambiguated Ctrl+H (raw `0x08` stays Backspace) before dialog input, resets outgoing navigation, propagates active-only focus, and runs first-activation callbacks. Callers wire every dialog completion to the same host sink and own resource cleanup (for example an idempotent `dispose()` on a consumer subclass). Bare Esc stays dialog input; Tab stays within sections; natural height follows the active dialog.
20
20
  - `section-strip.ts` — `renderSectionRule` draws active/inactive section labels in the top rule or rounded border, adding no height.
21
21
  - `label-window.ts` — Shared active-centered overflow window computation for tab and section strips.
22
22
  - `tab-strip.ts` — Width-aware tab strip: active label highlighted; overflow keeps a window around the active tab with `…` omission indicators. Labels are re-read each render.
@@ -29,7 +29,7 @@ export class SectionedModal<TResult> implements Component, Focusable {
29
29
  this.activeIndex = Math.min(Math.max(0, options.initialSectionIndex ?? 0), options.sections.length - 1);
30
30
  for (const section of options.sections) {
31
31
  section.dialog.focused = false;
32
- if (options.sections.length > 1) section.dialog.setExtraHints([['^]/^[', 'Section']]);
32
+ if (options.sections.length > 1) section.dialog.setExtraHints([['^L/^H', 'Section']]);
33
33
  }
34
34
  this.activate();
35
35
  }
@@ -48,9 +48,9 @@ export class SectionedModal<TResult> implements Component, Focusable {
48
48
  }
49
49
 
50
50
  public handleInput(data: string): void {
51
- if (matchesKey(data, 'ctrl+]')) {
51
+ if (matchesKey(data, 'ctrl+l')) {
52
52
  this.switchSection(1);
53
- } else if (data !== '\x1b' && matchesKey(data, 'ctrl+[')) {
53
+ } else if (data !== '\x08' && matchesKey(data, 'ctrl+h')) {
54
54
  this.switchSection(-1);
55
55
  } else {
56
56
  this.activeDialog().handleInput(data);
@@ -2,15 +2,16 @@
2
2
 
3
3
  ## Responsibility
4
4
 
5
- Shared subscription data pipeline for Claude and Codex, exported through `index.ts`.
5
+ Shared subscription data pipeline for Claude, Codex, and OpenCode Go (`opencode-go`, not Zen `opencode`), 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.
8
+ - `credential-resolver.ts`: requires an auth.json entry and checks per-provider accepted auth types through PathUtil and RawDataParser: `anthropic`/`openai-codex` accept `oauth` (missing type defaults to `oauth`); `opencode-go` accepts `api_key`. Asks the latest host context for credentials, falls back to stored access for OAuth or stored key for API keys; env-only credentials are not used. Codex account id comes from stored accountId or defensive JWT decoding.
9
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
10
  - `pace.ts`: pure elapsed-window pace and relative reset formatting.
11
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.
12
+ - `provider-color.ts`: fixed shared provider colors (Claude #D97706, Codex #10B981, OC-GO #00ADD8), exported as PROVIDER_USAGE_COLORS and providerUsageColor; no configuration dependency.
13
13
  - `strategy/`: pure request construction and JSON normalization; no network I/O.
14
+ - `strategy/opencode-go-usage.strategy.ts`: OpenCode Go bearer-key status request and meter normalization into `5h`, `Week`, and `Month` windows.
14
15
 
15
16
  ## Flow
16
17
 
@@ -2,7 +2,13 @@ import { readFileSync } from 'node:fs';
2
2
  import type { ExtensionContext } from '@earendil-works/pi-coding-agent';
3
3
  import { PathUtil } from '../../utils/path.util';
4
4
  import { RawDataParser } from '../../utils/raw-data-parser.util';
5
- import type { CredentialResolver } from './subscription-usage-api.util';
5
+ import type { CredentialResolver, SubscriptionProvider } from './subscription-usage-api.util';
6
+
7
+ const ACCEPTED_AUTH_TYPES: Record<SubscriptionProvider, readonly string[]> = {
8
+ anthropic: ['oauth'],
9
+ 'openai-codex': ['oauth'],
10
+ 'opencode-go': ['api_key'],
11
+ };
6
12
 
7
13
  function jwtAccountId(token: string): string | undefined {
8
14
  try {
@@ -23,15 +29,17 @@ export function createHostCredentialResolver(getCtx: () => ExtensionContext | un
23
29
  if (!path.exists) return undefined;
24
30
  const config = RawDataParser.asRecord(JSON.parse(readFileSync(path.path, 'utf8')));
25
31
  const stored = RawDataParser.asRecord(config?.[provider]);
26
- if (!stored || (stored.type !== undefined && stored.type !== 'oauth')) return undefined;
32
+ if (!stored) return undefined;
33
+ const authType = stored.type === undefined ? 'oauth' : stored.type;
34
+ if (typeof authType !== 'string' || !ACCEPTED_AUTH_TYPES[provider].includes(authType)) return undefined;
27
35
  let token: string | undefined;
28
36
  try {
29
37
  const resolved = await getCtx()?.modelRegistry.getProviderAuth(provider);
30
38
  token = RawDataParser.stringValue(resolved?.auth?.apiKey);
31
39
  } catch {
32
- // Stored access is the verified fallback when host refresh fails.
40
+ // The stored secret is the verified fallback when host resolution fails.
33
41
  }
34
- token ||= RawDataParser.stringValue(stored.access);
42
+ token ||= RawDataParser.stringValue(authType === 'api_key' ? stored.key : stored.access);
35
43
  if (!token) return undefined;
36
44
  return {
37
45
  token,
@@ -4,5 +4,6 @@ export * from './progress-bar';
4
4
  export * from './provider-color';
5
5
  export * from './strategy/anthropic-oauth-usage.strategy';
6
6
  export * from './strategy/openai-codex-usage.strategy';
7
+ export * from './strategy/opencode-go-usage.strategy';
7
8
  export * from './subscription-usage-api.util';
8
9
  export * from './subscription-usage-cache';
@@ -3,6 +3,7 @@ import type { SubscriptionProvider } from './subscription-usage-api.util';
3
3
  export const PROVIDER_USAGE_COLORS: Readonly<Record<SubscriptionProvider, string>> = {
4
4
  anthropic: '#D97706',
5
5
  'openai-codex': '#10B981',
6
+ 'opencode-go': '#00ADD8',
6
7
  };
7
8
 
8
9
  export function providerUsageColor(provider: SubscriptionProvider): string {
@@ -0,0 +1,45 @@
1
+ import { RawDataParser } from '../../../utils/raw-data-parser.util';
2
+ import type { ProviderAuth, RateWindow, SubscriptionUsageStrategy } from '../subscription-usage-api.util';
3
+
4
+ export class OpenCodeGoUsageStrategy implements SubscriptionUsageStrategy {
5
+ readonly provider = 'opencode-go';
6
+ readonly label = 'OC-GO';
7
+
8
+ parse(json: unknown): RateWindow[] {
9
+ const access = RawDataParser.asRecord(RawDataParser.asRecord(json)?.access);
10
+ const meters = RawDataParser.asRecord(access?.meters);
11
+ if (!meters) return [];
12
+
13
+ const windows: RateWindow[] = [];
14
+ for (const [key, label, fallbackSeconds] of [
15
+ ['fiveHour', '5h', 18000],
16
+ ['week', 'Week', 604800],
17
+ ['month', 'Month', undefined],
18
+ ] as const) {
19
+ const meter = RawDataParser.asRecord(meters[key]);
20
+ const limit = RawDataParser.numberValue(meter?.limitMicroCents);
21
+ const rawUsed = meter?.usedMicroCents;
22
+ if (typeof rawUsed !== 'number' && !RawDataParser.stringValue(rawUsed)) continue;
23
+ const used = RawDataParser.numberValue(rawUsed);
24
+ const reset = RawDataParser.stringValue(meter?.resetsAt);
25
+ const resetAt = reset ? new Date(reset) : undefined;
26
+ if (limit === undefined || limit <= 0 || used === undefined || !resetAt || !Number.isFinite(resetAt.getTime())) continue;
27
+ const start = RawDataParser.stringValue(key === 'month' ? access?.startsAt : meter?.startsAt);
28
+ const duration = start ? (resetAt.getTime() - new Date(start).getTime()) / 1000 : NaN;
29
+ windows.push({
30
+ label,
31
+ usedPercent: (used / limit) * 100,
32
+ resetAt,
33
+ windowSeconds: Number.isFinite(duration) && duration > 0 ? duration : fallbackSeconds,
34
+ });
35
+ }
36
+ return windows;
37
+ }
38
+
39
+ request(auth: ProviderAuth): Request {
40
+ return new Request('https://opencode.ai/console/api/go/status', {
41
+ method: 'GET',
42
+ headers: { Authorization: `Bearer ${auth.token}` },
43
+ });
44
+ }
45
+ }
@@ -1,13 +1,16 @@
1
1
  import { AnthropicOauthUsageStrategy } from './strategy/anthropic-oauth-usage.strategy';
2
2
  import { OpenAiCodexUsageStrategy } from './strategy/openai-codex-usage.strategy';
3
3
 
4
+ import { OpenCodeGoUsageStrategy } from './strategy/opencode-go-usage.strategy';
5
+
4
6
  export const SUBSCRIPTION_USAGE_FETCH_TIMEOUT_MS = 10_000;
5
7
  export const SUBSCRIPTION_USAGE_TTL_MS = 60_000;
6
8
 
7
- export type SubscriptionProvider = 'anthropic' | 'openai-codex';
9
+ export type SubscriptionProvider = 'anthropic' | 'openai-codex' | 'opencode-go';
8
10
  export const SUBSCRIPTION_PROVIDERS: readonly { provider: SubscriptionProvider; label: string }[] = [
9
11
  { provider: 'anthropic', label: new AnthropicOauthUsageStrategy().label },
10
12
  { provider: 'openai-codex', label: new OpenAiCodexUsageStrategy().label },
13
+ { provider: 'opencode-go', label: new OpenCodeGoUsageStrategy().label },
11
14
  ];
12
15
  export type ProviderAuth = { token: string; accountId?: string };
13
16
  export type CredentialResolver = (provider: SubscriptionProvider) => Promise<ProviderAuth | undefined>;
@@ -1,19 +1,29 @@
1
1
  import { formatResetDescription } from './pace';
2
2
  import { AnthropicOauthUsageStrategy } from './strategy/anthropic-oauth-usage.strategy';
3
3
  import { OpenAiCodexUsageStrategy } from './strategy/openai-codex-usage.strategy';
4
+ import { OpenCodeGoUsageStrategy } from './strategy/opencode-go-usage.strategy';
4
5
  import {
5
6
  type RateWindow,
6
7
  SUBSCRIPTION_USAGE_TTL_MS,
7
8
  type SubscriptionProvider,
8
9
  SubscriptionUsageApi,
9
10
  type SubscriptionUsageApiLike,
11
+ type SubscriptionUsageStrategy,
10
12
  type UsageResult,
11
13
  } from './subscription-usage-api.util';
12
14
 
15
+ const STRATEGIES: Record<SubscriptionProvider, SubscriptionUsageStrategy> = {
16
+ anthropic: new AnthropicOauthUsageStrategy(),
17
+ 'openai-codex': new OpenAiCodexUsageStrategy(),
18
+ 'opencode-go': new OpenCodeGoUsageStrategy(),
19
+ };
20
+
13
21
  export type UsageCacheEntry = { result?: UsageResult; lastSuccess?: { windows: RateWindow[]; fetchedAt: number }; inFlight: boolean };
14
22
 
15
23
  export function resolveSupportedProvider(provider?: string): SubscriptionProvider | undefined {
16
24
  switch (provider?.toLowerCase()) {
25
+ case 'opencode-go':
26
+ return 'opencode-go';
17
27
  case 'anthropic':
18
28
  return 'anthropic';
19
29
  case 'openai-codex':
@@ -64,7 +74,7 @@ export class SubscriptionUsageCache {
64
74
  const entry: UsageCacheEntry = { ...this.get(provider), inFlight: true };
65
75
  this.entries.set(provider, entry);
66
76
  this.lastAttemptAt.set(provider, this.now());
67
- const strategy = provider === 'anthropic' ? new AnthropicOauthUsageStrategy() : new OpenAiCodexUsageStrategy();
77
+ const strategy = STRATEGIES[provider];
68
78
  void Promise.resolve()
69
79
  .then(() => this.api.fetchUsage(strategy))
70
80
  .catch((): UsageResult => ({ status: 'network', label: strategy.label }))