@linxin666/dsh-liangshen 0.3.23 → 0.4.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 (59) hide show
  1. package/README.i18n.yaml +2 -2
  2. package/README.md +55 -41
  3. package/README.zh.md +54 -40
  4. package/cordis.patch.yml +3 -2
  5. package/icon.svg +3 -0
  6. package/lib/client.js +1380 -29
  7. package/lib/client.js.map +1 -1
  8. package/lib/index.js +616 -367
  9. package/lib/types/announce.test.d.ts +10 -0
  10. package/lib/types/client/LiangShenSettingsCard.d.ts +78 -0
  11. package/lib/types/client/PluginSettingsCard.d.ts +137 -0
  12. package/lib/types/client/index.d.ts +57 -4
  13. package/lib/types/client/lever-controller.d.ts +16 -2
  14. package/lib/types/client/locales.d.ts +40 -1
  15. package/lib/types/client/main-session.d.ts +32 -0
  16. package/lib/types/client/plugin-card-seat.d.ts +103 -0
  17. package/lib/types/client/settings-form.d.ts +197 -0
  18. package/lib/types/composition.d.ts +116 -0
  19. package/lib/types/composition.test.d.ts +7 -0
  20. package/lib/types/core/lever.d.ts +6 -3
  21. package/lib/types/index.d.ts +160 -33
  22. package/lib/types/index.test.d.ts +5 -0
  23. package/package.json +27 -18
  24. package/presets/liangshen/NOTICE +4 -4
  25. package/presets/liangshen/agent.cordis.yml +168 -123
  26. package/presets/liangshen/fact-ledger.mjs +141 -0
  27. package/presets/liangshen/guard.mjs +426 -0
  28. package/presets/liangshen/minimal-prompt.mjs +73 -38
  29. package/presets/liangshen/paging.mjs +232 -0
  30. package/presets/liangshen/tool-activate.mjs +176 -0
  31. package/presets/liangshen/tool-catalog.mjs +615 -219
  32. package/presets/liangshen/working-context.mjs +222 -0
  33. package/src/announce.test.ts +248 -55
  34. package/src/client/LiangShenLever.module.css +2 -0
  35. package/src/client/LiangShenLever.tsx +41 -10
  36. package/src/client/LiangShenSettingsCard.tsx +233 -0
  37. package/src/client/PluginSettingsCard.tsx +555 -0
  38. package/src/client/index.ts +102 -5
  39. package/src/client/lever-controller.ts +76 -9
  40. package/src/client/locales.ts +79 -1
  41. package/src/client/main-session.ts +43 -0
  42. package/src/client/plugin-card-seat.ts +192 -0
  43. package/src/client/settings-card.module.css +418 -0
  44. package/src/client/settings-form.ts +442 -0
  45. package/src/composition.test.ts +294 -0
  46. package/src/composition.ts +554 -0
  47. package/src/core/lever.ts +7 -4
  48. package/src/index.test.ts +68 -1
  49. package/src/index.ts +293 -101
  50. package/tools/benchmark-live-run.mjs +193 -63
  51. package/lib/types/schema.d.ts +0 -18
  52. package/lib/types/schema.test.d.ts +0 -1
  53. package/lib/types/sync.d.ts +0 -47
  54. package/lib/types/sync.test.d.ts +0 -1
  55. package/presets/liangshen/custom-bash.mjs +0 -213
  56. package/src/schema.test.ts +0 -64
  57. package/src/schema.ts +0 -110
  58. package/src/sync.test.ts +0 -224
  59. package/src/sync.ts +0 -222
@@ -3,7 +3,7 @@
3
3
  *
4
4
  * The view stays pure; every fact and verb comes from here. The roster arrives
5
5
  * over the agent-preset Remote namespace (the same one the official surfaces
6
- * read), the current session comes from the browser sessions service, and the
6
+ * read), the main-view session comes from the catalog's ownership marker, and the
7
7
  * switch goes through `agentPresets.select`, which the host accepts only while
8
8
  * the session is still blank.
9
9
  *
@@ -15,8 +15,9 @@
15
15
  */
16
16
 
17
17
  import type { Context as ClientContext } from '@deepseek-ai/cordis'
