dsh-extra-plan 0.0.0-stage → 1.7.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 (56) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +179 -2
  3. package/assets/presets/extra-plan/agent.cordis.yml +580 -0
  4. package/assets/presets/extra-plan/preset-definition-extra-plan-executor.generated.yml +115 -0
  5. package/assets/presets/extra-plan/preset-definition-extra-plan-planner.generated.yml +113 -0
  6. package/assets/presets/extra-plan/preset-definition-extra-plan-prober.generated.yml +107 -0
  7. package/assets/presets/extra-plan/preset-definition-extra-plan-reviewer.generated.yml +115 -0
  8. package/assets/presets/extra-plan/preset-definition.generated.yml +335 -0
  9. package/assets/presets/extra-plan/preset.yml +2 -0
  10. package/cordis.patch.yml +7 -0
  11. package/index.js +1671 -0
  12. package/lib/agent-runtime.js +172 -0
  13. package/lib/agent-session.js +65 -0
  14. package/lib/assembly-presentation.js +267 -0
  15. package/lib/client-carrier.js +7 -0
  16. package/lib/client.js +314 -0
  17. package/lib/extra-plan-gate-tool.js +387 -0
  18. package/lib/gate-decisions.js +744 -0
  19. package/lib/gate-words.js +108 -0
  20. package/lib/live-config.js +293 -0
  21. package/lib/log-retention.js +132 -0
  22. package/lib/model-routing.js +648 -0
  23. package/lib/path-policy.js +464 -0
  24. package/lib/plan-draft-tool.js +294 -0
  25. package/lib/planner-budget.js +136 -0
  26. package/lib/preset-defaults.generated.js +17 -0
  27. package/lib/preset-settings.js +3 -0
  28. package/lib/preset-sync.js +809 -0
  29. package/lib/preset-yaml.js +438 -0
  30. package/lib/role-contract.js +11 -0
  31. package/lib/run-code-scanner.js +360 -0
  32. package/lib/run-code-static.js +621 -0
  33. package/lib/runtime-diagnostics.js +89 -0
  34. package/lib/runtime-lifecycle.js +162 -0
  35. package/lib/runtime-static.js +23 -0
  36. package/lib/save-contract.js +263 -0
  37. package/lib/save-persistence.js +223 -0
  38. package/lib/save-plan-markdown-parser.js +369 -0
  39. package/lib/save-plan-validation-diagnostics.js +49 -0
  40. package/lib/save-plan-validation.js +812 -0
  41. package/lib/save-probe-validation.js +173 -0
  42. package/lib/save-source-verification.js +195 -0
  43. package/lib/save-tool-factories.js +270 -0
  44. package/lib/sdk-text-cache.js +161 -0
  45. package/lib/settings-contract.js +191 -0
  46. package/lib/settings.js +369 -0
  47. package/lib/shell-mutation.js +484 -0
  48. package/lib/usage-ledger-background.js +214 -0
  49. package/lib/usage-ledger-worker.js +116 -0
  50. package/lib/usage-ledger.js +1393 -0
  51. package/locale/en.json +6 -0
  52. package/locale/settings/en.json +6 -0
  53. package/locale/settings/zh.json +6 -0
  54. package/locale/zh.json +6 -0
  55. package/package.json +56 -4
  56. package/scripts/generate-runtime-defaults.mjs +796 -0
