@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
package/src/index.ts CHANGED
@@ -1,157 +1,349 @@
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
- * The preset combines a minimal persona with a staged, promoted tool surface:
13
- * the system prompt keeps a minimal persona with standing working discipline
14
- * and workspace instructions, the session's entire first user turn runs a native
15
- * foundational tool surface ([bash, str_replace_editor, exit_plan_mode, skill],
16
- * with bash-only preserved as a configuration experiment), and from the second
17
- * turn this session presents its tools in PTC mode upon successful activation,
18
- * so the wire carries the single `run_code` transport while the generated SDK
19
- * bindings and collapse rule travel in the tool list injected as a durable
20
- * message after the user's message, preserving full input and output key
21
- * parameter semantics.
19
+ * The preset combines a minimal persona with a lifetime-declared tool
20
+ * presentation: the system prompt keeps a minimal persona with standing
21
+ * working discipline and workspace instructions, and the wire runs the SDK's
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
27
+ * (default `mcp__*`) stay paged out of the executed surface through the
28
+ * host's scoped tool restriction until the preset's own `tool_activate` tool
29
+ * loads their namespace (LRU cap three), with the activation state replayed
30
+ * from the durable session event stream. The tool catalog — listing exactly
31
+ * the tools the request carries plus the paged-out namespace summaries — and a
32
+ * one-line working-context projection travel as durable user messages,
33
+ * republished only on change.
22
34
  */
23
35
 
24
- import { mkdirSync } from 'node:fs'
25
- import { join } from 'node:path'
26
36
  import { fileURLToPath } from 'node:url'
27
- 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'
28
41
  import type { SettingsNamespace } from '@deepseek-ai/dsh-settings'
29
42
  import type {} from '@deepseek-ai/dsh-system-prompt'
30
- import z from 'schemastery'
31
- import { dshHome } from './dsh-home.ts'
32
- 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'
33
46
  import { mountOnce } from './mount-once.ts'
34
47
 
35
48
  /** Stable cordis plugin name. */
36
49
  export const name = 'liangshen'
37
50
 
38
- /** Settings namespace of the plugin (the web settings surface edits it). */
39
- 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
40
59
 
41
60
  /** Prompt assembly must exist before the announcement section can register. */
42
61
  export const inject = ['systemPrompt']
43
62
 
44
- /** Plugin config, validated by the same-named schemastery schema. */
63
+ /** The wire presentations the preset's tool catalog accepts. */
64
+ export const PRESENTATION_OPTIONS = ['ptc', 'native', 'both'] as const
65
+
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
+ */
45
91
  export interface Config {
46
- /** Master switch: when false, neither sync nor announcement runs. */
47
- enabled?: boolean
92
+ /** Master switch: when false, neither the preset declaration nor the announcement runs. */
93
+ enabled?: ConfigField<boolean>
48
94
  /** When true, a system-prompt section announces the plugin (default false — keep prompts clean unless the user opts in). */
49
- 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>
115
+ /**
116
+ * Consecutive output-free reasoning steps that trip the slow-burn ladder
117
+ * (default 4).
118
+ */
119
+ guardGlobalStallCap?: ConfigField<number>
120
+ /** Identical-argument tool failures in a row that trip the echo ladder (default 3). */
121
+ guardEchoFailures?: ConfigField<number>
50
122
  }
51
123
 
52
- export const Config: z<Config> = z.object({
53
- enabled: z.boolean().default(true),
54
- announceToAgent: z.boolean().default(false),
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(),
55
133
  })
56
134
 
57
- /** Schema default, re-read for hand-built test contexts. */
58
- const DEFAULT_ANNOUNCE = false
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
+
155
+ /** Schema defaults, re-read for hand-built test contexts. */
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」时即指本插件,请据此协作。'
59
200
 
60
201
  /** Order of the announcement section within the tool-guidance band. */
61
202
  const SECTION_ORDER = 150
62
203
 
63
- /** Model-facing announcement: plugin presence, principle, and limits. */
64
- export const LIANGSHEN_GUIDANCE = '本机已安装 dsh-liangshen 插件(梁神模式 agent preset):新建会话的预设选择器中可选「梁神模式」。原理:系统提示词保持极简 persona(minimal-prompt 放行该段与 plan 模式的 plan:policy),persona 内置本模式工作纪律(思维循环即断、先理解需求与方案再实现验证、YAGNI/PDCA、代码不加冗余注释),并在组装时追加工作区目录 Your working directory is <cwd>. 与 AGENTS.md 工作区指令(workspace-instructions 段,65536 字节预算,每次组装重读);工具清单由 tool-catalog 从第一条用户消息起以 user 消息注入在用户消息之后,形如 skill catalog,仅当工具集变化或该消息离开可见面(压缩、恢复)时重发;wire 上的 schema 按回合分层:首轮整个 user turn 原生呈现基础锚定工具集(默认 [bash, str_replace_editor, exit_plan_mode, skill],且保留 bash-only 配置实验),第二个回合起在 PTC 成功激活后切换为 PTC 呈现(wire 上只有 run_code,其余工具在程序里以 await tools.<name>({...}) 调用,保留完整输入输出关键参数语义而非 200 字唯一契约;缺失 code runtime 时优雅回退至原生呈现);注入消息承载 SDK 绑定、程序契约(一段程序编排多步:独立只读调用用 Promise.all 并发、ToolCallError 处理、输出自选)与「激活后只有 run_code 可直接调用」的规则。工作区子目录动态指令支持注册文件工具含 str_replace_editor 及 PTC 内子调用触达的目录(不解析任意 bash/program 代码)。文件操作受宿主沙箱约束,Windows 下 bash 为 Git Bash 子进程且状态不跨调用保留。真实推理探针通过不等于模式集成通过,更不等于统计效果提升。preset 文件由插件维护于 ~/.dsh/.agent-presets,升级插件时自动更新;默认预设由用户自行选择。用户提到「梁神模式 / 锚定模式 / anchored standard」时即指本插件,请据此协作。'
65
- // The harness-home resolution (DSH_HOME override with the platform-home
66
- // fallback and ~ expansion) lives in the family-shared copy ./dsh-home.ts.
67
- // Re-export it so the plugin surface stays stable while the implementation is
68
- // shared across packages. A relative DSH_HOME resolves against the process CWD
69
- // (absolute), which is the shared contract.
70
- export { dshHome } from './dsh-home.ts'
71
-
72
- /** Absolute path of the bundled preset tree inside this package. */
73
- export function bundledPresetsRoot(): string {
74
- 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))
75
213
  }