18
- import type { AgentPresetRoster } from '@deepseek-ai/dsh-agent-presets/types'
18
+ import type { AgentPresetRoster } from '@deepseek-ai/dsh-agent-preset-registry/types'
19
19
  import type { ISessions } from '@deepseek-ai/dsh-api-session-controller/client'
20
+ import { mainViewSessionId } from './main-session.ts'
20
21
  import type { RemoteResult } from '@deepseek-ai/dsh-api-remotes/client'
21
22
  import { createSnapshotStore, type SnapshotStore } from '@deepseek-ai/dsh-client-store'
22
23
  import { LIANGSHEN_PRESET_ID, isActionable, leverState, restoreTarget, type LeverFacts, type LeverState } from '../core/lever.ts'
@@ -43,6 +44,15 @@ export type LeverError =
43
44
  /** How long one preset switch may stay in flight before it is reported as timed out. */
44
45
  export const SELECT_TIMEOUT_MS = 10_000
45
46
 
47
+ /**
48
+ * Settings entry ids whose writes can move the roster this lever reads: the
49
+ * agent-preset registry's own entry (its default and selection policy) and this
50
+ * plugin's row under either install shape — the aggregate's generated row id
51
+ * and the standalone row id — because disabling the plugin unregisters the
52
+ * preset it declares.
53
+ */
54
+ export const ROSTER_SETTINGS_ENTRY_IDS: readonly string[] = ['agent-preset-registry', 'web-ui-liangshen', 'liangshen']
55
+
46
56
  /** What the lever view renders. */
47
57
  export interface LeverSnapshot {
48
58
  /** Resolved lever state. */
@@ -142,7 +152,7 @@ export class LeverController {
142
152
  )
143
153
  if (typeof remote?.$on === 'function') {
144
154
  this.disposers.push(remote.$on('settings/document-updated', (ns: string) => {
145
- if (ns === 'agent-presets') void this.load()
155
+ if (ROSTER_SETTINGS_ENTRY_IDS.includes(ns)) void this.load()
146
156
  }))
147
157
  }
148
158
  this.refresh()
@@ -239,34 +249,91 @@ export class LeverController {
239
249
  }
240
250
  // The switch landed: remember where to return, then celebrate only the
241
251
  // pull that turned the mode on.
242
- this.previous = direction === 'down' ? facts.agentPreset : undefined
252
+ if (direction === 'down') {
253
+ const prev = facts.agentPreset ?? this.detectPreset()
254
+ if (prev !== undefined && prev !== LIANGSHEN_PRESET_ID) {
255
+ this.rememberPrevious(prev)
256
+ }
257
+ }
243
258
  const next = this.store.getSnapshot()
244
259
  this.store.set({ ...next, busy: false, error: undefined, burst: direction === 'down' ? next.burst + 1 : next.burst })
245
260
  this.refresh()
246
261
  }
247
262
 
263
+ /**
264
+ * Try to detect the active preset from the DOM hero chip or storage
265
+ * when session.projectionValues.agentPreset is absent.
266
+ */
267
+ private detectPreset(): string | undefined {
268
+ try {
269
+ if (typeof document !== 'undefined') {
270
+ const chip = document.querySelector<HTMLElement>('button[aria-haspopup="menu"] span[class*="seatLabel"]')
271
+ ?? Array.from(document.querySelectorAll<HTMLElement>('button[aria-haspopup="menu"] span')).find(s => s.className.includes('seatLabel'))
272
+ const text = chip?.textContent?.trim()
273
+ if (text) {
274
+ const matched = this.rows.find(row => (row.name === text || row.id === text) && row.id !== LIANGSHEN_PRESET_ID)
275
+ if (matched) return matched.id
276
+ }
277
+ }
278
+ } catch {
279
+ // Defensive
280
+ }
281
+
282
+ try {
283
+ if (typeof sessionStorage !== 'undefined') {
284
+ const stored = sessionStorage.getItem('dsh-liangshen:previous-preset')
285
+ if (stored && stored !== LIANGSHEN_PRESET_ID && this.rows.some(r => r.id === stored)) {
286
+ return stored
287
+ }
288
+ }
289
+ } catch {
290
+ // Defensive
291
+ }
292
+
293
+ return undefined
294
+ }
295
+
296
+ private rememberPrevious(presetId: string | undefined): void {
297
+ if (presetId === undefined || presetId === LIANGSHEN_PRESET_ID) return
298
+ this.previous = presetId
299
+ try {
300
+ if (typeof sessionStorage !== 'undefined') {
301
+ sessionStorage.setItem('dsh-liangshen:previous-preset', presetId)
302
+ }
303
+ } catch {
304
+ // Defensive
305
+ }
306
+ }
307
+
248
308
  /** The facts one decision reads, from the live session and the roster. */
