@0xkahi/pi-qol 0.1.1 → 1.0.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.
Files changed (44) hide show
  1. package/README.md +13 -0
  2. package/assets/config.schema.json +12 -0
  3. package/package.json +4 -4
  4. package/src/codemap.md +26 -16
  5. package/src/config-loader.ts +4 -0
  6. package/src/constants.ts +1 -0
  7. package/src/extensions/auto-session-name/codemap.md +17 -12
  8. package/src/extensions/auto-session-name/title-generator.ts +1 -1
  9. package/src/extensions/codemap.md +173 -13
  10. package/src/extensions/context-view/capture.ts +394 -0
  11. package/src/extensions/context-view/codemap.md +213 -0
  12. package/src/extensions/context-view/constants.ts +4 -0
  13. package/src/extensions/context-view/context-view-controller.ts +67 -0
  14. package/src/extensions/context-view/index.ts +120 -0
  15. package/src/extensions/context-view/measure.ts +307 -0
  16. package/src/extensions/context-view/model.ts +207 -0
  17. package/src/extensions/context-view/ui/codemap.md +82 -0
  18. package/src/extensions/context-view/ui/context-view-dialog.ts +59 -0
  19. package/src/extensions/context-view/ui/injections-model.ts +118 -0
  20. package/src/extensions/context-view/ui/injections-view.ts +264 -0
  21. package/src/extensions/context-view/ui/skill-preview.ts +82 -0
  22. package/src/extensions/context-view/ui/usage-map.ts +133 -0
  23. package/src/extensions/context-view/ui/usage-view.ts +613 -0
  24. package/src/extensions/context-view/usage.ts +432 -0
  25. package/src/extensions/model-select/codemap.md +34 -17
  26. package/src/extensions/model-select/model-select-dialog.ts +85 -324
  27. package/src/index.ts +2 -0
  28. package/src/libs/codemap.md +8 -1
  29. package/src/libs/modal/README.md +212 -0
  30. package/src/libs/modal/codemap.md +34 -0
  31. package/src/libs/modal/index.ts +29 -0
  32. package/src/libs/modal/list-navigator.ts +167 -0
  33. package/src/libs/modal/modal-dialog.ts +297 -0
  34. package/src/libs/modal/navigation/pi-scheme.ts +33 -0
  35. package/src/libs/modal/navigation/vim-scheme.ts +56 -0
  36. package/src/libs/modal/preview-layer.ts +87 -0
  37. package/src/libs/modal/render-cache.ts +33 -0
  38. package/src/libs/modal/tab-strip.ts +87 -0
  39. package/src/libs/modal/tabs/list-tab.ts +159 -0
  40. package/src/libs/modal/text.ts +88 -0
  41. package/src/libs/modal/types.ts +70 -0
  42. package/src/schemas/codemap.md +100 -18
  43. package/src/schemas/config.schema.ts +3 -0
  44. package/src/schemas/context-view.config.schema.ts +13 -0
