@linxin666/dsh-liangshen 0.3.24 → 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 (52) hide show
  1. package/README.i18n.yaml +2 -2
  2. package/README.md +24 -17
  3. package/README.zh.md +25 -18
  4. package/cordis.patch.yml +3 -2
  5. package/icon.svg +3 -0
  6. package/lib/client.js +381 -77
  7. package/lib/client.js.map +1 -1
  8. package/lib/index.js +594 -428
  9. package/lib/types/announce.test.d.ts +10 -0
  10. package/lib/types/client/LiangShenSettingsCard.d.ts +27 -10
  11. package/lib/types/client/PluginSettingsCard.d.ts +4 -0
  12. package/lib/types/client/index.d.ts +32 -13
  13. package/lib/types/client/lever-controller.d.ts +16 -2
  14. package/lib/types/client/locales.d.ts +13 -0
  15. package/lib/types/client/main-session.d.ts +32 -0
  16. package/lib/types/client/plugin-card-seat.d.ts +23 -16
  17. package/lib/types/client/settings-form.d.ts +17 -17
  18. package/lib/types/composition.d.ts +116 -0
  19. package/lib/types/composition.test.d.ts +7 -0
  20. package/lib/types/index.d.ts +146 -31
  21. package/lib/types/index.test.d.ts +5 -0
  22. package/package.json +25 -20
  23. package/presets/liangshen/agent.cordis.yml +44 -10
  24. package/presets/liangshen/fact-ledger.mjs +141 -0
  25. package/presets/liangshen/guard.mjs +426 -0
  26. package/presets/liangshen/minimal-prompt.mjs +2 -2
  27. package/presets/liangshen/tool-catalog.mjs +24 -20
  28. package/presets/liangshen/working-context.mjs +10 -2
  29. package/src/announce.test.ts +248 -55
  30. package/src/client/LiangShenLever.module.css +2 -0
  31. package/src/client/LiangShenLever.tsx +37 -9
  32. package/src/client/LiangShenSettingsCard.tsx +96 -12
  33. package/src/client/PluginSettingsCard.tsx +7 -2
  34. package/src/client/index.ts +61 -23
  35. package/src/client/lever-controller.ts +76 -9
  36. package/src/client/locales.ts +30 -4
  37. package/src/client/main-session.ts +43 -0
  38. package/src/client/plugin-card-seat.ts +24 -17
  39. package/src/client/settings-form.ts +34 -31
  40. package/src/composition.test.ts +294 -0
  41. package/src/composition.ts +554 -0
  42. package/src/index.test.ts +68 -1
  43. package/src/index.ts +278 -107
  44. package/tools/benchmark-live-run.mjs +171 -32
  45. package/lib/types/schema.d.ts +0 -18
  46. package/lib/types/schema.test.d.ts +0 -1
  47. package/lib/types/sync.d.ts +0 -74
  48. package/lib/types/sync.test.d.ts +0 -1
  49. package/src/schema.test.ts +0 -64
  50. package/src/schema.ts +0 -110
  51. package/src/sync.test.ts +0 -303
  52. package/src/sync.ts +0 -324
