@mrclrchtr/supi-lsp 2.1.0 → 2.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (29) hide show
  1. package/node_modules/@mrclrchtr/supi-code-runtime/node_modules/@mrclrchtr/supi-core/README.md +9 -8
  2. package/node_modules/@mrclrchtr/supi-code-runtime/node_modules/@mrclrchtr/supi-core/package.json +1 -1
  3. package/node_modules/@mrclrchtr/supi-code-runtime/node_modules/@mrclrchtr/supi-core/src/config.ts +2 -3
  4. package/node_modules/@mrclrchtr/supi-code-runtime/node_modules/@mrclrchtr/supi-core/src/debug-registry.ts +0 -5
  5. package/node_modules/@mrclrchtr/supi-code-runtime/node_modules/@mrclrchtr/supi-core/src/settings/scoped-settings-list.ts +372 -0
  6. package/node_modules/@mrclrchtr/supi-code-runtime/node_modules/@mrclrchtr/supi-core/src/settings/settings-action-menu.ts +101 -0
  7. package/node_modules/@mrclrchtr/supi-code-runtime/node_modules/@mrclrchtr/supi-core/src/settings/settings-registry.ts +13 -7
  8. package/node_modules/@mrclrchtr/supi-code-runtime/node_modules/@mrclrchtr/supi-core/src/settings/settings-schema.ts +464 -0
  9. package/node_modules/@mrclrchtr/supi-code-runtime/node_modules/@mrclrchtr/supi-core/src/settings/settings-submenus.ts +124 -0
  10. package/node_modules/@mrclrchtr/supi-code-runtime/node_modules/@mrclrchtr/supi-core/src/settings/settings-ui.ts +50 -309
  11. package/node_modules/@mrclrchtr/supi-code-runtime/node_modules/@mrclrchtr/supi-core/src/settings-ui.ts +2 -5
  12. package/node_modules/@mrclrchtr/supi-code-runtime/node_modules/@mrclrchtr/supi-core/src/settings.ts +17 -1
  13. package/node_modules/@mrclrchtr/supi-code-runtime/package.json +2 -2
  14. package/node_modules/@mrclrchtr/supi-core/README.md +9 -8
  15. package/node_modules/@mrclrchtr/supi-core/package.json +1 -1
  16. package/node_modules/@mrclrchtr/supi-core/src/config.ts +2 -3
  17. package/node_modules/@mrclrchtr/supi-core/src/debug-registry.ts +0 -5
  18. package/node_modules/@mrclrchtr/supi-core/src/settings/scoped-settings-list.ts +372 -0
  19. package/node_modules/@mrclrchtr/supi-core/src/settings/settings-action-menu.ts +101 -0
  20. package/node_modules/@mrclrchtr/supi-core/src/settings/settings-registry.ts +13 -7
  21. package/node_modules/@mrclrchtr/supi-core/src/settings/settings-schema.ts +464 -0
  22. package/node_modules/@mrclrchtr/supi-core/src/settings/settings-submenus.ts +124 -0
  23. package/node_modules/@mrclrchtr/supi-core/src/settings/settings-ui.ts +50 -309
  24. package/node_modules/@mrclrchtr/supi-core/src/settings-ui.ts +2 -5
  25. package/node_modules/@mrclrchtr/supi-core/src/settings.ts +17 -1
  26. package/package.json +3 -3
  27. package/src/config/lsp-settings.ts +1 -1
  28. package/node_modules/@mrclrchtr/supi-code-runtime/node_modules/@mrclrchtr/supi-core/src/config/config-settings.ts +0 -207
  29. package/node_modules/@mrclrchtr/supi-core/src/config/config-settings.ts +0 -207
@@ -1,79 +1,21 @@
1
- // Generic settings overlay for SuPi extensions.
1
+ // Declarative settings overlay for SuPi extensions.
2
2
  //
3
- // Uses pi-tui's SettingsList with scope toggle (Tab), extension grouping,
4
- // and search. Each extension declares its settings via registerSettings().
3
+ // Thin orchestration layer that collects settings contributions and opens the
4
+ // scoped settings list inside a pi-tui custom component overlay.
5
5
 
6
6
  import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