@@ -0,0 +1,432 @@
1
+ /** Forked from dimk90/pi-context-view at f6f007b867212bcf81a61519c8e40ce209cdd608 (MIT). */
2
+ /**
3
+ * Pure context-usage classification: combine the frozen Initial snapshot's
4
+ * prompt/tool decomposition with the live session messages into estimated
5
+ * category totals. No pi API access — unit-testable.
6
+ */
7
+ import { type ContextEvent, type ContextUsage, convertToLlm, estimateTokens } from '@earendil-works/pi-coding-agent';
8
+
9
+ import type {
10
+ ContextUsageSnapshot,
11
+ InitialSnapshot,
12
+ InjectionItem,
13
+ InvisibleReasoningEstimate,
14
+ ReportedContextUsage,
15
+ UsageCategory,
16
+ UsagePreviewEntry,
17
+ } from './model';
18
+
19
+ /** Everything computeUsage needs; messages must already be synthetic-filtered. */
20
+ export interface UsageInputs {
21
+ snapshot: InitialSnapshot;
22
+ messages: ContextEvent['messages'];
23
+ reported?: ReportedContextUsage;
24
+ modelLabel?: string;
25
+ computedAt?: Date;
26
+ /** Auto-compaction reserve (settings `reserveTokens`); omit when auto-compaction is disabled. */
27
+ autoCompactReserveTokens?: number;
28
+ }
29
+
30
+ /**
31
+ * Estimate the current/next-request context composition. Prompt and tool
32
+ * categories come from the frozen Initial snapshot; message categories are
33
+ * classified from the live session context. Empty categories are dropped and
34
+ * every aggregate equals the exact sum of its children.
35
+ */
36
+ export function computeUsage(inputs: UsageInputs): ContextUsageSnapshot {
37
+ const categories = [
38
+ ...classifyPromptCategories(inputs.snapshot),
39
+ ...classifyMessages(inputs.messages, contextOnlyMessages(inputs.snapshot)),
40
+ ].filter(category => category.tokens > 0);
41
+ return {
42
+ computedAt: inputs.computedAt ?? new Date(),
43
+ modelLabel: inputs.modelLabel,
44
+ reported: inputs.reported,
45
+ categories,
46
+ estimatedTokens: categories.reduce((sum, category) => sum + category.tokens, 0),
47
+ autoCompactReserveTokens: inputs.autoCompactReserveTokens,
48
+ };
49
+ }
50
+
51
+ /**
52
+ * Flatten one category's preview entries across its breakdown, chronologically
53
+ * when every entry is message-backed. Raw entry text is process-local; the
54
+ * caller must sanitize before rendering and never log or persist it.
55
+ */
56
+ export function collectPreviewEntries(category: UsageCategory): UsagePreviewEntry[] {
57
+ const entries: UsagePreviewEntry[] = [];
58
+ const visit = (node: UsageCategory): void => {
59
+ entries.push(...(node.entries ?? []));
60
+ for (const child of node.children ?? []) visit(child);
61
+ };
62
+ visit(category);
63
+ if (entries.length > 1 && entries.every(entry => entry.timestamp !== undefined)) {
64
+ entries.sort((a, b) => (a.timestamp ?? 0) - (b.timestamp ?? 0));
65
+ }
66
+ return entries;
67
+ }
68
+
69
+ /** Convert pi's nullable ContextUsage to the undefined-based model shape. */
70
+ export function toReportedUsage(usage: ContextUsage | undefined): ReportedContextUsage | undefined {
71
+ if (usage === undefined) return undefined;
72
+ return {
73
+ tokens: usage.tokens ?? undefined,
74
+ contextWindow: usage.contextWindow,
75
+ percent: usage.percent ?? undefined,
76
+ };
77
+ }
78
+
79
+ /** Map frozen snapshot items to prompt/tool/memory/skill categories. */
80
+ function classifyPromptCategories(snapshot: InitialSnapshot): UsageCategory[] {
81
+ const systemPrompt: UsageCategory[] = [];
82
+ const systemTools: UsageCategory[] = [];
83
+ const customTools: UsageCategory[] = [];
84
+ const mcpTools: UsageCategory[] = [];
85
+ const contextFiles: UsageCategory[] = [];
86
+ const skills: UsageCategory[] = [];
87
+ for (const group of snapshot.groups) {
88
+ for (const item of group.items) {
89
+ switch (item.kind) {
90
+ case 'base-prompt':
91
+ case 'append-prompt':
92
+ case 'prompt-addition':
93
+ systemPrompt.push(leafFromItem(item));
94
+ break;
95
+ case 'tool':
96
+ if (item.source.native) systemTools.push(...breakdownFromItem(item));
97
+ else if (isMcpTool(item)) mcpTools.push(leafFromItem(item));
98
+ else customTools.push(leafFromItem(item));
99
+ break;
100
+ case 'context-file':
101
+ contextFiles.push(leafFromItem(item));
102
+ break;
103
+ case 'skills':
104
+ skills.push(...breakdownFromItem(item));
105
+ break;
106
+ case 'message':
107
+ // Initial custom messages live in the session; classifyMessages counts them.
108
+ break;
109
+ }
110
+ }
111
+ }
112
+ return withoutEmpty([
113
+ aggregate('system-prompt', 'System Prompt', systemPrompt),
114
+ aggregate('system-tools', 'System Tools', systemTools),
115
+ aggregate('custom-tools', 'Custom Tools', customTools),
116
+ aggregate('mcp-tools', 'MCP Tools', mcpTools),
117
+ aggregate('context-files', 'Memory (AGENTS.md)', contextFiles),
118
+ aggregate('skills', 'Skills', skills),
119
+ ]);
120
+ }
121
+
122
+ /** Best-effort MCP attribution from the only public provenance field available. */
123
+ function isMcpTool(item: InjectionItem): boolean {
124
+ return /(^|[^a-z])mcp([^a-z]|$)/i.test(`${item.source.id} ${item.source.label}`);
125
+ }
126
+
127
+ /** Collect frozen messages that existed only in the transformed provider context. */
128
+ function contextOnlyMessages(snapshot: InitialSnapshot): InjectionItem[] {
129
+ return snapshot.groups.flatMap(group => group.items.filter(item => item.kind === 'message' && item.contextOnly === true));
130
+ }
131
+
132
+ /** Classify live session messages and frozen context-only injections with preview entries. */
133
+ function classifyMessages(messages: ContextEvent['messages'], contextOnly: readonly InjectionItem[]): UsageCategory[] {
134
+ const user: UsagePreviewEntry[] = [];
135
+ const agentText: UsagePreviewEntry[] = [];
136
+ const agentThinking: UsagePreviewEntry[] = [];
137
+ const agentToolCalls: UsagePreviewEntry[] = [];
138
+ const bashExecutions: UsagePreviewEntry[] = [];
139
+ const compacted: UsagePreviewEntry[] = [];
140
+ const toolResults = new Map<string, UsagePreviewEntry[]>();
141
+ const customMessages = new Map<string, UsagePreviewEntry[]>();
142
+
143
+ for (const item of contextOnly) {
144
+ appendEntry(customMessages, item.source.label, {
145
+ breadcrumb: [item.label],
146
+ tokens: item.tokens,
147
+ text: item.text,
148
+ });
149
+ }
150
+ for (const message of messages) {
151
+ switch (message.role) {
152
+ case 'user':
153
+ user.push({
154
+ timestamp: message.timestamp,
155
+ breadcrumb: ['user'],
156
+ tokens: estimateTokens(message),
157
+ text: contentToText(message.content),
158
+ });
159
+ break;
160
+ case 'assistant': {
161
+ const texts = message.content.flatMap(block => (block.type === 'text' ? [block.text] : []));
162
+ agentText.push(...blockEntries(message.timestamp, 'text', texts));
163
+ agentThinking.push(...thinkingEntries(message));
164
+ for (const block of message.content) {
165
+ if (block.type !== 'toolCall') continue;
166
+ const args = JSON.stringify(block.arguments);
167
+ agentToolCalls.push({
168
+ timestamp: message.timestamp,
169
+ breadcrumb: ['assistant', block.name],
170
+ tokens: textTokens(block.name.length + args.length),
171
+ text: `${block.name}(${args})`,
172
+ });
173
+ }
174
+ break;
175
+ }
176
+ case 'toolResult':
177
+ appendEntry(toolResults, message.toolName, {
178
+ timestamp: message.timestamp,
179
+ breadcrumb: [message.toolName],
180
+ tokens: estimateTokens(message),
181
+ text: contentToText(message.content),
182
+ });
183
+ break;
184
+ case 'custom':
185
+ appendEntry(customMessages, message.customType, {
186
+ timestamp: message.timestamp,
187
+ breadcrumb: [message.customType],
188
+ tokens: estimateTokens(message),
189
+ text: contentToText(message.content),
190
+ });
191
+ break;
192
+ case 'bashExecution': {
193
+ const tokens = transformedTokens(message);
194
+ // The transform drops `!!` bash executions: they never reach the provider.
195
+ if (tokens !== undefined) {
196
+ bashExecutions.push({
197
+ timestamp: message.timestamp,
198
+ breadcrumb: ['bash'],
199
+ tokens,
200
+ text: `$ ${message.command}\n${message.output}`,
201
+ });
202
+ }
203
+ break;
204
+ }
205
+ case 'branchSummary':
206
+ compacted.push({
207
+ timestamp: message.timestamp,
208
+ breadcrumb: ['branch'],
209
+ tokens: transformedTokens(message) ?? 0,
210
+ text: message.summary,
211
+ });
212
+ break;
213
+ case 'compactionSummary':
214
+ compacted.push({
215
+ timestamp: message.timestamp,
216
+ breadcrumb: ['compaction'],
217
+ tokens: transformedTokens(message) ?? 0,
218
+ text: message.summary,
219
+ });
220
+ break;
221
+ }
222
+ }
223
+
224
+ const toolOutput = aggregate(
225
+ 'tool-output',
226
+ 'Tool Output',
227
+ withoutEmpty([...leavesFromMap('tool-result', toolResults), leaf('bash-executions', 'Bash Executions', bashExecutions)]),
228
+ );
229
+ return withoutEmpty([
230
+ leaf('user-messages', 'User Messages', user),
231
+ leaf('agent-text-messages', 'Agent Text Messages', agentText),
232
+ leaf('agent-thinking-messages', 'Agent Thinking Messages', agentThinking),
233
+ leaf('agent-tool-call-messages', 'Agent Tool Call Messages', agentToolCalls),
234
+ toolOutput,
235
+ aggregate('extension-messages', 'Extensions', leavesFromMap('custom-message', customMessages)),
236
+ leaf('compacted-data', 'Compacted Data', compacted),
237
+ ]);
238
+ }
239
+
240
+ /** One category whose estimate is the exact sum of its preview entries. */
241
+ function leaf(id: string, label: string, entries: readonly UsagePreviewEntry[]): UsageCategory {
242
+ return {
243
+ id,
244
+ label,
245
+ tokens: entries.reduce((sum, entry) => sum + entry.tokens, 0),
246
+ entries,
247
+ };
248
+ }
249
+
250
+ /** Category carrying a snapshot item's label, estimate, and timeless content entry. */
251
+ function leafFromItem(item: InjectionItem): UsageCategory {
252
+ return {
253
+ id: `item:${item.id}`,
254
+ label: item.label,
255
+ tokens: item.tokens,
256
+ entries: [{ breadcrumb: [item.label], tokens: item.tokens, text: item.text }],
257
+ };
258
+ }
259
+
260
+ /**
261
+ * Tokens for a message as pi's LLM transform actually sends it, so wrapper text
262
+ * `estimateTokens` alone cannot see (summary tags, `Ran ...` bash framing) is
263
+ * counted. Returns undefined for messages the transform excludes from context.
264
+ */
265
+ function transformedTokens(message: ContextEvent['messages'][number]): number | undefined {
266
+ const converted = convertToLlm([message])[0];
267
+ return converted === undefined ? undefined : estimateTokens(converted);
268
+ }
269
+
270
+ /** Assistant-message shape narrowed out of the context event union. */
271
+ type AssistantContextMessage = Extract<ContextEvent['messages'][number], { role: 'assistant' }>;
272
+
273
+ /**
274
+ * Build thinking previews while accounting once per assistant message. Provider-reported
275
+ * reasoning replaces a smaller visible-text estimate; signature-only estimates stay approximate metadata.
276
+ */
277
+ function thinkingEntries(message: AssistantContextMessage): UsagePreviewEntry[] {
278
+ const texts = message.content.flatMap(block => (block.type === 'thinking' ? [block.thinking] : []));
279
+ const visibleTokens = textTokens(texts.reduce((sum, text) => sum + text.length, 0));
280
+ const reportedTokens = reportedReasoningTokens(message);
281
+ const countedTokens = Math.max(visibleTokens, reportedTokens ?? 0);
282
+ const signatureChars = message.content.reduce((sum, block) => {
283
+ if (block.type === 'thinking') return sum + stringLength(block.thinkingSignature);
284
+ if (block.type === 'toolCall') return sum + stringLength(block.thoughtSignature);
285
+ return sum;
286
+ }, 0);
287
+ const invisibleReasoning = createInvisibleReasoningEstimate(signatureChars, visibleTokens, reportedTokens);
288
+
289
+ if (texts.length === 0) {
290
+ if (countedTokens === 0 && invisibleReasoning === undefined) return [];
291
+ return [
292
+ {
293
+ timestamp: message.timestamp,
294
+ breadcrumb: ['assistant'],
295
+ tokens: countedTokens,
296
+ ...(invisibleReasoning === undefined ? {} : { visibleTokens: 0, invisibleReasoning }),
297
+ text: '',
298
+ },
299
+ ];
300
+ }
301
+
302
+ const allocations = allocateTextTokens(texts);
303
+ const entries = texts.map(
304
+ (text, index): UsagePreviewEntry => ({
305
+ timestamp: message.timestamp,
306
+ breadcrumb: texts.length > 1 ? ['assistant', `thinking ${index + 1}/${texts.length}`] : ['assistant'],
307
+ tokens: allocations[index] ?? 0,
308
+ text,
309
+ }),
310
+ );
311
+ const first = entries[0];
312
+ if (first !== undefined) {
313
+ const countedInvisibleTokens = countedTokens - visibleTokens;
314
+ entries[0] = {
315
+ ...first,
316
+ tokens: first.tokens + countedInvisibleTokens,
317
+ ...(invisibleReasoning === undefined ? {} : { visibleTokens: first.tokens, invisibleReasoning }),
318
+ };
319
+ }
320
+ return entries;
321
+ }
322
+
323
+ /** Describe a positive invisible share or signature-size proxy without retaining its source bytes. */
324
+ function createInvisibleReasoningEstimate(
325
+ signatureChars: number,
326
+ visibleTokens: number,
327
+ reportedTokens: number | undefined,
328
+ ): InvisibleReasoningEstimate | undefined {
329
+ if (reportedTokens !== undefined) {
330
+ const tokens = Math.max(0, reportedTokens - visibleTokens);
331
+ if (tokens === 0) return undefined;
332
+ return {
333
+ tokens,
334
+ basis: 'provider-reported',
335
+ encoded: signatureChars > 0,
336
+ };
337
+ }
338
+ if (signatureChars === 0) return undefined;
339
+ // chars/4 over a signature is a rough proxy, not a bound: the server decrypts the
340
+ // envelope and counts the reconstructed thinking, at a model-dependent ratio that
341
+ // measured either side of 4. See doc/THINKING.md.
342
+ return {
343
+ tokens: textTokens(signatureChars),
344
+ basis: 'signature-proxy',
345
+ encoded: true,
346
+ };
347
+ }
348
+
349
+ /** Accept only a finite, non-negative provider reasoning count from possibly old session data. */
350
+ function reportedReasoningTokens(message: AssistantContextMessage): number | undefined {
351
+ const usage: unknown = message.usage;
352
+ if (typeof usage !== 'object' || usage === null) return undefined;
353
+ const reasoning = (usage as { reasoning?: unknown }).reasoning;
354
+ return typeof reasoning === 'number' && Number.isFinite(reasoning) && reasoning >= 0 ? reasoning : undefined;
355
+ }
356
+
357
+ /** Pool chars/4 rounding across all blocks while retaining one preview entry per block. */
358
+ function allocateTextTokens(texts: readonly string[]): number[] {
359
+ const allocations = texts.map(text => Math.floor(text.length / 4));
360
+ const target = textTokens(texts.reduce((sum, text) => sum + text.length, 0));
361
+ let remainder = target - allocations.reduce((sum, tokens) => sum + tokens, 0);
362
+ const rankedIndexes = texts
363
+ .map((text, index) => ({ index, remainder: text.length % 4 }))
364
+ .filter(candidate => candidate.remainder > 0)
365
+ .sort((a, b) => b.remainder - a.remainder || a.index - b.index);
366
+ for (const candidate of rankedIndexes) {
367
+ if (remainder === 0) break;
368
+ allocations[candidate.index] = (allocations[candidate.index] ?? 0) + 1;
369
+ remainder--;
370
+ }
371
+ return allocations;
372
+ }
373
+
374
+ /** String length from an optional or untyped signature field without exposing its contents. */
375
+ function stringLength(value: unknown): number {
376
+ return typeof value === 'string' ? value.length : 0;
377
+ }
378
+
379
+ /** Per-block entries; the block-index cell appears only for multi-block messages. */
380
+ function blockEntries(timestamp: number, kind: string, texts: readonly string[]): UsagePreviewEntry[] {
381
+ return texts.map((text, index) => ({
382
+ timestamp,
383
+ breadcrumb: texts.length > 1 ? ['assistant', `${kind} ${index + 1}/${texts.length}`] : ['assistant'],
384
+ tokens: textTokens(text.length),
385
+ text,
386
+ }));
387
+ }
388
+
389
+ /** Text rendering of string-or-block message content; non-text blocks become placeholders. */
390
+ function contentToText(content: string | ReadonlyArray<{ type: string; text?: string }>): string {
391
+ if (typeof content === 'string') return content;
392
+ return content.map(block => (block.type === 'text' && block.text !== undefined ? block.text : `[${block.type}]`)).join('\n');
393
+ }
394
+
395
+ /** Expand an aggregate snapshot item into its children, or itself when it has none. */
396
+ function breakdownFromItem(item: InjectionItem): UsageCategory[] {
397
+ if (item.children === undefined || item.children.length === 0) return [leafFromItem(item)];
398
+ return item.children.map(child => leafFromItem(child));
399
+ }
400
+
401
+ /** Parent category whose total is the exact sum of its children; undefined when empty. */
402
+ function aggregate(id: string, label: string, children: UsageCategory[]): UsageCategory | undefined {
403
+ if (children.length === 0) return undefined;
404
+ return {
405
+ id,
406
+ label,
407
+ tokens: children.reduce((sum, child) => sum + child.tokens, 0),
408
+ children: [...children].sort((a, b) => b.tokens - a.tokens),
409
+ };
410
+ }
411
+
412
+ /** Keep only present categories with a non-zero estimate. */
413
+ function withoutEmpty(categories: Array<UsageCategory | undefined>): UsageCategory[] {
414
+ return categories.filter((category): category is UsageCategory => category !== undefined && category.tokens > 0);
415
+ }
416
+
417
+ /** Accumulate a preview entry under a map key. */
418
+ function appendEntry(totals: Map<string, UsagePreviewEntry[]>, key: string, entry: UsagePreviewEntry): void {
419
+ const entries = totals.get(key);
420
+ if (entries === undefined) totals.set(key, [entry]);
421
+ else entries.push(entry);
422
+ }
423
+
424
+ /** Leaves from accumulated per-key preview entries. */
425
+ function leavesFromMap(idPrefix: string, totals: Map<string, UsagePreviewEntry[]>): UsageCategory[] {
426
+ return [...totals.entries()].map(([label, entries]) => leaf(`${idPrefix}:${label}`, label, entries));
427
+ }
428
+
429
+ /** Same chars/4 heuristic pi's estimateTokens uses for text content. */
430
+ function textTokens(chars: number): number {
431
+ return Math.ceil(chars / 4);
432
+ }
@@ -6,17 +6,18 @@ This extension implements the `/select-model` command and its interactive picker
6
6
 