package/src/index.ts CHANGED
@@ -1,21 +1,29 @@
1
1
  /**
2
2
  * dsh-liangshen — LiangShen (梁神) agent preset plugin.
3
3
  *
4
- * Host half only: on startup it syncs the bundled `presets/` tree into the
5
- * harness-home agent-presets root (`~/.dsh/.agent-presets`), making the
6
- * LiangShen preset selectable for new sessions without copying files by hand.
7
- * The capability announcement is a system-prompt section that ships OFF by
8
- * default (`announceToAgent: false`) and can be enabled in the web settings
9
- * surface (plugin config) or the profile patch. No browser half, no routes,
10
- * no agent tools — the preset itself provides the tools.
4
+ * Host half only: at activation it DECLARES the bundled LiangShen agent preset
5
+ * to the harness's agent-preset registry (`ctx.agentPresets`), reading the
6
+ * composition rows of `presets/liangshen/agent.cordis.yml` and handing the
7
+ * registry a definition whose relative module paths resolve inside the bundled
8
+ * preset directory. Declare = enabled: the registry mounts the preset's rows
9
+ * eagerly and hands back a disposer this plugin owns, so disabling the plugin
10
+ * (or the row unloading) unmounts them, and nothing is written to the harness
11
+ * home. The registration is released in `ctx.effect`; the plugin's own Config
12
+ * is the settings page the Host generates for this profile entry, and a
13
+ * settings write re-declares the preset with the new values instead of
14
+ * remounting the row. The capability announcement is a system-prompt section
15
+ * that ships OFF by default (`announceToAgent: false`) and can be enabled in
16
+ * the web settings surface (plugin config) or the profile patch. No browser
17
+ * routes, no agent tools — the preset itself provides the tools.
11
18
  *
12
19
  * The preset combines a minimal persona with a lifetime-declared tool
13
20
  * presentation: the system prompt keeps a minimal persona with standing
14
21
  * working discipline and workspace instructions, and the wire runs the SDK's
15
- * 'ptc' presentation by default — the wire collapses to the `run_code`
16
- * transport and every other tool is reached through the generated SDK,
17
- * declared once per session instead of staged across a turn boundary
18
- * ('native' and 'both' are one-line opt-outs). High-fan-out tool families
22
+ * 'both' presentation by default — the assembled native roster stays on the
23
+ * wire for ordinary work and the `run_code` transport sits co-resident for
24
+ * programmatic batch computation and wide fan-out, declared once per session
25
+ * instead of staged across a turn boundary ('native' and 'ptc' are one-line
26
+ * opt-outs). High-fan-out tool families
19
27
  * (default `mcp__*`) stay paged out of the executed surface through the
20
28
  * host's scoped tool restriction until the preset's own `tool_activate` tool
21
29
  * loads their namespace (LRU cap three), with the activation state replayed
@@ -25,22 +33,29 @@
25
33
  * republished only on change.
26
34
  */
27
35
 
28
- import { mkdirSync } from 'node:fs'
29
- import { join } from 'node:path'
30
36
  import { fileURLToPath } from 'node:url'
31
- import type { Context } from '@deepseek-ai/cordis'
37
+ import type { Context, Volatile } from '@deepseek-ai/cordis'
38
+ import type { AgentPresetRegistry, PresetDefinition } from '@deepseek-ai/dsh-agent-preset-registry'
39
+ // Type-only: pulls the `ctx.agentPresets` Context merge and the registry types.
40
+ import type {} from '@deepseek-ai/dsh-agent-preset-registry'
32
41
  import type { SettingsNamespace } from '@deepseek-ai/dsh-settings'
33
42
  import type {} from '@deepseek-ai/dsh-system-prompt'
34
- import z from 'schemastery'
35
- import { dshHome } from './dsh-home.ts'
36
- import { syncPresetTrees } from './sync.ts'
43
+ import z from '@deepseek-ai/schemastery'
44
+ import { applyPresetOverrides, readPresetDefinition } from './composition.ts'
45
+ import { LIANGSHEN_PRESET_ID } from './core/lever.ts'
37
46
  import { mountOnce } from './mount-once.ts'
38
47
 
39
48
  /** Stable cordis plugin name. */
40
49
  export const name = 'liangshen'
41
50
 
42
- /** Settings namespace of the plugin (the web settings surface edits it). */
43
- export const LIANGSHEN_SETTINGS_NAMESPACE = 'dsh-liangshen' as SettingsNamespace
51
+ /**
52
+ * Settings namespace of the plugin. Under the 0.1.7 settings contract a
53
+ * plugin's own Config IS its settings page and the namespace IS the profile
54
+ * entry id, so this is the row id the standalone bundle patch inserts; the
55
+ * aggregate install names the generated `web-ui-liangshen` row and the family
56
+ * binder resolves between the two.
57
+ */
58
+ export const LIANGSHEN_SETTINGS_NAMESPACE = 'liangshen' as SettingsNamespace
44
59
 
45
60
  /** Prompt assembly must exist before the announcement section can register. */
46
61
  export const inject = ['systemPrompt']
