dsh-project-mcp 0.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.
@@ -0,0 +1,721 @@
1
+ /**
2
+ * The plugin's own configuration card (F-54): a `plugins.bundle.config` entry
3
+ * that edits the volatile configuration the host serves over `configForms`.
4
+ *
5
+ * The card is deliberately thin: the host owns the schema, the revision dance
6
+ * and the write path; this module renders the eighteen volatile fields as two
7
+ * groups of setting rows, commits valid edits through `form.set`, and offers a
8
+ * per-field reset (`form.unset`) only for fields the user layer overrides.
9
+ *
10
+ * Two host facts are mirrored here on purpose, because host code must never
11
+ * enter the client bundle: the volatile-field defaults (`src/index.ts`
12
+ * `DEFAULTS`, module-private and host-side) and the local-prefix rule
13
+ * (`src/naming.ts` `isValidLocalPrefix`). Both mirrors carry a comment at the
14
+ * copy.
15
+ */
16
+
17
+ import { createElement as h, useMemo, useState, useSyncExternalStore } from 'react'
18
+ import type { CSSProperties, ReactNode } from 'react'
19
+ import { PACKAGE_NAME } from '../shared.ts'
20
+ // settings.ts owns the locale namespace and the row/switch styles. Both are
21
+ // read inside function bodies only, never at module scope: `locales/ui.ts`
22
+ // imports this module while settings.ts imports `locales/ui.ts`, so a value
23
+ // read here during evaluation could land inside settings.ts's TDZ window.
24
+ import { NS, STYLE } from './settings.ts'
25
+
26
+ // ---------------------------------------------------------------------------
27
+ // Local faces — the vendored contracts, so the client never imports host types
28
+ // ---------------------------------------------------------------------------
29
+
30
+ /** The slice of `ConfigForm`'s snapshot the card reads. */
31
+ export interface ConfigFormSnapshotLike {
32
+ readonly status: 'loading' | 'ready' | 'unavailable'
33
+ readonly value: Record<string, unknown> | undefined
34
+ /** The user layer of the layered configuration; a field's PRESENCE marks an override. */
35
+ readonly user: unknown
36
+ readonly writable: boolean
37
+ }
38
+
39
+ /** The slice of the host's `ConfigForm` service object the card uses. */
40
+ export interface ConfigFormLike {
41
+ getSnapshot(): ConfigFormSnapshotLike
42
+ subscribe(listener: () => void): () => void
43
+ set(field: string, value: unknown): Promise<boolean>
44
+ unset(field: string): Promise<boolean>
45
+ }
46
+
47
+ /** The slice of the `configForms` service the registration block uses. */
48
+ export interface ConfigFormsLike {
49
+ get<T>(namespace: string): ConfigFormLike
50
+ whileServed(
51
+ namespaces: readonly string[],
52
+ register: (served: ReadonlySet<string>) => () => void,
53
+ ): () => void
54
+ }
55
+
56
+ /**
57
+ * The props the slot contract declares for `plugins.bundle.config`
58
+ * (`PluginConfigViewProps`), with `form` widened to `unknown`: this
59
+ * registration injects a factory under `form`, but the contract also lets an
60
+ * owner pass its own page form, and a card must survive every shape quietly.
61
+ */
62
+ export interface PluginConfigViewPropsLike {
63
+ readonly view: 'summary' | 'page'
64
+ readonly form?: unknown
65
+ readonly t?: Translate
66
+ }
67
+
68
+ // ---------------------------------------------------------------------------
69
+ // English dictionary (zh/ru live in `./locales/ui.ts`, which merges this table)
70
+ // ---------------------------------------------------------------------------
71
+
72
+ export const EN = {
73
+ configSummary: 'Edit this plugin’s activation and runtime configuration',
74
+ configGroupActivation: 'Activation',
75
+ configGroupRuntime: 'Runtime',
76
+ configLoading: 'Loading the configuration…',
77
+ configUnavailable: 'The host does not serve this plugin’s configuration to this client.',
78
+ configReadOnly: 'This client keeps its preferences process-local, so these values are read-only here.',
79
+ configOverridden: 'overridden',
80
+ configReset: 'Reset',
81
+ configResetHint: 'Clear this override and inherit the default',
82
+ configInvalidInteger: 'Enter a whole number ≥ {min}',
83
+ configInvalidRange: 'Enter a whole number between {min} and {max}',
84
+ configInvalidPrefix: 'Up to {max} characters: letters, digits, “_” or “-”',
85
+ // The Activation group: the tool-activation surface of `src/activation.ts`.
86
+ configActivationEnabled: 'Tool activation',
87
+ configActivationEnabledHint: 'Offer MCP tools progressively — counters, disclosure and the search gate',
88
+ configActivationSeeded: 'Seeded tools',
89
+ configActivationSeededHint: 'Tools offered from the first step, before any counter accrues; 0 seeds none',
90
+ configActivationMinCalls: 'Calls to pin',
91
+ configActivationMinCallsHint: 'Calls after which the counters pin a tool directly',
92
+ configToolIdleMs: 'Tool idle timeout (ms)',
93
+ configToolIdleMsHint: 'A tool unused for this long drops back out of the request',
94
+ configGuidanceEnabled: 'System-prompt guidance',
95
+ configGuidanceEnabledHint: 'Inject the plugin’s operating notes into the session prompt',
96
+ configActivationAutoLimit: 'Auto-activation limit',
97
+ configActivationAutoLimitHint: 'Most tools the counters may add on their own (0–50)',
98
+ configActivationAutoStickySteps: 'Sticky steps',
99
+ configActivationAutoStickyStepsHint: 'Steps a just-used tool stays pinned regardless of counters (0–20)',
100
+ configActivationToolBudgetChars: 'Tool budget (chars)',
101
+ configActivationToolBudgetCharsHint: 'Character budget for the tool schemas one request carries (≥ 1000)',
102
+ // The Runtime group: mounting, precedence and timeouts.
103
+ configAllowGlobalWrite: 'Global writes',
104
+ configAllowGlobalWriteHint: 'Allow saving into the user-level (~/.dsh) configuration',
105
+ configEnvFiles: '.env files',
106
+ configEnvFilesHint: 'Load .env files for server environment variables',
107
+ configLazy: 'Lazy mounting',
108
+ configLazyHint: 'Start project servers on the session’s first step, not at boot',
109
+ configLocalPrefix: 'Local prefix',
110
+ configLocalPrefixHint: 'Prefix for local tool names — up to 5 characters of A–Z, 0–9, _ or -; empty disables it',
111
+ configProfileWins: 'Profile wins',
112
+ configProfileWinsHint: 'Profile-level servers override project declarations of the same name',
113
+ configConnectTimeoutMs: 'Connect timeout (ms)',
114
+ configConnectTimeoutMsHint: 'How long starting one server may take',
115
+ configToolCallTimeoutMs: 'Call timeout (ms)',
116
+ configToolCallTimeoutMsHint: 'How long one tool call may take',
117
+ configIdleTimeoutMs: 'Server idle timeout (ms)',
118
+ configIdleTimeoutMsHint: 'A server idle for this long is stopped',
119
+ configDebounceMs: 'Watch debounce (ms)',
120
+ configDebounceMsHint: 'Quiet period before a config change triggers a rescan',
121
+ configActivationWaitMs: 'Activation wait (ms)',
122
+ configActivationWaitMsHint: 'How long the first step may wait for lazy servers',
123
+ } satisfies Record<string, string>
124
+
125
+ /** A dictionary key of this module's half of the namespace. */
126
+ export type LocaleKey = keyof typeof EN
127
+
128
+ /** Translate one key, with optional `{name}` template params (the DSH seat). */
129
+ export type Translate = (key: string, params?: Record<string, unknown>) => string
130
+
131
+ /**
132
+ * Bind the translate seat the framework injects, falling back to this module's
133
+ * own English dictionary when the card renders outside a DSH shell (tests, or
134
+ * a browser half newer than the host).
135
+ * @param t - the `t` seat of the composed props, when the framework passes one.
136
+ * @returns a translate function that always answers.
137
+ */
138
+ export function translateOf(t?: Translate): Translate {
139
+ return t ?? fallbackTranslate
140
+ }
141
+
142
+ function fallbackTranslate(key: string, params?: Record<string, unknown>): string {
143
+ const template = (EN as Record<string, string>)[key] ?? key
144
+ if (params === undefined) return template
145
+ return template.replace(/\{(\w+)\}/g, (match, name: string) =>
146
+ name in params ? String(params[name]) : match,
147
+ )
148
+ }
149
+
150
+ // ---------------------------------------------------------------------------
151
+ // The volatile fields — a mirror of the host table, with the card's own bounds
152
+ // ---------------------------------------------------------------------------
153
+
154
+ /** The eighteen keys of `VOLATILE_CONFIG_KEYS` (`src/index.ts`), redeclared. */
155
+ export type VolatileConfigKey =
156
+ | 'activationEnabled'
157
+ | 'activationSeeded'
158
+ | 'activationMinCalls'
159
+ | 'toolIdleMs'
160
+ | 'guidanceEnabled'
161
+ | 'activationAutoLimit'
162
+ | 'activationAutoStickySteps'
163
+ | 'activationToolBudgetChars'
164
+ | 'allowGlobalWrite'
165
+ | 'envFiles'
166
+ | 'lazy'
167
+ | 'localPrefix'
168
+ | 'profileWins'
169
+ | 'connectTimeoutMs'
170
+ | 'toolCallTimeoutMs'
171
+ | 'idleTimeoutMs'
172
+ | 'debounceMs'
173
+ | 'activationWaitMs'
174
+
175
+ /**
176
+ * The defaults the card displays when the served snapshot has no value for a
177
+ * field. Mirror of the host's module-private `DEFAULTS` (`src/index.ts`) and
178
+ * the activation constants (`src/activation.ts`): the host table cannot cross
179
+ * into the client bundle, so the copy lives here and the schema's own defaults
180
+ * remain the source of truth at write time.
181
+ */
182
+ export const CONFIG_DEFAULTS: Record<VolatileConfigKey, boolean | number | string> = {
183
+ activationEnabled: true,
184
+ activationSeeded: 8,
185
+ activationMinCalls: 5,
186
+ toolIdleMs: 1_800_000,
187
+ guidanceEnabled: true,
188
+ activationAutoLimit: 12,
189
+ activationAutoStickySteps: 2,
190
+ activationToolBudgetChars: 40_000,
191
+ allowGlobalWrite: false,
192
+ envFiles: true,
193
+ lazy: true,
194
+ localPrefix: '',
195
+ profileWins: true,
196
+ connectTimeoutMs: 60_000,
197
+ toolCallTimeoutMs: 60_000,
198
+ idleTimeoutMs: 300_000,
199
+ debounceMs: 300,
200
+ activationWaitMs: 2_000,
201
+ }
202
+
203
+ /**
204
+ * The local-prefix rule, mirrored from `src/naming.ts` (`MAX_LOCAL_PREFIX_LENGTH`
205
+ * and `PREFIX_SHAPE`, in `isValidLocalPrefix`): empty disables the prefix,
206
+ * otherwise at most five characters of letters, digits, `_` or `-`.
207
+ */
208
+ const LOCAL_PREFIX_MAX = 5
209
+ const LOCAL_PREFIX_SHAPE = /^[A-Za-z0-9_-]+$/
210
+
211
+ /** Client-side replica of the host's `isValidLocalPrefix`; see the note above. */
212
+ export function isValidLocalPrefix(value: string): boolean {
213
+ if (value === '') return true
214
+ return value.length <= LOCAL_PREFIX_MAX && LOCAL_PREFIX_SHAPE.test(value)
215
+ }
216
+
217
+ /** One editable field: how it is grouped, edited and bounded. */
218
+ interface FieldDef {
219
+ readonly key: VolatileConfigKey
220
+ readonly kind: 'boolean' | 'integer' | 'text'
221
+ readonly min?: number
222
+ readonly max?: number
223
+ readonly label: LocaleKey
224
+ readonly hint: LocaleKey
225
+ }
226
+
227
+ const ACTIVATION_FIELDS: readonly FieldDef[] = [
228
+ { key: 'activationEnabled', kind: 'boolean', label: 'configActivationEnabled', hint: 'configActivationEnabledHint' },
229
+ { key: 'activationSeeded', kind: 'integer', min: 0, label: 'configActivationSeeded', hint: 'configActivationSeededHint' },
230
+ { key: 'activationMinCalls', kind: 'integer', min: 1, label: 'configActivationMinCalls', hint: 'configActivationMinCallsHint' },
231
+ { key: 'toolIdleMs', kind: 'integer', min: 0, label: 'configToolIdleMs', hint: 'configToolIdleMsHint' },
232
+ { key: 'guidanceEnabled', kind: 'boolean', label: 'configGuidanceEnabled', hint: 'configGuidanceEnabledHint' },
233
+ { key: 'activationAutoLimit', kind: 'integer', min: 0, max: 50, label: 'configActivationAutoLimit', hint: 'configActivationAutoLimitHint' },
234
+ { key: 'activationAutoStickySteps', kind: 'integer', min: 0, max: 20, label: 'configActivationAutoStickySteps', hint: 'configActivationAutoStickyStepsHint' },
235
+ { key: 'activationToolBudgetChars', kind: 'integer', min: 1000, label: 'configActivationToolBudgetChars', hint: 'configActivationToolBudgetCharsHint' },
236
+ ]
237
+
238
+ const RUNTIME_FIELDS: readonly FieldDef[] = [
239
+ { key: 'allowGlobalWrite', kind: 'boolean', label: 'configAllowGlobalWrite', hint: 'configAllowGlobalWriteHint' },
240
+ { key: 'envFiles', kind: 'boolean', label: 'configEnvFiles', hint: 'configEnvFilesHint' },
241
+ { key: 'lazy', kind: 'boolean', label: 'configLazy', hint: 'configLazyHint' },
242
+ { key: 'localPrefix', kind: 'text', label: 'configLocalPrefix', hint: 'configLocalPrefixHint' },
243
+ { key: 'profileWins', kind: 'boolean', label: 'configProfileWins', hint: 'configProfileWinsHint' },
244
+ { key: 'connectTimeoutMs', kind: 'integer', min: 0, label: 'configConnectTimeoutMs', hint: 'configConnectTimeoutMsHint' },
245
+ { key: 'toolCallTimeoutMs', kind: 'integer', min: 0, label: 'configToolCallTimeoutMs', hint: 'configToolCallTimeoutMsHint' },
246
+ { key: 'idleTimeoutMs', kind: 'integer', min: 0, label: 'configIdleTimeoutMs', hint: 'configIdleTimeoutMsHint' },
247
+ { key: 'debounceMs', kind: 'integer', min: 0, label: 'configDebounceMs', hint: 'configDebounceMsHint' },
248
+ { key: 'activationWaitMs', kind: 'integer', min: 0, label: 'configActivationWaitMs', hint: 'configActivationWaitMsHint' },
249
+ ]
250
+
251
+ // ---------------------------------------------------------------------------
252
+ // The card
253
+ // ---------------------------------------------------------------------------
254
+
255
+ const QUIET: CSSProperties = {
256
+ fontSize: '0.85em',
257
+ color: 'var(--dsw-alias-label-tertiary, inherit)',
258
+ }
259
+
260
+ const OVERRIDDEN_CHIP: CSSProperties = {
261
+ marginLeft: 8,
262
+ padding: '0 6px',
263
+ borderRadius: 8,
264
+ border: '1px solid var(--dsw-alias-border-l2, rgba(127, 127, 127, 0.4))',
265
+ fontSize: '0.75em',
266
+ fontWeight: 400,
267
+ color: 'var(--dsw-alias-label-tertiary, inherit)',
268
+ verticalAlign: '1px',
269
+ }
270
+
271
+ const RESET_BUTTON: CSSProperties = {
272
+ border: 'none',
273
+ background: 'none',
274
+ padding: 0,
275
+ cursor: 'pointer',
276
+ font: 'inherit',
277
+ fontSize: '0.85em',
278
+ color: 'var(--dsw-alias-state-business-primary, #2563eb)',
279
+ }
280
+
281
+ const INPUT_WIDTH: CSSProperties = { width: 96 }
282
+
283
+ const INPUT_INVALID: CSSProperties = {
284
+ borderColor: 'var(--dsw-alias-state-error-primary, #ef4444)',
285
+ }
286
+
287
+ const INVALID_NOTE: CSSProperties = {
288
+ fontSize: '0.8em',
289
+ color: 'var(--dsw-alias-state-error-primary, #ef4444)',
290
+ }
291
+
292
+ /** The snapshot used while there is no form at all: the unavailable note. */
293
+ const NO_FORM_SNAPSHOT: ConfigFormSnapshotLike = {
294
+ status: 'unavailable',
295
+ value: undefined,
296
+ user: undefined,
297
+ writable: false,
298
+ }
299
+
300
+ const noFormSnapshot = (): ConfigFormSnapshotLike => NO_FORM_SNAPSHOT
301
+ const subscribeNone = (): (() => void) => () => undefined
302
+
303
+ /** The memoized store pair `useSyncExternalStore` needs, plus the form itself. */
304
+ interface FormSource {
305
+ readonly form: ConfigFormLike
306
+ readonly subscribe: (listener: () => void) => () => void
307
+ readonly getSnapshot: () => ConfigFormSnapshotLike
308
+ }
309
+
310
+ /**
311
+ * Resolve the `form` prop into a store the card can subscribe to. The
312
+ * registration injects a factory (`() => forms.get(ns)`); a direct
313
+ * `ConfigForm`-shaped object is accepted as well. Anything else — an absent
314
+ * prop, a factory that throws, an owner-provided page form the card cannot
315
+ * write through — resolves to `null`, and the card renders its quiet
316
+ * unavailable note instead of failing.
317
+ */
318
+ function formSourceOf(raw: unknown): FormSource | null {
319
+ let candidate: unknown = raw
320
+ if (typeof candidate === 'function') {
321
+ try {
322
+ candidate = (candidate as () => unknown)()
323
+ } catch {
324
+ return null
325
+ }
326
+ }
327
+ if (candidate === null || typeof candidate !== 'object') return null
328
+ const form = candidate as ConfigFormLike
329
+ if (
330
+ typeof form.getSnapshot !== 'function' ||
331
+ typeof form.subscribe !== 'function' ||
332
+ typeof form.set !== 'function' ||
333
+ typeof form.unset !== 'function'
334
+ ) {
335
+ return null
336
+ }
337
+ return {
338
+ form,
339
+ subscribe: (listener) => form.subscribe(listener),
340
+ getSnapshot: () => form.getSnapshot(),
341
+ }
342
+ }
343
+
344
+ /** A field is overridden when it is PRESENT in the user layer, whatever its value. */
345
+ function hasOverride(user: unknown, field: string): boolean {
346
+ return typeof user === 'object' && user !== null && Object.prototype.hasOwnProperty.call(user, field)
347
+ }
348
+
349
+ /** The displayed value: the served one, falling back to the mirrored default. */
350
+ function fieldValue(def: FieldDef, snapshot: ConfigFormSnapshotLike): boolean | number | string {
351
+ const raw = snapshot.value?.[def.key]
352
+ const fallback = CONFIG_DEFAULTS[def.key]
353
+ if (def.kind === 'boolean') return typeof raw === 'boolean' ? raw : (fallback as boolean)
354
+ if (def.kind === 'integer') {
355
+ return typeof raw === 'number' && Number.isFinite(raw) ? raw : (fallback as number)
356
+ }
357
+ return typeof raw === 'string' ? raw : (fallback as string)
358
+ }
359
+
360
+ /** Parse a draft into a bounded whole number; `undefined` means "do not write". */
361
+ function parseInteger(raw: string, min: number, max: number | undefined): number | undefined {
362
+ const trimmed = raw.trim()
363
+ if (!/^-?\d+$/.test(trimmed)) return undefined
364
+ const parsed = Number(trimmed)
365
+ if (!Number.isSafeInteger(parsed) || parsed < min || (max !== undefined && parsed > max)) return undefined
366
+ return parsed
367
+ }
368
+
369
+ /**
370
+ * The plugin's configuration card. `view: 'summary'` is the one-liner the
371
+ * contract allows an owner to ask for; the Plugins page today only ever asks
372
+ * for `'page'`, which is the full two-group form.
373
+ */
374
+ export function PluginConfigCard(props: PluginConfigViewPropsLike): ReactNode {
375
+ const t = translateOf(props.t)
376
+ // The injected face is cached per entry, so `props.form` is stable and this
377
+ // memo resolves the factory exactly once per entry.
378
+ const source = useMemo(() => formSourceOf(props.form), [props.form])
379
+ const snapshot = useSyncExternalStore(
380
+ source === null ? subscribeNone : source.subscribe,
381
+ source === null ? noFormSnapshot : source.getSnapshot,
382
+ )
383
+ if (props.view === 'summary') {
384
+ return h('div', { style: QUIET }, t('configSummary'))
385
+ }
386
+ if (source === null || snapshot.status === 'unavailable') {
387
+ return h('div', { style: QUIET }, t('configUnavailable'))
388
+ }
389
+ if (snapshot.status === 'loading') {
390
+ return h('div', { style: QUIET }, t('configLoading'))
391
+ }
392
+ const disabled = !snapshot.writable
393
+ return h(
394
+ 'div',
395
+ null,
396
+ disabled ? h('div', { style: { ...QUIET, marginBottom: 8 } }, t('configReadOnly')) : null,
397
+ fieldGroup('activation', 'configGroupActivation', ACTIVATION_FIELDS, snapshot, source.form, t, disabled),
398
+ fieldGroup('runtime', 'configGroupRuntime', RUNTIME_FIELDS, snapshot, source.form, t, disabled),
399
+ )
400
+ }
401
+
402
+ /** One titled group of setting rows, in the shape DSH's own settings pages use. */
403
+ function fieldGroup(
404
+ group: string,
405
+ titleKey: LocaleKey,
406
+ fields: readonly FieldDef[],
407
+ snapshot: ConfigFormSnapshotLike,
408
+ form: ConfigFormLike,
409
+ t: Translate,
410
+ disabled: boolean,
411
+ ): ReactNode {
412
+ return h(
413
+ 'section',
414
+ { key: group, style: group === 'activation' ? undefined : STYLE.settingGroup },
415
+ h('div', { style: STYLE.settingGroupHead }, t(titleKey)),
416
+ fields.map((def, index) =>
417
+ h(FieldRow, {
418
+ key: def.key,
419
+ def,
420
+ snapshot,
421
+ form,
422
+ t,
423
+ disabled,
424
+ last: index === fields.length - 1,
425
+ }),
426
+ ),
427
+ )
428
+ }
429
+
430
+ interface FieldRowProps {
431
+ readonly def: FieldDef
432
+ readonly snapshot: ConfigFormSnapshotLike
433
+ readonly form: ConfigFormLike
434
+ readonly t: Translate
435
+ readonly disabled: boolean
436
+ readonly last: boolean
437
+ }
438
+
439
+ /** One setting row: label and hint left, control right, reset when overridden. */
440
+ function FieldRow(props: FieldRowProps): ReactNode {
441
+ const { def, snapshot, form, t, disabled, last } = props
442
+ const overridden = hasOverride(snapshot.user, def.key)
443
+ const value = fieldValue(def, snapshot)
444
+ const label = t(def.label)
445
+ const control =
446
+ def.kind === 'boolean'
447
+ ? h(BooleanControl, {
448
+ label,
449
+ value: value as boolean,
450
+ disabled,
451
+ onToggle: (next: boolean) => void form.set(def.key, next),
452
+ })
453
+ : def.kind === 'integer'
454
+ ? h(IntegerControl, {
455
+ label,
456
+ value: value as number,
457
+ disabled,
458
+ min: def.min ?? 0,
459
+ max: def.max,
460
+ t,
461
+ onCommit: (next: number) => void form.set(def.key, next),
462
+ })
463
+ : h(TextControl, {
464
+ label,
465
+ value: value as string,
466
+ disabled,
467
+ t,
468
+ onCommit: (next: string) => void form.set(def.key, next),
469
+ })
470
+ return h(
471
+ 'div',
472
+ { style: last ? { ...STYLE.settingRow, ...STYLE.lastRow } : STYLE.settingRow },
473
+ h(
474
+ 'div',
475
+ { style: STYLE.settingRowText },
476
+ h(
477
+ 'span',
478
+ { style: STYLE.settingRowLabel },
479
+ label,
480
+ overridden ? h('span', { style: OVERRIDDEN_CHIP }, t('configOverridden')) : null,
481
+ ),
482
+ h('span', { style: STYLE.settingRowDesc }, t(def.hint)),
483
+ ),
484
+ h(
485
+ 'div',
486
+ { style: STYLE.settingRowControl },
487
+ control,
488
+ overridden
489
+ ? h(
490
+ 'button',
491
+ {
492
+ type: 'button',
493
+ style: RESET_BUTTON,
494
+ disabled,
495
+ title: t('configResetHint'),
496
+ 'aria-label': `${t('configReset')}: ${label}`,
497
+ onClick: () => void form.unset(def.key),
498
+ },
499
+ t('configReset'),
500
+ )
501
+ : null,
502
+ ),
503
+ )
504
+ }
505
+
506
+ interface BooleanControlProps {
507
+ readonly label: string
508
+ readonly value: boolean
509
+ readonly disabled: boolean
510
+ readonly onToggle: (next: boolean) => void
511
+ }
512
+
513
+ /** The settings pages' sliding switch, bound to one boolean field. */
514
+ function BooleanControl(props: BooleanControlProps): ReactNode {
515
+ return h(
516
+ 'button',
517
+ {
518
+ type: 'button',
519
+ role: 'switch',
520
+ 'aria-checked': props.value,
521
+ 'aria-label': props.label,
522
+ disabled: props.disabled,
523
+ style: props.value ? STYLE.switchOn : { ...STYLE.switchOn, ...STYLE.switchOff },
524
+ onClick: () => props.onToggle(!props.value),
525
+ },
526
+ h('span', {
527
+ style: props.value ? { ...STYLE.switchKnob, ...STYLE.switchKnobOn } : STYLE.switchKnob,
528
+ 'aria-hidden': true,
529
+ }),
530
+ )
531
+ }
532
+
533
+ interface IntegerControlProps {
534
+ readonly label: string
535
+ readonly value: number
536
+ readonly disabled: boolean
537
+ readonly min: number
538
+ readonly max: number | undefined
539
+ readonly t: Translate
540
+ readonly onCommit: (next: number) => void
541
+ }
542
+
543
+ /**
544
+ * A bounded whole-number input. The draft is local; only a dirty draft commits,
545
+ * on blur or Enter — a blur with no edit writes nothing. An invalid draft
546
+ * never reaches `form.set` — it marks the control and explains the bound
547
+ * instead. Escape abandons the draft.
548
+ */
549
+ function IntegerControl(props: IntegerControlProps): ReactNode {
550
+ const [draft, setDraft] = useState<string | undefined>(undefined)
551
+ const [invalid, setInvalid] = useState(false)
552
+ const invalidText =
553
+ props.max === undefined
554
+ ? props.t('configInvalidInteger', { min: props.min })
555
+ : props.t('configInvalidRange', { min: props.min, max: props.max })
556
+ const commit = (raw: string): void => {
557
+ const parsed = parseInteger(raw, props.min, props.max)
558
+ if (parsed === undefined) {
559
+ setInvalid(true)
560
+ return
561
+ }
562
+ setInvalid(false)
563
+ setDraft(undefined)
564
+ props.onCommit(parsed)
565
+ }
566
+ return h(
567
+ 'span',
568
+ { style: { display: 'inline-flex', flexDirection: 'column', gap: 2 } },
569
+ h('input', {
570
+ type: 'number',
571
+ inputMode: 'numeric',
572
+ step: 1,
573
+ min: props.min,
574
+ ...(props.max === undefined ? {} : { max: props.max }),
575
+ style: invalid ? { ...STYLE.input, ...INPUT_WIDTH, ...INPUT_INVALID } : { ...STYLE.input, ...INPUT_WIDTH },
576
+ value: draft ?? String(props.value),
577
+ disabled: props.disabled,
578
+ 'aria-label': props.label,
579
+ 'aria-invalid': invalid || undefined,
580
+ onChange: (event: { target: { value: string } }) => {
581
+ setDraft(String(event.target.value))
582
+ if (invalid) setInvalid(false)
583
+ },
584
+ onBlur: () => {
585
+ // Commit only a dirty draft: a blur with no edit must not write the
586
+ // displayed snapshot value (it would pin a phantom override), and the
587
+ // Enter path clears the draft, so an Enter-then-blur no-ops instead of
588
+ // committing the stale value the input fell back to.
589
+ if (draft !== undefined) commit(draft)
590
+ },
591
+ onKeyDown: (event: { key: string }) => {
592
+ if (event.key === 'Enter') {
593
+ if (draft !== undefined) commit(draft)
594
+ } else if (event.key === 'Escape') {
595
+ setDraft(undefined)
596
+ setInvalid(false)
597
+ }
598
+ },
599
+ }),
600
+ invalid ? h('span', { role: 'alert', style: INVALID_NOTE }, invalidText) : null,
601
+ )
602
+ }
603
+
604
+ interface TextControlProps {
605
+ readonly label: string
606
+ readonly value: string
607
+ readonly disabled: boolean
608
+ readonly t: Translate
609
+ readonly onCommit: (next: string) => void
610
+ }
611
+
612
+ /** The local-prefix input: same commit discipline as the numbers, prefix rule. */
613
+ function TextControl(props: TextControlProps): ReactNode {
614
+ const [draft, setDraft] = useState<string | undefined>(undefined)
615
+ const [invalid, setInvalid] = useState(false)
616
+ const commit = (raw: string): void => {
617
+ if (!isValidLocalPrefix(raw)) {
618
+ setInvalid(true)
619
+ return
620
+ }
621
+ setInvalid(false)
622
+ setDraft(undefined)
623
+ props.onCommit(raw)
624
+ }
625
+ return h(
626
+ 'span',
627
+ { style: { display: 'inline-flex', flexDirection: 'column', gap: 2 } },
628
+ h('input', {
629
+ type: 'text',
630
+ maxLength: LOCAL_PREFIX_MAX,
631
+ style: invalid ? { ...STYLE.input, ...INPUT_WIDTH, ...INPUT_INVALID } : { ...STYLE.input, ...INPUT_WIDTH },
632
+ value: draft ?? props.value,
633
+ placeholder: '—',
634
+ disabled: props.disabled,
635
+ 'aria-label': props.label,
636
+ 'aria-invalid': invalid || undefined,
637
+ onChange: (event: { target: { value: string } }) => {
638
+ setDraft(String(event.target.value))
639
+ if (invalid) setInvalid(false)
640
+ },
641
+ onBlur: () => {
642
+ // Same commit discipline as the number input: dirty drafts only.
643
+ if (draft !== undefined) commit(draft)
644
+ },
645
+ onKeyDown: (event: { key: string }) => {
646
+ if (event.key === 'Enter') {
647
+ if (draft !== undefined) commit(draft)
648
+ } else if (event.key === 'Escape') {
649
+ setDraft(undefined)
650
+ setInvalid(false)
651
+ }
652
+ },
653
+ }),
654
+ invalid
655
+ ? h('span', { role: 'alert', style: INVALID_NOTE }, props.t('configInvalidPrefix', { max: LOCAL_PREFIX_MAX }))
656
+ : null,
657
+ )
658
+ }
659
+
660
+ // ---------------------------------------------------------------------------
661
+ // Registration — the `plugins.bundle.config` entry, parked on the configForms
662
+ // service so the card appears exactly when the host serves the namespace
663
+ // ---------------------------------------------------------------------------
664
+
665
+ const PLUGIN_CONFIG_SLOT = 'plugins.bundle.config'
666
+ const PRIMARY_CONFIG_NS = 'dsh-project-mcp'
667
+ const LEGACY_CONFIG_NS = 'project-mcp'
668
+
669
+ /** The slot-services slice the registration needs, mirroring settings.ts. */
670
+ export interface PluginConfigSlotServices {
671
+ effect(execute: () => unknown, label?: string): unknown
672
+ slots: {
673
+ inject(slot: string, callback: () => unknown): unknown
674
+ register<Props>(
675
+ options: {
676
+ name: string
677
+ key: string
678
+ locale: string
679
+ inject: () => Record<string, unknown>
680
+ },
681
+ component: (props: Props) => ReactNode,
682
+ ): unknown
683
+ }
684
+ configForms: ConfigFormsLike
685
+ }
686
+
687
+ /**
688
+ * Register the card on the Plugins page.
689
+ *
690
+ * The keyed slot's options are exactly `{ name, key, locale, inject }` — the
691
+ * `id`/`order`/`label` options of list slots do not exist here. `whileServed`
692
+ * watches both config namespaces and prefers the plugin's own; the register
693
+ * callback fires once, when the first watched namespace becomes served (there
694
+ * is no re-fire while any of them stays served), and its returned disposer —
695
+ * the one `slots.inject` hands back — runs when the last one disappears.
696
+ */
697
+ export function registerPluginConfigCard(services: PluginConfigSlotServices): void {
698
+ const forms = services.configForms
699
+ services.effect(
700
+ () =>
701
+ forms.whileServed([PRIMARY_CONFIG_NS, LEGACY_CONFIG_NS], (served) => {
702
+ const ns = served.has(PRIMARY_CONFIG_NS) ? PRIMARY_CONFIG_NS : LEGACY_CONFIG_NS
703
+ // `slots.inject` keeps registration a no-op on a composition whose
704
+ // slots registry does not declare the slot (an older host) — the card
705
+ // is simply absent there, nothing throws.
706
+ const dispose = services.slots.inject(PLUGIN_CONFIG_SLOT, () =>
707
+ services.slots.register(
708
+ {
709
+ name: PLUGIN_CONFIG_SLOT,
710
+ key: PACKAGE_NAME,
711
+ locale: NS,
712
+ inject: () => ({ form: () => forms.get(ns) }),
713
+ },
714
+ (props: PluginConfigViewPropsLike) => h(PluginConfigCard, props),
715
+ ),
716
+ )
717
+ return typeof dispose === 'function' ? (dispose as () => void) : (): void => undefined
718
+ }),
719
+ 'project-mcp: plugin config card',
720
+ )
721
+ }