@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,159 @@
1
+ /**
2
+ * Generic selectable-list tab: the common "browse/filter/confirm a list"
3
+ * modal content. Built on `ListNavigator`; callers supply item rendering and
4
+ * the confirm action. Optional fuzzy filtering wires into the dialog's shared
5
+ * filter input.
6
+ */
7
+ import type { Theme } from '@earendil-works/pi-coding-agent';
8
+ import { fuzzyFilter } from '@earendil-works/pi-tui';
9
+ import { ListNavigator } from '../list-navigator';
10
+ import { BODY_INDENT, fitLine } from '../text';
11
+ import type { Hint, ModalTab, NavigationAction } from '../types';
12
+
13
+ /** Counts handed to dynamic labels so tab-strip text can track filtering. */
14
+ export interface ListTabCounts {
15
+ items: number;
16
+ filtered: number;
17
+ }
18
+
19
+ /** State handed to the footer hook after the list body has rendered. */
20
+ export interface ListTabFooterState<T> {
21
+ filtered: readonly T[];
22
+ selected: T | undefined;
23
+ selectedIndex: number;
24
+ width: number;
25
+ }
26
+
27
+ export interface ListTabOptions<T> {
28
+ /** Static label, or a function of live item counts (re-read every render). */
29
+ label: string | ((counts: ListTabCounts) => string);
30
+ items: readonly T[];
31
+ renderRow: (item: T, selected: boolean, width: number) => string;
32
+ onConfirm: (item: T) => void;
33
+ /** Per-item search text; enables `applyFilter` fuzzy filtering. */
34
+ filterText?: (item: T) => string;
35
+ /** Caption lines rendered above the dialog's shared filter input. */
36
+ filterCaption?: () => string[];
37
+ /** Lines below the list, for example a selection description or warnings. */
38
+ footer?: (state: ListTabFooterState<T>) => string[];
39
+ /** Shown when `items` is empty. */
40
+ emptyMessage?: string | (() => string);
41
+ /** Shown when items exist but the filter hides all of them. */
42
+ noMatchMessage?: string | (() => string);
43
+ /** Wrap selection at list boundaries (picker convention); default clamps. */
44
+ wrap?: boolean;
45
+ /** Fixed list window size; defaults to the render-provided height. */
46
+ visibleCount?: number;
47
+ /** Initially selected index, for example the current entry. */
48
+ initialIndex?: number;
49
+ /** Tab-specific hints; defaults to `[Enter, Select]`. */
50
+ hints?: () => Hint[];
51
+ }
52
+
53
+ export class ListTab<T> implements ModalTab {
54
+ private readonly navigator: ListNavigator;
55
+ private filtered: T[];
56
+
57
+ public constructor(
58
+ private readonly theme: Theme,
59
+ private readonly options: ListTabOptions<T>,
60
+ ) {
61
+ this.filtered = [...options.items];
62
+ this.navigator = new ListNavigator(this.filtered.length, 1, this.filtered.length, { wrap: options.wrap });
63
+ if (options.initialIndex !== undefined) this.navigator.moveTo(options.initialIndex);
64
+ }
65
+
66
+ public get label(): string {
67
+ const label = this.options.label;
68
+ return typeof label === 'function' ? label({ items: this.options.items.length, filtered: this.filtered.length }) : label;
69
+ }
70
+
71
+ public applyFilter(query: string): void {
72
+ const filterText = this.options.filterText;
73
+ const trimmed = query.trim();
74
+ this.filtered = filterText !== undefined && trimmed !== '' ? fuzzyFilter([...this.options.items], trimmed, filterText) : [...this.options.items];
75
+ this.navigator.setRowCount(this.filtered.length);
76
+ }
77
+
78
+ public filterCaption(): string[] {
79
+ return this.options.filterCaption?.() ?? [];
80
+ }
81
+
82
+ public hints(): Hint[] {
83
+ return this.options.hints?.() ?? [['Enter', 'Select']];
84
+ }
85
+
86
+ public handleInput(_data: string): void {
87
+ // List content is driven by the dialog's filter input; nothing to do.
88
+ }
89
+
90
+ public handleNavigation(action: NavigationAction): void {
91
+ switch (action) {
92
+ case 'step-back':
93
+ this.navigator.moveBy(-1);
94
+ break;
95
+ case 'step-forward':
96
+ this.navigator.moveBy(1);
97
+ break;
98
+ case 'page-back':
99
+ this.navigator.page(-1);
100
+ break;
101
+ case 'page-forward':
102
+ this.navigator.page(1);
103
+ break;
104
+ case 'first':
105
+ this.navigator.moveTo(0);
106
+ break;
107
+ case 'last':
108
+ this.navigator.moveTo(this.filtered.length - 1);
109
+ break;
110
+ case 'confirm': {
111
+ const item = this.filtered[this.navigator.selected];
112
+ if (item !== undefined) this.options.onConfirm(item);
113
+ break;
114
+ }
115
+ }
116
+ }
117
+
118
+ public render(width: number, height: number | undefined): string[] {
119
+ if (this.options.items.length === 0) {
120
+ return [this.message(this.options.emptyMessage ?? 'No items', width), ...this.renderFooter(width)];
121
+ }
122
+ if (this.filtered.length === 0) {
123
+ return [this.message(this.options.noMatchMessage ?? 'No matching items', width), ...this.renderFooter(width)];
124
+ }
125
+
126
+ const visibleCount = Math.max(1, this.options.visibleCount ?? height ?? this.filtered.length);
127
+ this.navigator.setVisibleCount(visibleCount);
128
+
129
+ const lines: string[] = [];
130
+ const start = this.navigator.offset;
131
+ for (let index = start; index < start + this.navigator.windowSize; index++) {
132
+ const item = this.filtered[index];
133
+ if (item === undefined) break;
134
+ lines.push(fitLine(this.options.renderRow(item, index === this.navigator.selected, width), width));
135
+ }
136
+ if (this.navigator.hasOverflow) {
137
+ lines.push(fitLine(this.theme.fg('dim', `${BODY_INDENT}(${this.navigator.selected + 1}/${this.filtered.length})`), width));
138
+ }
139
+
140
+ lines.push(...this.renderFooter(width));
141
+ return lines;
142
+ }
143
+
144
+ private renderFooter(width: number): string[] {
145
+ return (
146
+ this.options.footer?.({
147
+ filtered: this.filtered,
148
+ selected: this.filtered[this.navigator.selected],
149
+ selectedIndex: this.navigator.selected,
150
+ width,
151
+ }) ?? []
152
+ );
153
+ }
154
+
155
+ private message(message: string | (() => string), width: number): string {
156
+ const text = typeof message === 'function' ? message() : message;
157
+ return fitLine(this.theme.fg('muted', `${BODY_INDENT}${text}`), width);
158
+ }
159
+ }
@@ -0,0 +1,88 @@
1
+ /** Forked from dimk90/pi-context-view at f6f007b867212bcf81a61519c8e40ce209cdd608 (MIT). */
2
+ /**
3
+ * Shared modal text/layout helpers: indentation constants, terminal-height
4
+ * viewport math, width fitting, and hint-row formatting. Pure string/number
5
+ * logic — no pi access.
6
+ */
7
+ import type { Theme, ThemeColor } from '@earendil-works/pi-coding-agent';
8
+ import { truncateToWidth, visibleWidth, wrapTextWithAnsi } from '@earendil-works/pi-tui';
9
+
10
+ /** Hint-row key label for the single-step navigation keys modals accept. */
11
+ export const STEP_KEY_HINT = '↑↓/jk';
12
+
13
+ /** Two-space indent for descriptions, counters, hints, and body content. */
14
+ export const BODY_INDENT = ' ';
15
+ export const DEFAULT_TERMINAL_ROWS = 24;
16
+
17
+ /** How many content rows fit and whether an overflow indicator is needed. */
18
+ export interface Viewport {
19
+ visibleCount: number;
20
+ showScroll: boolean;
21
+ }
22
+
23
+ /** Divide terminal rows between content and an overflow indicator. */
24
+ export function calculateViewport(itemCount: number, terminalRows: number, fixedLineCount: number, extraLineCount = 0): Viewport {
25
+ const available = Math.max(1, terminalRows - fixedLineCount - extraLineCount);
26
+ const showScroll = itemCount > available && available > 1;
27
+ return {
28
+ visibleCount: Math.max(1, available - (showScroll ? 1 : 0)),
29
+ showScroll,
30
+ };
31
+ }
32
+
33
+ /** Keep emergency short-terminal output bounded while preserving both borders. */
34
+ export function fitToTerminalHeight(lines: string[], terminalRows: number, border: string): string[] {
35
+ if (lines.length <= terminalRows) return lines;
36
+ if (terminalRows === 1) return [border];
37
+ return [...lines.slice(0, terminalRows - 1), border];
38
+ }
39
+
40
+ /** Normalize an injected terminal-height reading to a usable positive integer. */
41
+ export function normalizeTerminalRows(rows: number): number {
42
+ return Number.isFinite(rows) ? Math.max(1, Math.floor(rows)) : DEFAULT_TERMINAL_ROWS;
43
+ }
44
+
45
+ /** Truncate one rendered line to the supplied width. */
46
+ export function fitLine(line: string, width: number): string {
47
+ return truncateToWidth(line, width, '…');
48
+ }
49
+
50
+ /** Collapse embedded newlines and truncate to one fitted single line. */
51
+ export function singleLine(text: string, width: number): string {
52
+ return truncateToWidth(text.replace(/[\r\n]+/g, ' '), Math.max(1, width), '');
53
+ }
54
+
55
+ /** Fit one line to the exact width, padding with trailing spaces. */
56
+ export function padLine(text: string, width: number): string {
57
+ const truncated = singleLine(text, width);
58
+ return truncated + ' '.repeat(Math.max(0, width - visibleWidth(truncated)));
59
+ }
60
+
61
+ /** Wrap plain dialog-description text with semantic color and an indented continuation column. */
62
+ export function wrapDescriptionLines(theme: Theme, text: string, color: ThemeColor, width: number): string[] {
63
+ const indentWidth = Math.min(BODY_INDENT.length, Math.max(0, width - 1));
64
+ const indent = BODY_INDENT.slice(0, indentWidth);
65
+ const contentWidth = Math.max(1, width - indentWidth);
66
+ const wrapped = wrapTextWithAnsi(text, contentWidth);
67
+ return (wrapped.length === 0 ? [''] : wrapped).map(line => truncateToWidth(theme.fg(color, `${indent}${line}`), width, ''));
68
+ }
69
+
70
+ /** Spread left and right content across the width, truncating the left side on overlap. */
71
+ export function spreadLine(left: string, right: string, width: number): string {
72
+ const gap = width - visibleWidth(left) - visibleWidth(right);
73
+ if (gap < 1) {
74
+ return fitLine(`${truncateToWidth(left, Math.max(1, width - visibleWidth(right) - 2), '…')} ${right}`, width);
75
+ }
76
+ return `${left}${' '.repeat(gap)}${right}`;
77
+ }
78
+
79
+ /** Pi-style hint row: two-space indent, `key description` pairs joined by ` · `. */
80
+ export function hintRow(theme: Theme, hints: ReadonlyArray<readonly [string, string]>): string {
81
+ const separator = theme.fg('dim', ' · ');
82
+ return `${BODY_INDENT}${hints.map(([key, description]) => hint(theme, key, description)).join(separator)}`;
83
+ }
84
+
85
+ /** Pi-style hint: dim key, slightly brighter (muted) description. */
86
+ function hint(theme: Theme, key: string, description: string): string {
87
+ return theme.fg('dim', key) + theme.fg('muted', ` ${description}`);
88
+ }
@@ -0,0 +1,70 @@
1
+ /**
2
+ * Shared modal contracts: navigation schemes, tabs, and layers.
3
+ *
4
+ * Everything in `src/libs/modal/` imports only from Pi host packages so the
5
+ * directory can be copied unchanged into other Pi plugin projects.
6
+ */
7
+
8
+ /** Semantic action produced by a navigation scheme for one key press. */
9
+ export type NavigationAction = 'step-back' | 'step-forward' | 'page-back' | 'page-forward' | 'first' | 'last' | 'confirm' | 'dismiss';
10
+
11
+ /** Result of a scheme consuming one raw key: swallowed, mapped, or ignored. */
12
+ export type NavigationResult = { handled: boolean; action?: NavigationAction };
13
+
14
+ /** One `[keys, description]` hint pair for the dialog help footer. */
15
+ export type Hint = readonly [string, string];
16
+
17
+ /**
18
+ * Pure key-to-action mapper. Schemes never see dialog state; stateful chords
19
+ * (for example `gg`) are cleared via `reset()` on tab switches and layer
20
+ * changes. `dismiss` is always intercepted by the dialog shell and is never
21
+ * forwarded to tabs or layers.
22
+ */
23
+ export interface NavigationScheme {
24
+ consume(data: string): NavigationResult;
25
+ reset(): void;
26
+ /** Movement key hints; `stepLabel` adapts the step verb (Navigate/Scroll). */
27
+ hints(stepLabel?: string): Hint[];
28
+ }
29
+
30
+ /** Content layer pushed above a tab, for example a scrollable preview. */
31
+ export interface ModalLayer {
32
+ render(width: number, height: number | undefined): string[];
33
+ handleInput(data: string): void;
34
+ handleNavigation(action: NavigationAction): void;
35
+ hints(): Hint[];
36
+ invalidate?(): void;
37
+ }
38
+
39
+ /** Per-tab services provided by the dialog shell at attachment time. */
40
+ export interface ModalTabContext {
41
+ /** Push a layer above this tab; dismissal pops it before closing the dialog. */
42
+ pushLayer(layer: ModalLayer): void;
43
+ }
44
+
45
+ /**
46
+ * Strategy interface for modal tab content. The shell owns framing, the tab
47
+ * strip, tab cycling, per-tab layer stacks, the optional filter input, and
48
+ * the help footer; a tab owns only its content.
49
+ *
50
+ * `render` receives the content width and, for height-bounded dialogs, the
51
+ * exact content height to fill; unbounded dialogs pass `undefined`.
52
+ */
53
+ export interface ModalTab {
54
+ /** Tab-strip label, re-read on every render so counts can update live. */
55
+ readonly label: string;
56
+ render(width: number, height: number | undefined): string[];
57
+ /** Raw keys the navigation scheme did not handle. */
58
+ handleInput(data: string): void;
59
+ /** Semantic navigation; never includes `dismiss`. */
60
+ handleNavigation(action: NavigationAction): void;
61
+ /** Re-filter content when the dialog owns a shared filter input. */
62
+ applyFilter?(query: string): void;
63
+ /** Caption lines rendered above the shared filter input, when present. */
64
+ filterCaption?(): string[];
65
+ /** Tab-specific hints for the help footer. */
66
+ hints(): Hint[];
67
+ /** Receive shell services; called once when the dialog is constructed. */
68
+ attach?(context: ModalTabContext): void;
69
+ invalidate?(): void;
70
+ }
@@ -2,28 +2,110 @@
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` (including favourites, groups, tab visibility, provider filtering, and layout), 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`, `custom-footer`, and `context-view`, plus reusable shared primitives (`ModelConfig`, `ReasoningLevel`, `ColorHex`).
6
6
 