249
309
  private facts(): LeverFacts {
250
310
  const summary = this.currentSession()
251
311
  const available = this.rows.filter(row => row.broken === undefined).map(row => row.id)
252
312
  const fallback = this.rows.find(row => row.isDefault)?.id
313
+ const currentPreset = presetOf(summary)
314
+
315
+ if (currentPreset !== undefined && currentPreset !== LIANGSHEN_PRESET_ID) {
316
+ this.rememberPrevious(currentPreset)
317
+ }
318
+
319
+ const previous = this.previous ?? this.detectPreset()
320
+
253
321
  return {
254
322
  blank: summary?.blank === true,
255
- agentPreset: presetOf(summary),
323
+ agentPreset: currentPreset,
256
324
  available,
257
325
  fallback,
258
- previous: this.previous,
326
+ previous,
259
327
  }
260
328
  }
261
329
 
262
330
  private currentSessionId(): string | undefined {
263
- const current = this.sessions?.list.getSnapshot().current
264
- return current === undefined ? undefined : String(current)
331
+ return mainViewSessionId(this.sessions?.list.getSnapshot().byId)
265
332
  }
266
333
 
267
334
  private currentSession(): { blank?: boolean, projectionValues?: Record<string, unknown> } | undefined {
268
335
  const state = this.sessions?.list.getSnapshot()
269
- const current = state?.current
336
+ const current = mainViewSessionId(state?.byId)
270
337
  if (state === undefined || current === undefined) return undefined
271
338
  return state.byId[current] as unknown as { blank?: boolean, projectionValues?: Record<string, unknown> } | undefined
272
339
  }
@@ -21,6 +21,45 @@ export const zh = {
21
21
  'lever.failed.failed': '切换失败:{reason}',
22
22
  'burst.line1': '三秒,三辈子的代码',
23
23
  'burst.line2': '文言文 · 二进制 · 摩斯电码',
24
+ 'settings.title': '梁神模式',
25
+ 'settings.description': '控制本插件与工具面呈现方式。',
26
+ 'settings.enabled': '启用梁神模式',
27
+ 'settings.enabledHint': '关闭后不声明预设、也不发 agent 公告。',
28
+ 'settings.announceToAgent': '向 agent 公告本插件',
29
+ 'settings.announceToAgentHint': '开启后向每一轮 agent 系统提示注入本插件公告;默认关闭以保持提示词干净。',
30
+ 'settings.presentation': '工具面呈现方式',
31
+ 'settings.presentationHint': '写入本插件声明的预设的 tool-catalog 行:both(出厂默认)让原生清单与 run_code 同驻(原生直调优先);native 保持原生工具清单;ptc 把 wire 收拢为 run_code。改动立即生效,但已开始的会话保持其已声明的组合。',
32
+ 'settings.on': '开',
33
+ 'settings.off': '关',
34
+ 'settings.inherit': '继承(跟随部署默认)',
35
+ 'settings.overridden': '已覆盖',
36
+ 'settings.reset': '重置',
37
+ 'settings.notExposed': '当前 DSH 版本未向设置页暴露本插件的配置命名空间,表单不可用。可编辑 ~/.dsh/settings.yaml 直接配置,或将本命名空间加入 Host 设置白名单后重启。',
38
+ 'settings.readOnly': '当前部署的设置只读。',
39
+ 'settings.expand': '展开设置',
40
+ 'settings.collapse': '收起设置',
41
+ 'settings.save': '保存',
42
+ 'settings.saving': '保存中…',
43
+ 'settings.discard': '放弃',
44
+ 'settings.unsaved': '未保存',
45
+ 'settings.saveFailed': '部署未接受这些值,已保留供你修改。',
46
+ 'settings.invalidValue': '该取值不被接受',
47
+ 'presentation.ptc': 'ptc(仅 run_code)',
48
+ 'presentation.native': 'native(原生工具清单)',
49
+ 'presentation.both': 'both(两者同驻)',
50
+ 'settings.guardEnabled': '启用退化熔断器',
51
+ 'settings.guardEnabledHint': '运行时检测思考退化(连续零产出长思考 / 同参重复失败),触发时注入熔断提示并临时下调推理档位。关闭后不干预任何请求。',
52
+ 'settings.guardStallChars': '单步暴走字符阈值',
53
+ 'settings.guardStallCharsHint': '单条推理达到该字符数且零产出即触发熔断(按 V4.1 官方 384K 最大输出校准;默认 8000,约 2-4K 思考 token)。',
54
+ 'settings.guardGlobalCap': '慢烧连续步数',
55
+ 'settings.guardGlobalCapHint': '连续多少步有真实推理但零产出触发慢烧熔断(默认 4;步数越小越敏感,真实长调查建议调大)。',
56
+ 'settings.guardSensitivity': '熔断灵敏度',
57
+ 'settings.guardSensitivityHint': '整体缩放熔断阈值:保守(更少打断,阈值×1.5)、均衡(出厂校准值)、激进(更早触发,阈值×0.5)。阈值随推理档位自适应:max 档 8000 / high 档 12000 / low 档 20000 字符。',
58
+ 'sensitivity.conservative': '保守(少打断)',
59
+ 'sensitivity.balanced': '均衡(默认)',
60
+ 'sensitivity.aggressive': '激进(早触发)',
61
+ 'settings.guardEchoFailures': '同参连续失败次数',
62
+ 'settings.guardEchoFailuresHint': '同一工具以相同参数连续失败多少次触发空转熔断(默认 3)。',
24
63
  }
