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,796 @@
1
+ #!/usr/bin/env node
2
+ // 生成 runtime fallback 与纯 preset definition 资产;替换前先解析并校验。
3
+ // 主 definition 来自 agent.cordis.yml 第一文档;4 个角色 definition 来自同文件第二文档
4
+ // (用 --- 分隔多文档;personaPrefix 逐字搬运,extra-plan 行 config 从主 definition 同 id 行逐字复制,
5
+ // plugins 列表末尾固定追加恰一行 executor(id/name 按主 definition 的 executor 行 id 派生、无 config)。
6
+
7
+ import { constants as fsConstants, copyFileSync, existsSync, lstatSync, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from 'node:fs'
8
+ import { dirname, join, resolve } from 'node:path'
9
+ import { fileURLToPath } from 'node:url'
10
+ import { createPathContext, prepareWriteTarget, resolveHostPath, resolveWorkspacePath, validateReadTarget } from '../lib/path-policy.js'
11
+ import { SETTING_DEFINITIONS, parsePresetYaml, resolveTemplateSettingDefault } from '../lib/preset-settings.js'
12
+ import { ROLE_IDS, ROLE_ORDERS } from '../lib/role-contract.js'
13
+ import { HOST_ROW_IDS, EXECUTOR_TOOL_NAME_PREFIX } from '../lib/settings-contract.js'
14
+ import { errorText } from '../lib/runtime-static.js'
15
+ import { Script } from 'node:vm'
16
+
17
+ const HERE = dirname(fileURLToPath(import.meta.url))
18
+ function repositoryRootFromKnownLayout() {
19
+ const candidate = resolve(HERE, '..')
20
+ const required = [
21
+ join(candidate, 'package.json'),
22
+ join(candidate, 'index.js'),
23
+ join(candidate, 'cordis.patch.yml'),
24
+ ]
25
+ if (!required.every((path) => existsSync(path))) return null
26
+ try {
27
+ const manifest = JSON.parse(readFileSync(required[0], 'utf8'))
28
+ return manifest?.name === 'dsh-extra-plan' ? candidate : null
29
+ } catch {
30
+ return null
31
+ }
32
+ }
33
+ const REPOSITORY_ROOT = repositoryRootFromKnownLayout()
34
+ const PRESET_ASSET_DIR = resolve(HERE, '..', 'assets', 'presets', 'extra-plan')
35
+ export const DEFAULT_SOURCE = resolve(PRESET_ASSET_DIR, 'agent.cordis.yml')
36
+ export const DEFAULT_OUTPUT = resolve(HERE, '..', 'lib', 'preset-defaults.generated.js')
37
+ export const DEFAULT_CLIENT_OUTPUT = resolve(HERE, '..', 'lib', 'client.js')
38
+ export const DEFAULT_META_SOURCE = resolve(PRESET_ASSET_DIR, 'preset.yml')
39
+ export const DEFAULT_DEFINITION_OUTPUT = resolve(PRESET_ASSET_DIR, 'preset-definition.generated.yml')
40
+
41
+ export const PRESET_ID = 'extra-plan'
42
+ export const PRESET_ORDER = 100
43
+ export const PLUGINS_INDENT = 2
44
+ /** 角色预设固定顺序(order 101..104):执行者 → 规划者 → 验收者 → 探查者。 */
45
+ export { ROLE_IDS, ROLE_ORDERS }
46
+ /** 角色 definition 里固定前两行:dsh-persona(prefix=personaPrefix)与 dsh-extra-plan(主预设同 id 行 config)。 */
47
+ export const ROLE_FIRST_ROW_IDS = Object.freeze(['persona', 'extra-plan'])
48
+ /** 角色 definition plugins 末尾固定追加的宿主行:按主 definition 的 toolPresentationMode 派生单行 executor(恰一行、无 config)。 */
49
+ export const ROLE_LAST_ROW_BY_MODE = Object.freeze({
50
+ native: { id: HOST_ROW_IDS.toolPresentationMode.native, name: EXECUTOR_TOOL_NAME_PREFIX + 'native' },
51
+ ptc: { id: HOST_ROW_IDS.toolPresentationMode.ptc, name: EXECUTOR_TOOL_NAME_PREFIX + 'ptc' },
52
+ })
53
+ /** 主 definition 同 id 行缺失/解析异常时回落设置合同的同名默认。 */
54
+ const TOOL_PRESENTATION_DEFINITION = SETTING_DEFINITIONS.find((item) => item.key === 'toolPresentationMode')
55
+ if (TOOL_PRESENTATION_DEFINITION === undefined) throw new Error('设置合同缺少 toolPresentationMode')
56
+ export const DEFAULT_TOOL_PRESENTATION_MODE = TOOL_PRESENTATION_DEFINITION.defaultValue
57
+
58
+ export function roleDefinitionFile(roleId, dir = PRESET_ASSET_DIR) {
59
+ return join(dir, 'preset-definition-' + roleId + '.generated.yml')
60
+ }
61
+
62
+ export function runtimeDefaultsFromTemplate(defaultText) {
63
+ return Object.fromEntries(SETTING_DEFINITIONS.map((definition) => [
64
+ definition.key,
65
+ resolveTemplateSettingDefault(defaultText, definition.key),
66
+ ]))
67
+ }
68
+
69
+ export function renderRuntimeDefaults(defaultText) {
70
+ const defaults = runtimeDefaultsFromTemplate(defaultText)
71
+ return [
72
+ '// GENERATED FILE - DO NOT EDIT.',
73
+ '// Generated by scripts/generate-runtime-defaults.mjs.',
74
+ 'export const DEFAULT_SETTINGS = Object.freeze(' + JSON.stringify(defaults, null, 2) + ')',
75
+ 'export const DEFAULT_EXPLORE_BUDGET = DEFAULT_SETTINGS.exploreBudget',
76
+ 'export const DEFAULT_PLANNER_PROMPT_SUFFIX = DEFAULT_SETTINGS.plannerPromptSuffix',
77
+ '',
78
+ ].join('\n')
79
+ }
80
+
81
+ export const CLIENT_FIELDS_BEGIN = '// BEGIN GENERATED SETTINGS FIELDS'
82
+ export const CLIENT_FIELDS_END = '// END GENERATED SETTINGS FIELDS'
83
+ const CLIENT_FIELD_METADATA_KEYS = Object.freeze(['options', 'optionLocale', 'locale', 'section', 'min', 'step', 'hint'])
84
+
85
+ function clientFieldMetadata(definition) {
86
+ if (definition === null || typeof definition !== 'object' || definition.ui === null || typeof definition.ui !== 'object') {
87
+ throw new Error('客户端字段缺少 ui 元数据:' + String(definition && definition.key))
88
+ }
89
+ const metadata = { key: definition.key, control: definition.ui.control }
90
+ for (const key of CLIENT_FIELD_METADATA_KEYS) {
91
+ const value = definition.ui[key]
92
+ if (value === undefined) continue
93
+ if (key === 'options') metadata.options = [...value]
94
+ else if (key === 'optionLocale') metadata.optionLocale = { ...value }
95
+ else metadata[key] = value
96
+ }
97
+ return metadata
98
+ }
99
+
100
+ function clientFieldLines(name, definitions) {
101
+ return [
102
+ ' const ' + name + ' = Object.freeze([',
103
+ ...definitions.map((definition) => ' ' + JSON.stringify(clientFieldMetadata(definition)) + ','),
104
+ ' ]);',
105
+ ]
106
+ }
107
+
108
+ export function renderClientFieldBlock(definitions = SETTING_DEFINITIONS) {
109
+ const list = Array.isArray(definitions) ? definitions : SETTING_DEFINITIONS
110
+ const extra = list.filter((definition) => definition.group === 'extra-plan')
111
+ const host = list.filter((definition) => definition.group === 'host-rows')
112
+ if (extra.length !== 10 || host.length !== 1) throw new Error('客户端字段分组必须为 10 项 extra-plan + 1 项 host-rows')
113
+ return [
114
+ ...clientFieldLines('EXTRA_FIELDS', extra),
115
+ '',
116
+ ...clientFieldLines('HOST_ROW_FIELDS', host),
117
+ ' const ALL_FIELDS = Object.freeze(EXTRA_FIELDS.concat(HOST_ROW_FIELDS));',
118
+ ].join('\n')
119
+ }
120
+
121
+ function markerMatches(text, marker) {
122
+ const escaped = marker.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
123
+ return [...String(text).matchAll(new RegExp('^[ \t]*' + escaped + '[ \t]*\\r?$', 'gm'))]
124
+ }
125
+
126
+ function clientFieldMarkerRange(clientText) {
127
+ const begin = markerMatches(clientText, CLIENT_FIELDS_BEGIN)
128
+ const end = markerMatches(clientText, CLIENT_FIELDS_END)
129
+ if (begin.length !== 1 || end.length !== 1) throw new Error('客户端字段生成标记必须各恰有一处')
130
+ const beginEnd = clientText.indexOf('\n', begin[0].index)
131
+ const contentStart = beginEnd === -1 ? clientText.length : beginEnd + 1
132
+ if (end[0].index < contentStart) throw new Error('客户端字段生成标记顺序逆序')
133
+ return { contentStart, contentEnd: end[0].index, eol: clientText.includes('\r\n') ? '\r\n' : '\n' }
134
+ }
135
+
136
+ export function renderClientFields(clientText, definitions = SETTING_DEFINITIONS) {
137
+ if (typeof clientText !== 'string') throw new Error('客户端源必须为字符串')
138
+ const range = clientFieldMarkerRange(clientText)
139
+ const block = renderClientFieldBlock(definitions).replaceAll('\n', range.eol)
140
+ return clientText.slice(0, range.contentStart) + block + range.eol + clientText.slice(range.contentEnd)
141
+ }
142
+
143
+ /** 顶格 YAML 文档分隔行(作者源第一文档结束、第二文档开始的唯一边界)。 */
144
+ const DOCUMENT_SEPARATOR = /^---\s*$/
145
+
146
+ function separatorIndexOf(lines) {
147
+ return lines.findIndex((line) => DOCUMENT_SEPARATOR.test(line))
148
+ }
149
+
150
+ /** 抽取 agent.cordis.yml 第一文档的顶层条目区间(结束边界=首个「---」行),保留注释、group、isolate 与 !!js。 */
151
+ export function topLevelRowsOf(defaultText) {
152
+ const lines = String(defaultText).split('\n')
153
+ const start = lines.findIndex((line) => /^- (?:id|insert):/.test(line))
154
+ if (start === -1) throw new Error('agent.cordis.yml 顶层条目缺失(未找到根级「- id:」行)')
155
+ const separator = separatorIndexOf(lines)
156
+ let end = separator === -1 ? lines.length : separator
157
+ while (end > start && lines[end - 1].trim() === '') end -= 1
158
+ const block = lines.slice(start, end)
159
+ if (block.length === 0) throw new Error('agent.cordis.yml 顶层条目为空')
160
+ return block
161
+ }
162
+
163
+ /** 抽取 agent.cordis.yml 第二文档原文(分隔行之后全部行,保留注释与工具面原文);缺分隔行即抛。 */
164
+ export function secondDocumentOf(defaultText) {
165
+ const lines = String(defaultText).split('\n')
166
+ const separator = separatorIndexOf(lines)
167
+ if (separator === -1) throw new Error('agent.cordis.yml 缺少第二文档分隔行「---」')
168
+ return lines.slice(separator + 1).join('\n')
169
+ }
170
+
171
+ function indentBlock(block, columns = PLUGINS_INDENT) {
172
+ const pad = ' '.repeat(columns)
173
+ return block.map((line) => (line === '' ? line : pad + line))
174
+ }
175
+
176
+ function indentOf(line) {
177
+ let count = 0
178
+ while (count < line.length && line[count] === ' ') count += 1
179
+ return count
180
+ }
181
+
182
+ function shiftBlock(block, delta) {
183
+ if (delta === 0) return block.slice()
184
+ return block.map((line) => {
185
+ if (line.trim() === '') return ''
186
+ const next = indentOf(line) + delta
187
+ if (next < 0) throw new Error('缩进平移越界:' + JSON.stringify(line))
188
+ return ' '.repeat(next) + line.slice(indentOf(line))
189
+ })
190
+ }
191
+
192
+ /**
193
+ * 取出「起始行 + 其后更深缩进的非空行」为一整块 raw 文本:
194
+ * 遇到缩进 <= base 的非空行即结束(同级注释留给外层),尾部空行剔除。
195
+ */
196
+ export function rawBlockFrom(lines, startIndex, baseIndent) {
197
+ if (startIndex < 0 || startIndex >= lines.length) throw new Error('raw 块起点越界')
198
+ const block = [lines[startIndex]]
199
+ for (let index = startIndex + 1; index < lines.length; index += 1) {
200
+ const line = lines[index]
201
+ if (line.trim() === '') { block.push(''); continue }
202
+ if (indentOf(line) <= baseIndent) break
203
+ block.push(line)
204
+ }
205
+ while (block.length > 1 && block[block.length - 1].trim() === '') block.pop()
206
+ return block
207
+ }
208
+
209
+ function quoteYamlSingle(value) {
210
+ return "'" + String(value).replace(/'/g, "''") + "'"
211
+ }
212
+
213
+ function assertDefinition(definition, label) {
214
+ // delegation 组固定子行数:作者源增删子行时只改这一处。
215
+ const EXPECTED_DELEGATION_CHILD_ROWS = 5
216
+ if (definition === null || typeof definition !== 'object' || Array.isArray(definition)) throw new Error(label + ' definition 不是对象')
217
+ if (definition.id !== PRESET_ID) throw new Error(label + ' id 必须为 ' + PRESET_ID)
218
+ if (typeof definition.name !== 'string' || definition.name === '') throw new Error(label + ' 缺少 name')
219
+ if (typeof definition.description !== 'string' || definition.description === '') throw new Error(label + ' 缺少 description')
220
+ if (!Number.isInteger(definition.order)) throw new Error(label + ' order 必须为整数')
221
+ if (!Array.isArray(definition.plugins) || definition.plugins.length !== 17) throw new Error(label + ' plugins 顶层必须恰有 17 条')
222
+ if (definition.plugins.some((row) => row === null || typeof row !== 'object' || row.insert !== undefined)) throw new Error(label + ' plugins 不得含 Loader insert wrapper')
223
+ const delegationRow = findRowById(definition.plugins, 'delegation')
224
+ if (delegationRow === null) throw new Error(label + ' 缺少 delegation 组行')
225
+ if (!Array.isArray(delegationRow.config) || delegationRow.config.length !== EXPECTED_DELEGATION_CHILD_ROWS) {
226
+ const actual = Array.isArray(delegationRow.config) ? delegationRow.config.length : '非数组'
227
+ throw new Error(label + ' delegation 组必须恰有 ' + EXPECTED_DELEGATION_CHILD_ROWS + ' 个子行(实际 ' + actual + ' 个)')
228
+ }
229
+ }
230
+
231
+ export function renderPresetDefinition(defaultText, metaText) {
232
+ const rows = topLevelRowsOf(defaultText)
233
+ const meta = parsePresetYaml(metaText)
234
+ if (meta === null || typeof meta !== 'object' || Array.isArray(meta)) throw new Error('preset.yml 解析结果不是对象')
235
+ if (typeof meta.name !== 'string' || meta.name === '') throw new Error('preset.yml 缺少 name')
236
+ if (typeof meta.description !== 'string' || meta.description === '') throw new Error('preset.yml 缺少 description')
237
+ const rendered = [
238
+ '# GENERATED FILE - DO NOT EDIT.',
239
+ '# Generated by scripts/generate-runtime-defaults.mjs.',
240
+ '# 纯 preset definition;由 settings owner 内部读取生成资产后交给官方 @deepseek-ai/dsh-agent-preset adapter。',
241
+ '# plugins = agent.cordis.yml 顶层条目逐字平移,保留 group/isolate/!!js 原文。',
242
+ 'id: ' + PRESET_ID,
243
+ 'name: ' + quoteYamlSingle(meta.name),
244
+ 'description: ' + quoteYamlSingle(meta.description),
245
+ 'order: ' + String(PRESET_ORDER),
246
+ 'plugins:',
247
+ ].concat(indentBlock(rows)).join('\n') + '\n'
248
+ assertDefinition(parsePresetYaml(rendered), '生成 definition')
249
+ return rendered
250
+ }
251
+
252
+ /** extra-plan 行(主 definition 内 group 子行)的 raw 块:id 行 + name 行 + 整段 config。 */
253
+ function mainExtraPlanRowBlock(definitionText) {
254
+ const lines = String(definitionText).split('\n')
255
+ const start = lines.findIndex((line) => /^\s*- id: extra-plan$/.test(line))
256
+ if (start === -1) throw new Error('主 definition 缺少 extra-plan 行')
257
+ const base = indentOf(lines[start])
258
+ const block = rawBlockFrom(lines, start, base)
259
+ const nameLine = block.find((line) => /^\s*name:/.test(line))
260
+ if (nameLine === undefined) throw new Error('主 definition 的 extra-plan 行缺少 name')
261
+ const configIndex = block.findIndex((line) => /^\s*config:$/.test(line))
262
+ if (configIndex === -1) throw new Error('主 definition 的 extra-plan 行缺少 config')
263
+ return { block, configBlock: block.slice(configIndex) }
264
+ }
265
+
266
+ /** 角色源里某角色的 personaPrefix 折叠块 raw 行(首行为 key 行)。 */
267
+ function personaPrefixBlock(roleText, personaText) {
268
+ const lines = String(roleText).split('\n')
269
+ const start = lines.findIndex((line) => line.trim() === 'personaPrefix: >-')
270
+ if (start === -1) throw new Error('角色源缺少 personaPrefix: >- 块')
271
+ const keyIndent = indentOf(lines[start])
272
+ // 定位属于本条目的 personaPrefix:按角色顺序逐个消费,这里以 personaText 内容做唯一性校验。
273
+ const candidates = []
274
+ for (let index = 0; index < lines.length; index += 1) {
275
+ if (lines[index].trim() === 'personaPrefix: >-') candidates.push(index)
276
+ }
277
+ for (const index of candidates) {
278
+ const block = rawBlockFrom(lines, index, indentOf(lines[index]))
279
+ const body = block.slice(1)
280
+ const text = [
281
+ 'x:',
282
+ ' personaPrefix: >-',
283
+ ...body,
284
+ '',
285
+ ].join('\n')
286
+ let parsed
287
+ try { parsed = parsePresetYaml(text) } catch { continue }
288
+ if (parsed !== null && typeof parsed === 'object' && parsed.x !== undefined && parsed.x.personaPrefix === personaText) {
289
+ return { body }
290
+ }
291
+ }
292
+ throw new Error('角色源 personaPrefix 块与解析值不匹配(' + keyIndent + ')')
293
+ }
294
+
295
+ /** 角色源里 tools 列表的 raw 行(首行为「tools:」行)。 */
296
+ function roleToolsBlock(roleText, roleIndex, roleCount) {
297
+ const lines = String(roleText).split('\n')
298
+ const starts = []
299
+ for (let index = 0; index < lines.length; index += 1) {
300
+ if (lines[index].trim() === 'tools:') starts.push(index)
301
+ }
302
+ if (starts.length !== roleCount) throw new Error('角色源 tools: 行数与角色数不符(' + starts.length + '/' + roleCount + ')')
303
+ const index = starts[roleIndex]
304
+ const base = indentOf(lines[index])
305
+ const block = rawBlockFrom(lines, index, base)
306
+ return { block: block.slice(1) }
307
+ }
308
+
309
+ /** 按行 id 深度优先查子行(含 group 行的 config 子行数组),返回首个命中;按自身生成合同定位,找不到返回 null。 */
310
+ function findRowById(rows, rowId) {
311
+ if (!Array.isArray(rows)) return null
312
+ for (const row of rows) {
313
+ if (row === null || typeof row !== 'object' || Array.isArray(row)) continue
314
+ if (row.id === rowId) return row
315
+ if (Array.isArray(row.config)) {
316
+ const nested = findRowById(row.config, rowId)
317
+ if (nested !== null) return nested
318
+ }
319
+ }
320
+ return null
321
+ }
322
+
323
+ /**
324
+ * 主 definition 里 executor 行的默认 mode(角色 definition 末行取同一个值):
325
+ * 只出现 tool-executor-native → native、只出现 tool-executor-ptc → ptc;
326
+ * 两种都出现、都缺失或解析异常时回落设置合同默认值,不抛错。
327
+ */
328
+ export function mainToolPresentationMode(definitionText) {
329
+ try {
330
+ const parsed = parsePresetYaml(definitionText)
331
+ const plugins = parsed !== null && typeof parsed === 'object' && Array.isArray(parsed.plugins) ? parsed.plugins : []
332
+ const nativeRow = findRowById(plugins, HOST_ROW_IDS.toolPresentationMode.native)
333
+ const ptcRow = findRowById(plugins, HOST_ROW_IDS.toolPresentationMode.ptc)
334
+ if ((nativeRow !== null) === (ptcRow !== null)) return DEFAULT_TOOL_PRESENTATION_MODE
335
+ return nativeRow !== null ? 'native' : 'ptc'
336
+ } catch {
337
+ return DEFAULT_TOOL_PRESENTATION_MODE
338
+ }
339
+ }
340
+
341
+ function assertRoleSource(roles, label = '角色源') {
342
+ if (!Array.isArray(roles) || roles.length !== ROLE_IDS.length) throw new Error(label + ' 必须恰有 ' + ROLE_IDS.length + ' 个角色')
343
+ const ids = roles.map((role) => role !== null && typeof role === 'object' ? role.id : undefined)
344
+ if (JSON.stringify(ids) !== JSON.stringify(ROLE_IDS)) throw new Error(label + ' id 顺序/取值必须为 ' + ROLE_IDS.join(','))
345
+ const orders = roles.map((role) => role.order)
346
+ if (JSON.stringify(orders) !== JSON.stringify(ROLE_ORDERS)) throw new Error(label + ' order 必须为 ' + ROLE_ORDERS.join(','))
347
+ for (const role of roles) {
348
+ if (typeof role.name !== 'string' || role.name === '') throw new Error(label + ' ' + role.id + ' 缺少中文 name')
349
+ if (typeof role.description !== 'string' || role.description === '') throw new Error(label + ' ' + role.id + ' 缺少 description')
350
+ if (typeof role.personaPrefix !== 'string' || role.personaPrefix === '') throw new Error(label + ' ' + role.id + ' 缺少 personaPrefix')
351
+ if (!Array.isArray(role.tools) || role.tools.length === 0) throw new Error(label + ' ' + role.id + ' 缺少 tools 行')
352
+ if (role.gateWords !== undefined) throw new Error(label + ' ' + role.id + ' 不得手写 gateWords(唯一编辑位置是 agent.cordis.yml)')
353
+ for (const row of role.tools) {
354
+ if (row === null || typeof row !== 'object' || typeof row.name !== 'string' || row.name === '') throw new Error(label + ' ' + role.id + ' 的 tools 行缺少 name')
355
+ if (row.insert !== undefined) throw new Error(label + ' ' + role.id + ' 的 tools 行不得含 insert wrapper')
356
+ // 生成器在 plugins 末尾固定追加恰一行 executor(按主 definition 的 toolPresentationMode 派生):作者源手写会产生第二行(宿主判为矛盾、拒绝挂载)。
357
+ if (
358
+ row.id === 'tool-presentation' ||
359
+ row.name === '@deepseek-ai/dsh-agent-tool-presentation' ||
360
+ Object.values(ROLE_LAST_ROW_BY_MODE).some((target) => row.id === target.id || row.name === target.name)
361
+ ) throw new Error(label + ' ' + role.id + ' 不得手写 executor / tool-presentation 行(executor 由生成器按 toolPresentationMode 派生恰一行)')
362
+ }
363
+ }
364
+ return roles
365
+ }
366
+
367
+ function assertRoleDefinition(definition, role, label, presentationMode) {
368
+ if (definition === null || typeof definition !== 'object' || Array.isArray(definition)) throw new Error(label + ' 不是对象')
369
+ if (definition.id !== role.id) throw new Error(label + ' id 必须为 ' + role.id)
370
+ if (definition.name !== role.name) throw new Error(label + ' name 与作者源不符')
371
+ if (definition.description !== role.description) throw new Error(label + ' description 与作者源不符')
372
+ if (definition.order !== role.order) throw new Error(label + ' order 与作者源不符')
373
+ if (!Array.isArray(definition.plugins) || definition.plugins.length !== role.tools.length + ROLE_FIRST_ROW_IDS.length + 1) throw new Error(label + ' plugins 行数不符(应为首两行 + tools 行 + 末行 executor)')
374
+ if (definition.plugins[0].id !== ROLE_FIRST_ROW_IDS[0] || definition.plugins[0].name !== '@deepseek-ai/dsh-persona') throw new Error(label + ' 首行必须是 dsh-persona')
375
+ if (definition.plugins[0].config === undefined || definition.plugins[0].config.prefix !== role.personaPrefix) throw new Error(label + ' persona prefix 必须逐字等于 personaPrefix')
376
+ if (definition.plugins[1].id !== ROLE_FIRST_ROW_IDS[1] || definition.plugins[1].name !== 'dsh-extra-plan') throw new Error(label + ' 第二行必须是 dsh-extra-plan')
377
+ if (definition.plugins.some((row) => row === null || typeof row !== 'object' || row.insert !== undefined)) throw new Error(label + ' 不得含 Loader insert wrapper')
378
+ // 同一 definition 内绝不允许第二行 executor(宿主判为矛盾并拒绝挂载)。
379
+ const lastRowTarget = ROLE_LAST_ROW_BY_MODE[presentationMode]
380
+ if (lastRowTarget === undefined) throw new Error(label + ' 未知 toolPresentationMode:' + presentationMode)
381
+ const executorRows = definition.plugins.filter((row) => row.id === lastRowTarget.id)
382
+ if (executorRows.length !== 1) throw new Error(label + ' 必须恰有一行 ' + lastRowTarget.id + '(实际 ' + executorRows.length + ' 行)')
383
+ const lastRow = definition.plugins[definition.plugins.length - 1]
384
+ if (lastRow.id !== lastRowTarget.id || lastRow.name !== lastRowTarget.name) throw new Error(label + ' 末行必须是 ' + lastRowTarget.id + ' / ' + lastRowTarget.name)
385
+ if (lastRow.config !== undefined) throw new Error(label + ' ' + lastRowTarget.id + ' 行不得带 config(executor 行由生成器按 toolPresentationMode 派生)')
386
+ return definition
387
+ }
388
+
389
+ /**
390
+ * 渲染 4 个角色 definition:plugins = [dsh-persona(prefix=personaPrefix),
391
+ * dsh-extra-plan(主预设同 id 行 config 逐字复制), ...角色 tools 行,
392
+ * executor(恰一行、无 config,id/name 按主 definition 的 executor 行 id 派生:native→tool-executor-native、ptc→tool-executor-ptc)]。
393
+ */
394
+ export function renderRoleDefinitions(roleText, definitionText) {
395
+ const roles = assertRoleSource(parsePresetYaml(roleText))
396
+ const mainExtra = mainExtraPlanRowBlock(definitionText)
397
+ const mainParsed = parsePresetYaml(mainExtra.block.join('\n'))
398
+ const mainRow = Array.isArray(mainParsed) ? mainParsed[0] : mainParsed
399
+ const mainConfigJson = JSON.stringify(mainRow !== null && typeof mainRow === 'object' && mainRow.config !== undefined ? mainRow.config : undefined)
400
+ if (mainConfigJson === undefined) throw new Error('主 definition 的 extra-plan 行缺少 config')
401
+ const configBlock = shiftBlock(mainExtra.configBlock, -4)
402
+ const presentationMode = mainToolPresentationMode(definitionText)
403
+ const lastRow = ROLE_LAST_ROW_BY_MODE[presentationMode]
404
+ const presentationBlock = [
405
+ ' - id: ' + lastRow.id,
406
+ " name: '" + lastRow.name + "'",
407
+ ]
408
+ return roles.map((role, index) => {
409
+ const persona = personaPrefixBlock(roleText, role.personaPrefix)
410
+ const tools = roleToolsBlock(roleText, index, roles.length)
411
+ const rendered = [
412
+ '# GENERATED FILE - DO NOT EDIT.',
413
+ '# Generated by scripts/generate-runtime-defaults.mjs(源:agent.cordis.yml 第二文档)。',
414
+ '# 角色预设 definition:dsh-persona 取 personaPrefix 原文,dsh-extra-plan 的行 config 由主预设同 id 行逐字复制,',
415
+ '# 其余为角色 tools 行,plugins 末尾固定追加恰一行 executor(id/name 按主 definition 的 executor 行 id 派生,无 config)。',
416
+ '# 角色人设与工具面在这里承载;主预设保留 persona,主委派 config 通过 agentPreset 引用角色,不写 persona/toolFilter/backgroundMode。',
417
+ 'id: ' + role.id,
418
+ 'name: ' + quoteYamlSingle(role.name),
419
+ 'description: ' + quoteYamlSingle(role.description),
420
+ 'order: ' + String(role.order),
421
+ 'plugins:',
422
+ ' - id: persona',
423
+ " name: '@deepseek-ai/dsh-persona'",
424
+ ' config:',
425
+ ' prefix: >-',
426
+ ...persona.body,
427
+ ' - id: extra-plan',
428
+ " name: 'dsh-extra-plan'",
429
+ ...configBlock,
430
+ ...shiftBlock(tools.block, -2),
431
+ ...presentationBlock,
432
+ ].join('\n') + '\n'
433
+ const parsed = parsePresetYaml(rendered)
434
+ assertRoleDefinition(parsed, role, '生成角色 definition ' + role.id, presentationMode)
435
+ const copied = JSON.stringify(parsed.plugins[1].config)
436
+ if (copied !== mainConfigJson) throw new Error('生成角色 definition ' + role.id + ' 的 extra-plan config 与主预设不逐字相等')
437
+ return { roleId: role.id, order: role.order, text: rendered }
438
+ })
439
+ }
440
+
441
+ function assertParses(text, what) {
442
+ try {
443
+ const parsed = parsePresetYaml(text)
444
+ if (what === 'preset-definition.generated.yml') assertDefinition(parsed, what)
445
+ return parsed
446
+ } catch (error) {
447
+ throw new Error(what + ' YAML parse failed: ' + (error instanceof Error ? error.message : String(error)))
448
+ }
449
+ }
450
+
451
+ function checkOutput(output, rendered, label) {
452
+ if (!existsSync(output)) throw new Error(label + ' missing: ' + output)
453
+ const existing = readFileSync(output, 'utf8')
454
+ if (existing !== rendered) throw new Error(label + ' out of date: ' + output)
455
+ }
456
+
457
+ const DEFAULT_PUBLISH_FS_OPS = Object.freeze({ copyFileSync, existsSync, mkdirSync, renameSync, unlinkSync, writeFileSync })
458
+ let publishSequence = 0
459
+
460
+ function publishFsOpsOf(overrides) {
461
+ if (overrides === null || overrides === undefined || typeof overrides !== 'object') return DEFAULT_PUBLISH_FS_OPS
462
+ return { ...DEFAULT_PUBLISH_FS_OPS, ...overrides }
463
+ }
464
+
465
+ function uniquePaths(paths) {
466
+ return [...new Set(paths)]
467
+ }
468
+
469
+ function cleanupPublishFiles(paths, ops) {
470
+ const failures = []
471
+ for (const path of uniquePaths(paths)) {
472
+ try {
473
+ if (ops.existsSync(path)) ops.unlinkSync(path)
474
+ } catch (error) {
475
+ failures.push(path + '(' + errorText(error) + ')')
476
+ }
477
+ }
478
+ return failures
479
+ }
480
+
481
+ function restorePublishedEntry(entry, ops) {
482
+ try {
483
+ if (entry.originalExists) {
484
+ if (ops.existsSync(entry.path)) ops.unlinkSync(entry.path)
485
+ ops.copyFileSync(entry.pathBackup, entry.path, fsConstants.COPYFILE_EXCL)
486
+ if (!ops.existsSync(entry.path)) throw new Error('恢复后目标未就位:' + entry.path)
487
+ } else if (ops.existsSync(entry.path)) {
488
+ ops.unlinkSync(entry.path)
489
+ }
490
+ return null
491
+ } catch (error) {
492
+ return entry.path + '(' + errorText(error) + ')'
493
+ }
494
+ }
495
+
496
+ function publishFailure(stage, original, rollbackErrors, cleanupErrors, remainingPaths) {
497
+ const details = []
498
+ if (rollbackErrors.length > 0) details.push('恢复失败:' + rollbackErrors.join(';'))
499
+ if (cleanupErrors.length > 0) details.push('清理失败:' + cleanupErrors.join(';'))
500
+ if (remainingPaths.length > 0) details.push('残留/备份路径:' + remainingPaths.join(';'))
501
+ const failure = new Error('生成链发布失败;阶段=' + stage + ';原始失败=' + errorText(original) + (details.length === 0 ? '' : ';' + details.join(';')))
502
+ failure.cause = original
503
+ failure.stage = stage
504
+ failure.rollbackErrors = rollbackErrors
505
+ failure.cleanupErrors = cleanupErrors
506
+ failure.remainingPaths = remainingPaths
507
+ return failure
508
+ }
509
+
510
+ function normalizedOutputEntries(entries) {
511
+ const seen = new Map()
512
+ return entries.map((entry) => {
513
+ const path = resolve(entry.path)
514
+ const previous = seen.get(path)
515
+ if (previous !== undefined) throw new Error('生成目标重复:' + path + '(' + previous + ' 与 ' + entry.label + ')')
516
+ seen.set(path, entry.label)
517
+ return { ...entry, path }
518
+ })
519
+ }
520
+
521
+ function publishGeneratedOutputs(entries, fsOps) {
522
+ publishSequence += 1
523
+ const suffix = String(process.pid) + '-' + String(Date.now()) + '-' + String(publishSequence)
524
+ const prepared = entries.map((entry, index) => ({
525
+ ...entry,
526
+ tempPath: entry.path + '.tmp-' + suffix + '-' + String(index),
527
+ pathBackup: entry.path + '.bak-' + suffix + '-' + String(index),
528
+ originalExists: false,
529
+ }))
530
+ const tempPaths = prepared.map((entry) => entry.tempPath)
531
+ const backupPaths = []
532
+ const createdTempPaths = []
533
+ const createdBackupPaths = []
534
+ const publishAttempts = []
535
+ const ops = publishFsOpsOf(fsOps)
536
+ let stage = '准备'
537
+ try {
538
+ stage = '暂存'
539
+ for (let index = 0; index < prepared.length; index += 1) {
540
+ const entry = prepared[index]
541
+ stage = '暂存第' + String(index + 1)
542
+ ops.mkdirSync(dirname(entry.path), { recursive: true })
543
+ entry.originalExists = ops.existsSync(entry.path)
544
+ if (entry.originalExists) {
545
+ backupPaths.push(entry.pathBackup)
546
+ if (ops.existsSync(entry.pathBackup)) throw new Error('备份文件已存在:' + entry.pathBackup)
547
+ createdBackupPaths.push(entry.pathBackup)
548
+ ops.copyFileSync(entry.path, entry.pathBackup, fsConstants.COPYFILE_EXCL)
549
+ }
550
+ if (ops.existsSync(entry.tempPath)) throw new Error('临时文件已存在:' + entry.tempPath)
551
+ createdTempPaths.push(entry.tempPath)
552
+ ops.writeFileSync(entry.tempPath, entry.content, { encoding: 'utf8', flag: 'wx' })
553
+ }
554
+ stage = '发布'
555
+ for (let index = 0; index < prepared.length; index += 1) {
556
+ const entry = prepared[index]
557
+ stage = '发布第' + String(index + 1)
558
+ publishAttempts.push(entry)
559
+ if (entry.originalExists) ops.unlinkSync(entry.path)
560
+ ops.renameSync(entry.tempPath, entry.path)
561
+ if (!ops.existsSync(entry.path)) throw new Error('发布后目标未就位:' + entry.path)
562
+ }
563
+ } catch (original) {
564
+ const rollbackErrors = []
565
+ for (let index = publishAttempts.length - 1; index >= 0; index -= 1) {
566
+ const rollbackError = restorePublishedEntry(publishAttempts[index], ops)
567
+ if (rollbackError !== null) rollbackErrors.push(rollbackError)
568
+ }
569
+ if (rollbackErrors.length > 0) {
570
+ throw publishFailure(stage, original, rollbackErrors, [], uniquePaths([...tempPaths, ...backupPaths]))
571
+ }
572
+ const cleanupErrors = cleanupPublishFiles([...createdTempPaths, ...createdBackupPaths], ops)
573
+ if (cleanupErrors.length > 0) {
574
+ throw publishFailure(stage, original, [], cleanupErrors, uniquePaths([...tempPaths, ...backupPaths]))
575
+ }
576
+ throw publishFailure(stage, original, [], [], [])
577
+ }
578
+ const cleanupErrors = cleanupPublishFiles([...createdTempPaths, ...createdBackupPaths], ops)
579
+ if (cleanupErrors.length > 0) {
580
+ const cleanupError = new Error(cleanupErrors.join(';'))
581
+ throw publishFailure('清理', cleanupError, [], cleanupErrors, uniquePaths([...tempPaths, ...backupPaths]))
582
+ }
583
+ }
584
+
585
+
586
+ function generatorPathContext(options) {
587
+ if (options.pathContext !== undefined) return options.pathContext
588
+ return createPathContext({
589
+ workspaceRoot: options.workspaceRoot === undefined ? REPOSITORY_ROOT : options.workspaceRoot,
590
+ hostDataRoot: options.hostDataRoot,
591
+ hostCapabilities: options.hostCapabilities,
592
+ })
593
+ }
594
+
595
+ function inputPathSpec(options, prefix) {
596
+ const kind = options[prefix + 'Kind'] === undefined ? 'workspace' : options[prefix + 'Kind']
597
+ if (kind !== 'workspace' && kind !== 'host') throw new Error('生成器 ' + prefix + 'Kind 必须为 workspace 或 host')
598
+ const pathOptions = {}
599
+ if (options[prefix + 'Capability'] !== undefined) pathOptions.capability = options[prefix + 'Capability']
600
+ if (options[prefix + 'Purpose'] !== undefined) pathOptions.purpose = options[prefix + 'Purpose']
601
+ return { kind, pathOptions }
602
+ }
603
+
604
+ function readGeneratorInput(context, value, options, prefix) {
605
+ const spec = inputPathSpec(options, prefix)
606
+ const candidate = spec.kind === 'host'
607
+ ? resolveHostPath(context, value, spec.pathOptions)
608
+ : resolveWorkspacePath(context, value, spec.pathOptions)
609
+ return validateReadTarget(context, candidate, { expectedType: 'file' }).path
610
+ }
611
+
612
+ function pathEntryExists(path) {
613
+ try {
614
+ lstatSync(path)
615
+ return true
616
+ } catch (error) {
617
+ if (error !== null && typeof error === 'object' && (error.code === 'ENOENT' || error.code === 'ENOTDIR')) return false
618
+ throw error
619
+ }
620
+ }
621
+
622
+ function ensureWorkspaceOutputParent(context, target) {
623
+ let cursor = dirname(target.path)
624
+ const missing = []
625
+ while (!pathEntryExists(cursor)) {
626
+ const parent = dirname(cursor)
627
+ if (parent === cursor) throw new Error('生成目标父路径不可解析:' + target.path)
628
+ missing.push(cursor)
629
+ cursor = parent
630
+ }
631
+ validateReadTarget(context, resolveWorkspacePath(context, cursor, { purpose: 'generator-output' }), { expectedType: 'directory' })
632
+ for (const directory of missing.reverse()) {
633
+ mkdirSync(directory)
634
+ validateReadTarget(context, resolveWorkspacePath(context, directory, { purpose: 'generator-output' }), { expectedType: 'directory' })
635
+ }
636
+ }
637
+
638
+ function generatorOutputTarget(context, value, options, prefix, check) {
639
+ const spec = inputPathSpec(options, prefix)
640
+ if (!check && spec.kind !== 'workspace') throw new Error('生成器非check输出必须为 workspace')
641
+ const pathOptions = { ...spec.pathOptions, purpose: spec.pathOptions.purpose === undefined ? 'generator-output' : spec.pathOptions.purpose }
642
+ const target = spec.kind === 'host'
643
+ ? resolveHostPath(context, value, pathOptions)
644
+ : resolveWorkspacePath(context, value, pathOptions)
645
+ return { ...target, kind: spec.kind, outputCapability: spec.pathOptions.capability === undefined ? null : spec.pathOptions.capability }
646
+ }
647
+
648
+ function outputEntryTarget(context, entry) {
649
+ const kind = entry.kind === undefined ? 'workspace' : entry.kind
650
+ const pathOptions = {
651
+ ...(entry.capability === undefined || entry.capability === null ? {} : { capability: entry.capability }),
652
+ purpose: entry.purpose === undefined ? 'generator-output' : entry.purpose,
653
+ }
654
+ const target = kind === 'host'
655
+ ? resolveHostPath(context, entry.path, pathOptions)
656
+ : resolveWorkspacePath(context, entry.path, pathOptions)
657
+ return { ...target, kind }
658
+ }
659
+
660
+ function authorizeOutputEntries(context, entries, check) {
661
+ return entries.map((entry) => {
662
+ const target = outputEntryTarget(context, entry)
663
+ if (check) {
664
+ validateReadTarget(context, target, { expectedType: 'file', purpose: 'generator-output' })
665
+ } else {
666
+ if (target.kind !== 'workspace') throw new Error('生成器非check输出必须为 workspace')
667
+ prepareWriteTarget(context, target, { expectedType: 'file', purpose: 'generator-output' })
668
+ ensureWorkspaceOutputParent(context, target)
669
+ prepareWriteTarget(context, target, { expectedType: 'file', purpose: 'generator-output' })
670
+ }
671
+ return { ...entry, path: target.path }
672
+ })
673
+ }
674
+
675
+ function outputMetadata(target) {
676
+ if (target === null) return {}
677
+ const capability = target.outputCapability === null || target.outputCapability === undefined ? target.capability : target.outputCapability
678
+ return {
679
+ kind: target.kind,
680
+ ...(capability === null || capability === undefined ? {} : { capability }),
681
+ purpose: target.purpose,
682
+ }
683
+ }
684
+
685
+ /**
686
+ * @param options.sourcePath / outputPath 自定义夹具路径时,默认不触碰仓库 definition 资产。
687
+ * @param options.workspaceRoot 工作区根;缺省为本包所在维护根。所有输出及暂存/备份只能落在此根。
688
+ * @param options.hostDataRoot / hostCapabilities 可选的明确 Host 只读输入上下文。
689
+ * @param options.sourceKind / metaSourceKind / clientSourceKind 输入类别,默认 workspace;host 必须有明确 Host 根或 capability。
690
+ * @param options.outputKind / definitionOutputKind / roleDefinitionDirKind / clientOutputKind:仅 --check 可取 host,普通生成强制 workspace。
691
+ * @param options.definitionOutputPath 显式 definition 路径;传 null 关闭 definition 生成。
692
+ * @param options.roleDefinitionDir 显式角色产出目录;传 null 关闭角色生成(角色作者源即 sourcePath 的第二文档)。
693
+ */
694
+ export function generateRuntimeDefaults(options = {}) {
695
+ const pathContext = generatorPathContext(options)
696
+ const sourcePath = options.sourcePath === undefined ? DEFAULT_SOURCE : options.sourcePath
697
+ const outputPath = options.outputPath === undefined ? DEFAULT_OUTPUT : options.outputPath
698
+ const metaSourcePath = options.metaSourcePath === undefined ? DEFAULT_META_SOURCE : options.metaSourcePath
699
+ const check = options.check === true
700
+ const source = readGeneratorInput(pathContext, sourcePath, options, 'source')
701
+ const outputTarget = generatorOutputTarget(pathContext, outputPath, options, 'output', check)
702
+ const output = outputTarget.path
703
+ const usesRepositoryDefaults = source === DEFAULT_SOURCE && output === DEFAULT_OUTPUT
704
+ const definitionOutputValue = options.definitionOutputPath === undefined
705
+ ? (usesRepositoryDefaults ? DEFAULT_DEFINITION_OUTPUT : null)
706
+ : options.definitionOutputPath
707
+ const definitionOutputTarget = definitionOutputValue === null
708
+ ? null
709
+ : generatorOutputTarget(pathContext, definitionOutputValue, options, 'definitionOutput', check)
710
+ const definitionOutput = definitionOutputTarget === null ? null : definitionOutputTarget.path
711
+ const roleDirValue = options.roleDefinitionDir === undefined
712
+ ? (definitionOutput === null ? null : (usesRepositoryDefaults ? PRESET_ASSET_DIR : null))
713
+ : options.roleDefinitionDir
714
+ const roleDirTarget = roleDirValue === null
715
+ ? null
716
+ : generatorOutputTarget(pathContext, roleDirValue, options, 'roleDefinitionDir', check)
717
+ const roleDir = roleDirTarget === null ? null : roleDirTarget.path
718
+ const clientOptionSelected = options.clientSourcePath !== undefined || options.clientOutputPath !== undefined
719
+ const clientOutputValue = options.clientOutputPath === undefined
720
+ ? (usesRepositoryDefaults && !clientOptionSelected ? DEFAULT_CLIENT_OUTPUT : null)
721
+ : options.clientOutputPath
722
+ const clientOutputTarget = clientOutputValue === null
723
+ ? null
724
+ : generatorOutputTarget(pathContext, clientOutputValue, options, 'clientOutput', check)
725
+ const clientOutput = clientOutputTarget === null ? null : clientOutputTarget.path
726
+ let clientSource = null
727
+ if (clientOutput !== null) {
728
+ const clientSourcePath = options.clientSourcePath === undefined
729
+ ? (usesRepositoryDefaults && !clientOptionSelected ? DEFAULT_CLIENT_OUTPUT : null)
730
+ : options.clientSourcePath
731
+ if (clientSourcePath === null) throw new Error('客户端输出已启用但未提供 clientSourcePath')
732
+ clientSource = readGeneratorInput(pathContext, clientSourcePath, options, 'clientSource')
733
+ }
734
+ // 角色作者源与主预设同文件:第二文档由同一份 sourceText 切分,不再读独立文件。
735
+ const roleSource = roleDir === null ? null : source
736
+ // 先读、解析、校验并渲染,再接触输出;坏模板/缺失输入保留 last-known-good 字节。
737
+ const sourceText = readFileSync(source, 'utf8')
738
+ const rendered = renderRuntimeDefaults(sourceText)
739
+ let metaSource = null
740
+ let renderedDefinition = null
741
+ let renderedRoles = []
742
+ if (definitionOutput !== null) {
743
+ metaSource = readGeneratorInput(pathContext, metaSourcePath, options, 'metaSource')
744
+ const metaText = readFileSync(metaSource, 'utf8')
745
+ assertParses(metaText, 'preset.yml')
746
+ renderedDefinition = renderPresetDefinition(sourceText, metaText)
747
+ assertParses(renderedDefinition, 'preset-definition.generated.yml')
748
+ }
749
+ if (roleDir !== null && renderedDefinition !== null) {
750
+ const roleText = secondDocumentOf(sourceText)
751
+ renderedRoles = renderRoleDefinitions(roleText, renderedDefinition)
752
+ }
753
+ let renderedClient = null
754
+ if (clientOutput !== null) {
755
+ const clientText = readFileSync(clientSource, 'utf8')
756
+ renderedClient = renderClientFields(clientText, SETTING_DEFINITIONS)
757
+ new Script(renderedClient, { filename: clientSource })
758
+ }
759
+ const roleOutputs = renderedRoles.map((role) => roleDefinitionFile(role.roleId, roleDir))
760
+ const outputEntries = authorizeOutputEntries(pathContext, normalizedOutputEntries([
761
+ { path: output, content: rendered, label: 'generated output', ...outputMetadata(outputTarget) },
762
+ ...(definitionOutputTarget === null ? [] : [{ path: definitionOutput, content: renderedDefinition, label: 'generated preset definition', ...outputMetadata(definitionOutputTarget) }]),
763
+ ...renderedRoles.map((role, index) => ({
764
+ path: roleOutputs[index],
765
+ content: role.text,
766
+ label: 'generated role definition ' + role.roleId,
767
+ ...outputMetadata(roleDirTarget),
768
+ })),
769
+ ...(clientOutputTarget === null ? [] : [{ path: clientOutput, content: renderedClient, label: 'generated client', ...outputMetadata(clientOutputTarget) }]),
770
+ ]), check)
771
+ if (check) {
772
+ for (const entry of outputEntries) checkOutput(entry.path, entry.content, entry.label)
773
+ return { source, output, metaSource, definitionOutput, roleSource, roleOutputs, clientSource, clientOutput, rendered, renderedDefinition, renderedRoles, renderedClient, changed: false }
774
+ }
775
+ publishGeneratedOutputs(outputEntries, options.fsOps)
776
+ return { source, output, metaSource, definitionOutput, roleSource, roleOutputs, clientSource, clientOutput, rendered, renderedDefinition, renderedRoles, renderedClient, changed: true }
777
+ }
778
+
779
+ function invokedAsMain() {
780
+ if (!process.argv[1]) return false
781
+ return resolve(process.argv[1]) === resolve(fileURLToPath(import.meta.url))
782
+ }
783
+
784
+ if (invokedAsMain()) {
785
+ try {
786
+ const check = process.argv.includes('--check')
787
+ const result = generateRuntimeDefaults({ check })
788
+ process.stdout.write((check ? '[check] ' : '[generated] ') + result.output + '\n')
789
+ if (result.definitionOutput !== null) process.stdout.write((check ? '[check] ' : '[generated] ') + result.definitionOutput + '\n')
790
+ for (const roleOutput of result.roleOutputs) process.stdout.write((check ? '[check] ' : '[generated] ') + roleOutput + '\n')
791
+ if (result.clientOutput !== null) process.stdout.write((check ? '[check] ' : '[generated] ') + result.clientOutput + '\n')
792
+ } catch (error) {
793
+ process.stderr.write('[generate-runtime-defaults] ' + (error instanceof Error ? error.message : String(error)) + '\n')
794
+ process.exitCode = 1
795
+ }
796
+ }