7
- ## Design Patterns
7
+ ## Files
8
8
 
9
- - **Schema-first configuration**: Uses Zod to declare schemas and derive TypeScript types via `z.infer`.
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
- - **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); 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
- - **Default object parsing**: `custom-footer-config.schema.ts` uses `Schema.parse({})` to derive concrete default objects rather than hand-writing inline literals.
9
+ | File | Exports | Purpose |
10
+ | --- | --- | --- |
11
+ | `shared-config.schema.ts` | `ReasoningLevelSchema`, `ReasoningLevel`; `ModelConfigSchema`, `ModelConfig`; `ColorHexSchema` | Reusable primitives shared across feature schemas. |
12
+ | `auto-session-name.config.schema.ts` | `AutoSessionNameConfigSchema`, `AutoSessionNameConfig`; `PartialAutoSessionNameConfigSchema`, `PartialAutoSessionNameConfig` | Full and partial schemas for the session-naming feature. |
13
+ | `model-select.config.schema.ts` | `FavouriteModelSchema` (private); `ModelSelectLayoutSchema`, `ModelSelectLayout`; `HideTabsSchema` (private); `ModelSelectConfigSchema`, `ModelSelectConfig`; `PartialModelSelectConfigSchema`, `PartialModelSelectConfig` | Full and partial schemas for the model picker, including favourites, groups, tab visibility, provider filtering, layout, and default reasoning. |
14
+ | `custom-footer-config.schema.ts` | `CustomFooterConfigSchema`, `CustomFooterConfig`; `DEFAULT_CUSTOM_FOOTER_CONFIG`; `PartialCustomFooterConfigSchema`, `PartialCustomFooterConfig` | Full and partial schemas for the footer, including colors, icons, and display flags. |
15
+ | `context-view.config.schema.ts` | `ContextViewConfigSchema`, `ContextViewConfig`; `DEFAULT_CONTEXT_VIEW_CONFIG`; `PartialContextViewConfigSchema`, `PartialContextViewConfig` | Full and partial schemas for the context-view feature (disabled by default). |
16
+ | `config.schema.ts` | `ConfigSchema`, `Config`; `PartialConfigSchema`, `PartialConfig` | Top-level schema that composes all feature schemas and exports the canonical full and partial config types. |
15
17
 