7
7
  ## Design Patterns
8
8
 
9
- - **Lazy command activation**: `registerModelSelect` waits for the first `session_start` event before calling `activateModelSelect`, ensuring the extension is wired up once a session exists.
9
+ - **Lazy command activation**: `registerModelSelect` waits for the first `session_start` event before calling `activateModelSelect`, ensuring the extension is wired up once a session exists and only when `model_select` is enabled.
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, applying the selected model, and bridging registry errors into the dialog.
13
+ - `index.ts`: orchestrates activation, command handling, applying the selected model, setting default reasoning, and bridging registry errors into the dialog.
14
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.
15
+ - `model-formatter.ts`: pure static utilities for labels, descriptions, sorting, token formatting, capability detection, and search-text generation.
16
+ - `model-select-dialog.ts`: thin `ModalDialog` (shared modal library) configuration: one `ListTab` per section (permanent Favourites, groups, Search), a shared filter input, notices for config warnings, and per-section row/empty-state/footer hooks.
17
17
  - `constants.ts`: command name, cross-extension event ID, and dialog rendering limits.
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
+ - `types.ts`: shared item, list, tab, and dialog option types.
19
+ - **Modal library delegation**: `ModelSelectDialog` implements `Component` and `Focusable` by delegating to a `ModalDialog` from `src/libs/modal/`; the shell owns the tab strip, tab cycling, keybinding-driven navigation (wrap-around selection via `ListTab`), the shared filter `Input`, and the help footer.
20
+ - **Layout-aware rendering**: the dialog uses the shell's `inline` frame or `bordered` frame (centered by host overlay options) depending on the `model_select.layout` config value.
20
21
  - **Defensive guards**: checks feature enablement, UI availability, idle state (`waitForIdle`), exact-match short-circuit, and auth availability before applying a model.