25
64
 
26
65
  /** English counterpart; the key set mirrors {@link zh} exactly. */
@@ -40,7 +79,46 @@ export const en: Record<keyof typeof zh, string> = {
40
79
  'lever.failed.failed': 'Switch failed: {reason}',
41
80
  'burst.line1': 'Three seconds, three lifetimes of code',
42
81
  'burst.line2': 'Classical Chinese · Binary · Morse code',
82
+ 'settings.title': 'LiangShen mode',
83
+ 'settings.description': 'Controls this plugin and the wire presentation.',
84
+ 'settings.enabled': 'Enable LiangShen mode',
85
+ 'settings.enabledHint': 'When off, the preset is not declared and the agent announcement does not run.',
86
+ 'settings.announceToAgent': 'Announce this plugin to agents',
87
+ 'settings.announceToAgentHint': 'Adds this plugin announcement to every agent system prompt; off by default so prompts stay clean.',
88
+ 'settings.presentation': 'Wire presentation',
89
+ 'settings.presentationHint': 'Written into the tool-catalog row of the preset this plugin declares: both (the shipped default) keeps the roster and run_code co-resident (direct native calls first); native keeps the native roster; ptc collapses the wire to run_code. A change re-declares the preset immediately; sessions that already started keep the composition they declared.',
90
+ 'settings.on': 'On',
91
+ 'settings.off': 'Off',
92
+ 'settings.inherit': 'Inherit (deployment default)',
93
+ 'settings.overridden': 'Overridden',
94
+ 'settings.reset': 'Reset',
95
+ 'settings.notExposed': "This DSH version does not expose this plugin's settings namespace to the configuration page, so the form is unavailable. Edit ~/.dsh/settings.yaml directly, or add the namespace to the Host settings allowlist and restart.",
96
+ 'settings.readOnly': 'This deployment serves settings read-only.',
97
+ 'settings.expand': 'Show settings',
98
+ 'settings.collapse': 'Hide settings',
99
+ 'settings.save': 'Save',
100
+ 'settings.saving': 'Saving…',
101
+ 'settings.discard': 'Discard',
102
+ 'settings.unsaved': 'Unsaved',
103
+ 'settings.saveFailed': 'The deployment did not accept these values; they were left for you to correct.',
104
+ 'settings.invalidValue': 'The value is not accepted',
105
+ 'presentation.ptc': 'ptc (run_code only)',
106
+ 'presentation.native': 'native (native tool roster)',
107
+ 'presentation.both': 'both (both co-resident)',
108
+ 'settings.guardEnabled': 'Degeneration circuit breaker',
109
+ 'settings.guardEnabledHint': 'Detects reasoning degeneration at runtime (consecutive zero-output long reasoning / repeated identical-argument failures), injecting a breaker message and stepping the reasoning effort down when it fires. Disabled means requests are never touched.',
110
+ 'settings.guardStallChars': 'Runaway reasoning character floor',
111
+ 'settings.guardStallCharsHint': 'One reasoning block reaching this many characters with no output fires the breaker (calibrated against V4.1\'s official 384K max output; default 8000, roughly 2-4K thinking tokens).',
112
+ 'settings.guardGlobalCap': 'Slow-burn step count',
113
+ 'settings.guardGlobalCapHint': 'Consecutive output-free steps of real reasoning that fire the slow-burn ladder (default 4; lower is more sensitive — raise it for genuinely long investigations).',
114
+ 'settings.guardSensitivity': 'Breaker sensitivity',
115
+ 'settings.guardSensitivityHint': 'Scales every breaker threshold: conservative (fewer interruptions, x1.5), balanced (the calibrated defaults), aggressive (fires earlier, x0.5). Thresholds adapt to the reasoning effort: 8000 at max / 12000 at high / 20000 at low.',
116
+ 'sensitivity.conservative': 'Conservative (fewer interruptions)',
117
+ 'sensitivity.balanced': 'Balanced (default)',
118
+ 'sensitivity.aggressive': 'Aggressive (fires earlier)',
119
+ 'settings.guardEchoFailures': 'Identical-argument failures',
120
+ 'settings.guardEchoFailuresHint': 'Identical-argument failures of the same tool in a row that fire the echo ladder (default 3).',
43
121
  }