16
- ## Data & Control Flow
18
+ ## Schema Composition
17
19
 
18
- 1. **Input**: Raw JSON/user config enters the system.
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`). `ModelSelectConfigSchema` also defines a `ModelSelectLayoutSchema` enum (`inline`/`overlay`) and `FavouriteModelSchema`, which omits `reasoning` from `ModelConfigSchema` and adds a `groups` array.
21
- 4. **Partial updates**: `PartialConfigSchema` and its feature-level partial variants allow validating incremental config changes without requiring a complete config object.
22
- 5. **Output**: Validated `Config` and `PartialConfig` types are exported for use by config loading, merging, and runtime feature code elsewhere in the plugin.
20
+ - **Shared primitives**: `shared-config.schema.ts` defines the lowest-level building blocks.
21
+ - `ReasoningLevelSchema` is a strict enum of `'off' | 'minimal' | 'low' | 'medium' | 'high' | 'xhigh'`.
22
+ - `ModelConfigSchema` requires `{ provider, modelId, reasoning }`, where `reasoning` is `ReasoningLevelSchema`.
23
+ - `ColorHexSchema` validates `#RRGGBB` hex strings using the `COLOR_HEX_REGEX` from `../constants`.
24
+ - **Per-feature schemas** are composed independently, then imported into the top-level `ConfigSchema` in `config.schema.ts`.
25
+ - `AutoSessionNameConfigSchema` contains `enabled: boolean` and an optional `model: ModelConfigSchema`.
26
+ - `ModelSelectConfigSchema` contains:
27
+ - `enabled: boolean`
28
+ - `favourite`: array of `FavouriteModelSchema`, which is `ModelConfigSchema.omit({ reasoning: true }).extend({ groups: string[] })`
29
+ - `favourite_label: string` (non-empty, default `'Favourites'`)
30
+ - `groups: string[]` (non-empty entries, default `[]`)
31
+ - `hide_tabs: { groups: boolean, search: boolean }` (default `false` for both)
32
+ - `provider_filter: string[]` (non-empty entries, default `[]`)
33
+ - `default_reasoning: ReasoningLevelSchema` (optional, no default)
34
+ - `layout: 'inline' | 'overlay'` (default `'inline'`)
35
+ - `CustomFooterConfigSchema` contains:
36
+ - `enabled: boolean`
37
+ - `colors: { directory?, modelName?, anthropicUsage?: '#D97706', codexUsage?: '#10B981' }`
38
+ - `icons: { directory?: ' ', refresh?: ' ', cache?: ' ', cacheRead?: ' ', cacheWrite?: ' ' }`
39
+ - `display: { tokens?: true, cache?: true }`
40
+ - `ContextViewConfigSchema` contains only `enabled: boolean`.
41
+ - **Top-level composition**: `ConfigSchema` is a `z.object({ $schema?, auto_session_name, model_select, custom_footer, context_view })` where each feature section is a full feature schema. `PartialConfigSchema` is a parallel object where every feature section is the corresponding partial schema and all keys are optional.
42
+
43
+ ## Defaults & Partial Overrides
44
+
45
+ - **Defaults are embedded in schemas** via `.default()` so that `ConfigSchema.parse({})` materializes every missing value.
46
+ - **Per-feature defaults**:
47
+ - `auto_session_name`: default object `{ enabled: false }` (model is omitted).
48
+ - `model_select`: default object `{ enabled: false, favourite: [], favourite_label: 'Favourites', groups: [], hide_tabs: { groups: false, search: false }, provider_filter: [], layout: 'inline' }` (`default_reasoning` is omitted).
49
+ - `custom_footer`: default object is derived by `CustomFooterConfigSchema.parse({ enabled: false })`, then re-exported as `DEFAULT_CUSTOM_FOOTER_CONFIG`. This yields all nested default colors, icons, and display flags.
50
+ - `context_view`: default object is derived by `ContextViewConfigSchema.parse({})`, re-exported as `DEFAULT_CONTEXT_VIEW_CONFIG`.
51
+ - **Partial schemas** are designed for config-layer merging:
52
+ - `PartialAutoSessionNameConfigSchema` is generated with `AutoSessionNameConfigSchema.partial()`.
53
+ - `PartialModelSelectConfigSchema`, `PartialCustomFooterConfigSchema`, and `PartialContextViewConfigSchema` are hand-written to make every field optional, so user/project overrides only specify the keys they want to override.
54
+ - `PartialConfigSchema` wraps all feature partial schemas as optional sections.
55
+ - **Merging semantics** (implemented in `src/config-loader.ts`):
56
+ - Defaults are computed with `ConfigSchema.parse({})`.
57
+ - Global config is validated with `PartialConfigSchema` and shallow-merged per feature section.
58
+ - Project config is validated with `PartialConfigSchema` and shallow-merged only when the project is trusted.
59
+ - For each feature section, if both the base value and the partial value are plain objects, the partial is spread over the base (`{ ...base, ...partial }`); arrays and primitives replace the base value entirely.
60
+ - The final merged object is run through `ConfigSchema.parse()` to apply defaults and catch any invalid merged values.
61
+ - `$schema` is ignored during merging.
62
+
63
+ ## Inferred Types
64
+
65
+ All schemas derive TypeScript types via `z.infer`:
66
+
67
+ - `Config` from `ConfigSchema`
68
+ - `PartialConfig` from `PartialConfigSchema`
69
+ - `AutoSessionNameConfig` / `PartialAutoSessionNameConfig`
70
+ - `ModelSelectConfig` / `PartialModelSelectConfig`
71
+ - `CustomFooterConfig` / `PartialCustomFooterConfig`
72
+ - `ContextViewConfig` / `PartialContextViewConfig`
73
+ - `ModelConfig` from `ModelConfigSchema`
74
+ - `ReasoningLevel` from `ReasoningLevelSchema`
75
+ - `ModelSelectLayout` from `ModelSelectLayoutSchema`
76
+
77
+ Because the full schemas use `.default()`, a successfully parsed `Config` has every top-level feature section and every required field fully present. The partial types preserve optionality for layered overrides.
78
+
79
+ ## Validation & Data Flow
80
+
81
+ 1. **Input**: Raw JSON is loaded from global and project config files (`ConfigLoader` via `PathUtil`).
82
+ 2. **Partial validation**: `PartialConfigSchema.safeParse(raw)` validates each config file independently. Invalid files surface a Zod error.
83
+ 3. **Merge**: Valid partial configs are layered over the defaults using per-feature shallow object merging.
84
+ 4. **Final validation**: `ConfigSchema.safeParse(merged)` ensures the merged result satisfies all constraints and fills in any remaining defaults. The validated `Config` is stored in the `ConfigLoader` instance.
85
+ 5. **Runtime read**: Feature code reads the validated config through `ConfigLoader` getters (`getAutoSessionName`, `getModelSelect`, `getCustomFooter`, `getContextView`) and typed aliases (`Config['custom_footer']` in `src/extensions/custom-footer/types.ts`).
86
+ 6. **Constraints**:
87
+ - `favourite_label`, `groups`, and `provider_filter` entries must be non-empty strings.
88
+ - `default_reasoning` must be one of the `ReasoningLevel` values when present.
89
+ - `layout` must be `inline` or `overlay`.
90
+ - Colors must be `#RRGGBB` hex strings.
91
+ - `enabled` must be a boolean.
92
+
93
+ ## Build & Runtime Consumers
94
+
95
+ - **Build-time JSON Schema generation**: `scripts/build-schema-document.ts` imports `ConfigSchema` and calls `z.toJSONSchema(ConfigSchema, { target: 'draft-7', unrepresentable: 'any', io: 'input' })`, then wraps it with draft-07 metadata (`$schema`, `$id`, title, description) to produce `assets/config.schema.json`. This generated file is the user-facing schema for editors and config validation tooling.
96
+ - **Runtime configuration loading**: `src/config-loader.ts` imports `ConfigSchema`, `PartialConfigSchema`, and their inferred types. It is the only runtime consumer that validates and merges configs.
97
+ - **Runtime feature consumers**:
98
+ - `src/extensions/model-select/index.ts` uses `ModelSelectConfig`.
99
+ - `src/extensions/model-select/types.ts` uses `ModelSelectLayout` and `ReasoningLevel`.
100
+ - `src/extensions/custom-footer/types.ts` re-exports `Config['custom_footer']` as `CustomFooterConfig` and derives `colors`/`display`/`icons` sub-types.
101
+ - `src/utils/model-resolver.util.ts` uses `ModelConfig` to resolve optional `{ provider, modelId, reasoning }` into runtime Pi models.
102
+ - **Tests**: `test/model-select/config-schema.test.ts`, `test/custom-footer/config-schema.test.ts`, `test/context-view/config-schema.test.ts`, and `test/model-select/default-reasoning.test.ts` exercise `ConfigSchema`, `PartialConfigSchema`, and `ModelSelectConfigSchema` to verify defaults, partial behavior, and validation errors.
23
103
 