@@ -0,0 +1,809 @@
1
+ // 预设核对组件:读取生成 definition,直接挂载官方 AgentPreset adapter。
2
+ // 当前规范配置唯一来源为 settings 行(id=dsh-extra-plan-settings,name=dsh-extra-plan/settings);普通缺项只取新默认。
3
+ // gateWords 与普通项同口径:属性缺失或显式对象非法都回落当前资产默认并写入补齐,旧键随整组写盘删除;资产本身坏才严格抛错。
4
+ // 历史配置 ID 不读取、不迁移、不回退;profile 写入仍一律经 configEditor.edit。
5
+ // definition 的 group/isolate/!!js 原文交给官方 adapter,不能提前求值或复制 registry。
6
+
7
+ import { createHash } from 'node:crypto'
8
+ import { existsSync, readFileSync } from 'node:fs'
9
+ import { join, dirname, isAbsolute } from 'node:path'
10
+ import { fileURLToPath } from 'node:url'
11
+ import { createRequire } from 'node:module'
12
+ import { createPathContext, resolveHostPath, resolveWorkspacePath, validateReadTarget } from './path-policy.js'
13
+ import {
14
+ HOST_ROW_IDS,
15
+ HOST_ROW_LEAF_KEYS,
16
+ PROJECTION_SETTING_DEFINITIONS,
17
+ SETTINGS_ROW_ID,
18
+ SETTING_DEFINITIONS,
19
+ createDefaultSettings,
20
+ findPluginsRow,
21
+ normalizeSettingValue,
22
+ validateSettingValue,
23
+ } from './preset-settings.js'
24
+ import {
25
+ GATE_WORDS_GROUP_DEFINITION,
26
+ validateGateWords,
27
+ } from './gate-words.js'
28
+ import { parsePresetYaml, resolveSetting, EXECUTOR_TOOL_NAME_PREFIX } from './preset-settings.js'
29
+ import { ROLE_IDS } from './role-contract.js'
30
+
31
+ const officialAgentPresetByAnchor = new Map()
32
+ function errorWithCause(message, cause) {
33
+ const error = new Error(message)
34
+ error.cause = cause
35
+ return error
36
+ }
37
+
38
+ function assertInstallAnchor(installAnchor) {
39
+ if (typeof installAnchor !== 'string' || installAnchor.trim() === '' || !isAbsolute(installAnchor) || installAnchor.split(/[\\/]/).pop() !== 'package.json') {
40
+ throw new Error('extra-plan: installAnchor 必须是绝对 dsh 应用 package.json 文件')
41
+ }
42
+ if (!existsSync(installAnchor)) throw new Error('extra-plan: installAnchor 不存在:' + installAnchor)
43
+ let manifest
44
+ try {
45
+ manifest = JSON.parse(readFileSync(installAnchor, 'utf8'))
46
+ } catch (cause) {
47
+ throw errorWithCause('extra-plan: installAnchor manifest 无法读取:' + installAnchor, cause)
48
+ }
49
+ if (manifest === null || typeof manifest !== 'object' || manifest.name !== '@deepseek-ai/dsh') {
50
+ throw new Error('extra-plan: installAnchor 不是 @deepseek-ai/dsh 应用 package.json:' + installAnchor)
51
+ }
52
+ return installAnchor
53
+ }
54
+
55
+ function loadOfficialAgentPreset(installAnchor) {
56
+ const cached = officialAgentPresetByAnchor.get(installAnchor)
57
+ if (cached !== undefined) return cached
58
+ try {
59
+ const anchor = assertInstallAnchor(installAnchor)
60
+ const officialRequire = createRequire(anchor)
61
+ const loaded = officialRequire('@deepseek-ai/dsh-agent-preset')
62
+ const adapter = loaded !== null && typeof loaded === 'object' && loaded.default !== undefined ? loaded.default : loaded
63
+ if (adapter === null || adapter === undefined) throw new Error('@deepseek-ai/dsh-agent-preset 导出为空')
64
+ officialAgentPresetByAnchor.set(anchor, adapter)
65
+ return adapter
66
+ } catch (cause) {
67
+ throw errorWithCause('extra-plan: @deepseek-ai/dsh-agent-preset 官方 adapter 不可用(installAnchor=' + String(installAnchor) + ')', cause)
68
+ }
69
+ }
70
+
71
+ const PRESET_ID = 'extra-plan'
72
+ export const CORE_FILES = ['preset.yml', 'agent.cordis.yml']
73
+ /** 生成 definition 顶层的 17 条 agent plugin 行。 */
74
+
75
+
76
+ const HERE = dirname(fileURLToPath(import.meta.url))
77
+ export const ASSET_DIR = join(HERE, '..', 'assets', 'presets', PRESET_ID)
78
+ export const ASSET_DEFINITION_FILE = join(ASSET_DIR, 'preset-definition.generated.yml')
79
+ /** 角色预设固定顺序(order 101..104),与生成器 ROLE_IDS 同源同序:主在前、角色在后。 */
80
+ export { ROLE_IDS }
81
+ export const ROLE_DEFINITION_FILES = Object.freeze(ROLE_IDS.map((roleId) => join(ASSET_DIR, 'preset-definition-' + roleId + '.generated.yml')))
82
+ /** 角色 definition 里固定前两行:dsh-persona 与 dsh-extra-plan。 */
83
+ export const ROLE_DEFINITION_LEADING_ROW_IDS = Object.freeze(['persona', 'extra-plan'])
84
+
85
+ const ASSET_CAPABILITY = 'dsh-extra-plan-assets'
86
+ const ASSET_RESOURCE_CONTEXT = createPathContext({
87
+ hostCapabilities: [{
88
+ name: ASSET_CAPABILITY,
89
+ path: ASSET_DIR,
90
+ type: 'directory',
91
+ access: 'read',
92
+ purpose: ASSET_CAPABILITY,
93
+ }],
94
+ })
95
+
96
+ function assetReadTarget(filePath) {
97
+ const candidate = resolveHostPath(ASSET_RESOURCE_CONTEXT, filePath, {
98
+ capability: ASSET_CAPABILITY,
99
+ purpose: ASSET_CAPABILITY,
100
+ })
101
+ return validateReadTarget(ASSET_RESOURCE_CONTEXT, candidate, { expectedType: 'file' }).path
102
+ }
103
+
104
+ function readAssetBytes(filePath, label) {
105
+ try {
106
+ return readFileSync(assetReadTarget(filePath))
107
+ } catch (error) {
108
+ if (error !== null && typeof error === 'object' && error.code === 'TARGET_MISSING') {
109
+ throw new Error(label + ' 缺失:' + filePath)
110
+ }
111
+ throw error
112
+ }
113
+ }
114
+
115
+ function resourceReadTarget(filePath, options = {}) {
116
+ const context = options.pathContext
117
+ if (context === undefined || context === null) throw new Error('extra-plan: 自定义资源读取缺少 pathContext')
118
+ const kind = options.kind
119
+ const pathOptions = {
120
+ ...(options.capability === undefined ? {} : { capability: options.capability }),
121
+ purpose: options.purpose === undefined ? 'preset-resource' : options.purpose,
122
+ }
123
+ const candidate = kind === 'host'
124
+ ? resolveHostPath(context, filePath, pathOptions)
125
+ : kind === 'workspace'
126
+ ? resolveWorkspacePath(context, filePath, pathOptions)
127
+ : (() => { throw new Error('extra-plan: 自定义资源 kind 必须为 workspace 或 host') })()
128
+ return validateReadTarget(context, candidate, { expectedType: 'file' }).path
129
+ }
130
+
131
+ function readResourceBytes(filePath, options = {}) {
132
+ try {
133
+ return readFileSync(resourceReadTarget(filePath, options))
134
+ } catch (error) {
135
+ if (error !== null && typeof error === 'object' && error.code === 'TARGET_MISSING') return null
136
+ throw error
137
+ }
138
+ }
139
+
140
+ export function contentHash(dir, options = {}) {
141
+ const h = createHash('sha256')
142
+ for (const file of CORE_FILES) {
143
+ const filePath = join(dir, file)
144
+ const bytes = dir === ASSET_DIR && options.pathContext === undefined && options.kind === undefined
145
+ ? (() => {
146
+ try { return readFileSync(assetReadTarget(filePath)) }
147
+ catch (error) {
148
+ if (error !== null && typeof error === 'object' && error.code === 'TARGET_MISSING') return null
149
+ throw error
150
+ }
151
+ })()
152
+ : readResourceBytes(filePath, options)
153
+ if (bytes === null) return null
154
+ h.update(bytes)
155
+ }
156
+ return h.digest('hex')
157
+ }
158
+
159
+ /** 单一深度优先遍历来源:按当前数组顺序展开 group.config 子行。 */
160
+ export function pluginRows(plugins) {
161
+ const rows = []
162
+ const visit = (items) => {
163
+ if (!Array.isArray(items)) return
164
+ for (const row of items) {
165
+ if (row === null || typeof row !== 'object' || Array.isArray(row)) continue
166
+ rows.push(row)
167
+ if (Array.isArray(row.config)) visit(row.config)
168
+ }
169
+ }
170
+ visit(plugins)
171
+ return rows
172
+ }
173
+
174
+ export function pluginRowIds(plugins) {
175
+ return pluginRows(plugins).filter((row) => typeof row.id === 'string' && row.id !== '').map((row) => row.id)
176
+ }
177
+
178
+
179
+
180
+ function plainObject(value) {
181
+ return value !== null && typeof value === 'object' && !Array.isArray(value)
182
+ }
183
+
184
+
185
+
186
+
187
+
188
+
189
+
190
+
191
+
192
+
193
+
194
+ export function effectiveRowConfig(row) {
195
+ if (row === null || typeof row !== 'object') return null
196
+ const layers = []
197
+ if (plainObject(row.inherited)) layers.push(row.inherited)
198
+ const own = row.entry !== undefined && row.entry.options !== undefined ? row.entry.options.config : undefined
199
+ if (plainObject(own)) layers.push(own)
200
+ if (plainObject(row.override)) {
201
+ if (plainObject(row.override.config)) layers.push(row.override.config)
202
+ else layers.push(row.override)
203
+ }
204
+ return layers.length === 0 ? null : Object.assign({}, ...layers)
205
+ }
206
+
207
+
208
+
209
+
210
+ function validDefinitionValue(definition, value) {
211
+ return validateSettingValue(definition, value)
212
+ }
213
+
214
+
215
+
216
+
217
+
218
+
219
+
220
+
221
+
222
+ /**
223
+ * 统一解析当前 settings 行;缺失或非法普通项只取新默认。
224
+ * gateWords 与普通项同口径:整个属性缺失或显式对象非法都回落当前资产默认(agent.cordis.yml 当前值),
225
+ * 并写入 patch 补齐——非法对象被整组替换,旧键随本次写盘删除。
226
+ * 资产自身损坏(缺 gateWords 行/资产值非法)仍由 assetDefinition/readDefinitionGateWords 严格抛错,不吞代码缺陷。
227
+ */
228
+ export function resolveUnifiedConfig(options = {}) {
229
+ const input = options !== null && typeof options === 'object' ? options : {}
230
+ const defaults = createDefaultSettings()
231
+ const authority = plainObject(input.settingsValues) ? input.settingsValues : {}
232
+ const authorityHasGateWords = Object.prototype.hasOwnProperty.call(authority, 'gateWords')
233
+ const diagnostics = []
234
+ let capturedGateWords
235
+ if (authorityHasGateWords) {
236
+ try { capturedGateWords = validateGateWords(authority.gateWords) }
237
+ catch (error) { diagnostics.push('gateWords-invalid-fallback-default:' + String(error && error.message || error)) }
238
+ }
239
+ const values = {}
240
+ const sources = {}
241
+ const patch = {}
242
+ for (const definition of SETTING_DEFINITIONS) {
243
+ const key = definition.key
244
+ const captured = validDefinitionValue(definition, authority[key])
245
+ if (captured) {
246
+ values[key] = normalizeSettingValue(definition, authority[key])
247
+ sources[key] = 'settings-row'
248
+ } else {
249
+ values[key] = defaults[key]
250
+ sources[key] = 'default'
251
+ patch[key] = values[key]
252
+ }
253
+ }
254
+ const gateWords = capturedGateWords === undefined
255
+ ? readDefinitionGateWords(assetDefinition())
256
+ : capturedGateWords
257
+ sources.gateWords = capturedGateWords === undefined ? 'default' : 'settings-row'
258
+ if (capturedGateWords === undefined) patch.gateWords = gateWords
259
+ return { values, defaults, sources, patch, gateWords, authority, diagnostics }
260
+ }
261
+
262
+ export function restateSettingsConfig(current, inherited, patch = {}, localConfig) {
263
+ const currentConfig = publicConfigOf(current)
264
+ const inheritedConfig = publicConfigOf(inherited)
265
+ const source = { ...inheritedConfig, ...currentConfig }
266
+ // 纯重述调用可传已知本地配置为首参;持久化调用必须显式区分 Loader 与本地覆写。
267
+ const own = localConfig === undefined ? currentConfig : localConfig
268
+ const hasGatePatch = Object.prototype.hasOwnProperty.call(patch, 'gateWords')
269
+ const validatedPatch = {}
270
+ for (const [key, value] of Object.entries(patch)) {
271
+ if (key === 'gateWords') validatedPatch.gateWords = validateGateWords(value)
272
+ else {
273
+ const definition = SETTING_DEFINITIONS.find((item) => item.key === key)
274
+ if (definition === undefined || !validDefinitionValue(definition, value)) throw new Error('非法全局配置:' + key)
275
+ validatedPatch[key] = normalizeSettingValue(definition, value)
276
+ }
277
+ }
278
+ // 只保留当前行自有的非管理字段;继承层陌生字段不物化到 override。
279
+ const next = Object.fromEntries(Object.entries(own).filter(([key]) =>
280
+ key !== 'gateWords' && !SETTING_DEFINITIONS.some((definition) => definition.key === key),
281
+ ))
282
+ for (const definition of SETTING_DEFINITIONS) {
283
+ const key = definition.key
284
+ if (validDefinitionValue(definition, source[key])) next[key] = normalizeSettingValue(definition, source[key])
285
+ }
286
+ if (hasGatePatch) next.gateWords = validatedPatch.gateWords
287
+ else if (Object.prototype.hasOwnProperty.call(source, 'gateWords')) {
288
+ // 与 resolveUnifiedConfig 同口径:持久值非法时回落当前资产默认,旧键随本次整组重述删除;
289
+ // 资产自身损坏仍抛错(代码缺陷不静默)。
290
+ try { next.gateWords = validateGateWords(source.gateWords) }
291
+ catch { next.gateWords = readDefinitionGateWords(assetDefinition()) }
292
+ }
293
+ for (const [key, value] of Object.entries(validatedPatch)) {
294
+ if (key !== 'gateWords') next[key] = value
295
+ }
296
+ return next
297
+ }
298
+
299
+ function assertPresetDefinition(definition, label = 'preset definition') {
300
+ if (!plainObject(definition)) throw new Error(label + ' 必须是对象')
301
+ if (definition.id !== PRESET_ID) throw new Error(label + ' id 必须为 ' + PRESET_ID)
302
+ if (typeof definition.name !== 'string' || definition.name === '') throw new Error(label + ' name 非法')
303
+ if (typeof definition.description !== 'string' || definition.description === '') throw new Error(label + ' description 非法')
304
+ if (!Number.isInteger(definition.order)) throw new Error(label + ' order 非法')
305
+ if (!Array.isArray(definition.plugins) || definition.plugins.length !== 17) throw new Error(label + ' plugins 顶层必须为 17 条')
306
+ if (definition.plugins.some((row) => !plainObject(row) || row.insert !== undefined)) throw new Error(label + ' 不得包含 Loader insert wrapper')
307
+ const groups = definition.plugins.filter((row) => row.group === true)
308
+ if (groups.length !== 3) throw new Error(label + ' 必须包含三个 group')
309
+ for (const group of groups) {
310
+ if (!plainObject(group.isolate) || Object.values(group.isolate).some((value) => value !== true)) throw new Error(label + ' isolate 必须全部为 true')
311
+ }
312
+ return definition
313
+ }
314
+
315
+ export function parsePresetDefinition(text) {
316
+ return assertPresetDefinition(parsePresetYaml(text))
317
+ }
318
+
319
+ // 资产构建期生成、运行期不可变;缓存对象视为只读,所有变异方均先 structuredClone。
320
+ let cachedAsset = null
321
+
322
+ export function assetDefinition() {
323
+ if (cachedAsset !== null) return cachedAsset
324
+ const parsed = parsePresetDefinition(readAssetBytes(ASSET_DEFINITION_FILE, '预设 definition').toString('utf8'))
325
+ cachedAsset = parsed
326
+ return cachedAsset
327
+ }
328
+
329
+ /** 角色 definition 校验:不套用主预设的 17 条/三组契约,只固定 id/name/description/order 与前两行。 */
330
+ function assertRoleDefinition(definition, roleId, label) {
331
+ if (!plainObject(definition)) throw new Error(label + ' 必须是对象')
332
+ if (definition.id !== roleId) throw new Error(label + ' id 必须为 ' + roleId)
333
+ if (typeof definition.name !== 'string' || definition.name === '') throw new Error(label + ' name 非法')
334
+ if (typeof definition.description !== 'string' || definition.description === '') throw new Error(label + ' description 非法')
335
+ if (!Number.isInteger(definition.order)) throw new Error(label + ' order 非法')
336
+ if (!Array.isArray(definition.plugins) || definition.plugins.length < 3) throw new Error(label + ' plugins 至少 3 行')
337
+ if (definition.plugins.some((row) => !plainObject(row) || row.insert !== undefined)) throw new Error(label + ' 不得包含 Loader insert wrapper')
338
+ const leading = definition.plugins.slice(0, 2).map((row) => row.id)
339
+ if (JSON.stringify(leading) !== JSON.stringify(ROLE_DEFINITION_LEADING_ROW_IDS)) throw new Error(label + ' 首两行必须为 persona 与 extra-plan')
340
+ if (definition.plugins[0].name !== '@deepseek-ai/dsh-persona' || definition.plugins[1].name !== 'dsh-extra-plan') throw new Error(label + ' 首两行 name 不符')
341
+ return definition
342
+ }
343
+
344
+ export function roleDefinitionOf(roleId) {
345
+ const index = ROLE_IDS.indexOf(roleId)
346
+ if (index === -1) throw new Error('未知角色预设:' + roleId)
347
+ const file = ROLE_DEFINITION_FILES[index]
348
+ return assertRoleDefinition(parsePresetYaml(readAssetBytes(file, '角色 definition').toString('utf8')), roleId, '角色 definition ' + roleId)
349
+ }
350
+
351
+ /** 注册顺序:主 definition 在前,4 个角色 definition 按 order 101..104 在后。 */
352
+ export function assetDefinitions() {
353
+ return [assetDefinition(), ...ROLE_IDS.map((roleId) => roleDefinitionOf(roleId))]
354
+ }
355
+
356
+ /**
357
+ * 四个角色 definition 跟随主 definition 的 toolPresentationMode:取值 = 主 definition
358
+ * (已由 cloneDefinitionWithProjection 按权威快照派生)plugins 内唯一一个 executor 行 id
359
+ * (tool-executor-native → native、tool-executor-ptc → ptc)——复用同一派生结果,不新增第二份配置读取;
360
+ * 落点与原语走 projectHostRow(与主 definition 同一条派生路径)。
361
+ * executor 行缺失/两行并存/克隆异常时原样返回生成物 definition(保留生成物默认值),永不抛错、不中断预设挂载。
362
+ */
363
+ export function roleDefinitionsWithPresentation(mainDefinition) {
364
+ const definitions = assetDefinitions().slice(1)
365
+ let mode
366
+ try {
367
+ const plugins = mainDefinition !== null && typeof mainDefinition === 'object' ? mainDefinition.plugins : undefined
368
+ const ids = pluginRowIds(plugins)
369
+ const nativeRows = ids.filter((id) => id === HOST_ROW_IDS.toolPresentationMode.native).length
370
+ const ptcRows = ids.filter((id) => id === HOST_ROW_IDS.toolPresentationMode.ptc).length
371
+ if (nativeRows + ptcRows !== 1) return definitions
372
+ mode = nativeRows === 1 ? 'native' : 'ptc'
373
+ } catch {
374
+ return definitions
375
+ }
376
+ return definitions.map((definition) => {
377
+ try {
378
+ const next = structuredClone(definition)
379
+ if (projectHostRow(next.plugins, 'toolPresentationMode', mode) !== 'ok') return definition
380
+ // 同一 definition 内绝不允许两个 executor 行并存(宿主判为矛盾并拒绝挂载):两行 id 合计不为 1 时保留生成物默认值。
381
+ if (pluginRowIds(next.plugins).filter((id) => id === HOST_ROW_IDS.toolPresentationMode.native || id === HOST_ROW_IDS.toolPresentationMode.ptc).length !== 1) return definition
382
+ return next
383
+ } catch {
384
+ return definition
385
+ }
386
+ })
387
+ }
388
+
389
+ export function readDefinitionGateWords(definition = assetDefinition()) {
390
+ const row = findPluginsRow(definition.plugins, GATE_WORDS_GROUP_DEFINITION.rowId)
391
+ if (row === null || !plainObject(row.config)) throw new Error('definition 缺少 gateWords 行')
392
+ return validateGateWords(row.config.gateWords)
393
+ }
394
+
395
+ /**
396
+ * 宿主行投影的单一实现:主 definition 与 4 个角色 definition 共用同一张定位表(HOST_ROW_IDS /
397
+ * HOST_ROW_LEAF_KEYS)与同一套校验/归一化原语(validateSettingValue / normalizeSettingValue)。
398
+ * toolPresentationMode 按 executor 行身份处理:按两个 executor 行 id 合计判定,恰一行时按目标 mode
399
+ * 改写该行 id/name 并删除其 config(executor 行无 config);投影集合当前只有该行身份项,不投影叶值
400
+ * (webFetch 已归 extra-plan 热读组,权威值在 settings 行、由运行期 restrict 生效)。
401
+ * 返回 'ok' = 已重述该值;'skipped' = 值非法或非投影键(调用方跳过);'missing' = 值合法但 definition
402
+ * 缺该行(executor 行 0 行或多行),或叶键投影路径下叶值键所在行无 config 对象(主 definition 视为
403
+ * 坏资产,角色 definition 保留生成物默认值)。
404
+ */
405
+ function projectHostRow(plugins, key, value) {
406
+ const setting = PROJECTION_SETTING_DEFINITIONS.find((item) => item.key === key)
407
+ if (setting === undefined || !validateSettingValue(setting, value)) return 'skipped'
408
+ if (key === 'toolPresentationMode') {
409
+ const nativeRow = findPluginsRow(plugins, HOST_ROW_IDS[key].native)
410
+ const ptcRow = findPluginsRow(plugins, HOST_ROW_IDS[key].ptc)
411
+ if ((nativeRow === null) === (ptcRow === null)) return 'missing'
412
+ const row = nativeRow !== null ? nativeRow : ptcRow
413
+ if (row.id === HOST_ROW_IDS[key][value]) return 'ok'
414
+ row.id = HOST_ROW_IDS[key][value]
415
+ row.name = EXECUTOR_TOOL_NAME_PREFIX + value
416
+ delete row.config
417
+ return 'ok'
418
+ }
419
+ // 当前投影集合只剩行身份项 toolPresentationMode,本叶键分支暂无消费者,保留为通用投影原语。
420
+ const row = findPluginsRow(plugins, HOST_ROW_IDS[key])
421
+ if (row === null || !plainObject(row.config)) return 'missing'
422
+ row.config[HOST_ROW_LEAF_KEYS[key]] = normalizeSettingValue(setting, value)
423
+ return 'ok'
424
+ }
425
+
426
+ function cloneDefinitionWithProjection(definition, projection = {}) {
427
+ const next = structuredClone(definition)
428
+ for (const [key, value] of Object.entries(projection)) {
429
+ if (key === 'gateWords') continue
430
+ if (projectHostRow(next.plugins, key, value) === 'missing') throw new Error('definition 缺少宿主行 ' + (key === 'toolPresentationMode' ? 'tool-executor-native/tool-executor-ptc' : HOST_ROW_IDS[key]))
431
+ }
432
+ if (projection.gateWords !== undefined && projection.gateWords !== null) {
433
+ const row = findPluginsRow(next.plugins, GATE_WORDS_GROUP_DEFINITION.rowId)
434
+ if (row === null || !plainObject(row.config)) throw new Error('definition 缺少 extra-plan gateWords 行')
435
+ row.config.gateWords = validateGateWords(projection.gateWords)
436
+ }
437
+ return next
438
+ }
439
+
440
+ export function definitionWithProjection(projection = {}) {
441
+ return cloneDefinitionWithProjection(assetDefinition(), projection)
442
+ }
443
+
444
+ function publicConfigOf(value) {
445
+ if (value !== null && typeof value === 'object' && value.entry !== undefined) return effectiveRowConfig(value) || {}
446
+ return plainObject(value) ? value : {}
447
+ }
448
+
449
+
450
+
451
+ function assertTemplateGateWords(text) {
452
+ const captured = resolveSetting(parsePresetYaml(text), GATE_WORDS_GROUP_DEFINITION, { aliases: false })
453
+ if (captured.kind !== 'ok') throw new Error('extra-plan: 厂商模板 gateWords ' + captured.kind)
454
+ return validateGateWords(captured.value)
455
+ }
456
+
457
+
458
+
459
+ /** 计算当前 settings 行补齐与官方 definition;不读取历史声明或原始 patch。 */
460
+ export async function syncPreset(options = {}) {
461
+ const templateFile = join(ASSET_DIR, 'agent.cordis.yml')
462
+ const templateText = readAssetBytes(templateFile, '预设模板').toString('utf8')
463
+ assertTemplateGateWords(templateText)
464
+ readAssetBytes(join(ASSET_DIR, 'preset.yml'), '预设资产')
465
+ const definition = assetDefinition()
466
+ const resolved = resolveUnifiedConfig({ settingsValues: options.settingsValues })
467
+ const settingsPatch = resolved.patch
468
+ if (Object.keys(settingsPatch).length === 0) {
469
+ // 不构造废弃投影,但仍拒绝与写回分支相同的缺失或冲突宿主行。
470
+ const { native, ptc } = HOST_ROW_IDS.toolPresentationMode
471
+ if ((findPluginsRow(definition.plugins, native) === null) === (findPluginsRow(definition.plugins, ptc) === null)) {
472
+ throw new Error('definition 缺少宿主行 tool-executor-native/tool-executor-ptc')
473
+ }
474
+ const gateRow = findPluginsRow(definition.plugins, GATE_WORDS_GROUP_DEFINITION.rowId)
475
+ if (gateRow === null || !plainObject(gateRow.config)) throw new Error('definition 缺少 extra-plan gateWords 行')
476
+ return { action: 'idle' }
477
+ }
478
+ const planned = {
479
+ settings: { values: settingsPatch, diagnostics: resolved.diagnostics },
480
+ definition: cloneDefinitionWithProjection(definition, {
481
+ toolPresentationMode: resolved.values.toolPresentationMode,
482
+ gateWords: resolved.gateWords,
483
+ }),
484
+ diagnostics: resolved.diagnostics,
485
+ }
486
+ if (typeof options.apply === 'function') await options.apply(planned, { action: 'written' })
487
+ return { action: 'written', plan: planned }
488
+ }
489
+
490
+ function findSettingsRow(rows) {
491
+ const matches = rows.filter((item) => item?.entry?.options?.id === SETTINGS_ROW_ID)
492
+ return matches.length === 1 && matches[0].entry.options.name === 'dsh-extra-plan/settings' ? matches[0] : undefined
493
+ }
494
+
495
+ export async function editSettingsConfig(editor, entry, patch) {
496
+ await editor.edit(entry, (current, inherited) => {
497
+ // 宿主已在写锁内重载。current 是 Loader 值;首次覆写时它可能全来自继承层。
498
+ const rows = editor.configuration()
499
+ const latest = Array.isArray(rows) ? findSettingsRow(rows) : undefined
500
+ const row = latest?.entry === entry ? latest : undefined
501
+ const own = row?.override
502
+ if (row === undefined || !plainObject(own) || row.disabled === true || entry.disabled === true || entry.options.disabled === true) {
503
+ throw new Error('无法确定唯一全局管理行的本地覆写:' + SETTINGS_ROW_ID)
504
+ }
505
+ return restateSettingsConfig(current, inherited, patch, own)
506
+ })
507
+ }
508
+
509
+ async function applyPlan(editor, rows, planned, isActive = () => true) {
510
+ if (planned.settings !== null) {
511
+ const entry = findSettingsRow(rows)?.entry
512
+ if (entry === undefined) throw new Error('全局管理行缺失:' + SETTINGS_ROW_ID)
513
+ if (!isActive()) return
514
+ await editSettingsConfig(editor, entry, planned.settings.values)
515
+ if (!isActive()) return
516
+ }
517
+ }
518
+
519
+ function trustedProfileContextOf(ctx) {
520
+ const direct = ctx !== null && typeof ctx === 'object' ? ctx.profileContext : undefined
521
+ if (direct !== undefined) return direct
522
+ if (ctx !== null && typeof ctx === 'object' && typeof ctx.get === 'function') {
523
+ try { return ctx.get('profileContext') } catch { return undefined }
524
+ }
525
+ return undefined
526
+ }
527
+
528
+
529
+
530
+ function settingsValuesFromRows(rows) {
531
+ const row = findSettingsRow(rows)
532
+ return row === undefined ? undefined : effectiveRowConfig(row)
533
+ }
534
+
535
+
536
+
537
+ /** 幂等落定路径的 definition:只按当前 settings 行值解析投影。 */
538
+ function projectedAssetDefinition(settingsValues) {
539
+ const resolved = resolveUnifiedConfig({ settingsValues })
540
+ return cloneDefinitionWithProjection(assetDefinition(), {
541
+ toolPresentationMode: resolved.values.toolPresentationMode,
542
+ gateWords: resolved.gateWords,
543
+ })
544
+ }
545
+
546
+ function structuralValue(value, seen = new Set()) {
547
+ if (value === null || typeof value !== 'object') return typeof value === 'function' ? '[function]' : value
548
+ if (seen.has(value)) return '[cycle]'
549
+ seen.add(value)
550
+ if (Array.isArray(value)) return value.map((item) => structuralValue(item, seen))
551
+ const out = {}
552
+ for (const key of Object.keys(value).sort()) {
553
+ if (key === 'fiber' || key === 'entry') continue
554
+ out[key] = structuralValue(value[key], seen)
555
+ }
556
+ return out
557
+ }
558
+
559
+ function rowStructureRecord(row) {
560
+ if (row === null || typeof row !== 'object' || Array.isArray(row)) return undefined
561
+ const entry = row.entry !== null && typeof row.entry === 'object' && row.entry.options !== null && typeof row.entry.options === 'object'
562
+ ? row.entry.options
563
+ : undefined
564
+ const id = entry !== undefined && typeof entry.id === 'string'
565
+ ? entry.id
566
+ : typeof row.id === 'string' ? row.id : row.override !== null && typeof row.override === 'object' && typeof row.override.id === 'string' ? row.override.id : ''
567
+ if (id === SETTINGS_ROW_ID) return undefined
568
+ const config = entry !== undefined && Object.prototype.hasOwnProperty.call(entry, 'config')
569
+ ? entry.config
570
+ : Object.prototype.hasOwnProperty.call(row, 'config') ? row.config : row.override !== null && typeof row.override === 'object' ? row.override.config : undefined
571
+ return {
572
+ id,
573
+ name: entry !== undefined && typeof entry.name === 'string' ? entry.name : typeof row.name === 'string' ? row.name : '',
574
+ disabled: row.disabled === true || (entry !== undefined && entry.disabled === true),
575
+ config: structuralValue(config),
576
+ override: structuralValue(row.override),
577
+ }
578
+ }
579
+
580
+ /** 非 settings 结构指纹:settings 行及其十一项/gateWords 永不参与 adapter handoff 判定。 */
581
+ export function structuralFingerprint(rows) {
582
+ const records = []
583
+ const visit = (items) => {
584
+ if (!Array.isArray(items)) return
585
+ for (const row of items) {
586
+ if (row === null || typeof row !== 'object' || Array.isArray(row)) continue
587
+ const record = rowStructureRecord(row)
588
+ if (record === undefined) continue
589
+ records.push(record)
590
+ const entry = row.entry !== null && typeof row.entry === 'object' && row.entry.options !== null && typeof row.entry.options === 'object'
591
+ ? row.entry.options
592
+ : undefined
593
+ const nested = entry !== undefined && Array.isArray(entry.config) ? entry.config : Array.isArray(row.config) ? row.config : undefined
594
+ if (nested !== undefined) visit(nested)
595
+ }
596
+ }
597
+ visit(rows)
598
+ return JSON.stringify({ rows: records })
599
+ }
600
+
601
+ function installAnchorOf(ctx, options) {
602
+ const profileContext = trustedProfileContextOf(ctx)
603
+ return profileContext !== undefined ? profileContext.installAnchor : options.installAnchor
604
+ }
605
+
606
+ export function mountPresetSync(ctx, options = {}) {
607
+ const child = ctx
608
+ const installAnchor = installAnchorOf(child, options)
609
+ const onSettledSettings = typeof options.onSettledSettings === 'function' ? options.onSettledSettings : undefined
610
+ const onSettledError = typeof options.onSettledError === 'function' ? options.onSettledError : undefined
611
+ const onAdapterError = typeof options.onAdapterError === 'function' ? options.onAdapterError : undefined
612
+ let active = true
613
+ let disposed = false
614
+ /** 已挂载的官方 adapter fiber(主 definition + 4 角色),按注册顺序保存以便整体回滚。 */
615
+ let adapterFibers = []
616
+ let adapterOwner = 'none'
617
+ let settledQueue = Promise.resolve()
618
+ let structuralQueue = Promise.resolve()
619
+ let lastStructureKey
620
+ const disposeFiber = async (fiber) => {
621
+ if (fiber !== undefined && fiber !== null && typeof fiber.dispose === 'function') return fiber.dispose()
622
+ return undefined
623
+ }
624
+ const reportSettledError = async (error, snapshot) => {
625
+ try {
626
+ if (onSettledError !== undefined) await onSettledError(error, snapshot)
627
+ else console.warn('[dsh-extra-plan] settled settings callback failed(不阻断 adapter):' + (error instanceof Error ? error.message : String(error)))
628
+ } catch (reportError) {
629
+ console.warn('[dsh-extra-plan] settled settings error reporter failed:' + (reportError instanceof Error ? reportError.message : String(reportError)))
630
+ }
631
+ }
632
+ const reportAdapterError = (error, phase) => {
633
+ const diagnostic = { phase, message: error instanceof Error ? error.message : String(error) }
634
+ try {
635
+ if (onAdapterError !== undefined) onAdapterError(diagnostic)
636
+ else console.warn('[dsh-extra-plan] adapter diagnostic phase=' + phase + ':' + diagnostic.message)
637
+ } catch (reportError) {
638
+ console.warn('[dsh-extra-plan] adapter diagnostic reporter failed:' + (reportError instanceof Error ? reportError.message : String(reportError)))
639
+ }
640
+ }
641
+ const readState = () => {
642
+ const editor = child.configEditor
643
+ const rows = typeof editor.configuration === 'function' ? editor.configuration() : []
644
+ return {
645
+ editor,
646
+ rows,
647
+ structureKey: structuralFingerprint(rows),
648
+ }
649
+ }
650
+ const snapshotOf = (state) => {
651
+ const resolved = resolveUnifiedConfig({
652
+ settingsValues: settingsValuesFromRows(state.rows),
653
+ })
654
+ return {
655
+ values: { ...resolved.values },
656
+ gateWords: structuredClone(resolved.gateWords),
657
+ }
658
+ }
659
+ const enqueueSettled = (snapshot) => {
660
+ const work = settledQueue.then(async () => {
661
+ if (!active) return
662
+ try {
663
+ if (onSettledSettings !== undefined) await onSettledSettings(structuredClone(snapshot))
664
+ } catch (error) {
665
+ await reportSettledError(error, snapshot)
666
+ }
667
+ })
668
+ settledQueue = work.catch(() => undefined)
669
+ return work
670
+ }
671
+ const settledSettingsUpdate = (state) => {
672
+ let snapshot
673
+ try {
674
+ snapshot = snapshotOf(state)
675
+ } catch (error) {
676
+ return reportSettledError(error, undefined)
677
+ }
678
+ return enqueueSettled(snapshot)
679
+ }
680
+ const enqueueStructural = (task) => {
681
+ const work = structuralQueue.then(task, task)
682
+ const safe = work.catch((error) => {
683
+ reportAdapterError(error, 'structuralHandoff')
684
+ console.warn('[dsh-extra-plan] structural handoff failed(不阻断 settled/profile sync):' + (error instanceof Error ? error.message : String(error)))
685
+ })
686
+ structuralQueue = safe
687
+ return safe
688
+ }
689
+ const disposeAdapterFibers = async (fibers) => {
690
+ let failed = false
691
+ let firstError
692
+ for (let index = fibers.length - 1; index >= 0; index -= 1) {
693
+ try { await disposeFiber(fibers[index]) }
694
+ catch (error) {
695
+ if (!failed) firstError = error
696
+ failed = true
697
+ }
698
+ }
699
+ if (failed) throw firstError
700
+ }
701
+ /**
702
+ * 顺序挂载 5 个 definition(主在前、角色在后);任一角色失败即整体回滚已挂载的全部 fiber,
703
+ * 并把诊断按 phase=mount:<presetId> 上报,不留下半套注册。
704
+ */
705
+ const mountOfficialAdapter = async (definitions) => {
706
+ if (!active) return
707
+ const officialAgentPreset = loadOfficialAgentPreset(installAnchor)
708
+ const mounted = []
709
+ for (const definition of definitions) {
710
+ if (!active) {
711
+ await disposeAdapterFibers(mounted)
712
+ return
713
+ }
714
+ try {
715
+ mounted.push(await child.plugin(officialAgentPreset, definition))
716
+ } catch (error) {
717
+ // 整体回滚已挂载的 definition,再把失败冒泡给 initialMount/structuralHandoff 的
718
+ // 既有单点诊断(phase 保持 initialMount/structuralHandoff),消息里带上失败的 preset id。
719
+ for (let index = mounted.length - 1; index >= 0; index -= 1) {
720
+ try { await disposeFiber(mounted[index]) } catch (disposeError) {
721
+ reportAdapterError(disposeError, 'rollback:' + definition.id)
722
+ }
723
+ }
724
+ const detail = error instanceof Error ? error.message : String(error)
725
+ throw new Error('mount ' + definition.id + ' failed: ' + detail)
726
+ }
727
+ }
728
+ adapterOwner = 'official'
729
+ adapterFibers = mounted
730
+ }
731
+ const disposeCurrentAdapter = async () => {
732
+ const previous = adapterFibers
733
+ adapterFibers = []
734
+ await disposeAdapterFibers(previous)
735
+ }
736
+ const structuralHandoff = async (state, settledPromise) => {
737
+ await settledPromise
738
+ if (!active) return
739
+ const current = readState()
740
+ const editor = current.editor
741
+ const rows = current.rows
742
+ const result = await syncPreset({
743
+ settingsValues: settingsValuesFromRows(rows),
744
+ apply: async (planned) => applyPlan(editor, rows, planned, () => active),
745
+ })
746
+ if (!active) return
747
+ const latest = readState()
748
+ const mainDefinition = result.plan !== undefined && result.plan.definition !== undefined
749
+ ? result.plan.definition
750
+ : projectedAssetDefinition(settingsValuesFromRows(latest.rows))
751
+ if (adapterOwner === 'official') await disposeCurrentAdapter()
752
+ await mountOfficialAdapter([mainDefinition, ...roleDefinitionsWithPresentation(mainDefinition)])
753
+ }
754
+ const initialMount = async () => {
755
+ if (!active) return
756
+ const initial = readState()
757
+ lastStructureKey = initial.structureKey
758
+ let result
759
+ try {
760
+ result = await syncPreset({
761
+ settingsValues: settingsValuesFromRows(initial.rows),
762
+ apply: async (planned) => applyPlan(initial.editor, initial.rows, planned, () => active),
763
+ })
764
+ if (!active) return
765
+ const latest = readState()
766
+ lastStructureKey = latest.structureKey
767
+ const settledPromise = settledSettingsUpdate(latest)
768
+ await settledPromise
769
+ if (!active) return
770
+ const mainDefinition = result.plan !== undefined && result.plan.definition !== undefined
771
+ ? result.plan.definition
772
+ : projectedAssetDefinition(settingsValuesFromRows(latest.rows))
773
+ await mountOfficialAdapter([mainDefinition, ...roleDefinitionsWithPresentation(mainDefinition)])
774
+ } catch (error) {
775
+ reportAdapterError(error, 'initialMount')
776
+ console.warn('[dsh-extra-plan] initial mount/adapter failed(不阻断 settled/profile sync):' + (error instanceof Error ? error.message : String(error)))
777
+ }
778
+ }
779
+ const settledOnlyUpdate = (state) => settledSettingsUpdate(state)
780
+ const offUpdate = typeof child.on === 'function' ? child.on('internal/update', () => {
781
+ if (!active) return
782
+ let state
783
+ try {
784
+ state = readState()
785
+ } catch (error) {
786
+ void reportSettledError(error, undefined)
787
+ return
788
+ }
789
+ const settledPromise = settledOnlyUpdate(state)
790
+ const structural = lastStructureKey === undefined || state.structureKey !== lastStructureKey
791
+ lastStructureKey = state.structureKey
792
+ if (!structural) return
793
+ void enqueueStructural(() => structuralHandoff(state, settledPromise))
794
+ }) : undefined
795
+ const dispose = async () => {
796
+ if (disposed) return undefined
797
+ disposed = true
798
+ active = false
799
+ if (typeof offUpdate === 'function') offUpdate()
800
+ await settledQueue
801
+ await structuralQueue
802
+ await disposeCurrentAdapter()
803
+ }
804
+ void enqueueStructural(initialMount)
805
+ return dispose
806
+ }
807
+
808
+
809
+ export { SETTINGS_ROW_ID }