44
122
 
45
- /** One lever copy key. */
123
+ /** Every key in the locale catalog. */
46
124
  export type LiangShenKey = keyof typeof zh
@@ -0,0 +1,43 @@
1
+ // Generated by scripts/sync-shared.mjs from shared/client/main-session.ts. Do not edit this copy; edit the shared source and run "node scripts/sync-shared.mjs".
2
+ /**
3
+ * Main-view Session derivation for the multi-instance Client Session model.
4
+ *
5
+ * The Client Session Controller carries no global "current" selection: view
6
+ * selection belongs to the workspace UI, which owns the main-area reference and
7
+ * publishes it through the catalog's per-source ownership counts
8
+ * (`SessionSummary.retainedBy.mainView`). A plugin that needs the Session the
9
+ * main view shows derives it from that marker instead of the removed
10
+ * `SessionListState.current` field.
11
+ *
12
+ * The marker describes view ownership, not authority. It is the right input for
13
+ * presentation and for deciding which view a navigation targets; it is not a
14
+ * business fallback, because source counts never imply visibility or success.
15
+ * @module dsh-web/shared/main-session
16
+ */
17
+
18
+ /** The catalog row subset this helper reads (a `SessionSummary` projection). */
19
+ export interface MainViewOwnedRow<Id extends string = string> {
20
+ /** Catalog row identity. */
21
+ readonly id: Id
22
+ /** Per-source local ownership counts; absent rows are never owned. */
23
+ readonly retainedBy?: Readonly<Partial<Record<string, number>>> | undefined
24
+ }
25
+
26
+ /**
27
+ * Resolve the Session the main view currently shows.
28
+ *
29
+ * Reads the catalog's rows rather than a per-id retain-info source: ownership
30
+ * counts ride the list snapshot, so this neither allocates observers nor opens
31
+ * history, and a subscription to the list still fires when the selection moves.
32
+ * @param byId - the session catalog's rows (`SessionListState.byId`), when available.
33
+ * @returns the main-view session id, or undefined when the main view shows none.
34
+ */
35
+ export function mainViewSessionId<Id extends string>(
36
+ byId: Readonly<Record<Id, MainViewOwnedRow<Id> | undefined>> | undefined | null,
37
+ ): Id | undefined {
38
+ if (byId === undefined || byId === null) return undefined
39
+ for (const row of Object.values<MainViewOwnedRow<Id> | undefined>(byId)) {
40
+ if (row !== undefined && (row.retainedBy?.mainView ?? 0) > 0) return row.id
41
+ }
42
+ return undefined
43
+ }
@@ -0,0 +1,192 @@
1
+ // Generated by scripts/sync-shared.mjs from shared/client/settings/plugin-card-seat.ts. Do not edit this copy; edit the shared source and run "node scripts/sync-shared.mjs".
2
+ /**
3
+ * Family plugin-card seat.
4
+ *
5
+ * A family plugin contributes its settings card to whichever plugin-card seat
6
+ * the running host actually renders:
7
+ *
8
+ * - `web-ui.plugin.item` — the list seat declared by the dsh-web-settings
9
+ * group section (this family's own first-level "Web UI plugins" section);
10
+ * - `plugins.bundle.config` — the official keyed seat of the harness's plugin
11
+ * manager page, keyed by the bundle's package name and rendered on that
12
+ * bundle's page. alpha.2 removed the `settings.plugin.item` keyed seat of the
13
+ * `ui-settings-plugins` tab that this helper used before, so a card keyed by
14
+ * its settings namespace has no seat to land in any more.
15
+ *
16
+ * SEAT SELECTION IS NOT A DECLARATION PROBE. The official plugin surface
17
+ * belongs to the harness bundle and declares its seats before any external
18
+ * plugin's `apply()` runs, so "is the official seat declared?" answers yes even
19
+ * in the deployment whose whole point is the family group. Choosing on that
20
+ * probe sends every family card to the official page and leaves the group's own
21
+ * section permanently empty — the family of reports where the section renders
22
+ * its heading and zero cards.
23
+ *
24
+ * The signal that actually distinguishes the two deployments is whether
25
+ * dsh-web-settings is loaded: it is the package that owns the group section and
26
+ * it publishes the `webUiSettings` service during `apply()`, which every
27
+ * family plugin already reads for its settings form. Group loaded -> the family
28
+ * seat; group absent -> the official seat.
29
+ *
30
+ * The decision is re-evaluated on every `slots/changed` because the group may
31
+ * apply after this plugin (the family aggregate orders it first, a profile that
32
+ * installs the group separately need not): the initial contribution goes to the
33
+ * official seat, then moves to the family seat the moment the group's section
34
+ * registers. The entry is disposed before the replacement is registered, so a
35
+ * card is never in two seats at once.
36
+ *
37
+ * The shared tree has no client-SDK dependency, so this module reads its
38
+ * context through the structural shape below; callers pass the plugin's own
39
+ * `ctx`.
40
+ */
41
+
42
+ /** The family list seat key. */
43
+ export const FAMILY_PLUGIN_CARD_SEAT = 'web-ui.plugin.item'
44
+
45
+ /** The official keyed plugin-card seat key (the alpha.2 bundle-configuration seat). */
46
+ export const OFFICIAL_PLUGIN_CARD_SEAT = 'plugins.bundle.config'
47
+
48
+ /** The service dsh-web-settings publishes while it is loaded. */
49
+ export const FAMILY_GROUP_SERVICE = 'webUiSettings'
50
+
51
+ /** The slot-registry member this helper uses (structurally satisfied by ctx.slots). */
52
+ export interface PluginCardSlots {
53
+ /** Contribution of one card entry. */
54
+ register(options: never, component: never): unknown
55
+ }
56
+
57
+ /** The slice of the client context a card contribution needs. */
58
+ export interface PluginCardContext {
59
+ slots: PluginCardSlots
60
+ /** Service lookup; absent on a context double that only models the slots. */
61
+ get?(name: string): unknown
62
+ /** Event subscription seat; absent on an event-less test double. */
63
+ on?(event: string, listener: (...args: never[]) => void): unknown
64
+ }
65
+
66
+ /** Owner share of a family list-seat card (that seat supplies nothing). */
67
+ export interface SettingsPluginItemOwnerProps {
68
+ /** Marker field: card owner props are intentionally empty. */
69
+ children?: never
70
+ }
71
+
72
+ /** One family plugin's card contribution. */
73
+ export interface PluginCardSeat {
74
+ /**
75
+ * Npm package name of the bundle this card configures; the official keyed
76
+ * seat dispatches on it. Every family package ships its own bundle patch, so
77
+ * a standalone install lists that package as the bundle whose page renders
78
+ * this card.
79
+ */
80
+ bundle: string
81
+ /** Family list-seat entry id. */
82
+ id: string
83
+ /** Family list-seat sort order. */
84
+ order?: number
85
+ /** Family list-seat display label; the official keyed seat carries none. */
86
+ label?: () => string
87
+ /** Locale namespace the card renders with. */
88
+ locale: string
89
+ /** Business-face factory of the registration. */
90
+ inject?: () => object
91
+ /**
92
+ * The card component. Its props type is the seat's composed shape, which is
93
+ * chosen at runtime, so the helper takes it erased; the registrant keeps its
94
+ * own precise typing at the call site.
95
+ */
96
+ component: unknown
97
+ }
98
+
99
+ /**
100
+ * Whether the family group (dsh-web-settings) is loaded in this page. The
101
+ * service is the group package's own contract, so the probe cannot be fooled
102
+ * by a harness release that starts declaring the official seat differently.
103
+ */
104
+ export function familyGroupLoaded(ctx: PluginCardContext): boolean {
105
+ const get = ctx.get
106
+ if (typeof get !== 'function') return false
107
+ try {
108
+ return get.call(ctx, FAMILY_GROUP_SERVICE) !== undefined
109
+ } catch {
110
+ // A context that refuses the lookup: treat the group as absent, which
111
+ // falls back to the official seat the harness declares.
112
+ return false
113
+ }
114
+ }
115
+
116
+ /** Report a refused registration instead of leaving the user with no card. */
117
+ function warnRefusedSeat(seat: string, error: unknown): void {
118
+ try {
119
+ console.warn(`[dsh-web] plugin card registration into "${seat}" was refused; the card will not render`, error)
120
+ } catch {
121
+ // Best-effort console write; a failed warning must not break the plugin.
122
+ }
123
+ }
124
+
125
+ /**
126
+ * Contribute one family plugin card to the seat this host renders, following
127
+ * the group if it loads later. The entry is disposed and re-registered on a
128
+ * seat change, never duplicated.
129
+ * @param ctx - client context (its slot registry decides the seat).
130
+ * @param seat - the card contribution.
131
+ */
132
+ export function installPluginCard(ctx: PluginCardContext, seat: PluginCardSeat): void {
133
+ const slots = ctx.slots
134
+ const component = seat.component as never
135
+ const inject = seat.inject as never
136
+
137
+ let dispose: (() => void) | undefined
138
+ let current: string | undefined
139
+ /**
140
+ * Re-entrancy latch. The registry emits a change event synchronously from
141
+ * inside both `register` and the previous entry's disposer, so an unguarded
142
+ * reconcile would re-enter itself mid-move and register the card twice into
143
+ * the seat it is leaving ("already has an entry for key ...").
144
+ */
145
+ let reconciling = false
146
+
147
+ /** Reconcile the contribution with the currently live seat (no-op when unchanged). */
148
+ const reconcile = (): void => {
149
+ if (reconciling) return
150
+ const target = familyGroupLoaded(ctx) ? FAMILY_PLUGIN_CARD_SEAT : OFFICIAL_PLUGIN_CARD_SEAT
151
+ if (current === target) return
152
+ reconciling = true
153
+ const previous = dispose
154
+ dispose = undefined
155
+ current = undefined
156
+ previous?.()
157
+ try {
158
+ dispose = slots.register((target === FAMILY_PLUGIN_CARD_SEAT
159
+ ? {
160
+ name: FAMILY_PLUGIN_CARD_SEAT,
161
+ id: seat.id,
162
+ ...(seat.order === undefined ? {} : { order: seat.order }),
163
+ ...(seat.label === undefined ? {} : { label: seat.label }),
164
+ locale: seat.locale,
165
+ ...(seat.inject === undefined ? {} : { inject }),
166
+ }
167
+ : {
168
+ name: OFFICIAL_PLUGIN_CARD_SEAT,
169
+ key: seat.bundle,
170
+ locale: seat.locale,
171
+ ...(seat.inject === undefined ? {} : { inject }),
172
+ }) as never, component) as () => void
173
+ current = target
174
+ } catch (error) {
175
+ warnRefusedSeat(target, error)
176
+ } finally {
177
+ reconciling = false
178
+ }
179
+ }
180
+
181
+ if (typeof ctx.on === 'function') {
182
+ try {
183
+ ctx.on('slots/changed', () => { reconcile() })
184
+ } catch {
185
+ // An event seat that refuses the subscription leaves the initial
186
+ // decision in place; the card still renders in the seat chosen below.
187
+ }
188
+ }
189
+ // The initial decision: the group, when it is already loaded (the aggregate
190
+ // order), otherwise the official seat the harness declares.
191
+ reconcile()
192
+ }