24
104
  ## Integration Points
25
105
 
26
- - **Config loading / merging layer**: `config.schema.ts` exports `Config` and `PartialConfig` types consumed by whatever loads and merges user config with defaults.
27
- - **Feature modules**: Auto-session-name, model-select, and custom-footer runtime code import their respective config types from this directory.
28
- - **Constants**: `shared-config.schema.ts` imports `COLOR_HEX_REGEX` from `../constants` to validate hex colors.
29
- - **Type system**: All schemas feed TypeScript types via `z.infer`, providing compile-time guarantees across the plugin.
106
+ - **`src/config-loader.ts`**: uses the full and partial schemas to load, merge, and validate global and project configuration.
107
+ - **`src/index.ts`**: creates the `ConfigLoader` and registers features; features are activated by the validated config.
108
+ - **`scripts/build-schema-document.ts`**: generates the published JSON Schema from `ConfigSchema`.
109
+ - **`assets/config.schema.json`**: generated artifact consumed by editors and user-facing config tooling.
110
+ - **`src/constants.ts`**: supplies `COLOR_HEX_REGEX` to `ColorHexSchema`.
111
+ - **Type system**: all exported types are consumed by feature modules and shared utilities to provide compile-time guarantees across the plugin.
@@ -1,5 +1,6 @@
1
1
  import z from 'zod';