@@ -48,131 +63,287 @@ export const inject = ['systemPrompt']
48
63
  /** The wire presentations the preset's tool catalog accepts. */
49
64
  export const PRESENTATION_OPTIONS = ['ptc', 'native', 'both'] as const
50
65
 
51
- /** Plugin config, validated by the same-named schemastery schema. */
66
+ /** Sensitivity presets for the circuit breaker's adaptive thresholds. */
67
+ export const SENSITIVITY_OPTIONS = ['conservative', 'balanced', 'aggressive'] as const
68
+
69
+ /** One wire presentation. */
70
+ export type Presentation = (typeof PRESENTATION_OPTIONS)[number]
71
+
72
+ /** One circuit-breaker sensitivity preset. */
73
+ export type GuardSensitivity = (typeof SENSITIVITY_OPTIONS)[number]
74
+
75
+ /**
76
+ * One activation field as the Host hands it over: a stable reference whose
77
+ * `get()` reads the value committed for this instance (a settings write updates
78
+ * it in place, without remounting the row), or the plain value a profile patch
79
+ * or a hand-built test context passes.
80
+ */
81
+ export type ConfigField<T> = Volatile<T> | T | undefined
82
+
83
+ /**
84
+ * Plugin config, validated by the same-named schemastery schema.
85
+ *
86
+ * Every field is `volatile()`: the Host serves exactly the volatile fields of a
87
+ * Config as this entry's settings form and refuses writes anywhere else, and a
88
+ * volatile write is committed into the references this activation holds instead
89
+ * of remounting the row.
90
+ */
52
91
  export interface Config {
53
- /** Master switch: when false, neither sync nor announcement runs. */
54
- enabled?: boolean
92
+ /** Master switch: when false, neither the preset declaration nor the announcement runs. */
93
+ enabled?: ConfigField<boolean>
55
94
  /** When true, a system-prompt section announces the plugin (default false — keep prompts clean unless the user opts in). */
56
- announceToAgent?: boolean
95
+ announceToAgent?: ConfigField<boolean>
96
+ /**
97
+ * Wire presentation written into the declared preset's tool-catalog row.
98
+ * `both` (default) keeps the assembled roster and the `run_code` transport
99
+ * co-resident; `native` keeps only the roster; `ptc` collapses the wire to
100
+ * the transport.
101
+ */
102
+ presentation?: ConfigField<Presentation>
103
+ /** Master switch for the runtime degeneration circuit breaker (default true). */
104
+ guardEnabled?: ConfigField<boolean>
105
+ /**
106
+ * Sensitivity preset scaling the breaker's adaptive thresholds
107
+ * (default 'balanced'). 'conservative' interrupts less, 'aggressive' fires earlier.
108
+ */
109
+ guardSensitivity?: ConfigField<GuardSensitivity>
110
+ /**
111
+ * Reasoning characters one zero-output step must reach for the per-step
112
+ * ladder to fire (default 8000, calibrated against V4.1's 384K max output).
113
+ */
114
+ guardStallReasoningChars?: ConfigField<number>
57
115
  /**
58
- * Wire presentation written into the synced preset's tool-catalog row.
59
- * `ptc` (default) collapses the wire to the `run_code` transport; `native`
60
- * keeps the assembled roster; `both` keeps the roster and the transport.
116
+ * Consecutive output-free reasoning steps that trip the slow-burn ladder
117
+ * (default 4).
61
118
  */
62
- presentation?: (typeof PRESENTATION_OPTIONS)[number]
119
+ guardGlobalStallCap?: ConfigField<number>
120
+ /** Identical-argument tool failures in a row that trip the echo ladder (default 3). */
121
+ guardEchoFailures?: ConfigField<number>
63
122
  }
64
123
 
