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,294 @@
1
+ import { readFileSync, unlinkSync } from 'node:fs'
2
+ import { basename, dirname, join } from 'node:path'
3
+ import { resolveWorkspacePath, assertAllowedPath, prepareWriteTarget, validateReadTarget } from './path-policy.js'
4
+ import { validateSavePlanContract } from './save-plan-validation.js'
5
+ import { extractProbeEvidenceRefs } from './save-contract.js'
6
+ import { cwdOf, pathContextOf, unexploredMarkerOf, verifyPlanSources, verifyProbeEvidenceRef } from './save-source-verification.js'
7
+ import { errorCodeOf, errorText } from './runtime-static.js'
8
+
9
+ // 草稿白名单:save_plan 失败草稿只落在 <savePlanDir>/draft 下的 方案-/验收- 前缀 .md_mid。
10
+ // 判定只看 resolveWorkspacePath 归一化后的绝对 target.path:父目录必须等于由 savePlanDir 推导出的
11
+ // 期望草稿目录(配置改成别的落盘目录时白名单随之改变,不硬编码任何目录字面量)、文件名后缀恰为
12
+ // .md_mid;链接与真实路径逃逸仍由 prepareWriteTarget/validateReadTarget 兜底。
13
+ // 配对草稿路径由 base 经 resolveWorkspacePath 重建,禁止用字符串拼接出落盘路径。
14
+ const DRAFT_SUFFIX = '.md_mid'
15
+ const PLAN_PREFIX = '方案-'
16
+ const CHECK_PREFIX = '验收-'
17
+ const PURPOSE = 'save-artifacts'
18
+ const STATUS_PROMOTED = 'promoted'
19
+ const STATUS_SAVED_WITH_ERRORS = 'saved-with-errors'
20
+
21
+ // 仅用于白名单比较的平台归一化 key;落盘路径一律取 resolveWorkspacePath 的 target.path。
22
+ function pathKey(value) {
23
+ const normalized = String(value).replace(/\\/g, '/')
24
+ return process.platform === 'win32' ? normalized.toLowerCase() : normalized
25
+ }
26
+
27
+ // 归一化绝对路径 → 草稿 base;父目录不是期望草稿目录、后缀不符或缺 方案-/验收- 前缀时返回 null(调用方一律拒绝)。
28
+ function draftBaseOf(targetPath, expectedDraftDir) {
29
+ if (typeof expectedDraftDir !== 'string' || expectedDraftDir === '') return null
30
+ const name = basename(targetPath)
31
+ if (!pathKey(name).endsWith(DRAFT_SUFFIX)) return null
32
+ if (pathKey(dirname(targetPath)) !== pathKey(expectedDraftDir)) return null
33
+ const stem = name.slice(0, name.length - DRAFT_SUFFIX.length)
34
+ if (stem.startsWith(PLAN_PREFIX)) return stem.length === PLAN_PREFIX.length ? null : stem.slice(PLAN_PREFIX.length)
35
+ if (stem.startsWith(CHECK_PREFIX)) return stem.length === CHECK_PREFIX.length ? null : stem.slice(CHECK_PREFIX.length)
36
+ return null
37
+ }
38
+
39
+ function readText(path) {
40
+ try {
41
+ return readFileSync(path, 'utf8')
42
+ } catch (error) {
43
+ throw new Error('edit_plan_draft: 文件读取失败:' + errorText(error))
44
+ }
45
+ }
46
+
47
+ // 行级语义:只剥掉一个结尾换行参与编号,写回时原样补回,保证行号与编辑器/grep 汇报一致。
48
+ function splitLines(text) {
49
+ const hasFinalNewline = text.endsWith('\n')
50
+ const body = hasFinalNewline ? text.slice(0, -1) : text
51
+ const lines = body === '' ? (text === '' ? [] : ['']) : body.split('\n')
52
+ return { lines, hasFinalNewline }
53
+ }
54
+
55
+ function joinLines(lines, hasFinalNewline) {
56
+ if (lines.length === 0) return ''
57
+ return lines.join('\n') + (hasFinalNewline ? '\n' : '')
58
+ }
59
+
60
+ function diagnosticText(diagnostic) {
61
+ const document = diagnostic.document || 'plan/checklist'
62
+ const task = diagnostic.taskId === null || diagnostic.taskId === undefined ? '任务全局' : '任务' + diagnostic.taskId
63
+ const position = Number.isInteger(diagnostic.line) && diagnostic.line > 0 ? ';位置:第 ' + diagnostic.line + ' 行' : ''
64
+ return document + ' ' + task + ' 字段「' + String(diagnostic.field || '') + '」:' + String(diagnostic.message || '') + position
65
+ }
66
+
67
+ function savedWithErrors(paths, lineCount, diagnostics, error) {
68
+ return { status: STATUS_SAVED_WITH_ERRORS, paths, lineCount, diagnostics, error }
69
+ }
70
+
71
+ // 三种操作:{ line, text } 替换、{ line, drop: true } 真删、{ line, insert } 行前插入。
72
+ // 同一批按行号倒序排序后应用;任一编辑非法或越界即整批不生效(调用方不会写入任何内容)。
73
+ function applyEdits(lines, edits) {
74
+ const planned = edits.map((edit, index) => {
75
+ const refuse = '(整批不生效,未写入任何修改)'
76
+ if (edit === null || typeof edit !== 'object' || Array.isArray(edit)) throw new Error('edit_plan_draft: edits[' + index + '] 必须是对象' + refuse)
77
+ const line = edit.line
78
+ if (!Number.isInteger(line) || line < 1) throw new Error('edit_plan_draft: edits[' + index + '].line 必须是从 1 开始的行号' + refuse)
79
+ if (line > lines.length) throw new Error('edit_plan_draft: edits[' + index + '].line=' + line + ' 越界:草稿当前共 ' + lines.length + ' 行' + refuse)
80
+ if (edit.drop !== undefined) {
81
+ if (edit.drop !== true) throw new Error('edit_plan_draft: edits[' + index + '].drop 只能为 true' + refuse)
82
+ if (edit.text !== undefined || edit.insert !== undefined) throw new Error('edit_plan_draft: edits[' + index + '] 的 drop 不能与 text/insert 同时出现' + refuse)
83
+ return { line, kind: 'drop' }
84
+ }
85
+ if (edit.insert !== undefined) {
86
+ if (typeof edit.insert !== 'string') throw new Error('edit_plan_draft: edits[' + index + '].insert 必须是字符串' + refuse)
87
+ if (edit.text !== undefined) throw new Error('edit_plan_draft: edits[' + index + '] 的 insert 不能与 text 同时出现' + refuse)
88
+ return { line, kind: 'insert', text: edit.insert }
89
+ }
90
+ if (typeof edit.text === 'string') return { line, kind: 'replace', text: edit.text }
91
+ throw new Error('edit_plan_draft: edits[' + index + '] 缺少操作:需 text 替换、drop: true 真删或 insert 行前插入' + refuse)
92
+ })
93
+ const ordered = planned.slice().sort((left, right) => right.line - left.line)
94
+ const next = lines.slice()
95
+ for (const edit of ordered) {
96
+ const index = edit.line - 1
97
+ if (edit.kind === 'drop') next.splice(index, 1)
98
+ else if (edit.kind === 'insert') next.splice(index, 0, edit.text)
99
+ else next[index] = edit.text
100
+ }
101
+ return next
102
+ }
103
+
104
+ // 删除草稿前的授权:与 save-persistence 内部 authorizeFile 同形(resolveWorkspacePath + prepareWriteTarget)。
105
+ function authorizeDraftFile(pathContext, draftPath) {
106
+ const target = resolveWorkspacePath(pathContext, draftPath, { purpose: PURPOSE })
107
+ return prepareWriteTarget(pathContext, target, { expectedType: 'file', purpose: PURPOSE })
108
+ }
109
+
110
+ export function createPlanDraftToolFactories({ savePlanDir, atomicCommit, atomicReplace, getPathContext }) {
111
+ // 期望草稿目录:与 save_plan 落草稿的 <dir>/draft 同源,由可配置的 savePlanDir 推导成归一化绝对路径。
112
+ // 推导失败(例如 savePlanDir 越出工作区)返回 null,调用方按非白名单一律拒绝,绝不回退硬编码目录。
113
+ function expectedDraftDirOf(pathContext) {
114
+ try {
115
+ return resolveWorkspacePath(pathContext, join(savePlanDir, 'draft'), { purpose: PURPOSE }).path
116
+ } catch (error) {
117
+ return null
118
+ }
119
+ }
120
+
121
+ // 报文里的草稿目录:与 save_plan 报错里给出的相对路径同形,只用于提示文案,不参与白名单判定。
122
+ const draftDirLabel = join(savePlanDir, 'draft').replace(/\\/g, '/')
123
+
124
+ // 写回草稿用覆盖语义 atomicReplace(dir, files, …);转正用 atomicCommit(dir, base, files, …)。
125
+ // 两者签名不同、不得互替;转正的 dir 必须是 savePlanDir 根,绝不能是 draft 子目录。
126
+ function writeDraft(dir, name, content, pathContext) {
127
+ if (typeof atomicReplace !== 'function') throw new Error('edit_plan_draft: 缺少 atomicReplace 依赖,无法写回草稿(未写入任何修改)')
128
+ atomicReplace(dir, [{ name, content }], undefined, { pathContext, purpose: PURPOSE })
129
+ }
130
+
131
+ function defineEditPlanDraft() {
132
+ return {
133
+ name: 'edit_plan_draft',
134
+ description: '修复 save_plan 报错后生成的 .md_mid 中间文档(仅少量错误时使用):行级增删改后先检查方案中的方括号包裹的未探查/待确认标记,命中即在写回前整批拒绝且不写;无标记时写回并自动重跑 save_plan 全套校验,通过即转正为正式工件并返回路径,写回后的合同、源或证据核实不通过则保留修改并返回带行号的诊断,可继续改;派遣摘要超限时 save_plan 不生成草稿,应改写更短的方案重新调用 save_plan。',
135
+ parameters: {
136
+ type: 'object',
137
+ properties: {
138
+ path: {
139
+ type: 'string',
140
+ description: '必须是 save_plan 报错里给出的 ' + draftDirLabel + '/*.md_mid(方案-<base>.md_mid 或 验收-<base>.md_mid);其它路径(' + savePlanDir + ' 根、draft 以外的目录、非 .md_mid 后缀)一律拒绝,且不会创建草稿',
141
+ },
142
+ edits: {
143
+ type: 'array',
144
+ description: '行级编辑列表:行号以文件当前内容为准(1 至当前行数),同批按行号倒序自动应用;三种操作为 { line, text } 替换该行、{ line, drop: true } 真删该行、{ line, insert } 在该行之前插入一行(insert 为新行整行文本);任一越界或基准不合法则整批不生效;传空数组 [] 也是合法输入,语义是不做任何修改、直接重跑全套检测,可用于上次因落盘等非内容问题失败后重试转正',
145
+ items: {
146
+ type: 'object',
147
+ properties: {
148
+ line: { type: 'integer', description: '从 1 开始的行号,以草稿当前内容为准;越界即整批不生效' },
149
+ text: { type: 'string', description: '替换后的整行文本(与 drop/insert 互斥)' },
150
+ drop: { type: 'boolean', description: '为 true 时真删该行(与 text/insert 互斥)' },
151
+ insert: { type: 'string', description: '在该行之前插入的整行文本(与 text/drop 互斥)' },
152
+ },
153
+ required: ['line'],
154
+ additionalProperties: false,
155
+ },
156
+ },
157
+ },
158
+ required: ['path', 'edits'],
159
+ additionalProperties: false,
160
+ },
161
+ output: {
162
+ schema: {
163
+ type: 'object',
164
+ properties: {
165
+ status: { type: 'string', enum: [STATUS_PROMOTED, STATUS_SAVED_WITH_ERRORS], description: 'promoted=全套校验通过并已转正为正式 .md;saved-with-errors=修改已保存但未通过校验,草稿保留可继续改' },
166
+ paths: { type: 'array', items: { type: 'string' }, description: 'promoted 时为转正后的 方案-/验收- 正式工件绝对路径;saved-with-errors 时为当前草稿路径' },
167
+ lineCount: { type: 'integer', description: '写回后草稿的行数(以文件当前内容为准)' },
168
+ diagnostics: { type: 'array', items: { type: 'string' }, description: '逐条诊断,能定位时带「位置:第 N 行」' },
169
+ error: { type: 'string', description: '未通过校验或转正异常时的说明;promoted 且无异常时为空串,删草稿失败时说明残留' },
170
+ },
171
+ required: ['status', 'paths', 'lineCount', 'diagnostics', 'error'],
172
+ additionalProperties: false,
173
+ },
174
+ // 结果 content 必须恰为一个 text ContentBlock、正文是返回值整体 JSON(裸字符串会崩宿主)。
175
+ render(_args, value) {
176
+ return [{ type: 'text', text: JSON.stringify(value) }]
177
+ },
178
+ },
179
+ timeoutMs: 60000,
180
+ async execute(args, exec) {
181
+ if (args === null || typeof args !== 'object' || Array.isArray(args)) throw new Error('edit_plan_draft: 参数必须是对象(未写入任何修改)')
182
+ if (typeof args.path !== 'string' || args.path.trim() === '') throw new Error('edit_plan_draft: 缺少 path 参数;path 必须是 save_plan 报错里给出的 ' + draftDirLabel + '/*.md_mid(未写入任何修改)')
183
+ if (!Array.isArray(args.edits)) throw new Error('edit_plan_draft: edits 必须是数组(未写入任何修改)')
184
+ const cwd = cwdOf(exec)
185
+ if (cwd === '') throw new Error('edit_plan_draft: 会话缺少工作区路径,无法定位草稿(未写入任何修改)')
186
+ const pathContext = pathContextOf(cwd, getPathContext)
187
+ // 白名单判定基于归一化后的 target.path;其它路径一律拒绝且不会创建草稿。
188
+ const requested = resolveWorkspacePath(pathContext, args.path.trim(), { purpose: PURPOSE })
189
+ const expectedDraftDir = expectedDraftDirOf(pathContext)
190
+ const base = draftBaseOf(requested.path, expectedDraftDir)
191
+ if (base === null) throw new Error('edit_plan_draft: path 必须是 save_plan 报错里给出的 ' + draftDirLabel + '/ 下的 方案-<base>.md_mid 或 验收-<base>.md_mid(收到 ' + requested.path + ');其它路径一律拒绝且不会创建草稿')
192
+ let currentTarget
193
+ try {
194
+ currentTarget = validateReadTarget(pathContext, requested, { expectedType: 'file', purpose: PURPOSE })
195
+ } catch (error) {
196
+ if (errorCodeOf(error) === 'TARGET_MISSING') return savedWithErrors([requested.path], 0, [], 'edit_plan_draft: 草稿不存在:' + requested.path + '(可能已转正为正式工件,或已被清理;如需重建请重新调用 save_plan)')
197
+ throw new Error('edit_plan_draft: 草稿无法读取:' + errorText(error))
198
+ }
199
+ const draftName = basename(currentTarget.path)
200
+ const isPlanDraft = draftName.startsWith(PLAN_PREFIX)
201
+ const original = splitLines(readText(currentTarget.realPath))
202
+ const editedLines = applyEdits(original.lines, args.edits)
203
+ const editedText = joinLines(editedLines, original.hasFinalNewline)
204
+ const lineCount = splitLines(editedText).lines.length
205
+ const pairedName = isPlanDraft ? CHECK_PREFIX + base + DRAFT_SUFFIX : PLAN_PREFIX + base + DRAFT_SUFFIX
206
+ // 配对草稿路径按 base 经 resolveWorkspacePath 重建并重新授权,不做字符串拼接。
207
+ const pairedDeclared = resolveWorkspacePath(pathContext, join(savePlanDir, 'draft', pairedName), { purpose: PURPOSE })
208
+ if (draftBaseOf(pairedDeclared.path, expectedDraftDir) === null) throw new Error('edit_plan_draft: 无法重建配对草稿路径:' + pairedDeclared.path + '(应为 ' + draftDirLabel + '/ 下的 .md_mid)')
209
+ let pairedTarget = null
210
+ let pairedText = ''
211
+ try {
212
+ pairedTarget = validateReadTarget(pathContext, pairedDeclared, { expectedType: 'file', purpose: PURPOSE })
213
+ } catch (error) {
214
+ if (errorCodeOf(error) !== 'TARGET_MISSING') throw new Error('edit_plan_draft: 配对草稿无法读取:' + errorText(error), { cause: error })
215
+ }
216
+ if (pairedTarget !== null) {
217
+ try {
218
+ pairedText = readText(pairedTarget.realPath)
219
+ } catch (error) {
220
+ throw new Error('edit_plan_draft: 配对草稿无法读取:' + errorText(error), { cause: error })
221
+ }
222
+ }
223
+ const planText = isPlanDraft ? editedText : pairedText
224
+ const checklistText = isPlanDraft ? pairedText : editedText
225
+ // 检测顺序与 save_plan 完全一致:未探查标记 → 合同校验 → 源核实 → 证据核实。
226
+ // 命中标记即整批拒绝且不写回草稿:否则可用编辑草稿旁路 save_plan 的未探查拒绝。
227
+ const unexploredMarker = unexploredMarkerOf(planText)
228
+ if (unexploredMarker !== null) {
229
+ const markerLine = planText.slice(0, planText.indexOf(unexploredMarker)).split('\n').length
230
+ return savedWithErrors([currentTarget.path], original.lines.length, ['位置:第 ' + markerLine + ' 行 方案中含未探查/待确认标记「' + unexploredMarker + '」'], 'edit_plan_draft: 方案中包含方括号包裹的未探查/待确认标记。请先申请追加预算继续探查,确认所有项均已探查核实后再调用 save_plan(本次修改未写回草稿)')
231
+ }
232
+ // 通过读取和标记前置检查后先写回再校验;合同等不通过时仍可继续编辑。
233
+ try {
234
+ writeDraft(dirname(currentTarget.path), draftName, editedText, pathContext)
235
+ } catch (error) {
236
+ throw new Error('edit_plan_draft: 草稿写回失败:' + errorText(error))
237
+ }
238
+ if (pairedTarget === null) {
239
+ return savedWithErrors([currentTarget.path], lineCount, [], 'edit_plan_draft: 修改已保存,但配对草稿不存在:' + pairedDeclared.path + '(可能已转正或已清理;请重新调用 save_plan 生成成对草稿)')
240
+ }
241
+ // 全套检测与 save_plan 同源:合同校验(含派遣摘要上限)→ 源核实 → 证据核实。
242
+ const contract = validateSavePlanContract(planText, checklistText)
243
+ if (!contract.ok) {
244
+ const limitNote = contract.limitExceeded === true ? '\n(派遣摘要超限:save_plan 不会为此生成草稿,应改写更短的方案后重新调用 save_plan)' : ''
245
+ return savedWithErrors([currentTarget.path], lineCount, contract.diagnostics.map(diagnosticText), contract.error + limitNote)
246
+ }
247
+ let sourceState
248
+ try {
249
+ sourceState = verifyPlanSources(contract.summary, pathContext)
250
+ } catch (error) {
251
+ return savedWithErrors([currentTarget.path], lineCount, [errorText(error)], 'edit_plan_draft: 修改已保存,但源核实失败:' + errorText(error))
252
+ }
253
+ try {
254
+ for (const ref of extractProbeEvidenceRefs(planText)) verifyProbeEvidenceRef(cwd, ref, sourceState, pathContext, '')
255
+ } catch (error) {
256
+ return savedWithErrors([currentTarget.path], lineCount, [errorText(error)], 'edit_plan_draft: 修改已保存,但证据核实失败:' + errorText(error))
257
+ }
258
+ const rootTarget = assertAllowedPath(pathContext, resolveWorkspacePath(pathContext, savePlanDir, { purpose: PURPOSE }))
259
+ const planFile = join(rootTarget.path, PLAN_PREFIX + base + '.md')
260
+ const checkFile = join(rootTarget.path, CHECK_PREFIX + base + '.md')
261
+ // 转正:dir 是 savePlanDir 根,文件名 方案-<base>.md 与 验收-<base>.md。
262
+ if (typeof atomicCommit !== 'function') return savedWithErrors([currentTarget.path], lineCount, [], 'edit_plan_draft: 缺少 atomicCommit 依赖,无法转正(草稿保留)')
263
+ try {
264
+ atomicCommit(rootTarget.path, base, [
265
+ { name: PLAN_PREFIX + base + '.md', content: planText },
266
+ { name: CHECK_PREFIX + base + '.md', content: checklistText },
267
+ ], undefined, { pathContext, purpose: PURPOSE })
268
+ } catch (error) {
269
+ return savedWithErrors([currentTarget.path], lineCount, [errorText(error)], 'edit_plan_draft: 校验已通过但转正落盘失败:' + errorText(error) + '(草稿保留;转正只创建不覆盖,若同 base 的正式工件已存在则重试必然失败——请先确认 方案-<base>.md / 验收-<base>.md 是否已存在,已存在说明本次草稿属残留、可手动删除,不要盲目重试)')
270
+ }
271
+ // 删除草稿:先 authorizeFile 授权再 unlink;删失败不回滚已转正工件,只在返回值说明残留。
272
+ const residues = []
273
+ for (const draftPath of [currentTarget.path, pairedTarget.path]) {
274
+ try {
275
+ authorizeDraftFile(pathContext, draftPath)
276
+ unlinkSync(draftPath)
277
+ } catch (error) {
278
+ const code = errorCodeOf(error)
279
+ if (code !== 'TARGET_MISSING' && code !== 'ENOENT') residues.push(draftPath + '(' + errorText(error) + ')')
280
+ }
281
+ }
282
+ return {
283
+ status: STATUS_PROMOTED,
284
+ paths: [planFile, checkFile],
285
+ lineCount,
286
+ diagnostics: [],
287
+ error: residues.length === 0 ? '' : 'edit_plan_draft: 已转正,但草稿删除失败(残留:' + residues.join(';') + ';可手动删除残留 .md_mid)',
288
+ }
289
+ },
290
+ }
291
+ }
292
+
293
+ return { defineEditPlanDraft }
294
+ }
@@ -0,0 +1,136 @@
1
+ // dsh-extra-plan planner budget 辅助函数。
2
+ // 纯 message、计数与预算策略函数;FREE_TOOLS 定义在 lib/gate-decisions.js(根入口 import 后透传)。
3
+
4
+ import { createUserMessage } from '@deepseek-ai/dsh-llm'
5
+ import { DEFAULT_EXPLORE_BUDGET } from './preset-defaults.generated.js'
6
+
7
+ export { DEFAULT_EXPLORE_BUDGET }
8
+
9
+ // 会话内 tool/call 成功配对计数(排除 skipNames,如 save_plan)——探查硬上限判据。
10
+ // 直呼 = tool/call + tool/result(ok) 配对;run_code 子调用由实例上限单独约束。
11
+ export function toolCallCount(events, skipNames) {
12
+ if (!Array.isArray(events)) return 0
13
+ const okCalls = new Set()
14
+ for (const e of events) {
15
+ if (e === null || typeof e !== 'object') continue
16
+ if (e.type !== 'tool/result') continue
17
+ const d = e.data
18
+ if (d === null || typeof d !== 'object') continue
19
+ if (d.error !== undefined && d.error !== null) continue
20
+ const message = d.message
21
+ if (message === null || typeof message !== 'object' || !Array.isArray(message.content)) continue
22
+ // 当前 message 在顶层提供 envelope;嵌套 tool-result content 仍保持兼容。
23
+ if (typeof message.toolCallId === 'string') {
24
+ if (message.isError !== true) okCalls.add(message.toolCallId)
25
+ continue
26
+ }
27
+ for (const outer of message.content) {
28
+ if (outer !== null && typeof outer === 'object' && outer.type === 'tool-result' && typeof outer.toolCallId === 'string' && outer.isError !== true) okCalls.add(outer.toolCallId)
29
+ }
30
+ }
31
+ let count = 0
32
+ for (const e of events) {
33
+ if (e === null || typeof e !== 'object' || e.type !== 'tool/call') continue
34
+ const d = e.data
35
+ if (d === null || typeof d !== 'object' || typeof d.name !== 'string') continue
36
+ if (skipNames !== undefined && skipNames.has(d.name)) continue
37
+ if (typeof d.callId === 'string' && okCalls.has(d.callId)) count += 1
38
+ }
39
+ return count
40
+ }
41
+
42
+ // 反向查找最近一条主会话 user/agent-message 锚点的下标;找不到返回 -1。
43
+ function lastMainSessionAnchorIndex(events) {
44
+ if (!Array.isArray(events)) return -1
45
+ for (let i = events.length - 1; i >= 0; i -= 1) {
46
+ const e = events[i]
47
+ if (e === null || typeof e !== 'object' || e.type !== 'user/message') continue
48
+ const d = e.data
49
+ const kind = d !== null && typeof d === 'object' && d.source !== null && typeof d.source === 'object' ? d.source.kind : ''
50
+ if (kind === 'user' || kind === 'agent-message') return i
51
+ }
52
+ return -1
53
+ }
54
+
55
+ // 自最近一条主会话 user/agent-message 锚点之后计数;无锚点时与 toolCallCount 同口径。
56
+ export function toolCallsSinceUser(events, skipNames) {
57
+ if (!Array.isArray(events)) return 0
58
+ const anchor = lastMainSessionAnchorIndex(events)
59
+ if (anchor === -1) return toolCallCount(events, skipNames)
60
+ return toolCallCount(events.slice(anchor + 1), skipNames)
61
+ }
62
+
63
+ function appendSuffixBlock(message, text) {
64
+ if (text === '') return message
65
+ if (message === null || typeof message !== 'object') return message
66
+ const src = message.source
67
+ if (src === null || typeof src !== 'object' || (src.kind !== 'user' && src.kind !== 'agent-message')) return message
68
+ if (!Array.isArray(message.content)) return message
69
+ let target = -1
70
+ for (let i = 0; i < message.content.length; i += 1) {
71
+ const block = message.content[i]
72
+ if (block === null || typeof block !== 'object' || block.type !== 'text' || typeof block.text !== 'string') continue
73
+ if (block.text.indexOf(text) !== -1) return message
74
+ if (target === -1) target = i
75
+ }
76
+ if (target === -1) return message
77
+ const next = [...message.content]
78
+ next[target] = { type: 'text', text: next[target].text + '\n' + text }
79
+ return { ...message, content: next }
80
+ }
81
+
82
+ export function withPlannerPromptSuffix(message, suffix) {
83
+ const r = appendSuffixBlock(message, suffix)
84
+ if (!Array.isArray(r.content) || r.content.length <= 1) return r
85
+ const first = r.content[0]
86
+ if (first === null || typeof first !== 'object' || first.type !== 'text' || typeof first.text !== 'string') return r
87
+ if (first.text.endsWith('\n')) return r
88
+ return { ...r, content: [{ ...first, text: first.text + '\n' }, ...r.content.slice(1)] }
89
+ }
90
+
91
+ // 阈值固定 3(不进配置文件)。
92
+ export const BUDGET_REMINDER_THRESHOLD = 3
93
+
94
+ export function budgetNoticeText(budget) {
95
+ return `本轮探查预算上限为 ${budget} 次工具调用。探查时 ≥ 2 个独立方向自行 read/glob/grep 分批核对;缺信息时输出「申请继续探查:<待查项> — <原因>」交主会话委派探查者。预算耗尽时输出「申请继续探查:<待查项> — <原因>」,主会话将探查待查项并转达线索文件路径,你读取线索继续工作。探查完成后直接调用 save_plan 落盘(系统会自动检测未探查项)`
96
+ }
97
+
98
+ export function withBudgetNotice(message, notice) { return appendSuffixBlock(message, notice) }
99
+
100
+ export function budgetReminderText(remaining, budget, threshold) {
101
+ if (budget <= threshold) return ''
102
+ if (remaining <= 0 || remaining > threshold) return ''
103
+ return `本轮探查预算还剩 ${remaining} 次`
104
+ }
105
+
106
+ // source 形状(v4 生产者自有 kind 要求):宿主行准入(dsh-session-format-v3-to-v4 包内
107
+ // lib/index.js 的 source 校验)要求 source 为非空字符串 kind,并明确排除旧兜底值 plugin ——
108
+ // 旧包裹形状(kind 取旧兜底值 plugin + plugin 包名字段)必被拒收(SessionFormatError: format v4
109
+ // message requires a producer-owned source kind)——即“消息必须提供生产者自有的 source kind”,并使会话当场终止;本插件按 V3 迁移惯例
110
+ // 自造 kind `plugin:<包名>`,无需任何 producer 注册(官方 dsh-tool-jobs 同法自造 tool-jobs)。
111
+ export function budgetReminderMessage(reminder) {
112
+ return createUserMessage({ source: { kind: 'plugin:dsh-extra-plan' }, content: [{ type: 'text', text: reminder }] })
113
+ }
114
+
115
+ export function budgetReminderSent(events, marker) {
116
+ if (!Array.isArray(events)) return false
117
+ const anchor = lastMainSessionAnchorIndex(events)
118
+ for (let i = anchor + 1; i < events.length; i += 1) {
119
+ const e = events[i]
120
+ if (e === null || typeof e !== 'object' || e.type !== 'user/message') continue
121
+ const d = e.data
122
+ if (d === null || typeof d !== 'object' || !Array.isArray(d.content)) continue
123
+ for (const block of d.content) {
124
+ if (block !== null && typeof block === 'object' && block.type === 'text' && typeof block.text === 'string' && block.text.indexOf(marker) !== -1) return true
125
+ }
126
+ }
127
+ return false
128
+ }
129
+
130
+ export function budgetExhaustedReason(used, budget) {
131
+ return `探查预算已耗尽(本轮已用 ${used}/${budget}):输出「申请继续探查:<待查项> — <原因>」。主会话将探查待查项并转达线索文件路径,你读取线索继续工作。探查完成则直接调用 save_plan 落盘。`
132
+ }
133
+
134
+ export function budgetExceeded(used, budget) {
135
+ return used > budget
136
+ }
@@ -0,0 +1,17 @@
1
+ // GENERATED FILE - DO NOT EDIT.
2
+ // Generated by scripts/generate-runtime-defaults.mjs.
3
+ export const DEFAULT_SETTINGS = Object.freeze({
4
+ "anchoredBootstrap": true,
5
+ "creativeMode": false,
6
+ "webFetch": false,
7
+ "toolPresentationMode": "native",
8
+ "runcodeCatchGate": false,
9
+ "crossProviderPlannerModel": false,
10
+ "plannerModel": "deepseek-v4-pro",
11
+ "plannerPromptSuffix": "你的深度思考部分需要以\"好了,现在我以全局视角来看待这个问题\"开头",
12
+ "exploreBudget": 18,
13
+ "otherAgentModel": "",
14
+ "reviewerUsesPlannerModel": false
15
+ })
16
+ export const DEFAULT_EXPLORE_BUDGET = DEFAULT_SETTINGS.exploreBudget
17
+ export const DEFAULT_PLANNER_PROMPT_SUFFIX = DEFAULT_SETTINGS.plannerPromptSuffix
@@ -0,0 +1,3 @@
1
+ // 稳定 facade:维持既有消费者导入路径,内部合同与 YAML 纯职责分离。
2
+ export * from './settings-contract.js'
3
+ export * from './preset-yaml.js'