2
2
  import { AutoSessionNameConfigSchema, PartialAutoSessionNameConfigSchema } from './auto-session-name.config.schema';
3
+ import { ContextViewConfigSchema, DEFAULT_CONTEXT_VIEW_CONFIG, PartialContextViewConfigSchema } from './context-view.config.schema';
3
4
  import { CustomFooterConfigSchema, DEFAULT_CUSTOM_FOOTER_CONFIG, PartialCustomFooterConfigSchema } from './custom-footer-config.schema';
4
5
  import { ModelSelectConfigSchema, PartialModelSelectConfigSchema } from './model-select.config.schema';
5
6
 
@@ -18,6 +19,7 @@ export const ConfigSchema = z.object({
18
19
  layout: 'inline',
19
20
  }),
20
21
  custom_footer: CustomFooterConfigSchema.default(DEFAULT_CUSTOM_FOOTER_CONFIG),
22
+ context_view: ContextViewConfigSchema.default(DEFAULT_CONTEXT_VIEW_CONFIG),
21
23
  });
22
24
  export type Config = z.infer<typeof ConfigSchema>;
23
25
 
@@ -26,5 +28,6 @@ export const PartialConfigSchema = z.object({
26
28
  auto_session_name: PartialAutoSessionNameConfigSchema.optional(),
27
29
  model_select: PartialModelSelectConfigSchema.optional(),
28
30
  custom_footer: PartialCustomFooterConfigSchema.optional(),
31
+ context_view: PartialContextViewConfigSchema.optional(),
29
32
  });
30
33
  export type PartialConfig = z.infer<typeof PartialConfigSchema>;
@@ -0,0 +1,13 @@
1
+ import z from 'zod';
2
+
3
+ export const ContextViewConfigSchema = z.object({
4
+ enabled: z.boolean().default(false),
5
+ });
6
+ export type ContextViewConfig = z.infer<typeof ContextViewConfigSchema>;
7
+
8
+ export const DEFAULT_CONTEXT_VIEW_CONFIG = ContextViewConfigSchema.parse({});
9
+
10
+ export const PartialContextViewConfigSchema = z.object({
11
+ enabled: z.boolean().optional(),
12
+ });
13
+ export type PartialContextViewConfig = z.infer<typeof PartialContextViewConfigSchema>;