65
- export const Config: z<Config> = z.object({
66
- enabled: z.boolean().default(true),
67
- announceToAgent: z.boolean().default(false),
68
- presentation: z.union([...PRESENTATION_OPTIONS]).default('ptc'),
124
+ export const Config = z.object({
125
+ enabled: z.boolean().default(true).volatile(),
126
+ announceToAgent: z.boolean().default(false).volatile(),
127
+ presentation: z.union([...PRESENTATION_OPTIONS]).default('both').volatile(),
128
+ guardEnabled: z.boolean().default(true).volatile(),
129
+ guardSensitivity: z.union([...SENSITIVITY_OPTIONS]).default('balanced').volatile(),
130
+ guardStallReasoningChars: z.number().default(8000).volatile(),
131
+ guardGlobalStallCap: z.number().default(4).volatile(),
132
+ guardEchoFailures: z.number().default(3).volatile(),
69
133
  })
70
134
 
135
+ /** The settings the runtime acts on, every field read at its use site. */
136
+ export interface ResolvedConfig {
137
+ /** Whether the preset is declared at all. */
138
+ enabled: boolean
139
+ /** Whether the announcement section registers. */
140
+ announceToAgent: boolean
141
+ /** Wire presentation the declared preset's tool-catalog row carries. */
142
+ presentation: Presentation
143
+ /** Breaker master switch written into the declared preset's guard row. */
144
+ guardEnabled: boolean
145
+ /** Breaker sensitivity written into the declared preset's guard row. */
146
+ guardSensitivity: GuardSensitivity
147
+ /** Per-step reasoning-character floor written into the guard row. */
148
+ guardStallReasoningChars: number
149
+ /** Slow-burn step cap written into the guard row. */
150
+ guardGlobalStallCap: number
151
+ /** Echo-ladder failure count written into the guard row. */
152
+ guardEchoFailures: number
153
+ }
154
+
71
155
  /** Schema defaults, re-read for hand-built test contexts. */
72
- const DEFAULT_ANNOUNCE = false
73
- const DEFAULT_PRESENTATION = 'ptc'
156
+ export const DEFAULT_CONFIG: ResolvedConfig = {
157
+ enabled: true,
158
+ announceToAgent: false,
159
+ presentation: 'both',
160
+ guardEnabled: true,
161
+ guardSensitivity: 'balanced',
162
+ guardStallReasoningChars: 8000,
163
+ guardGlobalStallCap: 4,
164
+ guardEchoFailures: 3,
165
+ }
166
+
167
+ /**
168
+ * Read one activation field. The Host validates the raw profile config and
169
+ * hands volatile fields over as references, so a read goes through `get()`; a
170
+ * plain value passes through, and an absent field falls back to the schema
171
+ * default.
172
+ */
173
+ function readField<T>(field: ConfigField<T>, fallback: T): T {
174
+ if (field === undefined || field === null) return fallback
175
+ const ref = field as { get?: () => T | undefined }
176
+ const value = typeof ref.get === 'function' ? ref.get() : field as T
177
+ return value === undefined ? fallback : value
178
+ }
179
+
180
+ /**
181
+ * Read the effective settings of this activation.
182
+ * @param config - the config the Host passed to the activation.
183
+ * @returns every field resolved against the schema defaults.
184
+ */
185
+ export function resolveConfig(config?: Config): ResolvedConfig {
186
+ return {
187
+ enabled: readField(config?.enabled, DEFAULT_CONFIG.enabled),
188
+ announceToAgent: readField(config?.announceToAgent, DEFAULT_CONFIG.announceToAgent),
189
+ presentation: readField(config?.presentation, DEFAULT_CONFIG.presentation),
190
+ guardEnabled: readField(config?.guardEnabled, DEFAULT_CONFIG.guardEnabled),
191
+ guardSensitivity: readField(config?.guardSensitivity, DEFAULT_CONFIG.guardSensitivity),
192
+ guardStallReasoningChars: readField(config?.guardStallReasoningChars, DEFAULT_CONFIG.guardStallReasoningChars),
193
+ guardGlobalStallCap: readField(config?.guardGlobalStallCap, DEFAULT_CONFIG.guardGlobalStallCap),
194
+ guardEchoFailures: readField(config?.guardEchoFailures, DEFAULT_CONFIG.guardEchoFailures),
195
+ }
196
+ }
197
+
198
+ /** Model-facing announcement: plugin presence, principle, and limits. */
199
+ export const LIANGSHEN_GUIDANCE = '本机已安装 dsh-liangshen 插件(梁神模式 agent preset):新建会话的预设选择器中可选「梁神模式」。原理:系统提示词保持极简 persona(minimal-prompt 放行该段与 plan 模式的 plan:policy),persona 内置本模式工作纪律(反思熔断——同一假设推演不超过两轮、缺事实立即闭合思考并调用原生检测工具;行动导向——思考只决定下一步具体操作、不在思考中预演代码实现;并发探索——多处独立检查或搜索在单轮内并发发射多个工具调用;YAGNI/PDCA——单步验证单一假设、不写冗余注释;有界收敛——不无限下钻依赖链、前置检查最多2-3轮后立即收敛并作答或编辑),并在组装时追加工作区目录行 Your working directory is <cwd>.。AGENTS.md 工作区指令默认交还宿主自身的 agent-instructions 行,以 user 角色注入,本插件不追加任何系统提示词段、也不改动 pre-step 的消息批次;可选 instructionSource: system-prompt 才由本插件在组装时读取 AGENTS.md 链并追加 workspace-instructions 段(65536 字节预算,每次组装重读)。wire 呈现由 tool-catalog 按会话一次声明,取值 \'both\'(默认:原生清单与 run_code 同驻,原生直调优先、run_code 用于程序化批处理与并发扇出)、\'native\'(组装出的原生清单)或 \'ptc\'(wire 收拢为唯一的 run_code),并可在插件设置界面切换(写入所声明预设的 tool-catalog 行);未挂载 code runtime 时不做声明,会话运行原生工具面。温和工具分页出厂开启(pagedToolPatterns 默认 [\'mcp__*\']):匹配工具在激活前被作用域级工具限制移出可见面(既不在 wire,也不在生成的 SDK 声明中),目录消息列出常驻工具签名与未激活命名空间摘要,调用 tool_activate({ namespace }) 按需激活(LRU 上限 3 个活跃命名空间,驱逐最久未用);激活状态从持久会话事件流重建,resume/压缩后自然恢复。运行时退化熔断器(guard)从事件流折叠停摆(连续零产出长思考)与空转(同参重复失败)信号,每 episode 触发一次:注入熔断消息并把推理档位临时下调一档(max→high→low,窗口 3 个请求);无信号时从不改写请求。关键事实登记簿(fact_register)让模型把硬约束/已确认决策/失败路径登记为单行事实,随 working-context 行每步投射进局部注意力窗口。working-context 插件在 pre-step 注入单行 [Working Context: ...] 就近状态投射(plan 模式、活跃命名空间、进行中 todo、登记事实,全部从事件流折叠,读不到则省略,全部为空则不注入)。历史工具结果修剪为 4096 字符阈值(head 2048 / tail 1024)。文件操作受宿主沙箱约束;shell 在每个平台都挂上游标准 Stdio 栈(POSIX 为 bash,Windows 为 pwsh),带简短描述标题卡片与确定性退出码。真实推理探针通过不等于模式集成通过,更不等于统计效果提升。预设由插件在激活时向 agent-preset registry 直接注册(不写任何预设目录),插件停用即注销;默认预设由用户自行选择。用户提到「梁神模式 / 锚定模式 / anchored standard」时即指本插件,请据此协作。'
74
200
 
75
201
  /** Order of the announcement section within the tool-guidance band. */
76
202
  const SECTION_ORDER = 150
77
203
 
78
- /** Model-facing announcement: plugin presence, principle, and limits. */
79
- export const LIANGSHEN_GUIDANCE = '本机已安装 dsh-liangshen 插件(梁神模式 agent preset):新建会话的预设选择器中可选「梁神模式」。原理:系统提示词保持极简 persona(minimal-prompt 放行该段与 plan 模式的 plan:policy),persona 内置本模式工作纪律(反思熔断——同一假设推演不超过两轮、缺事实立即闭合思考并调用原生检测工具;行动导向——思考只决定下一步具体操作、不在思考中预演代码实现;并发探索——多处独立检查或搜索在单轮内并发发射多个工具调用;YAGNI/PDCA——单步验证单一假设、不写冗余注释),并在组装时追加工作区目录行 Your working directory is <cwd>.。AGENTS.md 工作区指令默认交还宿主自身的 agent-instructions 行,以 user 角色注入,本插件不追加任何系统提示词段、也不改动 pre-step 的消息批次;可选 instructionSource: system-prompt 才由本插件在组装时读取 AGENTS.md 链并追加 workspace-instructions 段(65536 字节预算,每次组装重读)。wire 呈现由 tool-catalog 按会话一次声明,取值 \'ptc\'(默认:wire 收拢为唯一的 run_code,其余工具经生成的 SDK 触达)、\'native\'(组装出的原生清单)或 \'both\'(两者同驻),并可在插件设置界面切换(同步 preset 时写入 tool-catalog 行);未挂载 code runtime 时不做声明,会话运行原生工具面。温和工具分页:匹配 pagedToolPatterns(默认 mcp__*)的工具在激活前被作用域级工具限制移出可见面(既不在 wire,也不在生成的 SDK 声明中),目录消息列出常驻工具签名与未激活命名空间摘要,调用 tool_activate({ namespace }) 按需激活(LRU 上限 3 个活跃命名空间,驱逐最久未用);激活状态从持久会话事件流重建,resume/压缩后自然恢复。working-context 插件在 pre-step 注入单行 [Working Context: ...] 就近状态投射(plan 模式、活跃命名空间、进行中 todo 标题,全部从事件流折叠,读不到则省略,全部为空则不注入)。历史工具结果修剪为 4096 字符阈值(head 1500 / tail 500)。文件操作受宿主沙箱约束;shell 在每个平台都挂上游标准 Stdio 栈(POSIX 为 bash,Windows 为 pwsh),带简短描述标题卡片与确定性退出码。真实推理探针通过不等于模式集成通过,更不等于统计效果提升。preset 文件由插件维护于 ~/.dsh/.agent-presets,升级插件时自动更新;默认预设由用户自行选择。用户提到「梁神模式 / 锚定模式 / anchored standard」时即指本插件,请据此协作。'
80
- // The harness-home resolution (DSH_HOME override with the platform-home
81
- // fallback and ~ expansion) lives in the family-shared copy ./dsh-home.ts.
82
- // Re-export it so the plugin surface stays stable while the implementation is
83
- // shared across packages. A relative DSH_HOME resolves against the process CWD
84
- // (absolute), which is the shared contract.
85
- export { dshHome } from './dsh-home.ts'
86
-
87
- /** Absolute path of the bundled preset tree inside this package. */
88
- export function bundledPresetsRoot(): string {
89
- return fileURLToPath(new URL('../presets/', import.meta.url))
204
+ /**
205
+ * Absolute path of the bundled LiangShen preset directory: the composition,
206
+ * the display map, and the preset-local `.mjs` plugins this plugin declares.
207
+ * @returns the preset directory as a filesystem path.
208
+ */
209
+ export function bundledPresetDir(): string {
210
+ // Resolved from this module's own URL rather than the process CWD, so the
211
+ // declaration works whatever directory the host was started in.
212
+ return fileURLToPath(new URL('../presets/liangshen/', import.meta.url))
213
+ }
214
+
215
+ /**
216
+ * Build the registry declaration of the bundled preset with the settings
217
+ * currently committed applied to the rows they shape.
218
+ * @param values - the activation's effective settings.
219
+ * @returns the definition to submit to `ctx.agentPresets.register`.
220
+ */
221
+ function declaration(values: ResolvedConfig): PresetDefinition {
222
+ const definition = readPresetDefinition(LIANGSHEN_PRESET_ID, bundledPresetDir())
223
+ return { ...definition, plugins: applyPresetOverrides(definition.plugins, values) }
90
224
  }
91
225
 
92
226
  /**
93
- * Mount the plugin: sync bundled presets into the harness-home agent-presets
94
- * root, register the settings namespace (enabled / announceToAgent, live),
95
- * and announce through a system-prompt section when announceToAgent is on
96
- * (off by default).
227
+ * Mount the plugin: declare the bundled preset, register the announcement
228
+ * section when announceToAgent is on (off by default), and re-declare on every
229
+ * committed settings write.
97
230
  * @param ctx - host plugin context carrying systemPrompt.
98
231
  * @param config - resolved plugin config (schema defaults applied by the loader).
99
232
  */
100
233
  export const apply = mountOnce('@linxin666/dsh-liangshen', applyImpl)
101
234
 
102
235
  function applyImpl(ctx: Context, config?: Config): void {
103
- // The live source the announcement reads: the settings section once the web
104
- // settings surface is served, the composition entry otherwise
105
- // (installSection swaps it when the namespace registers).
106
- let current: () => Config = () => config ?? {}
107
- const resolve = (): Config => ({
108
- announceToAgent: current().announceToAgent ?? DEFAULT_ANNOUNCE,
109
- enabled: current().enabled ?? true,
110
- presentation: current().presentation ?? DEFAULT_PRESENTATION,
111
- })
112
-
113
- const sync = (): void => {
114
- const targetRoot = join(dshHome(), '.agent-presets')
236
+ /** The live registry, or undefined on a deployment that composes none. */
237
+ const registryOf = (): AgentPresetRegistry | undefined => {
115
238
  try {
116
- mkdirSync(targetRoot, { recursive: true })
117
- const settings = resolve()
118
- // The settings surface edits this plugin's namespace, while the values that
119
- // shape a session live in the preset's rows; the sync is where the two meet.
120
- const result = syncPresetTrees(bundledPresetsRoot(), targetRoot, ['liangshen-exact'], {
121
- presentation: settings.presentation,
122
- })
123
- for (const { id, error } of result.failed) {
124
- ctx.logger?.warn?.(`dsh-liangshen: preset ${id} sync failed: ${error}`)
125
- }
126
- if (result.synced.length > 0) {
127
- ctx.logger?.info?.(`dsh-liangshen: presets synced into ${targetRoot}: ${result.synced.join(', ')}`)
128
- }
129
- if (result.retired.length > 0) {
130
- ctx.logger?.info?.(`dsh-liangshen: retired stale presets from ${targetRoot}: ${result.retired.join(', ')}`)
131
- }
239
+ return ctx.get('agentPresets')
240
+ } catch {
241
+ return undefined
242
+ }
243
+ }
244
+
245
+ /** Disposer of the live declaration; the declaring plugin owns it. */
246
+ let release: (() => Promise<void>) | undefined
247
+ /** Declaration generation: a re-arm supersedes the one it replaced. */
248
+ let generation = 0
249
+ /** Set once the owning fiber unloads: a late re-arm must not declare again. */
250
+ let closed = false
251
+ /** Serializes declaration work, so a settings write cannot interleave with an in-flight activation. */
252
+ let queue: Promise<void> = Promise.resolve()
253
+
254
+ const warn = (message: string): void => { ctx.logger?.warn?.(`dsh-liangshen: ${message}`) }
255
+
256
+ /** Release the live declaration, waiting for the registry to unmount its rows. */
257
+ const undeclare = async (): Promise<void> => {
258
+ const dispose = release
259
+ release = undefined
260
+ if (dispose === undefined) return
261
+ try {
262
+ await dispose()
132
263
  } catch (error) {
133
- ctx.logger?.warn?.(`dsh-liangshen: preset sync failed: ${error instanceof Error ? error.message : String(error)}`)
264
+ // A registry already gone is not this plugin's failure.
265
+ warn(`releasing the preset declaration failed: ${error instanceof Error ? error.message : String(error)}`)
134
266
  }
135
267
  }
136
268
 
269
+ /**
270
+ * Declare the preset with the settings committed right now. Queued behind any
271
+ * in-flight activation and skipped when a newer re-arm superseded it, so a
272
+ * burst of settings writes settles on the last one.
273
+ */
274
+ const declare = (): void => {
275
+ const target = ++generation
276
+ queue = queue.then(async () => {
277
+ if (closed || target !== generation) return
278
+ await undeclare()
279
+ const values = resolveConfig(config)
280
+ if (!values.enabled) return
281
+ const registry = registryOf()
282
+ if (registry === undefined) {
283
+ warn('the agent-preset registry is unavailable; the preset is not declared')
284
+ return
285
+ }
286
+ try {
287
+ release = await registry.register(declaration(values))
288
+ ctx.logger?.info?.(`liangshen: preset ${LIANGSHEN_PRESET_ID} declared`)
289
+ } catch (error) {
290
+ warn(`declaring the preset failed: ${error instanceof Error ? error.message : String(error)}`)
291
+ }
292
+ }).catch((error: unknown) => {
293
+ warn(`preset declaration failed: ${error instanceof Error ? error.message : String(error)}`)
294
+ })
295
+ }
296
+
297
+ /** The live announcement section, replaced on every re-arm. */
137
298
  let disposeSection: (() => void) | undefined
138
- const refresh = (): void => {
299
+
300
+ /**
301
+ * Apply the committed settings: swap the announcement section and re-declare
302
+ * the preset. This is the edge the pre-0.1.7 settings `setSource`/`onChange`
303
+ * hooks ran on, from the settings write that the Loader now commits into this
304
+ * row's volatile references instead of remounting it.
305
+ */
306
+ const rearm = (): void => {
139
307
  disposeSection?.()
140
308
  disposeSection = undefined
141
- if (!resolve().enabled) return
142
- sync()
143
- if (resolve().announceToAgent) {
309
+ const values = resolveConfig(config)
310
+ if (values.enabled && values.announceToAgent) {
144
311
  disposeSection = ctx.systemPrompt.section({
145
312
  name: 'plugin:dsh-liangshen',
146
313
  order: SECTION_ORDER,
147
314
  text: LIANGSHEN_GUIDANCE,
148
315
  })
149
316
  }
317
+ declare()
150
318
  }
151
319
 
152
- // The web settings surface gets the plugin's enabled / announceToAgent
153
- // fields from this namespace; a settings edit re-runs refresh live, and
154
- // deployments without a settings service keep the composition entry.
155
- ctx.inject(['settings'], (settingsCtx) => {
156
- try {
157
- if (typeof settingsCtx.settings?.installSection === 'function') {
158
- settingsCtx.settings.installSection(ctx, LIANGSHEN_SETTINGS_NAMESPACE, Config, config ?? {}, {
159
- setSource: (source) => {
160
- current = source
161
- refresh()
162
- },
163
- onChange: refresh,
164
- })
165
- } else if (typeof settingsCtx.settings?.register === 'function') {
166
- const scope = settingsCtx.settings.register(LIANGSHEN_SETTINGS_NAMESPACE, Config, { base: config ?? {} })
167
- current = () => scope?.get?.() ?? (config ?? {})
168
- scope?.watch?.(() => { refresh() })
169
- refresh()
170
- }
171
- } catch {
172
- // Defensive fallback against settings registration differences
320
+ ctx.on('loader/volatile-update', () => { rearm() })
321
+
322
+ ctx.effect(() => {
323
+ rearm()
324
+ return async () => {
325
+ disposeSection?.()
326
+ disposeSection = undefined
327
+ // Stop any re-arm that arrives while this row is unloading, then wait for
328
+ // the declaration work already queued and release what it declared.
329
+ closed = true
330
+ generation += 1
331
+ await queue
332
+ await undeclare()
173
333
  }
174
- })
334
+ }, 'dsh-liangshen: preset declaration and announcement')
335
+ }
175
336
 
176
- refresh()
177
- ctx.effect(() => () => { disposeSection?.(); disposeSection = undefined }, 'dsh-liangshen: announcement')
178
- }
337
+ declare module '@deepseek-ai/cordis' {
338
+ interface Events {
339
+ /**
340
+ * Volatile config values were committed into the running fiber without a
341
+ * remount; dispatched to the owning fiber only. Spelled here because the
342
+ * Loader package is not a dependency of this plugin, with the Loader's own
343
+ * shape so the two declarations merge when a Host program carries both.
344
+ * @param paths - changed config paths as key arrays; every value is committed before dispatch.
345
+ * @mode emit
346
+ */
347
+ 'loader/volatile-update'(paths: readonly (readonly string[])[]): void
348
+ }
349
+ }