21
22
 
22
23
  ## Data & Control Flow
@@ -27,21 +28,22 @@ This extension implements the `/select-model` command and its interactive picker
27
28
 
28
29
  2. **Command invocation**
29
30
  - The command handler stores the command context as `latestCtx`.
30
- - It aborts if `model_select` is disabled.
31
+ - It aborts with a warning if `model_select` is disabled.
31
32
  - It calls `showModelSelector` with the raw argument string.
32
33
 
33
34
  3. **Selection short-circuit**
34
35
  - `showModelSelector` waits for idle if available, then refreshes the model registry.
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
+ - `findExactModel` tries two forms: `provider/modelId` and whitespace-separated `provider modelId`. If a matching model is found, it is applied immediately via `applySelectedModel` and the dialog is skipped.
36
37
  - If no UI is available and there is no exact match, a warning is shown and the picker exits.
37
38
 
38
39
  4. **Dialog path**
39
40
  - If no exact match is found and a UI is present, the extension loads the `model_select` config.
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.
41
+ - `buildModelLists` refreshes the registry, applies `provider_filter` only to the Search tab, sorts search items with the current model first, and validates configured favourites.
42
+ - Favourites must exist in the registry and have configured auth; missing or unauthenticated entries are collected as warnings and omitted from the list.
43
+ - Accepted favourites retain exact group memberships; the ordered `groups` config defines the visible group tabs. Duplicate favourite models are deduplicated by provider/id, and duplicate group names are collapsed while preserving configured order.
42
44
  - 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.