76
214
 
77
215
  /**
78
- * Mount the plugin: sync bundled presets into the harness-home agent-presets
79
- * root, register the settings namespace (enabled / announceToAgent, live),
80
- * and announce through a system-prompt section when announceToAgent is on
81
- * (off by default).
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) }
224
+ }
225
+
226
+ /**
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.
82
230
  * @param ctx - host plugin context carrying systemPrompt.
83
231
  * @param config - resolved plugin config (schema defaults applied by the loader).
84
232
  */
85
233
  export const apply = mountOnce('@linxin666/dsh-liangshen', applyImpl)
86
234
 
87
235
  function applyImpl(ctx: Context, config?: Config): void {
88
- // The live source the announcement reads: the settings section once the web
89
- // settings surface is served, the composition entry otherwise
90
- // (installSection swaps it when the namespace registers).
91
- let current: () => Config = () => config ?? {}
92
- const resolve = (): Config => ({
93
- announceToAgent: current().announceToAgent ?? DEFAULT_ANNOUNCE,
94
- enabled: current().enabled ?? true,
95
- })
96
-
97
- const sync = (): void => {
98
- const targetRoot = join(dshHome(), '.agent-presets')
236
+ /** The live registry, or undefined on a deployment that composes none. */
237
+ const registryOf = (): AgentPresetRegistry | undefined => {
99
238
  try {
100
- mkdirSync(targetRoot, { recursive: true })
101
- const result = syncPresetTrees(bundledPresetsRoot(), targetRoot, ['liangshen-exact'])
102
- for (const { id, error } of result.failed) {
103
- ctx.logger?.warn?.(`dsh-liangshen: preset ${id} sync failed: ${error}`)
104
- }
105
- if (result.synced.length > 0) {
106
- ctx.logger?.info?.(`dsh-liangshen: presets synced into ${targetRoot}: ${result.synced.join(', ')}`)
107
- }
108
- if (result.retired.length > 0) {
109
- ctx.logger?.info?.(`dsh-liangshen: retired stale presets from ${targetRoot}: ${result.retired.join(', ')}`)
110
- }
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()
111
263
  } catch (error) {
112
- 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)}`)
113
266
  }
114
267
  }
115
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. */
116
298
  let disposeSection: (() => void) | undefined
117
- 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 => {
118
307
  disposeSection?.()
119
308
  disposeSection = undefined
120
- if (!resolve().enabled) return
121
- sync()
122
- if (resolve().announceToAgent) {
309
+ const values = resolveConfig(config)
310
+ if (values.enabled && values.announceToAgent) {
123
311
  disposeSection = ctx.systemPrompt.section({
124
312
  name: 'plugin:dsh-liangshen',
125
313
  order: SECTION_ORDER,
126
314
  text: LIANGSHEN_GUIDANCE,
127
315
  })
128
316
  }
317
+ declare()
129
318
  }
130
319
 
131
- // The web settings surface gets the plugin's enabled / announceToAgent
132
- // fields from this namespace; a settings edit re-runs refresh live, and
133
- // deployments without a settings service keep the composition entry.
134
- ctx.inject(['settings'], (settingsCtx) => {
135
- try {
136
- if (typeof settingsCtx.settings?.installSection === 'function') {
137
- settingsCtx.settings.installSection(ctx, LIANGSHEN_SETTINGS_NAMESPACE, Config, config ?? {}, {
138
- setSource: (source) => {
139
- current = source
140
- refresh()
141
- },
142
- onChange: refresh,
143
- })
144
- } else if (typeof settingsCtx.settings?.register === 'function') {
145
- const scope = settingsCtx.settings.register(LIANGSHEN_SETTINGS_NAMESPACE, Config, { base: config ?? {} })
146
- current = () => scope?.get?.() ?? (config ?? {})
147
- scope?.watch?.(() => { refresh() })
148
- refresh()
149
- }
150
- } catch {
151
- // 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()
152
333
  }
153
- })
334
+ }, 'dsh-liangshen: preset declaration and announcement')
335
+ }
154
336
 
155
- refresh()
156
- ctx.effect(() => () => { disposeSection?.(); disposeSection = undefined }, 'dsh-liangshen: announcement')
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
+ }
157
349
  }