@0xkahi/pi-qol 0.0.6 → 0.1.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 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, optional favourites,
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** specified providers from model search
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
- "favourite": [{ "provider": "anthropic", "modelId": "claude-sonnet-4-5" }]
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 | Type | Default | Description |
140
- | ----------------- | --------- | -------- | --------------------------------------------------------- |
141
- | `enabled` | `boolean` | `false` | Turn the model picker on. |
142
- | `layout` | `enum` | `inline` | Picker layout: `inline` or `overlay`. |
143
- | `provider_filter` | `string[]`| `[]` | Restrict searchable models to these providers. |
144
- | `favourite` | `object[]`| `[]` | Favourite models shown in a separate tab (`provider`, `modelId`). |
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. If project
164
- config sets `model_select.favourite`, it replaces the global favourites array.
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",
@@ -87,6 +131,17 @@
87
131
  "minLength": 1
88
132
  }
89
133
  },
134
+ "default_reasoning": {
135
+ "type": "string",
136
+ "enum": [
137
+ "off",
138
+ "minimal",
139
+ "low",
140
+ "medium",
141
+ "high",
142
+ "xhigh"
143
+ ]
144
+ },
90
145
  "layout": {
91
146
  "default": "inline",
92
147
  "type": "string",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@0xkahi/pi-qol",
3
- "version": "0.0.6",
3
+ "version": "0.1.1",
4
4
  "description": "quality of life pi extensions",
5
5
  "type": "module",
6
6
  "keywords": [
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 and provider filtering.
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, output colorization, and Zod schemas for every feature.
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 favourites, search, and provider filtering.
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
- - The dialog uses fuzzy filtering, tab switching between favourites/search, and keyboard navigation; selection is applied via `pi.setModel`.
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
- - **Pure formatting helpers**: `token-stats.ts` and `progress-bar.ts` contain stateless functions for number formatting, usage aggregation, and progress-bar rendering, making them easy to test.
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. **Stats composition**: `buildStatsLeft` aggregates assistant-message usage from `sessionManager.getEntries()`, formats tokens, adds cache info, cost, context usage, and an optional subscription segment.
38
- 6. **Subscription usage**: `renderSubscriptionUsageSegment` resolves the provider, asks `SubscriptionUsageManager.ensureFresh(provider)` for cached data, picks the rate window with the nearest reset, and builds a colored progress segment.
39
- 7. **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.
40
- 8. **Git branch updates**: `footerData.onBranchChange` registers a render request callback that is cleaned up in `dispose`.
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
- - **`@0xkahi/cli-dye`**: Applies configured truecolor ANSI styling to directory text, model name, and subscription usage labels.
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.
@@ -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 a configured list of favourites. 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.
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, and applying the selected model.
14
- - `model-lists.ts`: queries the registry and prepares favourite + searchable model lists.
15
- - `model-formatter.ts`: pure static utilities for labels, descriptions, sorting, and token formatting.
16
- - `model-select-dialog.ts`: TUI component that renders the picker and translates user input into selection events.
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
- - If the argument can be parsed as `provider/modelId` and resolves through `findExactModel`, the model is applied immediately and the dialog is skipped.
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, optionally filters by `provider_filter`, sorts search items with the current model first, and validates configured favourites (collecting warnings for missing models or missing auth).
38
- - `ctx.ui.custom` creates a `ModelSelectDialog` with the prepared lists, current model, warnings, layout, and an `onDone` callback.
39
- - The dialog renders two sections (Favourites and Search), a search input, config warnings, and a help footer.
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, section switching, confirmation, and cancellation.
43
- - Typing printable characters switches focus to the search input and re-filters the search list via `fuzzyFilter`.
44
- - Confirming a selection invokes `onDone` with the chosen `Model`.
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, and lookup by `provider` + `modelId`.
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 `ModelSelectLayout` are defined by `../../schemas/config.schema` and `../../schemas/model-select.config.schema`.
65
+ - **Configuration schemas**: `model_select` shape, `ModelSelectLayout`, and `HideTabs` are defined by `../../schemas/config.schema` and `../../schemas/model-select.config.schema`.
@@ -1,22 +1,27 @@
1
- import type { Api, Model } from '@earendil-works/pi-ai';
1
+ import { type Api, getSupportedThinkingLevels, type Model } from '@earendil-works/pi-ai';
2
2
  import type { ExtensionAPI, ExtensionCommandContext, ExtensionContext } from '@earendil-works/pi-coding-agent';
3
3
  import type { ConfigLoader } from '../../config-loader';
4
+ import type { ModelSelectConfig } from '../../schemas/model-select.config.schema';
4
5
  import { COMMAND_NAME, PI_VIM_KEY_EVENT_ID } from './constants';
5
6
  import { ModelFormatter } from './model-formatter';
6
7
  import { buildModelLists, findExactModel } from './model-lists';
7
8
  import { ModelSelectDialog } from './model-select-dialog';
8
9
  import type { DialogResult } from './types';
9
10
 
10
- async function applySelectedModel(pi: ExtensionAPI, ctx: ExtensionContext, model: Model<Api>): Promise<void> {
11
+ export async function applySelectedModel(pi: ExtensionAPI, ctx: ExtensionContext, model: Model<Api>, config: ModelSelectConfig): Promise<void> {
11
12
  const success = await pi.setModel(model);
12
13
  if (success) {
14
+ const defaultReasoning = config.default_reasoning;
15
+ if (defaultReasoning && getSupportedThinkingLevels(model).includes(defaultReasoning)) {
16
+ pi.setThinkingLevel(defaultReasoning);
17
+ }
13
18
  ctx.ui.notify(`Model set to ${ModelFormatter.modelLabel(model)}`, 'info');
14
19
  } else {
15
20
  ctx.ui.notify(`No configured auth for ${ModelFormatter.modelLabel(model)}`, 'error');
16
21
  }
17
22
  }
18
23
 
19
- async function showModelSelector(pi: ExtensionAPI, args: string, ctx: ExtensionContext, configLoader: ConfigLoader): Promise<void> {
24
+ export async function showModelSelector(pi: ExtensionAPI, args: string, ctx: ExtensionContext, configLoader: ConfigLoader): Promise<void> {
20
25
  // `waitForIdle` only exists on command contexts. When invoked from the event
21
26
  // bus we get a plain ExtensionContext, so fall back to a best-effort guard.
22
27
  if ('waitForIdle' in ctx && typeof ctx.waitForIdle === 'function') {
@@ -24,9 +29,10 @@ async function showModelSelector(pi: ExtensionAPI, args: string, ctx: ExtensionC
24
29
  }
25
30
  ctx.modelRegistry.refresh();
26
31
 
32
+ const config = configLoader.getModelSelect();
27
33
  const exactModel = findExactModel(ctx, args);
28
34
  if (exactModel) {
29
- await applySelectedModel(pi, ctx, exactModel);
35
+ await applySelectedModel(pi, ctx, exactModel, config);
30
36
  return;
31
37
  }
32
38
 
@@ -35,7 +41,6 @@ async function showModelSelector(pi: ExtensionAPI, args: string, ctx: ExtensionC
35
41
  return;
36
42
  }
37
43
 
38
- const config = configLoader.getModelSelect();
39
44
  const modelLists = await buildModelLists(ctx, config);
40
45
  const registryError = ctx.modelRegistry.getError();
41
46
 
@@ -44,10 +49,14 @@ async function showModelSelector(pi: ExtensionAPI, args: string, ctx: ExtensionC
44
49
  new ModelSelectDialog(tui, theme, keybindings, {
45
50
  currentModel: ctx.model,
46
51
  favouriteItems: modelLists.favouriteItems,
52
+ favouriteLabel: config.favourite_label,
47
53
  favouriteWarnings: modelLists.favouriteWarnings,
48
- hasFavouriteSection: config.favourite.length > 0,
54
+ groupLists: modelLists.groupLists,
49
55
  searchItems: modelLists.searchItems,
56
+ hideGroupTabs: config.hide_tabs.groups,
57
+ hideSearchTab: config.hide_tabs.search,
50
58
  providerFilter: config.provider_filter,
59
+ defaultReasoning: config.default_reasoning,
51
60
  configWarnings: registryError ? [`models.json: ${registryError}`] : [],
52
61
  initialSearch: args.trim(),
53
62
  layout: config.layout,
@@ -66,7 +75,7 @@ async function showModelSelector(pi: ExtensionAPI, args: string, ctx: ExtensionC
66
75
  );
67
76
 
68
77
  if (selected) {
69
- await applySelectedModel(pi, ctx, selected);
78
+ await applySelectedModel(pi, ctx, selected, config);
70
79
  }
71
80
  }
72
81
 
@@ -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
- favouriteItems.push(ModelFormatter.toModelItem(model));
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
- return { favouriteItems, favouriteWarnings, searchItems: sortedSearchModels };
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, SelectionSection } from './types';
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 activeSection: SelectionSection;
11
- private selectedFavouriteIndex = 0;
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.activeSection = options.initialSearch || !options.hasFavouriteSection ? 'search' : 'favourites';
24
- const currentFavouriteIndex = options.currentModel
25
- ? options.favouriteItems.findIndex(item => modelsAreEqual(item.model, options.currentModel))
26
- : -1;
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.filteredSearchItems = this.filterItems(options.searchItems, options.initialSearch);
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.switchSection();
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 inner = safeWidth;
107
- const lines = this.buildContentLines(inner);
108
- const rule = this.theme.fg('border', '─'.repeat(inner));
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
- const wrapped = lines.map(line => `${side}${this.padLine(line, inner)}${side}`);
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 buildContentLines(inner: number): string[] {
127
- const lines: string[] = [];
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
- lines.push(this.line(this.renderTitle(), inner));
130
- lines.push(this.line(this.renderTabs(), inner));
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
- const padding = Math.max(0, innerWidth - visibleWidth(truncated));
158
- return truncated + ' '.repeat(padding);
176
+ return truncated + ' '.repeat(Math.max(0, innerWidth - visibleWidth(truncated)));
159
177
  }
160
178
 
161
- private switchSection(): void {
162
- if (!this.options.hasFavouriteSection) {
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,90 +186,146 @@ export class ModelSelectDialog implements Component, Focusable {
174
186
  }
175
187
 
176
188
  private moveSelection(delta: number): void {
177
- if (this.activeSection === 'favourites') {
178
- this.selectedFavouriteIndex = this.wrapIndex(this.selectedFavouriteIndex + delta, this.filteredFavouriteItems.length);
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
- if (length <= 0) {
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
- if (this.activeSection === 'favourites') {
194
- const item = this.filteredFavouriteItems[this.selectedFavouriteIndex];
195
- if (item) {
196
- this.options.onDone(item.model);
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 selectCurrentSearchItem(): void {
205
- const item = this.filteredSearchItems[this.selectedSearchIndex];
206
- if (item) {
207
- this.options.onDone(item.model);
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
- if (!trimmed) {
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 {
220
219
  const current = this.options.currentModel ? ModelFormatter.modelLabel(this.options.currentModel) : 'none';
221
- return `${this.theme.fg('customMessageLabel', this.theme.bold('Select Model'))} ${this.theme.fg('muted', `current: ${current}`)}`;
220
+ const reasoning = this.options.defaultReasoning ? ` • reasoning: ${this.options.defaultReasoning}` : '';
221
+ return `${this.theme.fg('customMessageLabel', this.theme.bold('Select Model'))} ${this.theme.fg('muted', `current: ${current}${reasoning}`)}`;
222
222
  }
223
223
 
224
- private renderTabs(): string {
225
- const tabs: string[] = [];
226
- if (this.options.hasFavouriteSection) {
227
- tabs.push(this.renderTab('favourites', `Favourites ${this.filteredFavouriteItems.length}`));
224
+ private renderTabs(width: number): string {
225
+ const labels = this.tabs.map(tab => `[${tab.label} ${tab.filteredItems.length}]`);
226
+ const separator = ' ';
227
+ if (visibleWidth(labels.join(separator)) <= width) {
228
+ return this.styleTabLabels(labels, 0, labels.length - 1, false, false);
228
229
  }
229
- tabs.push(this.renderTab('search', `Search ${this.filteredSearchItems.length}`));
230
- return tabs.join(this.theme.fg('muted', ' '));
230
+
231
+ let start = this.activeTabIndex;
232
+ let end = this.activeTabIndex;
233
+ let expandLeft = true;
234
+ while (true) {
235
+ const nextStart = expandLeft && start > 0 ? start - 1 : start;
236
+ const nextEnd = !expandLeft && end < labels.length - 1 ? end + 1 : end;
237
+ expandLeft = !expandLeft;
238
+
239
+ if (nextStart === start && nextEnd === end) {
240
+ if ((start === 0 || nextStart === start) && (end === labels.length - 1 || nextEnd === end)) break;
241
+ continue;
242
+ }
243
+
244
+ const candidate = this.plainTabViewport(labels, nextStart, nextEnd);
245
+ if (visibleWidth(candidate) <= width) {
246
+ start = nextStart;
247
+ end = nextEnd;
248
+ continue;
249
+ }
250
+
251
+ const otherStart = start > 0 ? start - 1 : start;
252
+ const otherEnd = end < labels.length - 1 ? end + 1 : end;
253
+ if ((otherStart === start && otherEnd === end) || visibleWidth(this.plainTabViewport(labels, otherStart, otherEnd)) > width) break;
254
+ start = otherStart;
255
+ end = otherEnd;
256
+ }
257
+
258
+ const leftOmitted = start > 0;
259
+ const rightOmitted = end < labels.length - 1;
260
+ const plain = this.plainTabViewport(labels, start, end);
261
+ if (visibleWidth(plain) <= width) {
262
+ return this.styleTabLabels(labels, start, end, leftOmitted, rightOmitted);
263
+ }
264
+
265
+ const prefix = leftOmitted ? '… ' : '';
266
+ const suffix = rightOmitted ? ' …' : '';
267
+ const activeBudget = Math.max(1, width - visibleWidth(prefix) - visibleWidth(suffix));
268
+ const active = truncateToWidth(labels[this.activeTabIndex] ?? '', activeBudget, '');
269
+ return this.line(`${this.theme.fg('muted', prefix)}${this.theme.fg('accent', this.theme.bold(active))}${this.theme.fg('muted', suffix)}`, width);
231
270
  }
232
271
 
233
- private renderTab(section: SelectionSection, label: string): string {
234
- const text = `[${label}]`;
235
- if (this.activeSection === section) {
236
- return this.theme.fg('accent', this.theme.bold(text));
272
+ private plainTabViewport(labels: string[], start: number, end: number): string {
273
+ const parts = labels.slice(start, end + 1);
274
+ if (start > 0) parts.unshift('…');
275
+ if (end < labels.length - 1) parts.push('…');
276
+ return parts.join(' ');
277
+ }
278
+
279
+ private styleTabLabels(labels: string[], start: number, end: number, leftOmitted: boolean, rightOmitted: boolean): string {
280
+ const parts: string[] = [];
281
+ if (leftOmitted) parts.push(this.theme.fg('muted', '…'));
282
+ for (let index = start; index <= end; index++) {
283
+ const label = labels[index] ?? '';
284
+ parts.push(index === this.activeTabIndex ? this.theme.fg('accent', this.theme.bold(label)) : this.theme.fg('muted', label));
237
285
  }
238
- return this.theme.fg('muted', text);
286
+ if (rightOmitted) parts.push(this.theme.fg('muted', '…'));
287
+ return parts.join(this.theme.fg('muted', ' '));
239
288
  }
240
289
 
241
- private renderFavourites(width: number): string[] {
290
+ private renderActiveTab(width: number): string[] {
291
+ const tab = this.activeTab();
242
292
  const lines: string[] = [];
243
293
 
244
- lines.push(this.line(this.theme.fg('muted', 'Filter:'), width));
245
- lines.push(...this.searchInput.render(width));
246
- lines.push('');
294
+ if (tab.identity.kind === 'search') {
295
+ const providerText =
296
+ this.options.providerFilter.length === 0 ? 'all authorized providers' : `providers: ${this.options.providerFilter.join(', ')}`;
297
+ lines.push(this.line(this.theme.fg('muted', `Provider filter: ${providerText}`), width));
298
+ lines.push(this.line(this.theme.fg('muted', 'Search query:'), width));
299
+ } else {
300
+ lines.push(this.line(this.theme.fg('muted', 'Filter:'), width));
301
+ }
302
+ lines.push(...this.searchInput.render(width), '');
247
303
 
248
- if (this.options.favouriteItems.length === 0) {
249
- lines.push(this.line(this.theme.fg('muted', ' No configured favourites are available.'), width));
250
- } else if (this.filteredFavouriteItems.length === 0) {
251
- lines.push(this.line(this.theme.fg('muted', ' No matching favourites'), width));
304
+ if (tab.items.length === 0) {
305
+ lines.push(this.line(this.theme.fg('muted', this.emptyTabMessage(tab)), width));
306
+ } else if (tab.filteredItems.length === 0) {
307
+ lines.push(this.line(this.theme.fg('muted', ` No matching ${tab.identity.kind === 'search' ? 'models' : 'favourites'}`), width));
252
308
  } else {
253
- lines.push(...this.renderModelList(this.filteredFavouriteItems, this.selectedFavouriteIndex, width));
254
- const selected = this.filteredFavouriteItems[this.selectedFavouriteIndex];
309
+ lines.push(...this.renderModelList(tab.filteredItems, tab.selectedIndex, width));
310
+ const selected = tab.filteredItems[tab.selectedIndex];
255
311
  if (selected) {
256
- lines.push('');
257
- lines.push(this.line(this.theme.fg('muted', ` ${selected.description}`), width));
312
+ lines.push('', this.line(this.theme.fg('muted', ` ${selected.description}`), width));
258
313
  }
259
314
  }
260
315
 
316
+ if (tab.identity.kind === 'favourites') {
317
+ this.appendFavouriteWarnings(lines, width);
318
+ }
319
+ return lines;
320
+ }
321
+
322
+ private emptyTabMessage(tab: DialogTab): string {
323
+ if (tab.identity.kind === 'favourites') return ' No configured favourites are available.';
324
+ if (tab.identity.kind === 'group') return ` No available favourites in ${tab.label}.`;
325
+ return ' No matching models';
326
+ }
327
+
328
+ private appendFavouriteWarnings(lines: string[], width: number): void {
261
329
  for (const warning of this.options.favouriteWarnings.slice(0, MAX_CONFIG_WARNING_LINES)) {
262
330
  lines.push(this.line(this.theme.fg('warning', ` ⚠ ${warning}`), width));
263
331
  }
@@ -269,52 +337,20 @@ export class ModelSelectDialog implements Component, Focusable {
269
337
  ),
270
338
  );
271
339
  }
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
340
  }
300
341
 
301
342
  private renderModelList(items: ModelItem[], selectedIndex: number, width: number): string[] {
302
- const lines: string[] = [];
303
343
  const startIndex = Math.max(0, Math.min(selectedIndex - Math.floor(MAX_VISIBLE_MODELS / 2), items.length - MAX_VISIBLE_MODELS));
304
344
  const endIndex = Math.min(startIndex + MAX_VISIBLE_MODELS, items.length);
345
+ const lines: string[] = [];
305
346
 
306
347
  for (let index = startIndex; index < endIndex; index++) {
307
348
  const item = items[index];
308
- if (!item) {
309
- continue;
310
- }
311
- lines.push(this.renderModelItem(item, index === selectedIndex, width));
349
+ if (item) lines.push(this.renderModelItem(item, index === selectedIndex, width));
312
350
  }
313
-
314
351
  if (startIndex > 0 || endIndex < items.length) {
315
352
  lines.push(this.line(this.theme.fg('dim', ` (${selectedIndex + 1}/${items.length})`), width));
316
353
  }
317
-
318
354
  return lines;
319
355
  }
320
356
 
@@ -327,7 +363,7 @@ export class ModelSelectDialog implements Component, Focusable {
327
363
  }
328
364
 
329
365
  private renderHelp(): string {
330
- const tabHint = this.options.hasFavouriteSection ? 'tab switch sections • ' : '';
366
+ const tabHint = this.tabs.length > 1 ? 'tab/shift+tab switch sections • ' : '';
331
367
  return this.theme.fg('dim', `${tabHint}↑↓ navigate • enter select • esc cancel`);
332
368
  }
333
369
 
@@ -1,5 +1,6 @@
1
1
  import type { Api, Model } from '@earendil-works/pi-ai';
2
2
  import type { ModelSelectLayout } from '../../schemas/model-select.config.schema';
3
+ import type { ReasoningLevel } from '../../schemas/shared-config.schema';
3
4
 
4
5
  export type ModelItem = {
5
6
  model: Model<Api>;
@@ -7,23 +8,33 @@ export type ModelItem = {
7
8
  searchText: string;
8
9
  };
9
10
 
11
+ export type ModelGroupList = {
12
+ name: string;
13
+ items: ModelItem[];
14
+ };
15
+
10
16
  export type ModelLists = {
11
17
  favouriteItems: ModelItem[];
12
18
  favouriteWarnings: string[];
19
+ groupLists: ModelGroupList[];
13
20
  searchItems: ModelItem[];
14
21
  };
15
22
 
16
- export type SelectionSection = 'favourites' | 'search';
23
+ export type TabIdentity = { kind: 'favourites' } | { kind: 'group'; name: string } | { kind: 'search' };
17
24
 
18
25
  export type DialogResult = Model<Api> | null;
19
26
 
20
27
  export type DialogOptions = {
21
28
  currentModel: Model<Api> | undefined;
22
29
  favouriteItems: ModelItem[];
30
+ favouriteLabel: string;
23
31
  favouriteWarnings: string[];
24
- hasFavouriteSection: boolean;
32
+ groupLists: ModelGroupList[];
25
33
  searchItems: ModelItem[];
34
+ hideGroupTabs: boolean;
35
+ hideSearchTab: boolean;
26
36
  providerFilter: string[];
37
+ defaultReasoning?: ReasoningLevel;
27
38
  configWarnings: string[];
28
39
  initialSearch: string;
29
40
  layout: ModelSelectLayout;
@@ -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`, and `custom-footer`, plus reusable shared schema building blocks.
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 `ColorHexSchema`.
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
- import { ModelConfigSchema } from './shared-config.schema';
2
+ import { ModelConfigSchema, ReasoningLevelSchema } from './shared-config.schema';
3
3
 
4
- const FavouriteModelSchema = ModelConfigSchema.omit({ reasoning: true });
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,34 @@ 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
- provider_filter: z.array(z.string().min(1)).default([]),
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([]),
25
+ default_reasoning: ReasoningLevelSchema.optional(),
13
26
  layout: ModelSelectLayoutSchema.default('inline'),
14
27
  });
15
28
  export type ModelSelectConfig = z.infer<typeof ModelSelectConfigSchema>;
16
29
 
17
- export const PartialModelSelectConfigSchema = ModelSelectConfigSchema.partial();
30
+ export const PartialModelSelectConfigSchema = z.object({
31
+ enabled: z.boolean().optional(),
32
+ favourite: z
33
+ .array(
34
+ ModelConfigSchema.omit({ reasoning: true }).extend({
35
+ groups: z.array(NonEmptyNameSchema).optional(),
36
+ }),
37
+ )
38
+ .optional(),
39
+ favourite_label: NonEmptyNameSchema.optional(),
40
+ groups: z.array(NonEmptyNameSchema).optional(),
41
+ hide_tabs: z
42
+ .object({
43
+ groups: z.boolean().optional(),
44
+ search: z.boolean().optional(),
45
+ })
46
+ .optional(),
47
+ provider_filter: z.array(NonEmptyNameSchema).optional(),
48
+ default_reasoning: ReasoningLevelSchema.optional(),
49
+ layout: ModelSelectLayoutSchema.optional(),
50
+ });
18
51
  export type PartialModelSelectConfig = z.infer<typeof PartialModelSelectConfigSchema>;
@@ -6,7 +6,7 @@ This folder contains low-level, reusable helpers used across the `pi-qol` extens
6
6
 
7
7
  - **`model-resolver.util.ts`** — Resolve a concrete AI model and its authentication credentials from a configured `ModelConfig` or the active session model.
8
8
  - **`raw-data-parser.util.ts`** — Type-safe coercion helpers for `unknown` runtime values into `Record<string, unknown>`, trimmed `string`, or finite `number`.
9
- - **`path.util.ts`** — Locate extension-specific files on disk: generic file existence checks, global/project extension `config.json`, and the shared `auth.json` file.
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.
10
10
 
11
11
  ## Design Patterns
12
12
 
@@ -30,6 +30,7 @@ This folder contains low-level, reusable helpers used across the `pi-qol` extens
30
30
  - `numberValue` coerces strings/numbers and returns only finite values.
31
31
 
32
32
  3. **Path resolution**
33
+ - `PathUtil.expandPath` replaces shell-style variables (`~`, `$HOME`, `$VAR`, `${VAR}`) and `~` with the user's home directory.
33
34
  - `PathUtil.findFile` checks `existsSync` and returns both existence and the resolved path.
34
35
  - `findExtensionConfig({ type: 'global' })` resolves to `<agentDir>/extensions/<EXTENSION_ID>/config.json`.
35
36
  - `findExtensionConfig({ type: 'project', cwd })` resolves to `<cwd>/.pi/extensions/<EXTENSION_ID>/config.json`.
@@ -46,5 +47,5 @@ This folder contains low-level, reusable helpers used across the `pi-qol` extens
46
47
  - `EXTENSION_ID` is used by `PathUtil` to build config directory paths.
47
48
  - `../schemas/shared-config.schema`
48
49
  - `ModelConfig` and its `reasoning` field are consumed by `ModelResolver`.
49
- - `node:fs` / `node:path`
50
- - `PathUtil` relies on Node built-ins for synchronous file existence and cross-platform path joining.
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`).