@0xkahi/pi-qol 1.3.0 → 1.4.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 +24 -10
- package/assets/config.schema.json +5 -0
- package/package.json +4 -4
- package/src/extensions/context-view/capture.ts +74 -35
- package/src/extensions/context-view/codemap.md +24 -16
- package/src/extensions/context-view/constants.ts +3 -0
- package/src/extensions/context-view/context-view-controller.ts +47 -13
- package/src/extensions/context-view/index.ts +25 -9
- package/src/extensions/context-view/measure.ts +2 -1
- package/src/extensions/context-view/model.ts +44 -3
- package/src/extensions/context-view/presentation.ts +6 -0
- package/src/extensions/context-view/prompt-additions.ts +5 -3
- package/src/extensions/context-view/ui/codemap.md +60 -93
- package/src/extensions/context-view/ui/context-view-dialog.ts +14 -7
- package/src/extensions/context-view/ui/copy.ts +42 -0
- package/src/extensions/context-view/ui/highlight.ts +91 -0
- package/src/extensions/context-view/ui/injections-model.ts +52 -0
- package/src/extensions/context-view/ui/injections-view.ts +124 -27
- package/src/extensions/context-view/ui/search.ts +28 -0
- package/src/extensions/context-view/ui/searchable-preview.ts +175 -0
- package/src/extensions/context-view/ui/usage-block-layer.ts +18 -7
- package/src/extensions/context-view/ui/usage-view.ts +57 -24
- package/src/extensions/custom-footer/footer-component.ts +1 -1
- package/src/extensions/model-select/codemap.md +1 -1
- package/src/libs/modal/README.md +13 -6
- package/src/libs/modal/codemap.md +6 -6
- package/src/libs/modal/index.ts +1 -1
- package/src/libs/modal/modal-dialog.ts +44 -3
- package/src/libs/modal/preview-layer.ts +3 -3
- package/src/libs/modal/sectioned-modal.ts +3 -3
- package/src/libs/modal/types.ts +11 -0
- package/src/libs/subscription-usage/codemap.md +4 -3
- package/src/libs/subscription-usage/credential-resolver.ts +12 -4
- package/src/libs/subscription-usage/index.ts +1 -0
- package/src/libs/subscription-usage/provider-color.ts +1 -0
- package/src/libs/subscription-usage/strategy/opencode-go-usage.strategy.ts +45 -0
- package/src/libs/subscription-usage/subscription-usage-api.util.ts +4 -1
- package/src/libs/subscription-usage/subscription-usage-cache.ts +11 -1
- package/src/schemas/context-view.config.schema.ts +2 -0
- package/src/extensions/context-view/ui/wheel-preview-layer.ts +0 -104
- package/src/extensions/context-view/ui/wheel.ts +0 -66
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
* shared modal library; this tab owns only its content.
|
|
8
8
|
*/
|
|
9
9
|
import type { Theme, ThemeColor } from '@earendil-works/pi-coding-agent';
|
|
10
|
-
import { matchesKey, visibleWidth, wrapTextWithAnsi } from '@earendil-works/pi-tui';
|
|
10
|
+
import { matchesKey, type TuiMouseEvent, type TuiMouseEventResult, visibleWidth, wrapTextWithAnsi } from '@earendil-works/pi-tui';
|
|
11
11
|
|
|
12
12
|
import {
|
|
13
13
|
BODY_INDENT,
|
|
@@ -24,14 +24,14 @@ import {
|
|
|
24
24
|
} from '../../../libs/modal';
|
|
25
25
|
import type { ContextUsageSnapshot, JsonSpan, UsageCategory, UsagePreviewEntry } from '../model';
|
|
26
26
|
import { collectPreviewEntries } from '../usage';
|
|
27
|
+
import { type CopyServices, copyWithNotice } from './copy';
|
|
27
28
|
import { normalizeInlineText, normalizePreviewText } from './injections-model';
|
|
28
29
|
import { expandJsonSpan } from './json-preview';
|
|
30
|
+
import { SearchablePreview } from './searchable-preview';
|
|
29
31
|
import { previewBodyLines, previewLegendLines } from './section-preview';
|
|
30
32
|
import { splitSkillPreview } from './skill-preview';
|
|
31
33
|
import { UsageBlockLayer } from './usage-block-layer';
|
|
32
34
|
import { buildUsageMap, calculateFitMapScale, DEFAULT_MAP_COLUMNS, DEFAULT_MAP_ROWS, type UsageMapCell } from './usage-map';
|
|
33
|
-
import { DEFAULT_WHEEL_SCROLL_LINES, parseWheelDirection } from './wheel';
|
|
34
|
-
import { WheelPreviewLayer } from './wheel-preview-layer';
|
|
35
35
|
|
|
36
36
|
const USAGE_DESCRIPTION =
|
|
37
37
|
'Estimated context for the next model request. ' + "Token counts are approximate and may differ from the provider's estimate.";
|
|
@@ -55,7 +55,7 @@ const COMPACTED_CELL = '▦';
|
|
|
55
55
|
const BUFFER_CELL = '⛝';
|
|
56
56
|
const FREE_CELL = '⛶';
|
|
57
57
|
const BREAKDOWN_MARKER = '•';
|
|
58
|
-
/** Title and its trailing blank row the full-content
|
|
58
|
+
/** Title and its trailing blank row the full-content layer spends outside its body. */
|
|
59
59
|
const FULL_CONTENT_FIXED_LINE_COUNT = 2;
|
|
60
60
|
|
|
61
61
|
/** Everything the Usage view renders, classified once when the view opens. */
|
|
@@ -98,16 +98,19 @@ export class UsageView implements ModalTab {
|
|
|
98
98
|
private readonly navigator: ListNavigator;
|
|
99
99
|
private readonly cache = new RenderCache();
|
|
100
100
|
private readonly fitMapScale: number | undefined;
|
|
101
|
-
private
|
|
101
|
+
private percentBasis: 'window' | 'used' = 'window';
|
|
102
102
|
private context: ModalTabContext | undefined;
|
|
103
103
|
private mapScale: UsageMapScale = 'window';
|
|
104
104
|
private currentWidth: number | undefined;
|
|
105
105
|
|
|
106
106
|
/** Create a view over one precomputed usage snapshot. */
|
|
107
|
-
public constructor(
|
|
107
|
+
public constructor(
|
|
108
|
+
theme: Theme,
|
|
109
|
+
input: UsageViewInput,
|
|
110
|
+
private readonly copy: CopyServices = { notices: { showNotice: () => undefined } },
|
|
111
|
+
) {
|
|
108
112
|
this.theme = theme;
|
|
109
113
|
this.usage = input.usage;
|
|
110
|
-
this.wheelScrollLines = wheelScrollLines;
|
|
111
114
|
this.legendRows = this.buildLegendRows();
|
|
112
115
|
const selectableCount = this.legendRows.filter(row => row.type === 'category').length;
|
|
113
116
|
this.navigator = new ListNavigator(this.legendRows.length, 1, selectableCount);
|
|
@@ -123,19 +126,42 @@ export class UsageView implements ModalTab {
|
|
|
123
126
|
}
|
|
124
127
|
|
|
125
128
|
public hints(): Hint[] {
|
|
126
|
-
const hints: Hint[] = [
|
|
129
|
+
const hints: Hint[] = [
|
|
130
|
+
['Enter', 'Preview'],
|
|
131
|
+
['y', 'Copy'],
|
|
132
|
+
];
|
|
133
|
+
if (this.canTogglePercentBasis()) hints.push(['p', 'Percent basis']);
|
|
127
134
|
if (this.canToggleMapScale(this.currentWidth)) hints.push(['Z', 'Zoom']);
|
|
128
135
|
return hints;
|
|
129
136
|
}
|
|
130
137
|
|
|
131
|
-
/** Handle
|
|
138
|
+
/** Handle view-local zoom, percentage basis, and copy bindings. */
|
|
132
139
|
public handleInput(data: string): void {
|
|
133
|
-
const wheel = parseWheelDirection(data);
|
|
134
|
-
if (wheel !== undefined) {
|
|
135
|
-
if (this.navigator.moveBy(wheel)) this.cache.clear();
|
|
136
|
-
return;
|
|
137
|
-
}
|
|
138
140
|
if (matchesKey(data, 'z')) this.toggleMapScale();
|
|
141
|
+
if (matchesKey(data, 'p') && this.canTogglePercentBasis()) {
|
|
142
|
+
this.percentBasis = this.percentBasis === 'window' ? 'used' : 'window';
|
|
143
|
+
this.cache.clear();
|
|
144
|
+
}
|
|
145
|
+
if (matchesKey(data, 'y')) {
|
|
146
|
+
const row = this.legendRows[this.navigator.selected];
|
|
147
|
+
const text =
|
|
148
|
+
row?.type === 'category'
|
|
149
|
+
? collectPreviewEntries(row.category)
|
|
150
|
+
.map(entry => entry.text)
|
|
151
|
+
.join('\n\n')
|
|
152
|
+
: '';
|
|
153
|
+
void copyWithNotice(this.copy, text);
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
public handleMouse(event: TuiMouseEvent): TuiMouseEventResult | undefined {
|
|
158
|
+
if (event.type !== 'wheel') return undefined;
|
|
159
|
+
if (this.navigator.moveBy(event.wheelDelta ?? 0)) this.cache.clear();
|
|
160
|
+
return { handled: true };
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
private canTogglePercentBasis(): boolean {
|
|
164
|
+
return (this.usage.reported?.contextWindow ?? 0) > 0 || this.usage.estimatedTokens > 0;
|
|
139
165
|
}
|
|
140
166
|
|
|
141
167
|
/** Apply semantic movement in the category list, or open a preview layer. */
|
|
@@ -277,7 +303,7 @@ export class UsageView implements ModalTab {
|
|
|
277
303
|
const viewport = calculateViewport(this.legendRows.length, rows, headerLineCount);
|
|
278
304
|
this.navigator.setVisibleCount(viewport.visibleCount);
|
|
279
305
|
|
|
280
|
-
const heading = theme.fg('mdHeading', theme.bold(
|
|
306
|
+
const heading = theme.fg('mdHeading', theme.bold(`Category (% of ${this.percentBasis}):`));
|
|
281
307
|
const rowWidth = Math.max(1, width - CURSOR_COLUMN_WIDTH);
|
|
282
308
|
const columns = this.legendColumns(rowWidth);
|
|
283
309
|
const visibleRows: string[] = [];
|
|
@@ -314,8 +340,8 @@ export class UsageView implements ModalTab {
|
|
|
314
340
|
if (reported === undefined) return this.theme.fg('muted', 'Context usage unavailable.');
|
|
315
341
|
const contextWindow = formatTokens(reported.contextWindow);
|
|
316
342
|
if (reported.tokens === undefined) {
|
|
317
|
-
const percent = formatPercent(this.usage.estimatedTokens / reported.contextWindow);
|
|
318
|
-
return this.theme.fg('text', `≈${formatTokens(this.usage.estimatedTokens)}/${contextWindow}
|
|
343
|
+
const percent = reported.contextWindow > 0 ? ` (${formatPercent(this.usage.estimatedTokens / reported.contextWindow)})` : '';
|
|
344
|
+
return this.theme.fg('text', `≈${formatTokens(this.usage.estimatedTokens)}/${contextWindow}${percent}`);
|
|
319
345
|
}
|
|
320
346
|
const percent = reported.percent === undefined ? '' : ` (${formatPercent(reported.percent / 100)})`;
|
|
321
347
|
return this.theme.fg('text', `${formatTokens(reported.tokens)}/${contextWindow}${percent}`);
|
|
@@ -354,7 +380,7 @@ export class UsageView implements ModalTab {
|
|
|
354
380
|
const rows = this.legendRows;
|
|
355
381
|
const labelWidth = Math.max(1, ...rows.map(row => this.plainLegendLabel(row).length));
|
|
356
382
|
const tokenWidth = Math.max(1, ...rows.map(row => formatTokens(legendTokens(row)).length));
|
|
357
|
-
const percentWidth = Math.max(0, ...rows.map(row => this.
|
|
383
|
+
const percentWidth = Math.max(0, ...rows.map(row => this.legendPercent(row).length));
|
|
358
384
|
const rightWidth = tokenWidth + (percentWidth > 0 ? LEGEND_VALUE_GAP + percentWidth : 0);
|
|
359
385
|
const idealValue = Math.min(MAX_LEGEND_VALUE_COLUMN, labelWidth + LEGEND_LEADER_GAP);
|
|
360
386
|
return {
|
|
@@ -371,7 +397,7 @@ export class UsageView implements ModalTab {
|
|
|
371
397
|
const tokens = formatTokens(legendTokens(row));
|
|
372
398
|
const valueColor = selected ? 'accent' : row.type === 'category' && row.depth > 1 ? 'dim' : 'muted';
|
|
373
399
|
const tokenPadding = ' '.repeat(Math.max(0, columns.tokenWidth - tokens.length));
|
|
374
|
-
const percent = this.
|
|
400
|
+
const percent = this.legendPercent(row);
|
|
375
401
|
const percentPart = percent === '' ? '' : `${' '.repeat(LEGEND_VALUE_GAP)}${this.theme.fg(selected ? 'accent' : 'dim', percent)}`;
|
|
376
402
|
return fitLine(`${left}${leader}${this.theme.fg(valueColor, tokens)}${tokenPadding}${percentPart}`, width);
|
|
377
403
|
}
|
|
@@ -406,10 +432,15 @@ export class UsageView implements ModalTab {
|
|
|
406
432
|
}
|
|
407
433
|
|
|
408
434
|
/** Percentage text used by the independently aligned rightmost column. */
|
|
435
|
+
private legendPercent(row: LegendRow): string {
|
|
436
|
+
if (this.percentBasis === 'used' && row.type !== 'category') return '';
|
|
437
|
+
return this.plainLegendPercent(legendTokens(row));
|
|
438
|
+
}
|
|
439
|
+
|
|
409
440
|
private plainLegendPercent(tokens: number): string {
|
|
410
|
-
const
|
|
411
|
-
if (
|
|
412
|
-
return formatPercent(tokens /
|
|
441
|
+
const denominator = this.percentBasis === 'window' ? this.usage.reported?.contextWindow : this.usage.estimatedTokens;
|
|
442
|
+
if (denominator === undefined || denominator <= 0) return '';
|
|
443
|
+
return formatPercent(tokens / denominator);
|
|
413
444
|
}
|
|
414
445
|
|
|
415
446
|
/** Colored occupied/partial/buffer/free glyph for one map cell. */
|
|
@@ -434,6 +465,7 @@ export class UsageView implements ModalTab {
|
|
|
434
465
|
title: () => this.theme.fg('accent', this.theme.bold(normalizeInlineText(row.category.label))),
|
|
435
466
|
meta: () => this.theme.fg('muted', `${formatTokens(row.category.tokens)}${percent === '' ? '' : ` · ${percent}`}`),
|
|
436
467
|
entries,
|
|
468
|
+
copy: this.copy,
|
|
437
469
|
entryHeader: entry => this.entryHeader(entry),
|
|
438
470
|
entryBody: (entry, width) => this.entryContentLines(entry, Math.max(10, width - BODY_INDENT.length * 2 - 1), compactSkills),
|
|
439
471
|
description: (width, height) => this.previewDescriptionLines(width, height, row, entries),
|
|
@@ -446,13 +478,14 @@ export class UsageView implements ModalTab {
|
|
|
446
478
|
private openFullContent(row: CategoryLegendRow, entry: UsagePreviewEntry, compactSkills: boolean): void {
|
|
447
479
|
const breadcrumb = entry.breadcrumb.map(normalizeInlineText).filter(Boolean).join(' / ');
|
|
448
480
|
this.context?.pushLayer(
|
|
449
|
-
new
|
|
481
|
+
new SearchablePreview(this.theme, {
|
|
450
482
|
title: () => this.theme.fg('accent', this.theme.bold(breadcrumb || normalizeInlineText(row.category.label))),
|
|
451
483
|
meta: () => this.theme.fg('muted', formatTokens(entry.tokens)),
|
|
452
484
|
// Match the block stream's two-column selection gutter so its hidden-line count stays exact.
|
|
453
485
|
body: width => this.entryContentLines(entry, Math.max(10, width - BODY_INDENT.length * 2 - 3), compactSkills),
|
|
454
486
|
description: (width, height) => this.fullContentLegendLines(width, height, entry, compactSkills),
|
|
455
|
-
|
|
487
|
+
copy: this.copy,
|
|
488
|
+
copyText: () => entry.text,
|
|
456
489
|
}),
|
|
457
490
|
);
|
|
458
491
|
}
|
|
@@ -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+
|
|
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
|
|
package/src/libs/modal/README.md
CHANGED
|
@@ -55,6 +55,7 @@ That's the whole job. The shell gives you: Esc-to-cancel, `↑↓`/PgUp/PgDn via
|
|
|
55
55
|
└──────────────────────────────────────────────┘
|
|
56
56
|
|
|
57
57
|
Input routing (first match wins):
|
|
58
|
+
0. capturesInput() is true → raw key to top layer, else active tab
|
|
58
59
|
1. Tab / Shift+Tab → cycle tabs (wraps; scheme resets)
|
|
59
60
|
2. navigation scheme → semantic action:
|
|
60
61
|
dismiss → pop active tab's top layer, else cancel dialog
|
|
@@ -86,9 +87,10 @@ Wire every dialog's `onComplete` to the same host `done` callback and choose its
|
|
|
86
87
|
`cancelValue`. Section state survives switches, and natural height follows the
|
|
87
88
|
active section. `onActivate` runs once per section, including the initial section.
|
|
88
89
|
|
|
89
|
-
Input routing: `Ctrl+
|
|
90
|
-
(both wrap); all other input goes to the active dialog.
|
|
91
|
-
|
|
90
|
+
Input routing: `Ctrl+L` goes forward and disambiguated `Ctrl+H` goes backward
|
|
91
|
+
(both wrap); all other input goes to the active dialog. A raw `0x08` byte is always
|
|
92
|
+
Backspace for the active dialog, so `Ctrl+H` needs a terminal that reports it
|
|
93
|
+
distinctly. Bare Esc always dismisses through that dialog (layers close first).
|
|
92
94
|
Tab/Shift+Tab stay inside the section. Switching clears pending navigation chords.
|
|
93
95
|
Only the active dialog receives focus. Multiple sections add a footer hint.
|
|
94
96
|
|
|
@@ -214,11 +216,14 @@ await presentModal(ctx.ui, layout, (tui, theme, keybindings, done, frame) =>
|
|
|
214
216
|
|
|
215
217
|
## Behavior contract (what users can rely on)
|
|
216
218
|
|
|
219
|
+
- **Input capture** — tabs and layers may implement `capturesInput?(): boolean`. While true, all raw keys (including Tab, j, q and Esc) go directly to that target's `handleInput`, before tab cycling or scheme mapping. Only its own `hints()` appear in the footer; it owns confirmation/cancellation and releasing capture.
|
|
220
|
+
- **Mouse** — optional `handleMouse(event: TuiMouseEvent): TuiMouseEventResult | undefined` receives pi-tui normalized events on the top layer, otherwise the active tab. The shell returns the result unchanged; a layer without a handler does not fall through to its tab. Wheel consumers use the host's `wheelDelta` without rescaling and return `{ handled: true }`.
|
|
221
|
+
- **Transient notices** — `dialog.showNotice(text, tone, ttlMs)` replaces the footer hint line without adding height. `ModalNoticeTone` is `'success' | 'warning' | 'error'`. The newest notice wins; expiry restores hints and requests a render. These are independent of the persistent `notices` option above the content.
|
|
217
222
|
- **Esc/q** closes the top preview layer first, then the dialog (`onComplete(cancelValue)`).
|
|
218
|
-
- **Tab / Shift+Tab** cycles tabs even while a preview is open; every tab keeps its selection, scroll, zoom, and open layers.
|
|
223
|
+
- **Tab / Shift+Tab** cycles tabs unless the active target captures input, even while a preview is open; every tab keeps its selection, scroll, zoom, and open layers.
|
|
219
224
|
- **Tab labels are live** — return counts from a closure and the strip updates on the next render.
|
|
220
225
|
- **`gg` chords never leak** across tab switches or layer push/pop (shell calls `scheme.reset()`).
|
|
221
|
-
- **
|
|
226
|
+
- **Shared filter + Vim don't mix** — the shell-level `filter` is for picker schemes. A view-owned temporary filter/search prompt can use `capturesInput()` with Vim navigation, releasing capture when editing ends.
|
|
222
227
|
- **Height 'half'** bounds the whole dialog to `floor(terminal.rows / 2)` lines including frame; tabs must render exactly the `height` they're given.
|
|
223
228
|
|
|
224
229
|
## API reference
|
|
@@ -243,7 +248,9 @@ await presentModal(ctx.ui, layout, (tui, theme, keybindings, done, frame) =>
|
|
|
243
248
|
|
|
244
249
|
`extraHints?: Hint[] | (() => Hint[])` inserts footer hints before Esc.
|
|
245
250
|
|
|
246
|
-
|
|
251
|
+
`PreviewLayer` exposes protected `scroller`, `theme`, and `options` for specialized subclasses; its default keyboard-only scrolling behavior is unchanged. Subclasses or wrappers can implement input capture and normalized mouse handling.
|
|
252
|
+
|
|
253
|
+
Methods: `showNotice(text, tone, ttlMs)`, `handleMouse(event)`, `complete(result)`, `setExtraHints(hints)`, `resetNavigation()`, `handleInput(data)`, `render(width)`, `invalidate()`, `focused`, `activeTab`, `activeIndex`.
|
|
247
254
|
|
|
248
255
|
### `ListTab<T>` options
|
|
249
256
|
|
|
@@ -8,15 +8,15 @@ The library is self-contained: it imports only from Pi host packages (`@earendil
|
|
|
8
8
|
|
|
9
9
|
## Module Roles
|
|
10
10
|
|
|
11
|
-
- `types.ts` — Contracts: `NavigationAction`/`NavigationResult`/`NavigationScheme` (pure key→action mappers), `ModalTab` (content strategy), `ModalLayer`, `ModalTabContext` (`pushLayer`), `Hint`.
|
|
12
|
-
- `modal-dialog.ts` — `ModalDialog<TResult>` shell (`Component + Focusable`). Options: tabs, initial tab, navigation scheme (default `PiKeybindingsScheme`), frame (`inline` rules | `bordered` rounded border | `none` embedded content), height (`auto` | `half` terminal), title, notices (+ cap), filter, cancel value, completion callback. Routes input: tab cycling (`Tab`/`Shift+Tab`, wrapping, scheme reset) → scheme action (`dismiss` pops the active tab's layer stack or completes with the cancel value; other actions go to the top layer, else active tab) → raw keys (top layer, else filter input, else active tab). Renders frame, strip, notices, filter slot, content region (exact height when bounded), and a footer composed of scheme + tab/layer hints + universal hints. `complete(result)` resolves explicit results (for example selections). `extraHints`/`setExtraHints` insert footer hints before Esc; `resetNavigation()` clears pending chords.
|
|
11
|
+
- `types.ts` — Contracts: `NavigationAction`/`NavigationResult`/`NavigationScheme` (pure key→action mappers), `ModalTab` (content strategy), `ModalLayer`, `ModalTabContext` (`pushLayer`), `Hint`, and notice tones. Tabs/layers may implement `capturesInput()` and `handleMouse(event)`.
|
|
12
|
+
- `modal-dialog.ts` — `ModalDialog<TResult>` shell (`Component + Focusable`). Options: tabs, initial tab, navigation scheme (default `PiKeybindingsScheme`), frame (`inline` rules | `bordered` rounded border | `none` embedded content), height (`auto` | `half` terminal), title, notices (+ cap), filter, cancel value, completion callback. Routes input: raw input to the top layer (otherwise active tab) when `capturesInput()` is true, before tab cycling (`Tab`/`Shift+Tab`, wrapping, scheme reset) → scheme action (`dismiss` pops the active tab's layer stack or completes with the cancel value; other actions go to the top layer, else active tab) → raw keys (top layer, else filter input, else active tab). Renders frame, strip, notices, filter slot, content region (exact height when bounded), and a footer composed of scheme + tab/layer hints + universal hints. `complete(result)` resolves explicit results (for example selections). `extraHints`/`setExtraHints` insert footer hints before Esc; `resetNavigation()` clears pending chords. While input is captured, the target's own hints replace normal navigation hints. `handleMouse` forwards normalized Pi mouse events to the same target's optional handler, returning its result or `undefined`; it does not parse mouse escape sequences. `showNotice(text, tone, ttlMs)` temporarily replaces the footer hint line without changing height; a generation counter and expiry render request ensure only the latest notice survives.
|
|
13
13
|
- `presenter.ts` — `presentModal<TResult>` and `ModalLayout`: host-facing presenter that maps semantic inline/overlay layouts to the renderer frame and Pi custom-UI mounting options (centered 85%-width overlay with one-cell margin).
|
|
14
14
|
- `navigation/pi-scheme.ts` — `PiKeybindingsScheme`: maps host `tui.select.*` keybindings to actions (default scheme; stateless).
|
|
15
15
|
- `navigation/vim-scheme.ts` — `VimNavigationScheme`: `j/k`/arrows, `Ctrl+u/d`, `gg/G` chord (cleared by `reset()`), Enter confirm, Esc/`q` dismiss; swallows PageUp/PageDown/Home/End. For read-only inspectors; do not combine with a filter input.
|
|
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
|
-
- `preview-layer.ts` — `PreviewLayer`: title + right-aligned meta header, `PreviewScroller`-windowed body, overflow counter, optional pinned description; dismissal is shell-owned (pops the layer).
|
|
17
|
+
- `preview-layer.ts` — `PreviewLayer`: optional normalized wheel handling via `handleMouse`/`wheelDelta`, 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+
|
|
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.
|
|
@@ -28,11 +28,11 @@ The library is self-contained: it imports only from Pi host packages (`@earendil
|
|
|
28
28
|
|
|
29
29
|
1. An extension builds `ModalTab`s (commonly `ListTab`, or custom tabs using `ListNavigator`/`PreviewLayer`/`RenderCache`) and calls `presentModal` with a semantic layout. The presenter supplies the resolved frame and host mounting options while the extension constructs `ModalDialog` with its own height/scheme/filter options plus `cancelValue`/`onComplete`.
|
|
30
30
|
2. The shell attaches a `ModalTabContext` to each tab (for `pushLayer`) and applies any initial filter query.
|
|
31
|
-
3. The host (`ctx.ui.custom`) drives `render(width)` and `
|
|
31
|
+
3. The host (`ctx.ui.custom`) drives `render(width)`, `handleInput(data)`, and normalized `handleMouse(event)`; the shell routes input per the order above and calls `tui.requestRender()` after input.
|
|
32
32
|
4. Confirm flows: scheme `confirm` → tab `handleNavigation` → tab's confirm callback → `dialog.complete(value)`. Dismissal pops the active tab's top layer first, then completes with the cancel value.
|
|
33
33
|
|
|
34
34
|
## Integration Points
|
|
35
35
|
|
|
36
|
-
- **Consumers**: `src/extensions/model-select/model-select-dialog.ts` (three `ListTab` sections, filter slot, both frame styles, wrap selection) and `src/extensions/context-view/ui/context-view-dialog.ts` (Vim scheme, half-height, notices; custom `UsageView`/`InjectionsView` tabs with
|
|
36
|
+
- **Consumers**: `src/extensions/model-select/model-select-dialog.ts` (three `ListTab` sections, filter slot, both frame styles, wrap selection) and `src/extensions/context-view/ui/context-view-dialog.ts` (Vim scheme, half-height, notices; custom `UsageView`/`InjectionsView` tabs with input-capturing filter/search targets and copy-result footer notices).
|
|
37
37
|
- **Host packages**: `pi-tui` (`Component`, `Focusable`, `Input`, `Key`, `matchesKey`, `fuzzyFilter`, width helpers), `pi-coding-agent` types (`ExtensionUIContext`, `Theme`, `KeybindingsManager`).
|
|
38
38
|
- **Tests**: `test/modal/` (schemes, shell behavior, self-containment audit).
|
package/src/libs/modal/index.ts
CHANGED
|
@@ -29,4 +29,4 @@ export {
|
|
|
29
29
|
type Viewport,
|
|
30
30
|
wrapDescriptionLines,
|
|
31
31
|
} from './text';
|
|
32
|
-
export type { Hint, ModalLayer, ModalTab, ModalTabContext, NavigationAction, NavigationResult, NavigationScheme } from './types';
|
|
32
|
+
export type { Hint, ModalLayer, ModalNoticeTone, ModalTab, ModalTabContext, NavigationAction, NavigationResult, NavigationScheme } from './types';
|
|
@@ -5,6 +5,7 @@
|
|
|
5
5
|
* implement content. See `types.ts` for the tab/layer/scheme contracts.
|
|
6
6
|
*
|
|
7
7
|
* Input routing order:
|
|
8
|
+
* 0. A capturing content target receives raw input directly.
|
|
8
9
|
* 1. Tab/Shift+Tab cycles tabs (wrapping, scheme reset).
|
|
9
10
|
* 2. The navigation scheme maps a key to a semantic action; `dismiss` pops
|
|
10
11
|
* the active tab's top layer, or completes the dialog with the cancel
|
|
@@ -14,11 +15,20 @@
|
|
|
14
15
|
* the active tab.
|
|
15
16
|
*/
|
|
16
17
|
import type { KeybindingsManager, Theme } from '@earendil-works/pi-coding-agent';
|
|
17
|
-
import {
|
|
18
|
+
import {
|
|
19
|
+
type Component,
|
|
20
|
+
type Focusable,
|
|
21
|
+
Input,
|
|
22
|
+
Key,
|
|
23
|
+
matchesKey,
|
|
24
|
+
type TUI,
|
|
25
|
+
type TuiMouseEvent,
|
|
26
|
+
type TuiMouseEventResult,
|
|
27
|
+
} from '@earendil-works/pi-tui';
|
|
18
28
|
import { PiKeybindingsScheme } from './navigation/pi-scheme';
|
|
19
29
|
import { renderTabStrip } from './tab-strip';
|
|
20
30
|
import { fitToTerminalHeight, hintRow, normalizeTerminalRows, padLine, singleLine } from './text';
|
|
21
|
-
import type { Hint, ModalLayer, ModalTab, NavigationScheme } from './types';
|
|
31
|
+
import type { Hint, ModalLayer, ModalNoticeTone, ModalTab, NavigationScheme } from './types';
|
|
22
32
|
|
|
23
33
|
/** Framing style: inline rules, or a rounded border for host-centered overlays. */
|
|
24
34
|
export type ModalFrame = 'inline' | 'bordered' | 'none';
|
|
@@ -61,6 +71,9 @@ export class ModalDialog<TResult> implements Component, Focusable {
|
|
|
61
71
|
private readonly layerStacks = new Map<ModalTab, ModalLayer[]>();
|
|
62
72
|
private activeTabIndex: number;
|
|
63
73
|
private _focused = false;
|
|
74
|
+
private notice: { text: string; tone: ModalNoticeTone } | undefined;
|
|
75
|
+
private noticeGeneration = 0;
|
|
76
|
+
private noticeTimer: ReturnType<typeof setTimeout> | undefined;
|
|
64
77
|
private extraHints: Hint[] | (() => Hint[]);
|
|
65
78
|
|
|
66
79
|
public constructor(
|
|
@@ -130,7 +143,33 @@ export class ModalDialog<TResult> implements Component, Focusable {
|
|
|
130
143
|
this.scheme.reset();
|
|
131
144
|
}
|
|
132
145
|
|
|
146
|
+
/** Replace the footer hints temporarily without changing the dialog height. */
|
|
147
|
+
public showNotice(text: string, tone: ModalNoticeTone, ttlMs: number): void {
|
|
148
|
+
const generation = ++this.noticeGeneration;
|
|
149
|
+
clearTimeout(this.noticeTimer);
|
|
150
|
+
this.notice = { text, tone };
|
|
151
|
+
this.noticeTimer = setTimeout(() => {
|
|
152
|
+
if (generation !== this.noticeGeneration) return;
|
|
153
|
+
this.notice = undefined;
|
|
154
|
+
this.noticeTimer = undefined;
|
|
155
|
+
this.tui.requestRender();
|
|
156
|
+
}, ttlMs);
|
|
157
|
+
this.noticeTimer.unref?.();
|
|
158
|
+
this.tui.requestRender();
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
public handleMouse(event: TuiMouseEvent): TuiMouseEventResult | undefined {
|
|
162
|
+
return this.content().handleMouse?.(event);
|
|
163
|
+
}
|
|
164
|
+
|
|
133
165
|
public handleInput(data: string): void {
|
|
166
|
+
const target = this.content();
|
|
167
|
+
if (target.capturesInput?.()) {
|
|
168
|
+
this.scheme.reset();
|
|
169
|
+
target.handleInput(data);
|
|
170
|
+
this.tui.requestRender();
|
|
171
|
+
return;
|
|
172
|
+
}
|
|
134
173
|
if (this.options.tabs.length > 1) {
|
|
135
174
|
if (matchesKey(data, Key.shift('tab'))) {
|
|
136
175
|
this.switchTab(-1);
|
|
@@ -266,7 +305,8 @@ export class ModalDialog<TResult> implements Component, Focusable {
|
|
|
266
305
|
}
|
|
267
306
|
lines.push(...content, '');
|
|
268
307
|
|
|
269
|
-
|
|
308
|
+
const footer = this.notice === undefined ? hintRow(this.theme, this.footerHints()) : this.theme.fg(this.notice.tone, this.notice.text);
|
|
309
|
+
lines.push(singleLine(footer, width));
|
|
270
310
|
return lines;
|
|
271
311
|
}
|
|
272
312
|
|
|
@@ -302,6 +342,7 @@ export class ModalDialog<TResult> implements Component, Focusable {
|
|
|
302
342
|
private footerHints(): Hint[] {
|
|
303
343
|
const layer = this.topLayer();
|
|
304
344
|
const target = layer ?? this.activeTab;
|
|
345
|
+
if (target.capturesInput?.()) return target.hints();
|
|
305
346
|
const hints: Hint[] = [...this.scheme.hints(layer === undefined ? 'Navigate' : 'Scroll'), ...target.hints()];
|
|
306
347
|
if (this.options.tabs.length > 1) hints.push(['Tab', 'Switch']);
|
|
307
348
|
hints.push(...(typeof this.extraHints === 'function' ? this.extraHints() : this.extraHints));
|
|
@@ -23,11 +23,11 @@ export interface PreviewLayerOptions {
|
|
|
23
23
|
}
|
|
24
24
|
|
|
25
25
|
export class PreviewLayer implements ModalLayer {
|
|
26
|
-
|
|
26
|
+
protected readonly scroller = new PreviewScroller();
|
|
27
27
|
|
|
28
28
|
public constructor(
|
|
29
|
-
|
|
30
|
-
|
|
29
|
+
protected readonly theme: Theme,
|
|
30
|
+
protected readonly options: PreviewLayerOptions,
|
|
31
31
|
) {}
|
|
32
32
|
|
|
33
33
|
public hints(): Hint[] {
|
|
@@ -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([['^
|
|
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 !== '\
|
|
53
|
+
} else if (data !== '\x08' && matchesKey(data, 'ctrl+h')) {
|
|
54
54
|
this.switchSection(-1);
|
|
55
55
|
} else {
|
|
56
56
|
this.activeDialog().handleInput(data);
|
package/src/libs/modal/types.ts
CHANGED
|
@@ -5,6 +5,11 @@
|
|
|
5
5
|
* directory can be copied unchanged into other Pi plugin projects.
|
|
6
6
|
*/
|
|
7
7
|
|
|
8
|
+
import type { TuiMouseEvent, TuiMouseEventResult } from '@earendil-works/pi-tui';
|
|
9
|
+
|
|
10
|
+
/** Tone for a transient footer notice. */
|
|
11
|
+
export type ModalNoticeTone = 'success' | 'warning' | 'error';
|
|
12
|
+
|
|
8
13
|
/** Semantic action produced by a navigation scheme for one key press. */
|
|
9
14
|
export type NavigationAction = 'step-back' | 'step-forward' | 'page-back' | 'page-forward' | 'first' | 'last' | 'confirm' | 'dismiss';
|
|
10
15
|
|
|
@@ -31,6 +36,9 @@ export interface NavigationScheme {
|
|
|
31
36
|
export interface ModalLayer {
|
|
32
37
|
render(width: number, height: number | undefined): string[];
|
|
33
38
|
handleInput(data: string): void;
|
|
39
|
+
/** Own raw keyboard input before tab cycling and navigation mapping. */
|
|
40
|
+
capturesInput?(): boolean;
|
|
41
|
+
handleMouse?(event: TuiMouseEvent): TuiMouseEventResult | undefined;
|
|
34
42
|
handleNavigation(action: NavigationAction): void;
|
|
35
43
|
hints(): Hint[];
|
|
36
44
|
invalidate?(): void;
|
|
@@ -56,6 +64,9 @@ export interface ModalTab {
|
|
|
56
64
|
render(width: number, height: number | undefined): string[];
|
|
57
65
|
/** Raw keys the navigation scheme did not handle. */
|
|
58
66
|
handleInput(data: string): void;
|
|
67
|
+
/** Own raw keyboard input before tab cycling and navigation mapping. */
|
|
68
|
+
capturesInput?(): boolean;
|
|
69
|
+
handleMouse?(event: TuiMouseEvent): TuiMouseEventResult | undefined;
|
|
59
70
|
/** Semantic navigation; never includes `dismiss`. */
|
|
60
71
|
handleNavigation(action: NavigationAction): void;
|
|
61
72
|
/** Re-filter content when the dialog owns a shared filter input. */
|
|
@@ -2,15 +2,16 @@
|
|
|
2
2
|
|
|
3
3
|
## Responsibility
|
|
4
4
|
|
|
5
|
-
Shared subscription data pipeline for Claude and
|
|
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`:
|
|
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
|
|
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
|
-
//
|
|
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>;
|