45
+ - `ctx.ui.custom` creates a `ModelSelectDialog` with favourite/group/search lists, tab visibility controls, the current model, warnings, `initialSearch`, `layout`, `defaultReasoning`, and an `onDone` callback. The overlay layout is centered at 85% width with a one-cell margin.
46
+ - The dialog always creates a Favourites tab, 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.
45
47
 
46
48
  5. **User interaction**
47
49
  - Keyboard input is mapped through `keybindings.matches` for navigation, ordered tab cycling (`tab`/`shift+tab`), page up/down, confirmation, and cancellation.
@@ -51,15 +53,30 @@ This extension implements the `/select-model` command and its interactive picker
51
53
 
52
54
  6. **Apply result**
53
55
  - If a model is selected, `applySelectedModel` calls `pi.setModel`.
56
+ - On success, if `model_select.default_reasoning` is configured and the chosen model supports that level, `pi.setThinkingLevel` is called to apply it.
54
57
  - A success or missing-auth notification is shown via `ctx.ui.notify`.
55
58
 
59
+ ## Configuration & Schema
60
+
61
+ The `model_select` configuration is defined by `../../schemas/model-select.config.schema` and included in the top-level `ConfigSchema` in `../../schemas/config.schema`.
62
+
63
+ - `enabled` (`boolean`, default `false`): feature toggle.
64
+ - `favourite` (`array`): each entry is `{ provider, modelId, groups?: string[] }`. Favourites are validated against the registry and auth state.
65
+ - `favourite_label` (`string`, default `'Favourites'`): label for the Favourites tab.
66
+ - `groups` (`array` of non-empty strings): ordered group names used as tabs; favourites can be assigned to one or more groups.
67
+ - `hide_tabs` (`{ groups: boolean, search: boolean }`, default both `false`): controls visibility of group tabs and the Search tab.
68
+ - `provider_filter` (`array` of non-empty strings): restricts the Search tab to the listed providers; Favourites and group tabs are not filtered.
69
+ - `default_reasoning` (optional `'off' | 'minimal' | 'low' | 'medium' | 'high' | 'xhigh'`): applied to the selected model if `getSupportedThinkingLevels` includes it.
70
+ - `layout` (`'inline' | 'overlay'`, default `'inline'`): picker layout.
71
+
56
72
  ## Integration Points
