@0xkahi/pi-qol 0.0.5 → 0.1.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 +40 -13
- package/assets/config.schema.json +44 -0
- package/package.json +2 -1
- package/src/codemap.md +3 -3
- package/src/extensions/codemap.md +3 -2
- package/src/extensions/custom-footer/codemap.md +11 -8
- package/src/extensions/custom-footer/footer-component.ts +3 -3
- package/src/extensions/custom-footer/token-stats.ts +6 -5
- package/src/extensions/model-select/codemap.md +21 -15
- package/src/extensions/model-select/index.ts +4 -1
- package/src/extensions/model-select/model-lists.ts +10 -2
- package/src/extensions/model-select/model-select-dialog.ts +176 -141
- package/src/extensions/model-select/types.ts +11 -2
- package/src/schemas/codemap.md +4 -4
- package/src/schemas/config.schema.ts +3 -0
- package/src/schemas/model-select.config.schema.ts +34 -3
- package/src/utils/codemap.md +8 -15
- package/src/utils/crayon.util.ts +0 -58
package/README.md
CHANGED
|
@@ -37,11 +37,13 @@ never blocks your turn.
|
|
|
37
37
|
|
|
38
38
|
### `model_select`
|
|
39
39
|
|
|
40
|
-
Adds `/select-model`, an interactive model picker with fuzzy search,
|
|
41
|
-
provider filtering, and inline or overlay layouts
|
|
40
|
+
Adds `/select-model`, an interactive model picker with fuzzy search, permanent
|
|
41
|
+
Favourites, ordered custom group tabs, provider filtering, and inline or overlay layouts.
|
|
42
42
|
|
|
43
|
-
- **quick access** to listed favourite models
|
|
44
|
-
- **filtering**
|
|
43
|
+
- **quick access** to listed favourite models and user-defined favourite subsets
|
|
44
|
+
- **shared filtering** across Favourites, group, and Search tabs
|
|
45
|
+
- **bidirectional tab navigation** with Tab and Shift+Tab
|
|
46
|
+
- **provider filtering** for Search without removing models from favourite tabs
|
|
45
47
|
|
|
46
48
|
allow keybindings with [pi-vim-keys](https://github.com/0xKahi/pi-vim-keys) with eventId of `pi.vimKeys.event:pi-qol.model_select`
|
|
47
49
|
|
|
@@ -95,8 +97,17 @@ them (project overrides global):
|
|
|
95
97
|
"model_select": {
|
|
96
98
|
"enabled": true,
|
|
97
99
|
"layout": "overlay",
|
|
100
|
+
"favourite_label": "Pinned",
|
|
98
101
|
"provider_filter": ["anthropic", "openai"],
|
|
99
|
-
"
|
|
102
|
+
"groups": ["work", "fast"],
|
|
103
|
+
"favourite": [
|
|
104
|
+
{
|
|
105
|
+
"provider": "anthropic",
|
|
106
|
+
"modelId": "claude-sonnet-4-5",
|
|
107
|
+
"groups": ["work", "fast"]
|
|
108
|
+
}
|
|
109
|
+
],
|
|
110
|
+
"hide_tabs": { "groups": false, "search": false }
|
|
100
111
|
},
|
|
101
112
|
"custom_footer": {
|
|
102
113
|
"enabled": true,
|
|
@@ -136,12 +147,24 @@ falls back to the active session model and surfaces a warning notification.
|
|
|
136
147
|
|
|
137
148
|
#### `model_select`
|
|
138
149
|
|
|
139
|
-
| Key
|
|
140
|
-
|
|
|
141
|
-
| `enabled`
|
|
142
|
-
| `layout`
|
|
143
|
-
| `
|
|
144
|
-
| `
|
|
150
|
+
| Key | Type | Default | Description |
|
|
151
|
+
| ---------------------- | ---------- | -------- | --------------------------------------------------------- |
|
|
152
|
+
| `enabled` | `boolean` | `false` | Turn the model picker on. |
|
|
153
|
+
| `layout` | `enum` | `inline` | Picker layout: `inline` or `overlay`. |
|
|
154
|
+
| `favourite_label` | `string` | `Favourites` | Non-empty label for the permanent first tab. |
|
|
155
|
+
| `provider_filter` | `string[]` | `[]` | Restrict Search models to these providers; favourite tabs are unaffected. |
|
|
156
|
+
| `groups` | `string[]` | `[]` | Ordered custom group tabs. Exact duplicate names use their first occurrence. |
|
|
157
|
+
| `favourite` | `object[]` | `[]` | Favourite models (`provider`, `modelId`, optional `groups`). |
|
|
158
|
+
| `favourite[].groups` | `string[]` | `[]` | Exact, case-sensitive group memberships for a favourite. Unknown names are ignored. |
|
|
159
|
+
| `hide_tabs.groups` | `boolean` | `false` | Hide all custom group tabs. |
|
|
160
|
+
| `hide_tabs.search` | `boolean` | `false` | Hide the Search tab. Favourites cannot be hidden. |
|
|
161
|
+
|
|
162
|
+
The favourites tab is always first, even when empty, and uses `favourite_label`
|
|
163
|
+
as its display label. Unique groups follow in configured order, and Search is
|
|
164
|
+
last when visible. Use Tab to cycle forward and Shift+Tab to cycle backward
|
|
165
|
+
through visible tabs. A favourite can belong to multiple groups; group tabs
|
|
166
|
+
contain only resolved, authenticated favourites and preserve favourite order.
|
|
167
|
+
Duplicate favourite declarations remain first-entry-wins.
|
|
145
168
|
|
|
146
169
|
#### `custom_footer`
|
|
147
170
|
|
|
@@ -160,8 +183,12 @@ falls back to the active session model and surfaces a warning notification.
|
|
|
160
183
|
| `icons.cacheWrite` | `string` | nerd font | Glyph for cache-write tokens. |
|
|
161
184
|
| `icons.refresh` | `string` | nerd font | Glyph shown before the subscription reset time. |
|
|
162
185
|
|
|
163
|
-
Project config shallow-merges each top-level section over global config.
|
|
164
|
-
|
|
186
|
+
Project config shallow-merges each top-level section over global config. Arrays
|
|
187
|
+
replace lower-precedence arrays, so project `model_select.favourite` or
|
|
188
|
+
`model_select.groups` replaces the corresponding global array. Nested objects are
|
|
189
|
+
also replaced as values during that section merge; for example, a project
|
|
190
|
+
`hide_tabs` object replaces the global one, then omitted `groups` or `search`
|
|
191
|
+
fields receive their default of `false`.
|
|
165
192
|
|
|
166
193
|
## How it works
|
|
167
194
|
|
|
@@ -51,6 +51,12 @@
|
|
|
51
51
|
"default": {
|
|
52
52
|
"enabled": false,
|
|
53
53
|
"favourite": [],
|
|
54
|
+
"favourite_label": "Favourites",
|
|
55
|
+
"groups": [],
|
|
56
|
+
"hide_tabs": {
|
|
57
|
+
"groups": false,
|
|
58
|
+
"search": false
|
|
59
|
+
},
|
|
54
60
|
"provider_filter": [],
|
|
55
61
|
"layout": "inline"
|
|
56
62
|
},
|
|
@@ -71,6 +77,14 @@
|
|
|
71
77
|
},
|
|
72
78
|
"modelId": {
|
|
73
79
|
"type": "string"
|
|
80
|
+
},
|
|
81
|
+
"groups": {
|
|
82
|
+
"default": [],
|
|
83
|
+
"type": "array",
|
|
84
|
+
"items": {
|
|
85
|
+
"type": "string",
|
|
86
|
+
"minLength": 1
|
|
87
|
+
}
|
|
74
88
|
}
|
|
75
89
|
},
|
|
76
90
|
"required": [
|
|
@@ -79,6 +93,36 @@
|
|
|
79
93
|
]
|
|
80
94
|
}
|
|
81
95
|
},
|
|
96
|
+
"favourite_label": {
|
|
97
|
+
"default": "Favourites",
|
|
98
|
+
"type": "string",
|
|
99
|
+
"minLength": 1
|
|
100
|
+
},
|
|
101
|
+
"groups": {
|
|
102
|
+
"default": [],
|
|
103
|
+
"type": "array",
|
|
104
|
+
"items": {
|
|
105
|
+
"type": "string",
|
|
106
|
+
"minLength": 1
|
|
107
|
+
}
|
|
108
|
+
},
|
|
109
|
+
"hide_tabs": {
|
|
110
|
+
"default": {
|
|
111
|
+
"groups": false,
|
|
112
|
+
"search": false
|
|
113
|
+
},
|
|
114
|
+
"type": "object",
|
|
115
|
+
"properties": {
|
|
116
|
+
"groups": {
|
|
117
|
+
"default": false,
|
|
118
|
+
"type": "boolean"
|
|
119
|
+
},
|
|
120
|
+
"search": {
|
|
121
|
+
"default": false,
|
|
122
|
+
"type": "boolean"
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
},
|
|
82
126
|
"provider_filter": {
|
|
83
127
|
"default": [],
|
|
84
128
|
"type": "array",
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@0xkahi/pi-qol",
|
|
3
|
-
"version": "0.0
|
|
3
|
+
"version": "0.1.0",
|
|
4
4
|
"description": "quality of life pi extensions",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"keywords": [
|
|
@@ -54,6 +54,7 @@
|
|
|
54
54
|
"typescript": "^5"
|
|
55
55
|
},
|
|
56
56
|
"dependencies": {
|
|
57
|
+
"@0xkahi/cli-dye": "^1.1.0",
|
|
57
58
|
"zod": "^4.4.3"
|
|
58
59
|
}
|
|
59
60
|
}
|
package/src/codemap.md
CHANGED
|
@@ -7,10 +7,10 @@ Top-level source root for `pi-qol`, a Pi coding-agent extension that layers smal
|
|
|
7
7
|
It coordinates three feature modules:
|
|
8
8
|
|
|
9
9
|
- **auto_session_name**: Generates and applies a concise session title from the user's first message before the agent runs.
|
|
10
|
-
- **model_select**: Registers a `/select-model` command (plus a cross-extension event) for picking or searching available models with favourites
|
|
10
|
+
- **model_select**: Registers a `/select-model` command (plus a cross-extension event) for picking or searching available models with favourites, ordered custom groups, provider filtering, and an inline or overlay layout.
|
|
11
11
|
- **custom_footer**: Replaces the default footer with a richer status bar showing cwd/branch/session, token/cost/cache stats, context-window usage, subscription-rate usage, and the current model/thinking level.
|
|
12
12
|
|
|
13
|
-
Shared concerns live here too: extension configuration loading, path resolution, model/auth resolution,
|
|
13
|
+
Shared concerns live here too: extension configuration loading, path resolution, model/auth resolution, and Zod schemas for every feature.
|
|
14
14
|
|
|
15
15
|
## Design Patterns
|
|
16
16
|
|
|
@@ -42,7 +42,7 @@ Shared concerns live here too: extension configuration loading, path resolution,
|
|
|
42
42
|
|
|
43
43
|
4. **model_select** (`extensions/model-select/`)
|
|
44
44
|
- Lazily registers once on `session_start` when enabled.
|
|
45
|
-
- `/select-model [args]` handler refreshes the registry, attempts an exact provider/model match, otherwise opens a custom TUI dialog.
|
|
45
|
+
- `/select-model [args]` handler refreshes the registry, attempts an exact provider/model match, otherwise opens a custom TUI dialog with Favourites, group, and Search tabs.
|
|
46
46
|
- `ModelSelectDialog` filters search items with fuzzy matching, navigates favourites/search sections, and returns the chosen model to `pi.setModel`.
|
|
47
47
|
- `PI_VIM_KEY_EVENT_ID` allows other extensions to trigger the same picker.
|
|
48
48
|
|
|
@@ -7,7 +7,7 @@ This folder contains the feature-level extension modules for `pi-qol`. Each chil
|
|
|
7
7
|
Current features:
|
|
8
8
|
|
|
9
9
|
- `auto-session-name` – automatically generates and applies a concise session title from the user’s first message.
|
|
10
|
-
- `model-select` – provides an interactive `/select-model` command (and cross-extension activation hook) for choosing models from the registry with
|
|
10
|
+
- `model-select` – provides an interactive `/select-model` command (and cross-extension activation hook) for choosing models from the registry with permanent Favourites, ordered custom groups, Search, provider filtering, and inline or overlay layout.
|
|
11
11
|
- `custom-footer` – replaces the TUI footer with a richer status bar showing cwd, git branch, session name, model, token/cost usage, context-window usage, and subscription usage.
|
|
12
12
|
|
|
13
13
|
## Design Patterns
|
|
@@ -39,7 +39,8 @@ Current features:
|
|
|
39
39
|
3. **model-select flow**
|
|
40
40
|
- Lazy-activated once on `session_start` if enabled.
|
|
41
41
|
- Command handler calls `waitForIdle` (when available), refreshes `ctx.modelRegistry`, attempts an exact provider/model match from arguments, then falls back to an interactive `ModelSelectDialog`.
|
|
42
|
-
-
|
|
42
|
+
- List preparation resolves authenticated favourites, derives exact case-sensitive group subsets, and applies provider filtering only to Search.
|
|
43
|
+
- The dialog uses one fuzzy query across dynamically visible Favourites/group/Search tabs, preserves per-tab selection, keeps the active tab represented at narrow widths, and renders in an inline or overlay layout; selection is applied via `pi.setModel`.
|
|
43
44
|
- The event-bus handler captures the latest context so the picker can also be opened without a command context.
|
|
44
45
|
|
|
45
46
|
4. **custom-footer flow**
|
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
|
|
5
5
|
Renders a custom TUI footer that replaces the default agent footer. It displays:
|
|
6
6
|
|
|
7
|
-
- The current working directory, git branch, and session name.
|
|
7
|
+
- The current working directory (with an optional custom color), git branch, and session name.
|
|
8
8
|
- Token usage totals (input/output) for assistant messages in the current session.
|
|
9
9
|
- Cache read/write totals and the latest cache hit rate.
|
|
10
10
|
- Estimated session cost, with a subscription indicator when using OAuth models.
|
|
@@ -23,7 +23,9 @@ The extension is feature-gated by the `custom_footer` config flag and can dynami
|
|
|
23
23
|
- **Data provider abstraction**: `FooterDataProvider` isolates footer-specific data (git branch, extension statuses, provider count, branch-change notifications) from the broader `ExtensionContext`.
|
|
24
24
|
- **Cache manager**: `SubscriptionUsageManager` caches OAuth usage responses with a TTL and coalesces in-flight requests per provider.
|
|
25
25
|
- **Strategy pattern**: Provider-specific OAuth usage fetch strategies (`AnthropicOauthUsageStrategy`, `OpenAiCodexUsageStrategy`) are selected at runtime inside `SubscriptionUsageManager`.
|
|
26
|
-
- **
|
|
26
|
+
- **Provider normalization**: `resolveSupportedProvider` maps provider aliases (`codex`, `openai`, `chatgpt`) to the internal `SupportedProvider` union.
|
|
27
|
+
- **Window selection**: `pickSubscriptionUsageWindow` chooses the rate window with the nearest reset, falling back to the first window when no resets are available.
|
|
28
|
+
- **Pure formatting helpers**: `token-stats.ts` and `progress-bar.ts` contain stateless functions for number formatting, usage aggregation, subscription segment construction, and progress-bar rendering, making them easy to test.
|
|
27
29
|
|
|
28
30
|
## Data & Control Flow
|
|
29
31
|
|
|
@@ -31,13 +33,14 @@ The extension is feature-gated by the `custom_footer` config flag and can dynami
|
|
|
31
33
|
2. **Rendering trigger**: The TUI calls `CustomFooterComponent.render(width)` on every footer repaint.
|
|
32
34
|
3. **Dynamic disable**: If `custom_footer` is disabled at render time, the component calls `ctx.ui.setFooter(undefined)` once and returns an empty array so the default footer is restored.
|
|
33
35
|
4. **Line assembly**: `render` builds up to three lines:
|
|
34
|
-
- `renderPathLine`: directory, branch, session name.
|
|
36
|
+
- `renderPathLine`: directory (with optional custom color), branch, session name.
|
|
35
37
|
- `renderStatsLine`: token/cost/context/subscription stats plus the model name.
|
|
36
38
|
- Extension status line (only when statuses exist).
|
|
37
|
-
5. **
|
|
38
|
-
6. **
|
|
39
|
-
7. **
|
|
40
|
-
8. **
|
|
39
|
+
5. **Usage aggregation**: `calculateUsageTotals` in `token-stats.ts` sums assistant-message token counts and computes the latest cache hit rate from `sessionManager.getEntries()`.
|
|
40
|
+
6. **Stats composition**: `buildStatsLeft` receives the pre-computed totals, display toggles, context usage, context window, subscription segment, and theme; it returns the left-hand stats string.
|
|
41
|
+
7. **Subscription usage**: `renderSubscriptionUsageSegment` resolves the provider, asks `SubscriptionUsageManager.ensureFresh(provider)` for cached data, picks the rate window with the nearest reset via `pickSubscriptionUsageWindow`, and builds a colored progress segment via `buildSubscriptionUsageSegment` in `token-stats.ts`.
|
|
42
|
+
8. **Async refresh**: `SubscriptionUsageManager` fetches usage asynchronously when the cached entry is older than `SUBSCRIPTION_USAGE_TTL_MS`. On success it calls `tui.requestRender()` via the `onUpdate` callback to update the footer.
|
|
43
|
+
9. **Git branch updates**: `footerData.onBranchChange` registers a render request callback that is cleaned up in `dispose`.
|
|
41
44
|
|
|
42
45
|
## Integration Points
|
|
43
46
|
|
|
@@ -45,5 +48,5 @@ The extension is feature-gated by the `custom_footer` config flag and can dynami
|
|
|
45
48
|
- **`@earendil-works/pi-tui`**: Implements the `Component` contract and uses `truncateToWidth`, `visibleWidth`, and `TUI.requestRender`.
|
|
46
49
|
- **`../../config-loader`**: Reads the `custom_footer` feature flag and full footer config (colors, icons, display toggles) via `ConfigLoader`.
|
|
47
50
|
- **`../../schemas/config.schema`**: `CustomFooterConfig` is derived from the `Config` schema's `custom_footer` shape.
|
|
48
|
-
-
|
|
51
|
+
- **`@0xkahi/cli-dye`**: Applies configured truecolor ANSI styling to directory text, model name, subscription usage labels, and progress-bar fill.
|
|
49
52
|
- **`../../libs/subscription-usage/**`**: Delegates OAuth usage fetching and reset formatting to `SubscriptionUsageApi` and provider-specific strategies.
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { basename } from 'node:path';
|
|
2
|
+
import { dye } from '@0xkahi/cli-dye';
|
|
2
3
|
import type { Component } from '@earendil-works/pi-tui';
|
|
3
4
|
import { truncateToWidth, visibleWidth } from '@earendil-works/pi-tui';
|
|
4
|
-
import { crayon } from '../../utils/crayon.util';
|
|
5
5
|
import { pickSubscriptionUsageWindow, resolveSupportedProvider, SubscriptionUsageManager } from './subscription-usage-manager';
|
|
6
6
|
import { buildStatsLeft, buildSubscriptionUsageSegment, calculateUsageTotals } from './token-stats';
|
|
7
7
|
import type { CustomFooterComponentDeps, CustomFooterConfig } from './types';
|
|
@@ -74,7 +74,7 @@ export class CustomFooterComponent implements Component {
|
|
|
74
74
|
|
|
75
75
|
let line: string;
|
|
76
76
|
if (config.colors.directory) {
|
|
77
|
-
line =
|
|
77
|
+
line = dye.colorize(directoryText, { fg: dye.hex(config.colors.directory) });
|
|
78
78
|
if (branch) line += this.deps.theme.fg('dim', ` (${branch})`);
|
|
79
79
|
if (sessionName) line += this.deps.theme.fg('dim', ` • ${sessionName}`);
|
|
80
80
|
} else {
|
|
@@ -140,7 +140,7 @@ export class CustomFooterComponent implements Component {
|
|
|
140
140
|
const model = this.deps.ctx.model;
|
|
141
141
|
const modelName = model?.id ?? 'no-model';
|
|
142
142
|
const modelNameSegment = config.colors.modelName
|
|
143
|
-
?
|
|
143
|
+
? dye.colorize(modelName, { fg: dye.hex(config.colors.modelName) })
|
|
144
144
|
: this.deps.theme.fg('dim', modelName);
|
|
145
145
|
|
|
146
146
|
if (!model?.reasoning) return modelNameSegment;
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
+
import { dye } from '@0xkahi/cli-dye';
|
|
1
2
|
import type { ContextUsage, SessionEntry } from '@earendil-works/pi-coding-agent';
|
|
2
|
-
import { crayon } from '../../utils/crayon.util';
|
|
3
3
|
import { clampPercent, renderProgressBar } from './progress-bar';
|
|
4
4
|
import type { CustomFooterColors, CustomFooterDisplay, CustomFooterIcons, FooterTheme, SupportedProvider, UsageTotals } from './types';
|
|
5
5
|
|
|
@@ -71,14 +71,15 @@ export function buildSubscriptionUsageSegment({
|
|
|
71
71
|
const pct = clampPercent(usage.usedPercent);
|
|
72
72
|
const roundedPercent = Math.round(pct).toString();
|
|
73
73
|
const bar = renderProgressBar(pct);
|
|
74
|
+
const foreground = dye.hex(providerColor);
|
|
74
75
|
|
|
75
76
|
const resetParts = usage.resetDescription ? [icons.refresh, usage.resetDescription].filter(Boolean).join(' ') : '';
|
|
76
77
|
|
|
77
78
|
return [
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
`${
|
|
81
|
-
|
|
79
|
+
dye.colorize(usage.responseLabel, { fg: foreground }),
|
|
80
|
+
dye.colorize(usage.windowLabel, { fg: foreground }),
|
|
81
|
+
`${dye.colorize(bar.filled, { fg: foreground })}${theme.fg('dim', bar.empty)}`,
|
|
82
|
+
dye.colorize(`${roundedPercent}%`, { fg: foreground }),
|
|
82
83
|
resetParts ? theme.fg('dim', resetParts) : undefined,
|
|
83
84
|
]
|
|
84
85
|
.filter((part): part is string => Boolean(part))
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
## Responsibility
|
|
4
4
|
|
|
5
|
-
This extension implements the `/select-model` command and its interactive picker. Its job is to let the user search, browse, and choose a model from the global model registry, optionally constrained by a provider filter and
|
|
5
|
+
This extension implements the `/select-model` command and its interactive picker. Its job is to let the user search, browse, and choose a model from the global model registry, optionally constrained by a provider filter and organized through configured favourites and ordered group tabs. It highlights the currently active model, supports keyboard navigation, and applies the final selection by calling the extension API. It can be triggered both as a user-facing command and programmatically from another extension (e.g., `pi-vim-keys`) via an event-bus hook. The picker can render inline or as a centered overlay, and it surfaces registry errors and favourite configuration warnings inside the UI.
|
|
6
6
|
|
|
7
7
|
## Design Patterns
|
|
8
8
|
|
|
@@ -10,11 +10,13 @@ This extension implements the `/select-model` command and its interactive picker
|
|
|
10
10
|
- **Command + event-bus controller**: `activateModelSelect` registers the `/select-model` command and also listens on a cross-extension event ID so external extensions can open the picker without invoking the command directly.
|
|
11
11
|
- **Context caching for async triggers**: The most recent `ExtensionContext` is stored (`latestCtx`) so the event-bus handler (which receives no context argument) can still open the dialog.
|
|
12
12
|
- **Separation of concerns**:
|
|
13
|
-
- `index.ts`: orchestrates activation, command handling,
|
|
14
|
-
- `model-lists.ts`: queries the registry and prepares favourite
|
|
15
|
-
- `model-formatter.ts`: pure static utilities for labels, descriptions, sorting, and
|
|
16
|
-
- `model-select-dialog.ts`: TUI component that renders
|
|
13
|
+
- `index.ts`: orchestrates activation, command handling, applying the selected model, and bridging registry errors into the dialog.
|
|
14
|
+
- `model-lists.ts`: queries the registry and prepares favourite, grouped favourite, and searchable model lists; validates favourite entries against the registry and configured auth.
|
|
15
|
+
- `model-formatter.ts`: pure static utilities for labels, descriptions, sorting, token formatting, and search-text generation.
|
|
16
|
+
- `model-select-dialog.ts`: TUI component that builds dynamic visible tabs, renders a width-aware tab viewport, and translates user input into selection events.
|
|
17
|
+
- `constants.ts`: command name, cross-extension event ID, and dialog rendering limits.
|
|
17
18
|
- **TUI Component pattern**: `ModelSelectDialog` implements `Component` and `Focusable`, rendering itself into lines and delegating focus to an internal `Input` component.
|
|
19
|
+
- **Layout-aware rendering**: the dialog renders either an inline bordered panel or a centered overlay depending on the `model_select.layout` config value.
|
|
18
20
|
- **Defensive guards**: checks feature enablement, UI availability, idle state (`waitForIdle`), exact-match short-circuit, and auth availability before applying a model.
|
|
19
21
|
|
|
20
22
|
## Data & Control Flow
|
|
@@ -30,18 +32,22 @@ This extension implements the `/select-model` command and its interactive picker
|
|
|
30
32
|
|
|
31
33
|
3. **Selection short-circuit**
|
|
32
34
|
- `showModelSelector` waits for idle if available, then refreshes the model registry.
|
|
33
|
-
-
|
|
35
|
+
- `findExactModel` tries two forms: `provider/modelId` and whitespace-separated `provider modelId`. If a matching model is found, it is applied immediately and the dialog is skipped.
|
|
36
|
+
- If no UI is available and there is no exact match, a warning is shown and the picker exits.
|
|
34
37
|
|
|
35
38
|
4. **Dialog path**
|
|
36
39
|
- If no exact match is found and a UI is present, the extension loads the `model_select` config.
|
|
37
|
-
- `buildModelLists` refreshes the registry,
|
|
38
|
-
-
|
|
39
|
-
-
|
|
40
|
+
- `buildModelLists` refreshes the registry, applies `provider_filter` only to Search, sorts search items with the current model first, and validates configured favourites (collecting warnings for missing models or missing auth).
|
|
41
|
+
- Accepted favourites retain exact group memberships long enough to derive ordered group subsets; duplicate group names and favourite models use first-occurrence semantics.
|
|
42
|
+
- Any model-registry error is added to the dialog's `configWarnings` so it appears inside the picker.
|
|
43
|
+
- `ctx.ui.custom` creates a `ModelSelectDialog` with favourite/group/search lists, tab visibility controls, the current model, warnings, `initialSearch`, `layout`, and an `onDone` callback. The overlay layout is centered at 85% width with a one-cell margin.
|
|
44
|
+
- The dialog always creates Favourites first, adds visible group tabs and optional Search, and renders a width-aware tab strip, shared filter input, warnings, and help footer. If `initialSearch` is non-empty and Search is visible, the dialog starts on the Search tab and seeds the input.
|
|
40
45
|
|
|
41
46
|
5. **User interaction**
|
|
42
|
-
- Keyboard input is mapped through `keybindings.matches` for navigation,
|
|
43
|
-
- Typing
|
|
44
|
-
-
|
|
47
|
+
- Keyboard input is mapped through `keybindings.matches` for navigation, ordered tab cycling (`tab`/`shift+tab`), page up/down, confirmation, and cancellation.
|
|
48
|
+
- Typing updates one shared query and re-filters every visible tab via `fuzzyFilter`; each tab retains its own selection index.
|
|
49
|
+
- The Search tab displays the active `provider_filter` above the query input.
|
|
50
|
+
- Confirming a selection invokes `onDone` with the chosen `Model`; cancelling invokes `onDone(null)`.
|
|
45
51
|
|
|
46
52
|
6. **Apply result**
|
|
47
53
|
- If a model is selected, `applySelectedModel` calls `pi.setModel`.
|
|
@@ -51,9 +57,9 @@ This extension implements the `/select-model` command and its interactive picker
|
|
|
51
57
|
|
|
52
58
|
- **`ExtensionAPI` (`@earendil-works/pi-coding-agent`)**: used to register the command, listen to `session_start`, set the active model (`pi.setModel`), and access the shared event bus (`pi.events`).
|
|
53
59
|
- **`ExtensionContext` / `ExtensionCommandContext` (`@earendil-works/pi-coding-agent`)**: provides `modelRegistry`, `ui`, `hasUI`, `model`, and the optional `waitForIdle` guard.
|
|
54
|
-
- **`ModelRegistry`**: refreshed and queried for available models, configured auth,
|
|
60
|
+
- **`ModelRegistry`**: refreshed and queried for available models, configured auth, lookup by `provider` + `modelId`, and error state (`getError`).
|
|
55
61
|
- **`ConfigLoader` (`../../config-loader`)**: provides feature toggle state (`isEnabled('model_select')`) and the typed `model_select` configuration object.
|
|
56
62
|
- **`@earendil-works/pi-ai`**: supplies the `Model<Api>` type and `modelsAreEqual` for stable identity comparisons.
|
|
57
|
-
- **`@earendil-works/pi-tui`**: supplies the `Input` component, `fuzzyFilter`, theme helpers, and rendering utilities (`truncateToWidth`, `visibleWidth`) used by the dialog.
|
|
63
|
+
- **`@earendil-works/pi-tui`**: supplies the `Input` component, `fuzzyFilter`, `matchesKey`, theme helpers, and rendering utilities (`truncateToWidth`, `visibleWidth`) used by the dialog.
|
|
58
64
|
- **`pi-vim-keys` / other extensions**: can trigger the picker by emitting `PI_VIM_KEY_EVENT_ID` on the shared event bus.
|
|
59
|
-
- **Configuration schemas**: `model_select` shape and `
|
|
65
|
+
- **Configuration schemas**: `model_select` shape, `ModelSelectLayout`, and `HideTabs` are defined by `../../schemas/config.schema` and `../../schemas/model-select.config.schema`.
|
|
@@ -44,9 +44,12 @@ async function showModelSelector(pi: ExtensionAPI, args: string, ctx: ExtensionC
|
|
|
44
44
|
new ModelSelectDialog(tui, theme, keybindings, {
|
|
45
45
|
currentModel: ctx.model,
|
|
46
46
|
favouriteItems: modelLists.favouriteItems,
|
|
47
|
+
favouriteLabel: config.favourite_label,
|
|
47
48
|
favouriteWarnings: modelLists.favouriteWarnings,
|
|
48
|
-
|
|
49
|
+
groupLists: modelLists.groupLists,
|
|
49
50
|
searchItems: modelLists.searchItems,
|
|
51
|
+
hideGroupTabs: config.hide_tabs.groups,
|
|
52
|
+
hideSearchTab: config.hide_tabs.search,
|
|
50
53
|
providerFilter: config.provider_filter,
|
|
51
54
|
configWarnings: registryError ? [`models.json: ${registryError}`] : [],
|
|
52
55
|
initialSearch: args.trim(),
|
|
@@ -15,6 +15,8 @@ export async function buildModelLists(ctx: ExtensionContext, config: Config['mod
|
|
|
15
15
|
const favouriteItems: ModelItem[] = [];
|
|
16
16
|
const favouriteWarnings: string[] = [];
|
|
17
17
|
const seenFavouriteModels = new Set<string>();
|
|
18
|
+
const uniqueGroups = [...new Set(config.groups)];
|
|
19
|
+
const groupedItems = new Map(uniqueGroups.map(name => [name, [] as ModelItem[]]));
|
|
18
20
|
|
|
19
21
|
for (const favourite of config.favourite) {
|
|
20
22
|
const model = ctx.modelRegistry.find(favourite.provider, favourite.modelId);
|
|
@@ -35,10 +37,16 @@ export async function buildModelLists(ctx: ExtensionContext, config: Config['mod
|
|
|
35
37
|
continue;
|
|
36
38
|
}
|
|
37
39
|
seenFavouriteModels.add(key);
|
|
38
|
-
|
|
40
|
+
|
|
41
|
+
const item = ModelFormatter.toModelItem(model);
|
|
42
|
+
favouriteItems.push(item);
|
|
43
|
+
for (const group of favourite.groups) {
|
|
44
|
+
groupedItems.get(group)?.push(item);
|
|
45
|
+
}
|
|
39
46
|
}
|
|
40
47
|
|
|
41
|
-
|
|
48
|
+
const groupLists = uniqueGroups.map(name => ({ name, items: groupedItems.get(name) ?? [] }));
|
|
49
|
+
return { favouriteItems, favouriteWarnings, groupLists, searchItems: sortedSearchModels };
|
|
42
50
|
}
|
|
43
51
|
|
|
44
52
|
export function findExactModel(ctx: ExtensionContext, args: string): Model<Api> | undefined {
|
|
@@ -1,17 +1,22 @@
|
|
|
1
1
|
import { modelsAreEqual } from '@earendil-works/pi-ai';
|
|
2
2
|
import type { KeybindingsManager, Theme } from '@earendil-works/pi-coding-agent';
|
|
3
|
-
import { type Component, type Focusable, fuzzyFilter, Input, type TUI, truncateToWidth, visibleWidth } from '@earendil-works/pi-tui';
|
|
3
|
+
import { type Component, type Focusable, fuzzyFilter, Input, matchesKey, type TUI, truncateToWidth, visibleWidth } from '@earendil-works/pi-tui';
|
|
4
4
|
import { MAX_CONFIG_WARNING_LINES, MAX_VISIBLE_MODELS } from './constants';
|
|
5
5
|
import { ModelFormatter } from './model-formatter';
|
|
6
|
-
import type { DialogOptions, ModelItem,
|
|
6
|
+
import type { DialogOptions, ModelItem, TabIdentity } from './types';
|
|
7
|
+
|
|
8
|
+
type DialogTab = {
|
|
9
|
+
identity: TabIdentity;
|
|
10
|
+
label: string;
|
|
11
|
+
items: ModelItem[];
|
|
12
|
+
filteredItems: ModelItem[];
|
|
13
|
+
selectedIndex: number;
|
|
14
|
+
};
|
|
7
15
|
|
|
8
16
|
export class ModelSelectDialog implements Component, Focusable {
|
|
9
17
|
private readonly searchInput = new Input();
|
|
10
|
-
private
|
|
11
|
-
private
|
|
12
|
-
private selectedSearchIndex = 0;
|
|
13
|
-
private filteredSearchItems: ModelItem[];
|
|
14
|
-
private filteredFavouriteItems: ModelItem[];
|
|
18
|
+
private readonly tabs: DialogTab[];
|
|
19
|
+
private activeTabIndex: number;
|
|
15
20
|
private _focused = false;
|
|
16
21
|
|
|
17
22
|
constructor(
|
|
@@ -20,16 +25,14 @@ export class ModelSelectDialog implements Component, Focusable {
|
|
|
20
25
|
private readonly keybindings: KeybindingsManager,
|
|
21
26
|
private readonly options: DialogOptions,
|
|
22
27
|
) {
|
|
23
|
-
this.
|
|
24
|
-
const
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
this.selectedFavouriteIndex = currentFavouriteIndex >= 0 ? currentFavouriteIndex : 0;
|
|
28
|
+
this.tabs = this.createTabs();
|
|
29
|
+
const searchTabIndex = this.tabs.findIndex(tab => tab.identity.kind === 'search');
|
|
30
|
+
this.activeTabIndex = options.initialSearch && searchTabIndex >= 0 ? searchTabIndex : 0;
|
|
31
|
+
|
|
28
32
|
this.searchInput.setValue(options.initialSearch);
|
|
29
33
|
this.searchInput.onSubmit = () => this.selectCurrentItem();
|
|
30
34
|
this.searchInput.onEscape = () => this.options.onDone(null);
|
|
31
|
-
this.
|
|
32
|
-
this.filteredFavouriteItems = this.filterItems(options.favouriteItems, options.initialSearch);
|
|
35
|
+
this.applyFilter(options.initialSearch);
|
|
33
36
|
this.syncFocus();
|
|
34
37
|
}
|
|
35
38
|
|
|
@@ -47,8 +50,14 @@ export class ModelSelectDialog implements Component, Focusable {
|
|
|
47
50
|
}
|
|
48
51
|
|
|
49
52
|
handleInput(data: string): void {
|
|
53
|
+
if (matchesKey(data, 'shift+tab')) {
|
|
54
|
+
this.switchTab(-1);
|
|
55
|
+
this.tui.requestRender();
|
|
56
|
+
return;
|
|
57
|
+
}
|
|
58
|
+
|
|
50
59
|
if (this.keybindings.matches(data, 'tui.input.tab')) {
|
|
51
|
-
this.
|
|
60
|
+
this.switchTab(1);
|
|
52
61
|
this.tui.requestRender();
|
|
53
62
|
return;
|
|
54
63
|
}
|
|
@@ -92,42 +101,62 @@ export class ModelSelectDialog implements Component, Focusable {
|
|
|
92
101
|
this.tui.requestRender();
|
|
93
102
|
}
|
|
94
103
|
|
|
95
|
-
private applyFilter(query: string): void {
|
|
96
|
-
this.filteredSearchItems = this.filterItems(this.options.searchItems, query);
|
|
97
|
-
this.filteredFavouriteItems = this.filterItems(this.options.favouriteItems, query);
|
|
98
|
-
this.selectedSearchIndex = Math.min(this.selectedSearchIndex, Math.max(0, this.filteredSearchItems.length - 1));
|
|
99
|
-
this.selectedFavouriteIndex = Math.min(this.selectedFavouriteIndex, Math.max(0, this.filteredFavouriteItems.length - 1));
|
|
100
|
-
}
|
|
101
|
-
|
|
102
104
|
render(width: number): string[] {
|
|
103
105
|
const safeWidth = Math.max(3, width);
|
|
104
106
|
|
|
105
107
|
if (this.options.layout === 'inline') {
|
|
106
|
-
const
|
|
107
|
-
const
|
|
108
|
-
|
|
109
|
-
const body = lines.map(line => this.padLine(line, inner));
|
|
110
|
-
return [rule, ...body, rule];
|
|
108
|
+
const lines = this.buildContentLines(safeWidth);
|
|
109
|
+
const rule = this.theme.fg('border', '─'.repeat(safeWidth));
|
|
110
|
+
return [rule, ...lines.map(line => this.padLine(line, safeWidth)), rule];
|
|
111
111
|
}
|
|
112
112
|
|
|
113
113
|
const inner = safeWidth - 2;
|
|
114
114
|
const lines = this.buildContentLines(inner);
|
|
115
|
-
|
|
116
115
|
const borderColor = (str: string) => this.theme.fg('border', str);
|
|
117
116
|
const horizontal = '─'.repeat(inner);
|
|
118
|
-
const top = borderColor(`╭${horizontal}╮`);
|
|
119
|
-
const bottom = borderColor(`╰${horizontal}╯`);
|
|
120
117
|
const side = borderColor('│');
|
|
121
118
|
|
|
122
|
-
|
|
123
|
-
return [top, ...wrapped, bottom];
|
|
119
|
+
return [borderColor(`╭${horizontal}╮`), ...lines.map(line => `${side}${this.padLine(line, inner)}${side}`), borderColor(`╰${horizontal}╯`)];
|
|
124
120
|
}
|
|
125
121
|
|
|
126
|
-
private
|
|
127
|
-
const
|
|
122
|
+
private createTabs(): DialogTab[] {
|
|
123
|
+
const definitions: Array<{ identity: TabIdentity; label: string; items: ModelItem[] }> = [
|
|
124
|
+
{ identity: { kind: 'favourites' }, label: this.options.favouriteLabel, items: this.options.favouriteItems },
|
|
125
|
+
];
|
|
126
|
+
|
|
127
|
+
if (!this.options.hideGroupTabs) {
|
|
128
|
+
definitions.push(
|
|
129
|
+
...this.options.groupLists.map(group => ({
|
|
130
|
+
identity: { kind: 'group', name: group.name } as const,
|
|
131
|
+
label: group.name,
|
|
132
|
+
items: group.items,
|
|
133
|
+
})),
|
|
134
|
+
);
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
if (!this.options.hideSearchTab) {
|
|
138
|
+
definitions.push({ identity: { kind: 'search' }, label: 'Search', items: this.options.searchItems });
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
return definitions.map(definition => {
|
|
142
|
+
const currentIndex = this.options.currentModel ? definition.items.findIndex(item => modelsAreEqual(item.model, this.options.currentModel)) : -1;
|
|
143
|
+
return {
|
|
144
|
+
...definition,
|
|
145
|
+
filteredItems: definition.items,
|
|
146
|
+
selectedIndex: currentIndex >= 0 ? currentIndex : 0,
|
|
147
|
+
};
|
|
148
|
+
});
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
private applyFilter(query: string): void {
|
|
152
|
+
for (const tab of this.tabs) {
|
|
153
|
+
tab.filteredItems = this.filterItems(tab.items, query);
|
|
154
|
+
tab.selectedIndex = Math.min(tab.selectedIndex, Math.max(0, tab.filteredItems.length - 1));
|
|
155
|
+
}
|
|
156
|
+
}
|
|
128
157
|
|
|
129
|
-
|
|
130
|
-
lines
|
|
158
|
+
private buildContentLines(inner: number): string[] {
|
|
159
|
+
const lines: string[] = [this.line(this.renderTitle(), inner), this.renderTabs(inner)];
|
|
131
160
|
|
|
132
161
|
for (const warning of this.options.configWarnings.slice(0, MAX_CONFIG_WARNING_LINES)) {
|
|
133
162
|
lines.push(this.line(this.theme.fg('warning', `⚠ ${warning}`), inner));
|
|
@@ -138,34 +167,17 @@ export class ModelSelectDialog implements Component, Focusable {
|
|
|
138
167
|
);
|
|
139
168
|
}
|
|
140
169
|
|
|
141
|
-
lines.push('');
|
|
142
|
-
|
|
143
|
-
if (this.activeSection === 'favourites') {
|
|
144
|
-
lines.push(...this.renderFavourites(inner));
|
|
145
|
-
} else {
|
|
146
|
-
lines.push(...this.renderSearch(inner));
|
|
147
|
-
}
|
|
148
|
-
|
|
149
|
-
lines.push('');
|
|
150
|
-
lines.push(this.line(this.renderHelp(), inner));
|
|
151
|
-
|
|
170
|
+
lines.push('', ...this.renderActiveTab(inner), '', this.line(this.renderHelp(), inner));
|
|
152
171
|
return lines;
|
|
153
172
|
}
|
|
154
173
|
|
|
155
174
|
private padLine(text: string, innerWidth: number): string {
|
|
156
175
|
const truncated = truncateToWidth(text.replace(/[\r\n]+/g, ' '), innerWidth, '');
|
|
157
|
-
|
|
158
|
-
return truncated + ' '.repeat(padding);
|
|
176
|
+
return truncated + ' '.repeat(Math.max(0, innerWidth - visibleWidth(truncated)));
|
|
159
177
|
}
|
|
160
178
|
|
|
161
|
-
private
|
|
162
|
-
|
|
163
|
-
this.activeSection = 'search';
|
|
164
|
-
this.syncFocus();
|
|
165
|
-
return;
|
|
166
|
-
}
|
|
167
|
-
|
|
168
|
-
this.activeSection = this.activeSection === 'favourites' ? 'search' : 'favourites';
|
|
179
|
+
private switchTab(direction: -1 | 1): void {
|
|
180
|
+
this.activeTabIndex = this.wrapIndex(this.activeTabIndex + direction, this.tabs.length);
|
|
169
181
|
this.syncFocus();
|
|
170
182
|
}
|
|
171
183
|
|
|
@@ -174,46 +186,33 @@ export class ModelSelectDialog implements Component, Focusable {
|
|
|
174
186
|
}
|
|
175
187
|
|
|
176
188
|
private moveSelection(delta: number): void {
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
return;
|
|
180
|
-
}
|
|
181
|
-
|
|
182
|
-
this.selectedSearchIndex = this.wrapIndex(this.selectedSearchIndex + delta, this.filteredSearchItems.length);
|
|
189
|
+
const tab = this.activeTab();
|
|
190
|
+
tab.selectedIndex = this.wrapIndex(tab.selectedIndex + delta, tab.filteredItems.length);
|
|
183
191
|
}
|
|
184
192
|
|
|
185
193
|
private wrapIndex(index: number, length: number): number {
|
|
186
|
-
|
|
187
|
-
return 0;
|
|
188
|
-
}
|
|
189
|
-
return ((index % length) + length) % length;
|
|
194
|
+
return length <= 0 ? 0 : ((index % length) + length) % length;
|
|
190
195
|
}
|
|
191
196
|
|
|
192
197
|
private selectCurrentItem(): void {
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
}
|
|
198
|
-
return;
|
|
198
|
+
const tab = this.activeTab();
|
|
199
|
+
const item = tab.filteredItems[tab.selectedIndex];
|
|
200
|
+
if (item) {
|
|
201
|
+
this.options.onDone(item.model);
|
|
199
202
|
}
|
|
200
|
-
|
|
201
|
-
this.selectCurrentSearchItem();
|
|
202
203
|
}
|
|
203
204
|
|
|
204
|
-
private
|
|
205
|
-
const
|
|
206
|
-
if (
|
|
207
|
-
|
|
205
|
+
private activeTab(): DialogTab {
|
|
206
|
+
const tab = this.tabs[this.activeTabIndex];
|
|
207
|
+
if (!tab) {
|
|
208
|
+
throw new Error('Model selector requires at least the Favourites tab');
|
|
208
209
|
}
|
|
210
|
+
return tab;
|
|
209
211
|
}
|
|
210
212
|
|
|
211
213
|
private filterItems(items: ModelItem[], query: string): ModelItem[] {
|
|
212
214
|
const trimmed = query.trim();
|
|
213
|
-
|
|
214
|
-
return items;
|
|
215
|
-
}
|
|
216
|
-
return fuzzyFilter(items, trimmed, item => item.searchText);
|
|
215
|
+
return trimmed ? fuzzyFilter(items, trimmed, item => item.searchText) : items;
|
|
217
216
|
}
|
|
218
217
|
|
|
219
218
|
private renderTitle(): string {
|
|
@@ -221,43 +220,111 @@ export class ModelSelectDialog implements Component, Focusable {
|
|
|
221
220
|
return `${this.theme.fg('customMessageLabel', this.theme.bold('Select Model'))} ${this.theme.fg('muted', `current: ${current}`)}`;
|
|
222
221
|
}
|
|
223
222
|
|
|
224
|
-
private renderTabs(): string {
|
|
225
|
-
const tabs
|
|
226
|
-
|
|
227
|
-
|
|
223
|
+
private renderTabs(width: number): string {
|
|
224
|
+
const labels = this.tabs.map(tab => `[${tab.label} ${tab.filteredItems.length}]`);
|
|
225
|
+
const separator = ' ';
|
|
226
|
+
if (visibleWidth(labels.join(separator)) <= width) {
|
|
227
|
+
return this.styleTabLabels(labels, 0, labels.length - 1, false, false);
|
|
228
228
|
}
|
|
229
|
-
|
|
230
|
-
|
|
229
|
+
|
|
230
|
+
let start = this.activeTabIndex;
|
|
231
|
+
let end = this.activeTabIndex;
|
|
232
|
+
let expandLeft = true;
|
|
233
|
+
while (true) {
|
|
234
|
+
const nextStart = expandLeft && start > 0 ? start - 1 : start;
|
|
235
|
+
const nextEnd = !expandLeft && end < labels.length - 1 ? end + 1 : end;
|
|
236
|
+
expandLeft = !expandLeft;
|
|
237
|
+
|
|
238
|
+
if (nextStart === start && nextEnd === end) {
|
|
239
|
+
if ((start === 0 || nextStart === start) && (end === labels.length - 1 || nextEnd === end)) break;
|
|
240
|
+
continue;
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
const candidate = this.plainTabViewport(labels, nextStart, nextEnd);
|
|
244
|
+
if (visibleWidth(candidate) <= width) {
|
|
245
|
+
start = nextStart;
|
|
246
|
+
end = nextEnd;
|
|
247
|
+
continue;
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
const otherStart = start > 0 ? start - 1 : start;
|
|
251
|
+
const otherEnd = end < labels.length - 1 ? end + 1 : end;
|
|
252
|
+
if ((otherStart === start && otherEnd === end) || visibleWidth(this.plainTabViewport(labels, otherStart, otherEnd)) > width) break;
|
|
253
|
+
start = otherStart;
|
|
254
|
+
end = otherEnd;
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
const leftOmitted = start > 0;
|
|
258
|
+
const rightOmitted = end < labels.length - 1;
|
|
259
|
+
const plain = this.plainTabViewport(labels, start, end);
|
|
260
|
+
if (visibleWidth(plain) <= width) {
|
|
261
|
+
return this.styleTabLabels(labels, start, end, leftOmitted, rightOmitted);
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
const prefix = leftOmitted ? '… ' : '';
|
|
265
|
+
const suffix = rightOmitted ? ' …' : '';
|
|
266
|
+
const activeBudget = Math.max(1, width - visibleWidth(prefix) - visibleWidth(suffix));
|
|
267
|
+
const active = truncateToWidth(labels[this.activeTabIndex] ?? '', activeBudget, '');
|
|
268
|
+
return this.line(`${this.theme.fg('muted', prefix)}${this.theme.fg('accent', this.theme.bold(active))}${this.theme.fg('muted', suffix)}`, width);
|
|
231
269
|
}
|
|
232
270
|
|
|
233
|
-
private
|
|
234
|
-
const
|
|
235
|
-
if (
|
|
236
|
-
|
|
271
|
+
private plainTabViewport(labels: string[], start: number, end: number): string {
|
|
272
|
+
const parts = labels.slice(start, end + 1);
|
|
273
|
+
if (start > 0) parts.unshift('…');
|
|
274
|
+
if (end < labels.length - 1) parts.push('…');
|
|
275
|
+
return parts.join(' ');
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
private styleTabLabels(labels: string[], start: number, end: number, leftOmitted: boolean, rightOmitted: boolean): string {
|
|
279
|
+
const parts: string[] = [];
|
|
280
|
+
if (leftOmitted) parts.push(this.theme.fg('muted', '…'));
|
|
281
|
+
for (let index = start; index <= end; index++) {
|
|
282
|
+
const label = labels[index] ?? '';
|
|
283
|
+
parts.push(index === this.activeTabIndex ? this.theme.fg('accent', this.theme.bold(label)) : this.theme.fg('muted', label));
|
|
237
284
|
}
|
|
238
|
-
|
|
285
|
+
if (rightOmitted) parts.push(this.theme.fg('muted', '…'));
|
|
286
|
+
return parts.join(this.theme.fg('muted', ' '));
|
|
239
287
|
}
|
|
240
288
|
|
|
241
|
-
private
|
|
289
|
+
private renderActiveTab(width: number): string[] {
|
|
290
|
+
const tab = this.activeTab();
|
|
242
291
|
const lines: string[] = [];
|
|
243
292
|
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
293
|
+
if (tab.identity.kind === 'search') {
|
|
294
|
+
const providerText =
|
|
295
|
+
this.options.providerFilter.length === 0 ? 'all authorized providers' : `providers: ${this.options.providerFilter.join(', ')}`;
|
|
296
|
+
lines.push(this.line(this.theme.fg('muted', `Provider filter: ${providerText}`), width));
|
|
297
|
+
lines.push(this.line(this.theme.fg('muted', 'Search query:'), width));
|
|
298
|
+
} else {
|
|
299
|
+
lines.push(this.line(this.theme.fg('muted', 'Filter:'), width));
|
|
300
|
+
}
|
|
301
|
+
lines.push(...this.searchInput.render(width), '');
|
|
247
302
|
|
|
248
|
-
if (
|
|
249
|
-
lines.push(this.line(this.theme.fg('muted',
|
|
250
|
-
} else if (
|
|
251
|
-
lines.push(this.line(this.theme.fg('muted',
|
|
303
|
+
if (tab.items.length === 0) {
|
|
304
|
+
lines.push(this.line(this.theme.fg('muted', this.emptyTabMessage(tab)), width));
|
|
305
|
+
} else if (tab.filteredItems.length === 0) {
|
|
306
|
+
lines.push(this.line(this.theme.fg('muted', ` No matching ${tab.identity.kind === 'search' ? 'models' : 'favourites'}`), width));
|
|
252
307
|
} else {
|
|
253
|
-
lines.push(...this.renderModelList(
|
|
254
|
-
const selected =
|
|
308
|
+
lines.push(...this.renderModelList(tab.filteredItems, tab.selectedIndex, width));
|
|
309
|
+
const selected = tab.filteredItems[tab.selectedIndex];
|
|
255
310
|
if (selected) {
|
|
256
|
-
lines.push('');
|
|
257
|
-
lines.push(this.line(this.theme.fg('muted', ` ${selected.description}`), width));
|
|
311
|
+
lines.push('', this.line(this.theme.fg('muted', ` ${selected.description}`), width));
|
|
258
312
|
}
|
|
259
313
|
}
|
|
260
314
|
|
|
315
|
+
if (tab.identity.kind === 'favourites') {
|
|
316
|
+
this.appendFavouriteWarnings(lines, width);
|
|
317
|
+
}
|
|
318
|
+
return lines;
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
private emptyTabMessage(tab: DialogTab): string {
|
|
322
|
+
if (tab.identity.kind === 'favourites') return ' No configured favourites are available.';
|
|
323
|
+
if (tab.identity.kind === 'group') return ` No available favourites in ${tab.label}.`;
|
|
324
|
+
return ' No matching models';
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
private appendFavouriteWarnings(lines: string[], width: number): void {
|
|
261
328
|
for (const warning of this.options.favouriteWarnings.slice(0, MAX_CONFIG_WARNING_LINES)) {
|
|
262
329
|
lines.push(this.line(this.theme.fg('warning', ` ⚠ ${warning}`), width));
|
|
263
330
|
}
|
|
@@ -269,52 +336,20 @@ export class ModelSelectDialog implements Component, Focusable {
|
|
|
269
336
|
),
|
|
270
337
|
);
|
|
271
338
|
}
|
|
272
|
-
|
|
273
|
-
return lines;
|
|
274
|
-
}
|
|
275
|
-
|
|
276
|
-
private renderSearch(width: number): string[] {
|
|
277
|
-
const lines: string[] = [];
|
|
278
|
-
const providerText =
|
|
279
|
-
this.options.providerFilter.length === 0 ? 'all authorized providers' : `providers: ${this.options.providerFilter.join(', ')}`;
|
|
280
|
-
|
|
281
|
-
lines.push(this.line(this.theme.fg('muted', `Provider filter: ${providerText}`), width));
|
|
282
|
-
lines.push(this.line(this.theme.fg('muted', 'Search query:'), width));
|
|
283
|
-
lines.push(...this.searchInput.render(width));
|
|
284
|
-
lines.push('');
|
|
285
|
-
|
|
286
|
-
if (this.filteredSearchItems.length === 0) {
|
|
287
|
-
lines.push(this.line(this.theme.fg('muted', ' No matching models'), width));
|
|
288
|
-
return lines;
|
|
289
|
-
}
|
|
290
|
-
|
|
291
|
-
lines.push(...this.renderModelList(this.filteredSearchItems, this.selectedSearchIndex, width));
|
|
292
|
-
const selected = this.filteredSearchItems[this.selectedSearchIndex];
|
|
293
|
-
if (selected) {
|
|
294
|
-
lines.push('');
|
|
295
|
-
lines.push(this.line(this.theme.fg('muted', ` ${selected.description}`), width));
|
|
296
|
-
}
|
|
297
|
-
|
|
298
|
-
return lines;
|
|
299
339
|
}
|
|
300
340
|
|
|
301
341
|
private renderModelList(items: ModelItem[], selectedIndex: number, width: number): string[] {
|
|
302
|
-
const lines: string[] = [];
|
|
303
342
|
const startIndex = Math.max(0, Math.min(selectedIndex - Math.floor(MAX_VISIBLE_MODELS / 2), items.length - MAX_VISIBLE_MODELS));
|
|
304
343
|
const endIndex = Math.min(startIndex + MAX_VISIBLE_MODELS, items.length);
|
|
344
|
+
const lines: string[] = [];
|
|
305
345
|
|
|
306
346
|
for (let index = startIndex; index < endIndex; index++) {
|
|
307
347
|
const item = items[index];
|
|
308
|
-
if (
|
|
309
|
-
continue;
|
|
310
|
-
}
|
|
311
|
-
lines.push(this.renderModelItem(item, index === selectedIndex, width));
|
|
348
|
+
if (item) lines.push(this.renderModelItem(item, index === selectedIndex, width));
|
|
312
349
|
}
|
|
313
|
-
|
|
314
350
|
if (startIndex > 0 || endIndex < items.length) {
|
|
315
351
|
lines.push(this.line(this.theme.fg('dim', ` (${selectedIndex + 1}/${items.length})`), width));
|
|
316
352
|
}
|
|
317
|
-
|
|
318
353
|
return lines;
|
|
319
354
|
}
|
|
320
355
|
|
|
@@ -327,7 +362,7 @@ export class ModelSelectDialog implements Component, Focusable {
|
|
|
327
362
|
}
|
|
328
363
|
|
|
329
364
|
private renderHelp(): string {
|
|
330
|
-
const tabHint = this.
|
|
365
|
+
const tabHint = this.tabs.length > 1 ? 'tab/shift+tab switch sections • ' : '';
|
|
331
366
|
return this.theme.fg('dim', `${tabHint}↑↓ navigate • enter select • esc cancel`);
|
|
332
367
|
}
|
|
333
368
|
|
|
@@ -7,22 +7,31 @@ export type ModelItem = {
|
|
|
7
7
|
searchText: string;
|
|
8
8
|
};
|
|
9
9
|
|
|
10
|
+
export type ModelGroupList = {
|
|
11
|
+
name: string;
|
|
12
|
+
items: ModelItem[];
|
|
13
|
+
};
|
|
14
|
+
|
|
10
15
|
export type ModelLists = {
|
|
11
16
|
favouriteItems: ModelItem[];
|
|
12
17
|
favouriteWarnings: string[];
|
|
18
|
+
groupLists: ModelGroupList[];
|
|
13
19
|
searchItems: ModelItem[];
|
|
14
20
|
};
|
|
15
21
|
|
|
16
|
-
export type
|
|
22
|
+
export type TabIdentity = { kind: 'favourites' } | { kind: 'group'; name: string } | { kind: 'search' };
|
|
17
23
|
|
|
18
24
|
export type DialogResult = Model<Api> | null;
|
|
19
25
|
|
|
20
26
|
export type DialogOptions = {
|
|
21
27
|
currentModel: Model<Api> | undefined;
|
|
22
28
|
favouriteItems: ModelItem[];
|
|
29
|
+
favouriteLabel: string;
|
|
23
30
|
favouriteWarnings: string[];
|
|
24
|
-
|
|
31
|
+
groupLists: ModelGroupList[];
|
|
25
32
|
searchItems: ModelItem[];
|
|
33
|
+
hideGroupTabs: boolean;
|
|
34
|
+
hideSearchTab: boolean;
|
|
26
35
|
providerFilter: string[];
|
|
27
36
|
configWarnings: string[];
|
|
28
37
|
initialSearch: string;
|
package/src/schemas/codemap.md
CHANGED
|
@@ -2,22 +2,22 @@
|
|
|
2
2
|
|
|
3
3
|
## Responsibility
|
|
4
4
|
|
|
5
|
-
This directory defines the Zod-based configuration schemas for the pi-qol plugin. It is the single source of truth for the shape, defaults, and validation rules of user-facing configuration. It covers the top-level config object and per-feature schemas for `auto-session-name`, `model-select
|
|
5
|
+
This directory defines the Zod-based configuration schemas for the pi-qol plugin. It is the single source of truth for the shape, defaults, and validation rules of user-facing configuration. It covers the top-level config object and per-feature schemas for `auto-session-name`, `model-select` (including favourites, groups, tab visibility, provider filtering, and layout), and `custom-footer`, plus reusable shared schema building blocks.
|
|
6
6
|
|
|
7
7
|
## Design Patterns
|
|
8
8
|
|
|
9
9
|
- **Schema-first configuration**: Uses Zod to declare schemas and derive TypeScript types via `z.infer`.
|
|
10
10
|
- **Composition over monolith**: Per-feature schemas (`auto-session-name.config.schema.ts`, `model-select.config.schema.ts`, `custom-footer-config.schema.ts`) are composed into the top-level `ConfigSchema` in `config.schema.ts`.
|
|
11
11
|
- **Defaults embedded in schemas**: `.default()` is used heavily so schemas are self-describing and can parse incomplete inputs safely.
|
|
12
|
-
- **Full vs. Partial schemas**: Each feature exposes a full schema and a `Partial*` variant to support partial/merging updates (e.g., user overrides layered over defaults).
|
|
13
|
-
- **Shared primitives**: `shared-config.schema.ts` centralizes reusable concepts like `ModelConfigSchema` and `
|
|
12
|
+
- **Full vs. Partial schemas**: Each feature exposes a full schema and a `Partial*` variant to support partial/merging updates (e.g., user overrides layered over defaults); model-select's explicit partial schema avoids materializing defaults before precedence merging.
|
|
13
|
+
- **Shared primitives**: `shared-config.schema.ts` centralizes reusable concepts like `ModelConfigSchema`, `ColorHexSchema`, and `ReasoningLevelSchema`.
|
|
14
14
|
- **Default object parsing**: `custom-footer-config.schema.ts` uses `Schema.parse({})` to derive concrete default objects rather than hand-writing inline literals.
|
|
15
15
|
|
|
16
16
|
## Data & Control Flow
|
|
17
17
|
|
|
18
18
|
1. **Input**: Raw JSON/user config enters the system.
|
|
19
19
|
2. **Validation**: The top-level `ConfigSchema.parse()` validates the whole object, falling back to per-field defaults for missing keys.
|
|
20
|
-
3. **Feature decomposition**: `ConfigSchema` delegates validation of each feature section to its dedicated schema (`AutoSessionNameConfigSchema`, `ModelSelectConfigSchema`, `CustomFooterConfigSchema`), which in turn use shared schemas (`ModelConfigSchema`, `ColorHexSchema`, `ReasoningLevelSchema`).
|
|
20
|
+
3. **Feature decomposition**: `ConfigSchema` delegates validation of each feature section to its dedicated schema (`AutoSessionNameConfigSchema`, `ModelSelectConfigSchema`, `CustomFooterConfigSchema`), which in turn use shared schemas (`ModelConfigSchema`, `ColorHexSchema`, `ReasoningLevelSchema`). `ModelSelectConfigSchema` also defines a `ModelSelectLayoutSchema` enum (`inline`/`overlay`) and `FavouriteModelSchema`, which omits `reasoning` from `ModelConfigSchema` and adds a `groups` array.
|
|
21
21
|
4. **Partial updates**: `PartialConfigSchema` and its feature-level partial variants allow validating incremental config changes without requiring a complete config object.
|
|
22
22
|
5. **Output**: Validated `Config` and `PartialConfig` types are exported for use by config loading, merging, and runtime feature code elsewhere in the plugin.
|
|
23
23
|
|
|
@@ -11,6 +11,9 @@ export const ConfigSchema = z.object({
|
|
|
11
11
|
model_select: ModelSelectConfigSchema.default({
|
|
12
12
|
enabled: false,
|
|
13
13
|
favourite: [],
|
|
14
|
+
favourite_label: 'Favourites',
|
|
15
|
+
groups: [],
|
|
16
|
+
hide_tabs: { groups: false, search: false },
|
|
14
17
|
provider_filter: [],
|
|
15
18
|
layout: 'inline',
|
|
16
19
|
}),
|
|
@@ -1,7 +1,16 @@
|
|
|
1
1
|
import z from 'zod';
|
|
2
2
|
import { ModelConfigSchema } from './shared-config.schema';
|
|
3
3
|
|
|
4
|
-
const
|
|
4
|
+
const NonEmptyNameSchema = z.string().min(1);
|
|
5
|
+
|
|
6
|
+
const FavouriteModelSchema = ModelConfigSchema.omit({ reasoning: true }).extend({
|
|
7
|
+
groups: z.array(NonEmptyNameSchema).default([]),
|
|
8
|
+
});
|
|
9
|
+
|
|
10
|
+
const HideTabsSchema = z.object({
|
|
11
|
+
groups: z.boolean().default(false),
|
|
12
|
+
search: z.boolean().default(false),
|
|
13
|
+
});
|
|
5
14
|
|
|
6
15
|
const ModelSelectLayoutSchema = z.enum(['inline', 'overlay']);
|
|
7
16
|
export type ModelSelectLayout = z.infer<typeof ModelSelectLayoutSchema>;
|
|
@@ -9,10 +18,32 @@ export type ModelSelectLayout = z.infer<typeof ModelSelectLayoutSchema>;
|
|
|
9
18
|
export const ModelSelectConfigSchema = z.object({
|
|
10
19
|
enabled: z.boolean().default(false),
|
|
11
20
|
favourite: z.array(FavouriteModelSchema).default([]),
|
|
12
|
-
|
|
21
|
+
favourite_label: NonEmptyNameSchema.default('Favourites'),
|
|
22
|
+
groups: z.array(NonEmptyNameSchema).default([]),
|
|
23
|
+
hide_tabs: HideTabsSchema.default({ groups: false, search: false }),
|
|
24
|
+
provider_filter: z.array(NonEmptyNameSchema).default([]),
|
|
13
25
|
layout: ModelSelectLayoutSchema.default('inline'),
|
|
14
26
|
});
|
|
15
27
|
export type ModelSelectConfig = z.infer<typeof ModelSelectConfigSchema>;
|
|
16
28
|
|
|
17
|
-
export const PartialModelSelectConfigSchema =
|
|
29
|
+
export const PartialModelSelectConfigSchema = z.object({
|
|
30
|
+
enabled: z.boolean().optional(),
|
|
31
|
+
favourite: z
|
|
32
|
+
.array(
|
|
33
|
+
ModelConfigSchema.omit({ reasoning: true }).extend({
|
|
34
|
+
groups: z.array(NonEmptyNameSchema).optional(),
|
|
35
|
+
}),
|
|
36
|
+
)
|
|
37
|
+
.optional(),
|
|
38
|
+
favourite_label: NonEmptyNameSchema.optional(),
|
|
39
|
+
groups: z.array(NonEmptyNameSchema).optional(),
|
|
40
|
+
hide_tabs: z
|
|
41
|
+
.object({
|
|
42
|
+
groups: z.boolean().optional(),
|
|
43
|
+
search: z.boolean().optional(),
|
|
44
|
+
})
|
|
45
|
+
.optional(),
|
|
46
|
+
provider_filter: z.array(NonEmptyNameSchema).optional(),
|
|
47
|
+
layout: ModelSelectLayoutSchema.optional(),
|
|
48
|
+
});
|
|
18
49
|
export type PartialModelSelectConfig = z.infer<typeof PartialModelSelectConfigSchema>;
|
package/src/utils/codemap.md
CHANGED
|
@@ -4,39 +4,33 @@
|
|
|
4
4
|
|
|
5
5
|
This folder contains low-level, reusable helpers used across the `pi-qol` extension. They are pure utility modules with no business logic or UI concerns.
|
|
6
6
|
|
|
7
|
-
- **`crayon.util.ts`** — ANSI terminal styling: colorize text with hex foreground/background colors, apply reverse video, and strip ANSI escape sequences.
|
|
8
7
|
- **`model-resolver.util.ts`** — Resolve a concrete AI model and its authentication credentials from a configured `ModelConfig` or the active session model.
|
|
9
8
|
- **`raw-data-parser.util.ts`** — Type-safe coercion helpers for `unknown` runtime values into `Record<string, unknown>`, trimmed `string`, or finite `number`.
|
|
10
|
-
- **`path.util.ts`** —
|
|
9
|
+
- **`path.util.ts`** — Resolve extension-specific paths on disk: shell-style variable expansion (`~`, `$HOME`, `$VAR`), generic file existence checks, global/project extension `config.json`, and the shared `auth.json` file.
|
|
11
10
|
|
|
12
11
|
## Design Patterns
|
|
13
12
|
|
|
14
13
|
- **Static utility classes** (`RawDataParser`, `PathUtil`) group related stateless functions under a clear namespace.
|
|
15
14
|
- **Service class with injected context** (`ModelResolver`) receives an `ExtensionContext` dependency rather than importing global state, keeping it testable and decoupled.
|
|
16
|
-
- **Object-as-namespace export** (`crayon`) exposes a small, discoverable API surface while hiding internal helpers (`hexToRgb`, `fgAnsi`, `bgAnsi`, `ANSI_ESCAPE_REGEX`).
|
|
17
15
|
- **Result/Option types** (`ResolveModelResult`, `FileSearchResult`) avoid exceptions and force callers to handle success and failure paths explicitly.
|
|
18
16
|
- **Function overloads** (`PathUtil.findExtensionConfig`) provide type-safe, domain-driven entry points for global vs. project lookups.
|
|
19
|
-
- **Defensive validation** (`RawDataParser
|
|
17
|
+
- **Defensive validation** (`RawDataParser`) silently returns `undefined` when data is invalid instead of throwing.
|
|
20
18
|
|
|
21
19
|
## Data & Control Flow
|
|
22
20
|
|
|
23
|
-
1. **
|
|
24
|
-
- `crayon.colorize(text, { fg?, bg? })` validates hex strings against `COLOR_HEX_REGEX`.
|
|
25
|
-
- Valid colors are converted to RGB and wrapped in ANSI escape codes; the text is returned unchanged if no valid colors are provided.
|
|
26
|
-
- `crayon.stripAnsi(text)` removes all ANSI escape sequences using a compiled regex.
|
|
27
|
-
|
|
28
|
-
2. **Model resolution**
|
|
21
|
+
1. **Model resolution**
|
|
29
22
|
- `ModelResolver.resolveModel(configModel?)` builds a candidate list in priority order: configured model first, then the active session model (deduplicated).
|
|
30
23
|
- For each candidate it calls `ctx.modelRegistry.getApiKeyAndHeaders(model)`.
|
|
31
24
|
- The first candidate with successful auth is returned as a `ResolvedModel`, including the API key, headers, reasoning settings, and OAuth flag.
|
|
32
25
|
- If all candidates fail, a consolidated error string is returned.
|
|
33
26
|
|
|
34
|
-
|
|
27
|
+
2. **Raw data parsing**
|
|
35
28
|
- `RawDataParser.asRecord` checks for non-null, non-array objects.
|
|
36
29
|
- `stringValue` returns only non-empty trimmed strings.
|
|
37
30
|
- `numberValue` coerces strings/numbers and returns only finite values.
|
|
38
31
|
|
|
39
|
-
|
|
32
|
+
3. **Path resolution**
|
|
33
|
+
- `PathUtil.expandPath` replaces shell-style variables (`~`, `$HOME`, `$VAR`, `${VAR}`) and `~` with the user's home directory.
|
|
40
34
|
- `PathUtil.findFile` checks `existsSync` and returns both existence and the resolved path.
|
|
41
35
|
- `findExtensionConfig({ type: 'global' })` resolves to `<agentDir>/extensions/<EXTENSION_ID>/config.json`.
|
|
42
36
|
- `findExtensionConfig({ type: 'project', cwd })` resolves to `<cwd>/.pi/extensions/<EXTENSION_ID>/config.json`.
|
|
@@ -50,9 +44,8 @@ This folder contains low-level, reusable helpers used across the `pi-qol` extens
|
|
|
50
44
|
- `@earendil-works/pi-ai`
|
|
51
45
|
- `Model<Api>` is the resolved entity returned by `ModelResolver`.
|
|
52
46
|
- `../constants`
|
|
53
|
-
- `COLOR_HEX_REGEX` drives hex validation in `crayon`.
|
|
54
47
|
- `EXTENSION_ID` is used by `PathUtil` to build config directory paths.
|
|
55
48
|
- `../schemas/shared-config.schema`
|
|
56
49
|
- `ModelConfig` and its `reasoning` field are consumed by `ModelResolver`.
|
|
57
|
-
- `node:fs` / `node:path`
|
|
58
|
-
- `PathUtil` relies on Node built-ins for synchronous file existence
|
|
50
|
+
- `node:fs` / `node:path` / `node:os`
|
|
51
|
+
- `PathUtil` relies on Node built-ins for synchronous file existence, cross-platform path joining, and shell-style variable expansion (`homedir`, `userInfo`).
|
package/src/utils/crayon.util.ts
DELETED
|
@@ -1,58 +0,0 @@
|
|
|
1
|
-
import { COLOR_HEX_REGEX } from '../constants';
|
|
2
|
-
|
|
3
|
-
type ColorizeOptions = {
|
|
4
|
-
bg?: string;
|
|
5
|
-
fg?: string;
|
|
6
|
-
};
|
|
7
|
-
|
|
8
|
-
function hexToRgb(hex: string): { r: number; g: number; b: number } {
|
|
9
|
-
return {
|
|
10
|
-
r: Number.parseInt(hex.slice(1, 3), 16),
|
|
11
|
-
g: Number.parseInt(hex.slice(3, 5), 16),
|
|
12
|
-
b: Number.parseInt(hex.slice(5, 7), 16),
|
|
13
|
-
};
|
|
14
|
-
}
|
|
15
|
-
|
|
16
|
-
function fgAnsi(hex: string): string {
|
|
17
|
-
const { r, g, b } = hexToRgb(hex);
|
|
18
|
-
return `\x1b[38;2;${r};${g};${b}m`;
|
|
19
|
-
}
|
|
20
|
-
|
|
21
|
-
function bgAnsi(hex: string): string {
|
|
22
|
-
const { r, g, b } = hexToRgb(hex);
|
|
23
|
-
return `\x1b[48;2;${r};${g};${b}m`;
|
|
24
|
-
}
|
|
25
|
-
|
|
26
|
-
function colorize(text: string, { bg, fg }: ColorizeOptions = {}): string {
|
|
27
|
-
const hasFg = fg !== undefined && COLOR_HEX_REGEX.test(fg);
|
|
28
|
-
const hasBg = bg !== undefined && COLOR_HEX_REGEX.test(bg);
|
|
29
|
-
|
|
30
|
-
if (!hasFg && !hasBg) {
|
|
31
|
-
return text;
|
|
32
|
-
}
|
|
33
|
-
|
|
34
|
-
const prefix = `${hasBg ? bgAnsi(bg) : ''}${hasFg ? fgAnsi(fg) : ''}`;
|
|
35
|
-
const suffix = `${hasFg ? '\x1b[39m' : ''}${hasBg ? '\x1b[49m' : ''}`;
|
|
36
|
-
|
|
37
|
-
return `${prefix}${text}${suffix}`;
|
|
38
|
-
}
|
|
39
|
-
|
|
40
|
-
const ANSI_ESCAPE_REGEX = new RegExp(`${String.fromCharCode(27)}\\[[0-?]*[ -/]*[@-~]`, 'g');
|
|
41
|
-
|
|
42
|
-
function stripAnsi(text: string): string {
|
|
43
|
-
return text.replace(ANSI_ESCAPE_REGEX, '');
|
|
44
|
-
}
|
|
45
|
-
|
|
46
|
-
export const crayon = {
|
|
47
|
-
colorize(text: string, opts: ColorizeOptions = {}): string {
|
|
48
|
-
return colorize(text, opts);
|
|
49
|
-
},
|
|
50
|
-
|
|
51
|
-
reverseVideo(text: string): string {
|
|
52
|
-
return `\x1b[7m${text}\x1b[27m`;
|
|
53
|
-
},
|
|
54
|
-
|
|
55
|
-
stripAnsi(text: string): string {
|
|
56
|
-
return stripAnsi(text);
|
|
57
|
-
},
|
|
58
|
-
};
|