7
- import { getSettingsListTheme } from "@earendil-works/pi-coding-agent";
8
- import {
9
- Container,
10
- Input,
11
- Key,
12
- matchesKey,
13
- type SelectItem,
14
- SelectList,
15
- type SelectListTheme,
16
- type SettingItem,
17
- SettingsList,
18
- Text,
19
- } from "@earendil-works/pi-tui";
20
- import { getSelectableModels } from "../model-selection.ts";
7
+ import { Container, Key, matchesKey, Text } from "@earendil-works/pi-tui";
8
+ import { ScopedSettingsList } from "./scoped-settings-list.ts";
9
+ import type { SettingsCollectionDiagnostic, SettingsScope } from "./settings-registry.ts";
21
10
  import {
22
11
  createSettingsContributionCollector,
23
- type SettingsCollectionDiagnostic,
24
- type SettingsScope,
25
- type SettingsSection,
26
12
  SUPI_SETTINGS_COLLECT_EVENT,
27
13
  } from "./settings-registry.ts";
28
14
 
29
- // ── Input submenu component ──────────────────────────────────
30
-
31
- /**
32
- * Creates a pi-tui Input-backed submenu component with enter-to-confirm
33
- * and escape-to-cancel handling.
34
- *
35
- * @param currentValue - Initial value for the text input.
36
- * @param label - Label text displayed above the input.
37
- * @param done - Callback invoked with the confirmed value, or undefined on cancel.
38
- */
39
- export function createInputSubmenu(
40
- currentValue: string,
41
- label: string,
42
- done: (selectedValue?: string) => void,
43
- ): {
44
- render: (width: number) => string[];
45
- invalidate: () => void;
46
- handleInput: (data: string) => boolean;
47
- } {
48
- const input = new Input();
49
- input.setValue(currentValue);
50
-
51
- return {
52
- render: (_width: number) => {
53
- const lines = [` ${label}`];
54
- lines.push(...input.render(_width));
55
- lines.push(" enter confirm • esc cancel");
56
- return lines;
57
- },
58
- invalidate: () => {
59
- input.invalidate();
60
- },
61
- handleInput: (data: string) => {
62
- if (matchesKey(data, Key.escape)) {
63
- done();
64
- return true;
65
- }
66
- if (matchesKey(data, Key.enter)) {
67
- done(input.getValue());
68
- return true;
69
- }
70
- input.handleInput(data);
71
- return true;
72
- },
73
- };
74
- }
15
+ // Re-export submenu helpers
16
+ export { createInputSubmenu, createModelPickerSubmenu } from "./settings-submenus.ts";
75
17
 
76
- // ── Types ────────────────────────────────────────────────────
18
+ // ── Overlay ────────────────────────────────────────────────────────────────
77
19
 