57
73
 
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`).
59
- - **`ExtensionContext` / `ExtensionCommandContext` (`@earendil-works/pi-coding-agent`)**: provides `modelRegistry`, `ui`, `hasUI`, `model`, and the optional `waitForIdle` guard.
74
+ - **`ExtensionAPI` (`@earendil-works/pi-coding-agent`)**: used to register the command, listen to `session_start`, set the active model (`pi.setModel`), set the thinking level (`pi.setThinkingLevel`), and access the shared event bus (`pi.events`).
75
+ - **`ExtensionContext` / `ExtensionCommandContext` (`@earendil-works/pi-coding-agent`)**: provides `modelRegistry`, `ui`, `hasUI`, `model`, `cwd`, and the optional `waitForIdle` guard.
60
76
  - **`ModelRegistry`**: refreshed and queried for available models, configured auth, lookup by `provider` + `modelId`, and error state (`getError`).
61
- - **`ConfigLoader` (`../../config-loader`)**: provides feature toggle state (`isEnabled('model_select')`) and the typed `model_select` configuration object.
62
- - **`@earendil-works/pi-ai`**: supplies the `Model<Api>` type and `modelsAreEqual` for stable identity comparisons.
77
+ - **`ConfigLoader` (`../../config-loader`)**: provides feature toggle state (`isEnabled('model_select')`), the typed `model_select` configuration object, and merges global + project JSON config.
78
+ - **`@earendil-works/pi-ai`**: supplies the `Model<Api>` type, `modelsAreEqual` for stable identity comparisons, and `getSupportedThinkingLevels` for reasoning-level validation.
63
79
  - **`@earendil-works/pi-tui`**: supplies the `Input` component, `fuzzyFilter`, `matchesKey`, theme helpers, and rendering utilities (`truncateToWidth`, `visibleWidth`) used by the dialog.
64
80
  - **`pi-vim-keys` / other extensions**: can trigger the picker by emitting `PI_VIM_KEY_EVENT_ID` on the shared event bus.
65
- - **Configuration schemas**: `model_select` shape, `ModelSelectLayout`, and `HideTabs` are defined by `../../schemas/config.schema` and `../../schemas/model-select.config.schema`.
81
+ - **`../../constants`**: provides the `piVimKeyEventId` helper used to derive the cross-extension event ID.
82
+ - **Configuration schemas**: `model_select` shape, `ModelSelectLayout`, `HideTabs`, and `ReasoningLevel` are defined by `../../schemas/model-select.config.schema`, `../../schemas/config.schema`, and `../../schemas/shared-config.schema`.