78
20
  interface OverlayStatus {
79
21
  kind: "warning" | "error";
@@ -86,45 +28,10 @@ interface OverlayState {
86
28
  status?: OverlayStatus;
87
29
  }
88
30
 
89
- // ── Pure helpers ─────────────────────────────────────────────
90
-
91
31
  function getScopeLabel(scope: SettingsScope): string {
92
32
  return scope === "project" ? "Project" : "Global";
93
33
  }
94
34
 
95
- function buildFlatItems(
96
- sections: SettingsSection[],
97
- scope: SettingsScope,
98
- cwd: string,
99
- ctx?: ExtensionContext,
100
- ): SettingItem[] {
101
- const items: SettingItem[] = [];
102
- for (const section of sections) {
103
- const sectionItems = section.loadValues(scope, cwd, ctx);
104
- for (const item of sectionItems) {
105
- items.push({
106
- ...item,
107
- id: `${section.id}.${item.id}`,
108
- label: `${section.label}: ${item.label}`,
109
- });
110
- }
111
- }
112
- return items;
113
- }
114
-
115
- function findSectionAndId(
116
- sections: SettingsSection[],
117
- flatId: string,
118
- ): { section: SettingsSection; itemId: string } | null {
119
- const dotIndex = flatId.indexOf(".");
120
- if (dotIndex === -1) return null;
121
- const sectionId = flatId.slice(0, dotIndex);
122
- const itemId = flatId.slice(dotIndex + 1);
123
- const section = sections.find((s) => s.id === sectionId);
124
- if (!section) return null;
125
- return { section, itemId };
126
- }
127
-
128
35
  function collectSettingsSections(pi: ExtensionAPI) {
129
36
  const collector = createSettingsContributionCollector();
130
37
  pi.events.emit(SUPI_SETTINGS_COLLECT_EVENT, collector);
@@ -136,199 +43,6 @@ function latestStatus(diagnostics: SettingsCollectionDiagnostic[]): OverlayStatu
136
43
  return latest ? { kind: latest.kind, message: latest.message } : undefined;
137
44
  }
138
45
 
139
- function formatSettingsError(settingId: string, error: unknown): string {
140
- const message = error instanceof Error ? error.message : String(error);
141
- return `Could not save SuPi setting "${settingId}": ${message}`;
142
- }
143
-
144
- // ── Component ────────────────────────────────────────────────
145
-
146
- interface SettingsOverlayDeps {
147
- ctx: ExtensionContext;
148
- sections: SettingsSection[];
149
- state: OverlayState;
150
- container: Container;
151
- settingsList: SettingsList | null;
152
- tui: Parameters<Parameters<ExtensionContext["ui"]["custom"]>[0]>[0];
153
- theme: Parameters<Parameters<ExtensionContext["ui"]["custom"]>[0]>[1];
154
- done: () => void;
155
- }
156
-
157
- function createSettingsList(deps: SettingsOverlayDeps): SettingsList {
158
- const items = buildFlatItems(deps.sections, deps.state.scope, deps.state.cwd, deps.ctx);
159
- const onChange = (flatId: string, newValue: string) => {
160
- const found = findSectionAndId(deps.sections, flatId);
161
- try {
162
- if (found) {
163
- found.section.persistChange(deps.state.scope, deps.state.cwd, found.itemId, newValue);
164
- deps.state.status = undefined;
165
- }
166
- } catch (error) {
167
- deps.state.status = {
168
- kind: "error",
169
- message: formatSettingsError(found?.itemId ?? flatId, error),
170
- };
171
- }
172
- // Re-read all values to reflect persisted changes, but keep the list
173
- // instance (and its selectedIndex) intact.
174
- const updatedItems = buildFlatItems(deps.sections, deps.state.scope, deps.state.cwd, deps.ctx);
175
- for (const updated of updatedItems) {
176
- const existing = items.find((i) => i.id === updated.id);
177
- if (existing && existing.currentValue !== updated.currentValue) {
178
- settingsList.updateValue(updated.id, updated.currentValue);
179
- }
180
- }
181
- deps.tui.requestRender();
182
- };
183
- const settingsList = new SettingsList(
184
- items,
185
- Math.min(items.length + 4, 20),
186
- getSettingsListTheme(),
187
- onChange,
188
- () => deps.done(),
189
- { enableSearch: true },
190
- );
191
- return settingsList;
192
- }
193
-
194
- function rebuildSettingsList(deps: SettingsOverlayDeps): SettingsList {
195
- const settingsList = createSettingsList(deps);
196
- deps.settingsList = settingsList;
197
-
198
- deps.container.clear();
199
- deps.container.addChild(createHeaderComponent(deps));
200
- deps.container.addChild(createStatusComponent(deps));
201
- deps.container.addChild(settingsList);
202
-
203
- return settingsList;
204
- }
205
-
206
- function createHeaderComponent(deps: SettingsOverlayDeps): Text {
207
- const { theme, state } = deps;
208
- const scopeLabel = getScopeLabel(state.scope);
209
- const otherScope = state.scope === "project" ? "Global" : "Project";
210
- const headerText = new Text(
211
- `${theme.fg("accent", theme.bold("SuPi Settings"))} ${theme.fg("text", `Scope: ${scopeLabel}`)} ${theme.fg("dim", `(tab → ${otherScope})`)}`,
212
- 0,
213
- 0,
214
- );
215
- return headerText;
216
- }
217
-
218
- function createStatusComponent(deps: SettingsOverlayDeps): {
219
- render: () => string[];
220
- invalidate: () => void;
221
- } {
222
- return {
223
- render: () => {
224
- const status = deps.state.status;
225
- if (!status) return [];
226
- return [deps.theme.fg(status.kind, status.message)];
227
- },
228
- invalidate: () => {},
229
- };
230
- }
231
-
232
- function handleScopeToggle(deps: SettingsOverlayDeps): void {
233
- deps.state.scope = deps.state.scope === "project" ? "global" : "project";
234
- rebuildSettingsList(deps);
235
- deps.tui.requestRender();
236
- }
237
-
238
- /** Minimal SelectList theme — uses identity so the parent SettingsList provides styling context. */
239
- const PASSTHROUGH_THEME: SelectListTheme = {
240
- selectedPrefix: (text) => `› ${text}`,
241
- selectedText: (text) => text,
242
- description: (text) => text,
243
- scrollInfo: (text) => text,
244
- noMatch: (text) => text,
245
- };
246
-
247
- /**
248
- * Create a model picker submenu for settings.
249
- *
250
- * Shows a scrollable list of selectable models from the scoped model set,
251
- * with the current session model annotated `[current]`. The first entry is
252
- * always `"disabled"`.
253
- *
254
- * @param currentValue - Currently configured canonical model id or `"disabled"`.
255
- * @param done - Callback invoked with the selected value, or undefined on cancel.
256
- * @param ctx - Extension context for model listing. When undefined, only
257
- * `"disabled"` is offered.
258
- */
259
- export function createModelPickerSubmenu(
260
- currentValue: string,
261
- done: (selectedValue?: string) => void,
262
- ctx?: ExtensionContext,
263
- ): {
264
- render: (width: number) => string[];
265
- invalidate: () => void;
266
- handleInput: (data: string) => boolean;
267
- } {
268
- const items = buildModelItems(ctx);
269
-
270
- const initialIndex =
271
- currentValue === "disabled"
272
- ? 0
273
- : Math.max(
274
- 0,
275
- items.findIndex((item) => item.value === currentValue),
276
- );
277
-
278
- const container = new Container();
279
- container.addChild(new Text(" Select suggestion model", 1, 0));
280
- container.addChild(new Text("", 1, 0));
281
-
282
- const selectList = new SelectList(items, Math.min(items.length, 15), PASSTHROUGH_THEME);
283
-
284
- if (initialIndex >= 0) {
285
- selectList.setSelectedIndex(initialIndex);
286
- }
287
-
288
- selectList.onSelect = (item) => done(item.value);
289
- selectList.onCancel = () => done();
290
-
291
- container.addChild(selectList);
292
- container.addChild(new Text(" ↑↓ navigate • enter select • esc cancel", 1, 0));
293
-
294
- return {
295
- render: (width: number) => container.render(width),
296
- invalidate: () => container.invalidate(),
297
- handleInput: (data: string) => {
298
- selectList.handleInput(data);
299
- return true;
300
- },
301
- };
302
- }
303
-
304
- /** Build selectable model items with "disabled" first. */
305
- function buildModelItems(ctx?: ExtensionContext): SelectItem[] {
306
- const items: SelectItem[] = [
307
- {
308
- value: "disabled",
309
- label: "disabled",
310
- description: "No prompt suggestions",
311
- },
312
- ];
313
-
314
- if (!ctx) return items;
315
-
316
- const models = getSelectableModels(ctx);
317
-
318
- for (const model of models) {
319
- const suffix = model.isCurrent ? " [current]" : "";
320
- items.push({
321
- value: model.canonicalId,
322
- label: `${model.canonicalId}${suffix}`,
323
- description: model.label !== model.canonicalId ? model.label : undefined,
324
- });
325
- }
326
-
327
- return items;
328
- }
329
-
330
- // ── Entry point ──────────────────────────────────────────────
331
-
332
46
  export function openSettingsOverlay(pi: ExtensionAPI, ctx: ExtensionContext): void {
333
47
  const collection = collectSettingsSections(pi);
334
48
  if (collection.sections.length === 0) {
@@ -342,32 +56,59 @@ export function openSettingsOverlay(pi: ExtensionAPI, ctx: ExtensionContext): vo
342
56
  cwd: ctx.cwd,
343
57
  status: latestStatus(collection.diagnostics),
344
58
  };
345
- const container = new Container();
346
59
 
347
- const deps: SettingsOverlayDeps = {
60
+ const container = new Container();
61
+ const scopedList = new ScopedSettingsList(
62
+ collection.sections,
63
+ state.scope,
64
+ state.cwd,
348
65
  ctx,
349
- sections: collection.sections,
350
- state,
351
- container,
352
- settingsList: null,
353
- tui,
354
66
  theme,
67
+ tui,
355
68
  done,
69
+ (message) => {
70
+ state.status = { kind: "error", message };
71
+ rebuildOverlay();
72
+ tui.requestRender();
73
+ },
74
+ );
75
+ scopedList.enableSearch();
76
+
77
+ const rebuildOverlay = () => {
78
+ container.clear();
79
+ const scopeLabel = getScopeLabel(state.scope);
80
+ const otherScope = state.scope === "project" ? "Global" : "Project";
81
+ container.addChild(
82
+ new Text(
83
+ `${theme.fg("accent", theme.bold("SuPi Settings"))} ${theme.fg("text", `Scope: ${scopeLabel}`)} ${theme.fg("dim", `(tab → ${otherScope})`)}`,
84
+ 0,
85
+ 0,
86
+ ),
87
+ );
88
+ if (state.status) {
89
+ container.addChild(new Text(theme.fg(state.status.kind, state.status.message), 0, 0));
90
+ }
356
91
  };
357
92
 
358
- rebuildSettingsList(deps);
93
+ rebuildOverlay();
359
94
 
360
95
  const component = {
361
- render: (width: number) => container.render(width),
362
- invalidate: () => container.invalidate(),
96
+ render: (width: number) => [...container.render(width), ...scopedList.render(width)],
97
+ invalidate: () => {
98
+ container.invalidate();
99
+ scopedList.invalidate();
100
+ },
363
101
  handleInput: (data: string) => {
364
102
  if (matchesKey(data, Key.tab)) {
365
- handleScopeToggle(deps);
103
+ state.scope = state.scope === "project" ? "global" : "project";
104
+ state.status = undefined;
105
+ scopedList.reload(state.scope, state.cwd, ctx);
106
+ rebuildOverlay();
107
+ tui.requestRender();
366
108
  return true;
367
109
  }
368
- // Delegate input to the settings list (always set after rebuildSettingsList)
369
- deps.settingsList?.handleInput?.(data);
370
- deps.tui.requestRender();
110
+ scopedList.handleInput(data);
111
+ tui.requestRender();
371
112
  return true;
372
113
  },
373
114
  };
@@ -1,6 +1,3 @@
1
1
  // supi-core settings-ui domain — settings TUI components (imports pi-tui at runtime, heavy).
2
- export {
3
- createInputSubmenu,
4
- createModelPickerSubmenu,
5
- openSettingsOverlay,
6
- } from "./settings/settings-ui.ts";
2
+ export { createInputSubmenu, createModelPickerSubmenu } from "./settings/settings-submenus.ts";
3
+ export { openSettingsOverlay } from "./settings/settings-ui.ts";
@@ -1,4 +1,4 @@
1
- // supi-core settings domain — event-backed settings contribution types and command wiring.
1
+ // supi-core settings domain — event-backed declarative settings contributions and command wiring.
2
2
 
3
3
  export { registerSettingsCommand } from "./settings/settings-command.ts";
4
4
  export type {
@@ -13,3 +13,19 @@ export {
13
13
  isSettingsContributionCollector,
14
14
  SUPI_SETTINGS_COLLECT_EVENT,
15
15
  } from "./settings/settings-registry.ts";
16
+ export type {
17
+ BoolField,
18
+ ConfigHelpers,
19
+ CustomField,
20
+ DeclarativeSettingsOptions,
21
+ EnumField,
22
+ ModelPickerField,
23
+ NumberField,
24
+ ScopedFieldValue,
25
+ SettingsField,
26
+ SettingsFieldAction,
27
+ SettingsPersistedChange,
28
+ StringListField,
29
+ ValueSource,
30
+ } from "./settings/settings-schema.ts";
31
+ export { registerDeclarativeSettings } from "./settings/settings-schema.ts";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mrclrchtr/supi-lsp",
3
- "version": "2.1.0",
3
+ "version": "2.2.0",
4
4
  "description": "SuPi LSP extension — Language Server Protocol integration for pi",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -38,8 +38,8 @@
38
38
  "vscode-jsonrpc": "^9.0.0",
39
39
  "vscode-languageserver-protocol": "^3.17.5",
40
40
  "vscode-languageserver-types": "^3.17.5",
41
- "@mrclrchtr/supi-code-runtime": "2.1.0",
42
- "@mrclrchtr/supi-core": "2.1.0"
41
+ "@mrclrchtr/supi-code-runtime": "2.2.0",
42
+ "@mrclrchtr/supi-core": "2.2.0"
43
43
  },
44
44
  "bundledDependencies": [
45
45
  "@mrclrchtr/supi-code-runtime",
@@ -8,7 +8,7 @@ import { loadSupiConfig, loadSupiConfigForScope } from "@mrclrchtr/supi-core/con
8
8
 
9
9
  // ── Types ────────────────────────────────────────────────────
10
10
 
11
- export interface LspSettings {
11
+ export interface LspSettings extends Record<string, unknown> {
12
12
  enabled: boolean;
13
13
  severity: number;
14
14
  active: string[];
@@ -1,207 +0,0 @@
1
- // Config-aware settings contribution helper for SuPi packages.
2
- //
3
- // Registers config-backed settings sections through PI's shared event bus so
4
- // /supi-settings can collect contributions from all loaded extensions without
5
- // relying on a shared supi-core module instance.
6
-
7
- import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
8
- import type { SettingItem } from "@earendil-works/pi-tui";
9
- import {
10
- isSettingsContributionCollector,
11
- type SettingsScope,
12
- type SettingsSection,
13
- SUPI_SETTINGS_COLLECT_EVENT,
14
- } from "../settings/settings-registry.ts";
15
- import { loadSupiConfigForScope, removeSupiConfigKey, writeSupiConfig } from "./config.ts";
16
-
17
- // ── Types ──────────────────────────────────────────────────────────────────
18
-
19
- /**
20
- * Supported config value types for declarative persistChange.
21
- *
22
- * - `"boolean"`: maps "on" → true, "off" → false
23
- * - `"number"`: parses integer via Number.parseInt, falls back to unset on invalid
24
- * - `"stringList"`: splits on comma, trims whitespace, unsets on empty
25
- */
26
- export type ConfigSettingType = "boolean" | "number" | "stringList";
27
-
28
- /** Extended setting item that can declare its config type for persistence. */
29
- export interface ConfigSettingItem extends SettingItem {
30
- /** Config value type used for auto-generated persistence. */
31
- configType?: ConfigSettingType;
32
- }
33
-
34
- /** Helpers provided to persistChange for scoped SuPi config writes. */
35
- export interface ConfigSettingsHelpers {
36
- /** Write a key to the selected scope's config section. */
37
- set(key: string, value: unknown): void;
38
- /** Remove a key from the selected scope's config section. */
39
- unset(key: string): void;
40
- }
41
-
42
- export interface ConfigSettingsPersistedChange {
43
- scope: SettingsScope;
44
- cwd: string;
45
- settingId: string;
46
- value: string;
47
- }
48
-
49
- export interface ConfigSettingsOptions<T> {
50
- /** Settings contribution identifier — e.g. "lsp", "claude-md". */
51
- id: string;
52
- /** Human-readable label shown in the UI. */
53
- label: string;
54
- /** SuPi config section name — e.g. "lsp", "claude-md". */
55
- section: string;
56
- /** Default config values. */
57
- defaults: T;
58
- /** Build SettingItem[] from scoped config. */
59
- buildItems: (
60
- settings: T,
61
- scope: SettingsScope,
62
- cwd: string,
63
- ctx?: ExtensionContext,
64
- ) => ConfigSettingItem[];
65
- /**
66
- * Convert a UI value into scoped SuPi config writes.
67
- *
68
- * Optional when every item returned by `buildItems` declares `configType`.
69
- * Required when any item lacks `configType`.
70
- */
71
- persistChange?: (
72
- scope: SettingsScope,
73
- cwd: string,
74
- settingId: string,
75
- value: string,
76
- helpers: ConfigSettingsHelpers,
77
- ) => void;
78
- /** Optional live runtime sync after successful persistence. */
79
- afterPersist?: (change: ConfigSettingsPersistedChange) => void;
80
- /** Optional home directory for config resolution (testing). */
81
- homeDir?: string;
82
- }
83
-
84
- // ── Auto-generated persistChange ───────────────────────────────────────────
85
-
86
- function autoPersistChange(
87
- settingId: string,
88
- value: string,
89
- helpers: ConfigSettingsHelpers,
90
- items: ConfigSettingItem[],
91
- ): void {
92
- const item = items.find((i) => i.id === settingId);
93
- if (!item?.configType) return;
94
-
95
- switch (item.configType) {
96
- case "boolean": {
97
- helpers.set(settingId, value === "on");
98
- break;
99
- }
100
- case "number": {
101
- const num = Number.parseInt(value, 10);
102
- if (Number.isFinite(num) && num > 0) {
103
- helpers.set(settingId, num);
104
- } else {
105
- helpers.unset(settingId);
106
- }
107
- break;
108
- }
109
- case "stringList": {
110
- const names = value
111
- .split(",")
112
- .map((s) => s.trim())
113
- .filter((s) => s.length > 0);
114
- if (names.length > 0) {
115
- helpers.set(settingId, names);
116
- } else {
117
- helpers.unset(settingId);
118
- }
119
- break;
120
- }
121
- }
122
- }
123
-
124
- function areAllItemsDeclarative(items: ConfigSettingItem[]): boolean {
125
- return items.length > 0 && items.every((i) => i.configType !== undefined);
126
- }
127
-
128
- function createHelpers<T>(options: ConfigSettingsOptions<T>, scope: SettingsScope, cwd: string) {
129
- return {
130
- set: (key: string, val: unknown) => {
131
- writeSupiConfig(
132
- { section: options.section, scope, cwd },
133
- { [key]: val },
134
- { homeDir: options.homeDir },
135
- );
136
- },
137
- unset: (key: string) => {
138
- removeSupiConfigKey({ section: options.section, scope, cwd }, key, {
139
- homeDir: options.homeDir,
140
- });
141
- },
142
- } satisfies ConfigSettingsHelpers;
143
- }
144
-
145
- function toSettingsSection<T>(options: ConfigSettingsOptions<T>): SettingsSection {
146
- let cachedItems: ConfigSettingItem[] | undefined;
147
-
148
- return {
149
- id: options.id,
150
- label: options.label,
151
- loadValues: (scope, cwd, ctx) => {
152
- const settings = loadSupiConfigForScope(options.section, cwd, options.defaults, {
153
- scope,
154
- homeDir: options.homeDir,
155
- });
156
- const items = options.buildItems(settings, scope, cwd, ctx);
157
- cachedItems = items;
158
- return items;
159
- },
160
- persistChange: (scope, cwd, settingId, value) => {
161
- const helpers = createHelpers(options, scope, cwd);
162
-
163
- if (options.persistChange) {
164
- options.persistChange(scope, cwd, settingId, value, helpers);
165
- } else {
166
- const items = cachedItems ?? options.buildItems(options.defaults, scope, cwd, undefined);
167
- if (!areAllItemsDeclarative(items)) {
168
- throw new Error(
169
- `Settings contribution "${options.id}" needs persistChange or configType on every item.`,
170
- );
171
- }
172
- autoPersistChange(settingId, value, helpers, items);
173
- }
174
-
175
- try {
176
- options.afterPersist?.({ scope, cwd, settingId, value });
177
- } catch (error) {
178
- const message = error instanceof Error ? error.message : String(error);
179
- throw new Error(`Saved setting, but live sync failed: ${message}`, { cause: error });
180
- }
181
- },
182
- };
183
- }
184
-
185
- // ── Registration ───────────────────────────────────────────────────────────
186
-
187
- /**
188
- * Register a config-backed settings contribution for `/supi-settings`.
189
- *
190
- * Contributions are collected through PI's process-local event bus. Call this
191
- * during the extension factory function, not in async session handlers.
192
- */
193
- export function registerConfigSettings<T>(
194
- pi: ExtensionAPI,
195
- options: ConfigSettingsOptions<T>,
196
- ): void {
197
- const section = toSettingsSection(options);
198
- const dispose = pi.events.on(SUPI_SETTINGS_COLLECT_EVENT, (collector) => {
199
- if (isSettingsContributionCollector(collector)) {
200
- collector.add(section);
201
- }
202
- });
203
-
204
- pi.on("session_shutdown", () => {
205
- dispose();
206
- });
207
- }