dsh-project-flow 0.9.3 → 0.10.1

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 (70) hide show
  1. package/CHANGELOG.md +197 -12
  2. package/README.md +25 -0
  3. package/checks/assertion.mjs +104 -0
  4. package/checks/command.mjs +416 -0
  5. package/checks/requirement.mjs +91 -0
  6. package/commands/slash.mjs +754 -0
  7. package/commands/steer.mjs +43 -0
  8. package/config/settings.mjs +217 -0
  9. package/docs/FEATURES.md +9 -6
  10. package/docs/anchors/file-whitelist.md +1 -1
  11. package/http/routes.mjs +252 -0
  12. package/index.js +173 -8612
  13. package/issues/issue.mjs +322 -0
  14. package/package.json +16 -1
  15. package/persistence/lock.mjs +67 -0
  16. package/persistence/log.mjs +43 -0
  17. package/persistence/recovery.mjs +118 -0
  18. package/persistence/state.mjs +202 -0
  19. package/pricing/estimate.mjs +72 -0
  20. package/prompts/rules.mjs +192 -0
  21. package/rollback/ledger.mjs +237 -0
  22. package/runner/pipeline.mjs +1190 -0
  23. package/runner/stage.mjs +370 -0
  24. package/runner/tools/context.mjs +64 -0
  25. package/runner/tools/decorate-cost.mjs +49 -0
  26. package/runner/tools/doctor.mjs +59 -0
  27. package/runner/tools/estimate.mjs +63 -0
  28. package/runner/tools/execute-run.mjs +255 -0
  29. package/runner/tools/models.mjs +55 -0
  30. package/runner/tools/resume.mjs +136 -0
  31. package/runner/tools/rollback.mjs +291 -0
  32. package/runner/tools/run.mjs +262 -0
  33. package/runner/tools/set.mjs +65 -0
  34. package/runner/tools/snapshots.mjs +83 -0
  35. package/runner/tools/status.mjs +70 -0
  36. package/runner/tools.mjs +94 -0
  37. package/shared/constants.mjs +273 -0
  38. package/shared/tool.mjs +32 -0
  39. package/shared/util.mjs +231 -0
  40. package/snapshot/repo.mjs +452 -0
  41. package/state/registry.mjs +40 -0
  42. package/tests/aesthetic.test.mjs +20 -12
  43. package/tests/apply-wiring.test.mjs +172 -0
  44. package/tests/assertions-e2e.mjs +2 -1
  45. package/tests/atomic-write.test.mjs +129 -0
  46. package/tests/client-bundle.test.mjs +3 -3
  47. package/tests/command-whitelist.test.mjs +135 -0
  48. package/tests/contract.test.mjs +2 -2
  49. package/tests/desktop.test.mjs +2 -2
  50. package/tests/domains.test.mjs +10 -7
  51. package/tests/e2e.mjs +2 -1
  52. package/tests/extra-phase.test.mjs +2 -2
  53. package/tests/feedback.test.mjs +2 -1
  54. package/tests/flow-gate.test.mjs +16 -56
  55. package/tests/issues-e2e.mjs +2 -1
  56. package/tests/panel-independence.test.mjs +2 -2
  57. package/tests/panel-report.test.mjs +2 -2
  58. package/tests/paths.mjs +70 -1
  59. package/tests/preview-path.test.mjs +2 -1
  60. package/tests/qa-assertions.test.mjs +10 -3
  61. package/tests/run-all.mjs +5 -0
  62. package/tests/snapshot-core.test.mjs +234 -0
  63. package/tests/stage-model.test.mjs +2 -2
  64. package/tests/stop-resume.test.mjs +7 -2
  65. package/tests/watch-root.test.mjs +2 -1
  66. package/ui/prompt.mjs +101 -0
  67. package/workspace/models.mjs +111 -0
  68. package/workspace/panel.mjs +359 -0
  69. package/workspace/paths.mjs +393 -0
  70. package/workspace/resume.mjs +107 -0
@@ -0,0 +1,370 @@
1
+ /**
2
+ * 单阶执行:开子会话、合并信号、超时、重试、把结果压成一段文字。
3
+ */
4
+ import { phaseReadKeys, readArtifact } from '../persistence/state.mjs'
5
+ import { ARTIFACT, DIFF_LIMIT_CHARS, LOG_TAIL_CHARS, STAGE_IO, STAGE_LABEL } from '../shared/constants.mjs'
6
+ import { messageOf, sleep, textOf } from '../shared/util.mjs'
7
+ import { snapshotCommand } from '../snapshot/repo.mjs'
8
+
9
+ export function subagentsOf(ctx) {
10
+ const usable = candidate => (candidate?.startActivation === undefined ? undefined : candidate)
11
+ try {
12
+ const own = usable(ctx?.subagents)
13
+ if (own !== undefined) return own
14
+ } catch {
15
+ // The plugin fiber was disposed by a reload; fall through to the root.
16
+ }
17
+ try {
18
+ const viaRoot = usable(ctx?.root?.subagents)
19
+ if (viaRoot !== undefined) return viaRoot
20
+ } catch {
21
+ // The root cannot resolve it either; report that below.
22
+ }
23
+ throw new Error('subagents 服务不可用:宿主已重载或会话已结束,请用 project_resume 从断点接着跑')
24
+ }
25
+
26
+ export async function runStage(ctx, options) {
27
+ const {
28
+ provider, llmProvider = '', model, label, prompt, promptParts, parent, signal, cwd,
29
+ retries = 0, retryDelayMs = 0, timeoutMs = 0, onAttempt, onFail, onHeartbeat, onBegin,
30
+ } = options
31
+ const notes = []
32
+
33
+ // 先把「这一阶是谁在跑」告诉守护器:它据此切静默窗口、记模型费率。
34
+ // 放在最前面而不是放进 attemptOnce,因为重试时阶段和模型都没变,
35
+ // 每试一次都报一遍只会把账单切碎。
36
+ try {
37
+ onBegin?.()
38
+ } catch {
39
+ // 记账失败不能让这一阶跑不起来
40
+ }
41
+
42
+ // prompt 可以是纯文本,也可以是一组内容块(文本 + 图片)。
43
+ // 质检要真的看见渲染结果,光靠文字描述评的不是那个东西。
44
+ const content = Array.isArray(promptParts) && promptParts.length > 0
45
+ ? promptParts
46
+ : [{ type: 'text', text: prompt }]
47
+
48
+ const attemptOnce = async () => {
49
+ const deadline = stageDeadline(signal, timeoutMs)
50
+ const start = async route => subagentsOf(ctx).startActivation({
51
+ provider: route.provider,
52
+ label,
53
+ prompt: content,
54
+ parent,
55
+ signal: deadline.signal,
56
+ delivery: 'caller',
57
+ ...(cwd === undefined ? {} : { cwd }),
58
+ // 这里要传两样东西,少一样就选不中:
59
+ // provider —— LLM 路由(workbuddy / qwen-token-plan / deepseek-official…)
60
+ // model —— 该路由下的模型名
61
+ // 只传 model 的话,DSH 会拿父路由去找这个名字;workbuddy 的模型就永远
62
+ // 报「has no configured model」,明明 `llm.listModels('workbuddy')` 里列得好好的。
63
+ // 模型留空仍表示不覆盖父路由(继承主对话)。
64
+ ...(() => {
65
+ const agentOptions = {
66
+ ...(route.llmProvider === undefined || route.llmProvider === '' ? {} : { provider: route.llmProvider }),
67
+ ...(route.model === '' ? {} : { model: route.model }),
68
+ }
69
+ return Object.keys(agentOptions).length === 0 ? {} : { agentOptions }
70
+ })(),
71
+ })
72
+
73
+ /**
74
+ * 把子会话的内部动静接到守护器上。
75
+ *
76
+ * 缺陷背景:以前只有「每阶结束」才 beat 一次心跳,一阶跑一小时,
77
+ * 中间那一个小时在活性探针眼里跟挂死没区别。实测踩过——实施子会话一直在
78
+ * 吐 token、一直在写渲染图(260k token / 114 步),却被连续 900 秒无心跳
79
+ * 判成 FAULT_SILENT_HANG 掐掉。
80
+ *
81
+ * 接入点选在子会话自己的 session/event 上:那是它每出一步都会响的地方,
82
+ * 文本增量、工具调用、工具结果都算。真正的静默是「连一个事件都不再有了」,
83
+ * 这一点只有接到会话流上才看得出来。
84
+ *
85
+ * 非本地的 activation(外部后端)没有 session 可接,静默窗口还是老规矩
86
+ * 按「每阶结束」算——那种情况下人也确实没别的信号可看。
87
+ */
88
+ const attachHeartbeat = activation => {
89
+ if (onHeartbeat === undefined) return () => {}
90
+ const child = activation?.kind === 'local' ? activation.handle?.agent : undefined
91
+ if (child?.ctx?.on === undefined) return () => {}
92
+ const session = child.session
93
+ let off
94
+ try {
95
+ off = child.ctx.on('session/event', eventSession => {
96
+ // 只认这个孩子自己的事件:ctx.on 挂在整个 agent 的上下文上,
97
+ // 不判归属的话,旁边随便谁动一下都会把心跳顶起来。
98
+ if (eventSession !== undefined && eventSession !== session) return
99
+ onHeartbeat()
100
+ })
101
+ } catch {
102
+ return () => {}
103
+ }
104
+ return () => {
105
+ try {
106
+ off?.()
107
+ } catch {
108
+ // 摘监听失败不能影响主流程收尾
109
+ }
110
+ }
111
+ }
112
+
113
+ /**
114
+ * 等一个已经起来的 activation 结束,并且无论成败都收掉它。
115
+ * 单独抽出来是因为下面可能连着起两次(回退),收尾逻辑不能抄两遍。
116
+ */
117
+ const settle = async activation => {
118
+ const detach = attachHeartbeat(activation)
119
+ let result
120
+ try {
121
+ result = await activation.result
122
+ } finally {
123
+ detach()
124
+ try {
125
+ await activation.dispose()
126
+ } catch {
127
+ // teardown failure does not change the captured result
128
+ }
129
+ }
130
+ const timedOut = deadline.timedOut()
131
+ // diagnostic 有时候是空的:不同 stopReason 下 DSH 把原因放在
132
+ // result.error / result.reason 里。只读 diagnostic 会得到一句
133
+ // 「直接报错退出,没给原因」,等于什么都没说。
134
+ const reason = result.diagnostic
135
+ ?? (typeof result.error === 'string' ? result.error : result.error?.message)
136
+ ?? (typeof result.reason === 'string' ? result.reason : undefined)
137
+ return {
138
+ stopReason: timedOut ? 'timeout' : result.stopReason,
139
+ diagnostic: timedOut
140
+ ? `${label}:超过 ${Math.round(timeoutMs / 1000)} 秒仍未结束,已取消`
141
+ : reason,
142
+ text: textOf(result.output),
143
+ }
144
+ }
145
+
146
+ // 依次试几条路由:配置里写的 → 继承主对话 → DSH 内置 spawn。
147
+ // 这层兜底是为了让「模型名写错」或「换了 subagent 后端」不至于把整条流水掐死。
148
+ const routes = [{ provider, llmProvider, model }]
149
+ if (model !== '' || llmProvider !== '') routes.push({ provider, llmProvider: '', model: '' })
150
+ if (provider !== 'spawn') routes.push({ provider: 'spawn', llmProvider, model })
151
+
152
+ let routeNote = ''
153
+ try {
154
+ let activation
155
+ let used = routes[0]
156
+ // 每级失败都留一条,不只是第一个:三级都试过之后,用户要知道是哪一级
157
+ // 顶住了。只记 firstError 的话,「配置那个起不来」会把「继承主对话也起不来」
158
+ // 吞掉,日志上看着像一次成功回退。
159
+ const failures = []
160
+ for (const route of routes) {
161
+ try {
162
+ activation = await start(route)
163
+ used = route
164
+ break
165
+ } catch (error) {
166
+ failures.push({ route, error })
167
+ }
168
+ }
169
+ if (activation === undefined) throw failures[0]?.error ?? new Error('所有路由都起不来')
170
+ const describe = route => route.model === ''
171
+ ? '主对话模型'
172
+ : `${route.llmProvider === '' ? route.provider : route.llmProvider}/${route.model}`
173
+ if (used !== routes[0]) {
174
+ routeNote = `${label}|` + failures
175
+ .map(item => `tried=${describe(item.route)} reason=${messageOf(item.error).slice(0, 120)}`)
176
+ .join(';')
177
+ + `|fellBackTo=${describe(used)}`
178
+ }
179
+
180
+ let outcome = await settle(activation)
181
+
182
+ // 模型能起来、但一起来就报错且一个字都没吐——多半是这个 profile 里
183
+ // 压根没有这个模型。改走主对话模型再试一次,总比让人对着一个光秃秃的
184
+ // error 猜半天强。只有确实没产出文本才回退,真跑崩的那种不回退。
185
+ if (outcome.stopReason === 'error' && used.model !== '' && outcome.text.trim() === '') {
186
+ try {
187
+ const fallback = await settle(await start({ provider: used.provider, llmProvider: '', model: '' }))
188
+ if (fallback.stopReason === 'completed') {
189
+ routeNote = `${label}:模型 ${used.model} 一起来就报错,已改走主对话模型`
190
+ outcome = fallback
191
+ }
192
+ } catch {
193
+ // 回退也起不来就维持原先的失败,不掩盖
194
+ }
195
+ }
196
+
197
+ return {
198
+ ok: outcome.stopReason === 'completed',
199
+ stopReason: outcome.stopReason,
200
+ diagnostic: outcome.diagnostic,
201
+ text: outcome.text,
202
+ routeNote,
203
+ }
204
+ } catch (error) {
205
+ return {
206
+ ok: false,
207
+ stopReason: deadline.timedOut() ? 'timeout' : 'error',
208
+ diagnostic: deadline.timedOut()
209
+ ? `${label}:超过 ${Math.round(timeoutMs / 1000)} 秒仍未结束,已取消`
210
+ : `${label}:启动或等待环节时出错(${messageOf(error).slice(0, 240)})`,
211
+ text: '',
212
+ routeNote,
213
+ }
214
+ } finally {
215
+ deadline.dispose()
216
+ }
217
+ }
218
+
219
+ for (let attempt = 0; ; attempt += 1) {
220
+ onAttempt?.(attempt)
221
+ const outcome = await attemptOnce()
222
+ if (outcome.routeNote !== '') notes.push(outcome.routeNote)
223
+ if (outcome.ok) {
224
+ return { ...outcome, routeNote: notes.join(';') }
225
+ }
226
+ // 没成的话把这次的原因交出去。
227
+ // 不记的话日志里就只剩「第 N 次尝试」,用户只能看着它一次次重跑,
228
+ // 完全不知道在等什么——实测过:跑了一小时,日志里三行「第 2/3 次尝试」,
229
+ // 每个字都对,就是没有一个是原因。
230
+ onFail?.(attempt, outcome)
231
+ // A caller-side abort is the user stopping the run: never retry it.
232
+ if (signal?.aborted === true) {
233
+ return { ...outcome, routeNote: notes.join(';'), diagnostic: outcome.diagnostic ?? '已被取消' }
234
+ }
235
+ if (attempt >= retries) {
236
+ return {
237
+ ...outcome,
238
+ routeNote: notes.join(';'),
239
+ diagnostic: notes.length === 0 || outcome.diagnostic === undefined
240
+ ? outcome.diagnostic
241
+ : `${outcome.diagnostic}(共试 ${attempt + 1} 次)`,
242
+ }
243
+ }
244
+ if (retryDelayMs > 0) {
245
+ try {
246
+ await sleep(retryDelayMs * (attempt + 1), signal)
247
+ } catch {
248
+ return { ...outcome, routeNote: notes.join(';'), diagnostic: '已被取消' }
249
+ }
250
+ }
251
+ }
252
+ }
253
+
254
+ export function ticketBlock(title, body) {
255
+ return `# ${title}\n\n${body.trim()}\n`
256
+ }
257
+
258
+ export function diagnoseEmptyError(stopReason, diagnostic) {
259
+ if (typeof diagnostic === 'string' && diagnostic.trim() !== '') return diagnostic
260
+ if (diagnostic !== undefined && diagnostic !== null && diagnostic !== '') return diagnostic
261
+ if (stopReason !== 'error') return diagnostic
262
+ return '子会话直接报错退出,没给原因。多半是这一阶指定的模型在这个 profile 里不存在或被禁用:'
263
+ + '先看 project_models 当前路由,再用 project_set_model 或 /flow-set 换成列表里真有的模型'
264
+ }
265
+
266
+ export function stageDeadline(parent, timeoutMs) {
267
+ const controller = new AbortController()
268
+ let timedOut = false
269
+ const forward = () => controller.abort(new Error('aborted by caller'))
270
+ if (parent?.aborted === true) forward()
271
+ else parent?.addEventListener('abort', forward, { once: true })
272
+ const timer = timeoutMs > 0
273
+ ? setTimeout(() => {
274
+ timedOut = true
275
+ controller.abort(new Error('stage deadline exceeded'))
276
+ }, timeoutMs)
277
+ : undefined
278
+ return {
279
+ signal: controller.signal,
280
+ timedOut: () => timedOut,
281
+ dispose: () => {
282
+ if (timer !== undefined) clearTimeout(timer)
283
+ parent?.removeEventListener('abort', forward)
284
+ },
285
+ }
286
+ }
287
+
288
+ export function mergeSignals(...sources) {
289
+ const live = sources.filter(source => source !== undefined && source !== null)
290
+ if (live.length === 0) return undefined
291
+ if (live.length === 1) return live[0]
292
+ const merged = new AbortController()
293
+ for (const source of live) {
294
+ if (source.aborted === true) {
295
+ merged.abort(source.reason)
296
+ return merged.signal
297
+ }
298
+ source.addEventListener('abort', () => { merged.abort(source.reason) }, { once: true })
299
+ }
300
+ return merged.signal
301
+ }
302
+
303
+ export class StopRequested extends Error {
304
+ constructor(project) {
305
+ super(`${project}:已按你的要求停止`)
306
+ this.name = 'StopRequested'
307
+ }
308
+ }
309
+
310
+ export function explainStop({ stage, verdict, reason, resumable, next }) {
311
+ const label = STAGE_LABEL[stage] ?? '?'
312
+ return [
313
+ `为什么停:${reason}`,
314
+ `停在:第 ${stage} 阶「${label}」(${verdict})`,
315
+ resumable
316
+ ? `能不能接着跑:能。${next}`
317
+ : `能不能接着跑:不能自动接。${next}`,
318
+ '不管它会怎样:它不会自己动,也不会自己重试。产物全在磁盘上,等你说一声。',
319
+ ].join('\n')
320
+ }
321
+
322
+ export async function stageContext(cwd, project, stage, extraKeys = [], flow = undefined, contractText = undefined) {
323
+ const keys = flow === undefined
324
+ ? [...(STAGE_IO[stage]?.reads ?? []), ...extraKeys]
325
+ : [...phaseReadKeys(flow.phases?.[stage - 1]), ...extraKeys]
326
+ const parts = []
327
+ // 契约排在最前面:它是这一阶的前提,不是附录。
328
+ // 放最前还有一个实际好处——上下文被截断时,截掉的是后面的产物,不是约定。
329
+ //
330
+ // 收参数而不是自己读:这个函数是纯拼装,读盘交给调用方。自己读的话它就跟
331
+ // 契约那套(哈希、上限)绑死了,单测也抠不出来单独跑。
332
+ if (typeof contractText === 'string' && contractText !== '') parts.push(contractText)
333
+ for (const key of keys) {
334
+ let text = await readArtifact(cwd, project, ARTIFACT[key])
335
+ if (text === undefined) continue
336
+ if (key === 'log' && text.length > LOG_TAIL_CHARS) {
337
+ text = `(只保留最后 ${LOG_TAIL_CHARS} 字,更早的轮次已省略)\n\n${text.slice(-LOG_TAIL_CHARS)}`
338
+ }
339
+ parts.push(`## ${ARTIFACT[key]}\n\n${text.trim()}`)
340
+ }
341
+ return parts.join('\n\n')
342
+ }
343
+
344
+ export async function attemptDiff(cwd, project, attempts, limitChars = DIFF_LIMIT_CHARS) {
345
+ const list = Array.isArray(attempts) ? attempts : []
346
+ const first = list.find(item => typeof item?.before === 'string' && item.before !== '')
347
+ const last = [...list].reverse().find(item => typeof item?.after === 'string' && item.after !== '')
348
+ if (first === undefined || last === undefined) return { ok: false, text: '' }
349
+ const result = await snapshotCommand(cwd, project, [
350
+ 'diff', '--no-renames', first.before, last.after, '--',
351
+ ], { timeoutMs: 300000 })
352
+ if (result.ok !== true) return { ok: false, text: '' }
353
+ const text = result.stdout
354
+ if (text.trim() === '') return { ok: true, text: '' }
355
+ const body = text.length > limitChars
356
+ ? `${text.slice(0, limitChars)}\n\n…(diff 太长,只给前 ${limitChars} 字;剩下的自己读文件核)`
357
+ : text
358
+ return { ok: true, text: body }
359
+ }
360
+
361
+ export function buildSummaryFiles(attempts) {
362
+ const set = new Set()
363
+ for (const item of Array.isArray(attempts) ? attempts : []) {
364
+ for (const path of Array.isArray(item?.files) ? item.files : []) {
365
+ if (typeof path === 'string' && path !== '') set.add(path)
366
+ }
367
+ }
368
+ return [...set]
369
+ }
370
+
@@ -0,0 +1,64 @@
1
+ /**
2
+ * contextTool。正文原样搬自 runner/tools.mjs 1097-1146。
3
+ */
4
+ import { BLINDSPOT_LABELS, CONTEXT_FILE } from '../../shared/constants.mjs'
5
+ import { DIMENSION_KEYS } from '../../gate.mjs'
6
+ import { cwdOf } from '../../workspace/paths.mjs'
7
+ import { defineTool } from '../../shared/tool.mjs'
8
+ import { isAbsolute } from 'node:path'
9
+ import { readRememberedContext } from '../../persistence/state.mjs'
10
+
11
+ export function create(ctx, rt) {
12
+ const contextTool = defineTool({
13
+ name: 'project_context',
14
+ description: '取这个工作流目录上次确认过的五个盲区结论和假设。开新任务前先调它:能沿用的直接沿用、照原样交给 project_run,只问这次确实变了的那几格。',
15
+ parameters: {
16
+ cwd: {
17
+ type: 'string',
18
+ description: '.project-flow 所在的绝对目录;不填就用当前对话的工作目录。',
19
+ },
20
+ },
21
+ output: {
22
+ schema: {
23
+ type: 'object',
24
+ additionalProperties: false,
25
+ required: ['found', 'line'],
26
+ properties: {
27
+ found: { type: 'boolean' },
28
+ line: { type: 'string' },
29
+ },
30
+ },
31
+ render: (_args, value) => [{ type: 'text', text: value.line }],
32
+ },
33
+ async execute(args, exec) {
34
+ const cwd = args.cwd !== undefined && isAbsolute(args.cwd) ? args.cwd : cwdOf(ctx, exec.agent)
35
+ const remembered = await readRememberedContext(cwd)
36
+ if (remembered === undefined) {
37
+ return {
38
+ found: false,
39
+ line: [
40
+ '这个目录还没有确认过的结论,五格要一个一个问。',
41
+ `问完之后把它们交给 project_run,会自动记到 .project-flow/${CONTEXT_FILE},下次就能沿用。`,
42
+ ].join('\n'),
43
+ }
44
+ }
45
+ const blindspots = remembered.blindspots ?? {}
46
+ const assumptions = Array.isArray(remembered.assumptions) ? remembered.assumptions : []
47
+ const labelOf = key => BLINDSPOT_LABELS[key] ?? key
48
+ const line = [
49
+ `上次确认于 ${remembered.savedAt ?? '未知时间'}${remembered.project === undefined ? '' : `(项目 ${remembered.project})`}:`,
50
+ ...DIMENSION_KEYS.map(key => `- ${labelOf(key)}:${typeof blindspots[key] === 'string' && blindspots[key] !== '' ? blindspots[key] : '(上次没结论)'}`),
51
+ ...(assumptions.length === 0
52
+ ? ['- 假设:无']
53
+ : ['- 假设:', ...assumptions.map(item => ` - ${item}`)]),
54
+ '',
55
+ '能沿用的照原样交上去,别改字;只有这次确实变了的才重新问用户。',
56
+ '五格仍然要全部有结论——门控看的是「有没有具体结论」,不是「是不是这次写的」。',
57
+ ].join('\n')
58
+ return { found: true, line }
59
+ },
60
+ })
61
+
62
+
63
+ return contextTool
64
+ }
@@ -0,0 +1,49 @@
1
+ /**
2
+ * decorateCost。正文原样搬自 runner/tools.mjs 1059-1096。
3
+ */
4
+ import { CONFIDENCE_LABEL } from '../../prices.mjs'
5
+ import { estimateCost } from '../../pricing/estimate.mjs'
6
+ import { readState } from '../../persistence/state.mjs'
7
+
8
+ export function create(ctx, rt) {
9
+ async function decorateCost(result, settings, requirements, cwd) {
10
+ if (result === null || typeof result !== 'object') return result
11
+ const money = value => `¥${Number(value ?? 0).toFixed(2)}`
12
+
13
+ // 预估:开工前那一份。跑完了也留着,好跟实际比一比估得准不准。
14
+ const estimate = estimateCost(settings, {
15
+ requirements: Array.isArray(requirements) ? requirements.length : 0,
16
+ })
17
+ const estimateLine = [
18
+ `开工前预估:约 ${money(estimate.cny)}($${estimate.usd},不含返工)`,
19
+ ...estimate.byStage.map(row => ` ${row.label}(${row.model}):${money(row.cny)} · ${CONFIDENCE_LABEL[row.confidence] ?? row.confidence}`),
20
+ ` 返工一轮约再加 ${money(estimate.perRework.cny)}`,
21
+ ].join('\n')
22
+
23
+ // 实际:从 state.json 读回来。
24
+ let costLine = ''
25
+ try {
26
+ const state = await readState(cwd, result.project)
27
+ const cost = state?.cost
28
+ if (cost !== undefined && cost !== null) {
29
+ const rows = Array.isArray(cost.breakdown) ? cost.breakdown : []
30
+ costLine = [
31
+ `实际花费:${money(cost.spentCny)}($${Number(cost.spentUsd ?? 0).toFixed(4)},汇率 ${cost.cnyRate ?? 7.2})`,
32
+ ...(rows.length === 0
33
+ ? []
34
+ : [
35
+ ` 按模型分账:`,
36
+ ...rows.map(row => ` ${row.model}:${money(row.estimatedCny)}(输入 ${Number(row.inputTokens).toLocaleString()} / 输出 ${Number(row.outputTokens).toLocaleString()} token)`),
37
+ ]),
38
+ ].join('\n')
39
+ }
40
+ } catch {
41
+ // 读不到就不写这一段,别让记账拖垮结果
42
+ }
43
+
44
+ return { ...result, estimate: estimateLine, cost: costLine }
45
+ }
46
+
47
+
48
+ return decorateCost
49
+ }
@@ -0,0 +1,59 @@
1
+ /**
2
+ * doctorTool。正文原样搬自 runner/tools.mjs 385-430。
3
+ */
4
+ import { cwdOf } from '../../workspace/paths.mjs'
5
+ import { defineTool } from '../../shared/tool.mjs'
6
+ import { isAbsolute } from 'node:path'
7
+ import { settingsOf } from '../../config/settings.mjs'
8
+ import { sweep } from '../../persistence/recovery.mjs'
9
+
10
+ export function create(ctx, rt) {
11
+ const doctorTool = defineTool({
12
+ name: 'project_doctor',
13
+ description: '检查 .project-flow 的健康状况:遗留锁、损坏的 state.json、开了头没收尾的阶段。默认只报告;fix=true 才动手,会移开死锁、按产物重建 state、把没收尾的段标成中断。',
14
+ parameters: {
15
+ project: {
16
+ type: 'string',
17
+ description: '只检查这一个项目;不填就检查工作目录下全部项目。',
18
+ },
19
+ fix: {
20
+ type: 'boolean',
21
+ description: 'true 才动手修;不填只报告,不改任何文件。',
22
+ },
23
+ cwd: {
24
+ type: 'string',
25
+ description: '.project-flow 所在的绝对目录;不填就用当前对话的工作目录。',
26
+ },
27
+ },
28
+ output: {
29
+ schema: {
30
+ type: 'object',
31
+ additionalProperties: false,
32
+ required: ['line', 'actions'],
33
+ properties: {
34
+ line: { type: 'string' },
35
+ actions: { type: 'array', items: { type: 'string' } },
36
+ },
37
+ },
38
+ render: (_args, value) => [{
39
+ type: 'text',
40
+ text: [value.line, ...value.actions].join('\n'),
41
+ }],
42
+ },
43
+ async execute(args, exec) {
44
+ const settings = settingsOf()
45
+ const cwd = args.cwd !== undefined && isAbsolute(args.cwd) ? args.cwd : cwdOf(ctx, exec.agent)
46
+ const fix = args.fix === true
47
+ const actions = await sweep(cwd, settings, args.project, fix)
48
+ return {
49
+ line: actions.length === 0
50
+ ? '没发现问题:没有遗留锁,state.json 都在,也没有悬空没收尾的阶段。'
51
+ : `${actions.length} 处需要处理(${fix ? '已尝试修复' : '只报告,未改动任何文件'}):`,
52
+ actions,
53
+ }
54
+ },
55
+ })
56
+
57
+
58
+ return doctorTool
59
+ }
@@ -0,0 +1,63 @@
1
+ /**
2
+ * estimateTool。正文原样搬自 runner/tools.mjs 1008-1058。
3
+ */
4
+ import { CONFIDENCE_LABEL } from '../../prices.mjs'
5
+ import { defineTool } from '../../shared/tool.mjs'
6
+ import { estimateCost } from '../../pricing/estimate.mjs'
7
+ import { settingsOf } from '../../config/settings.mjs'
8
+
9
+ export function create(ctx, rt) {
10
+ const estimateTool = defineTool({
11
+ name: 'project_estimate',
12
+ description: '开工前估算这个项目跑完四阶要花多少人民币(按各阶模型单价分别算)。回答「这活大概多少钱」用这个,别用 project_status——那个只有已经花掉的。',
13
+ parameters: {
14
+ requirements: {
15
+ type: 'integer',
16
+ description: '这次列了几条要求,影响规划段的输入量。不填按 8 条估。',
17
+ },
18
+ cwd: {
19
+ type: 'string',
20
+ description: '.project-flow 所在的绝对目录;不填就用当前对话的工作目录。',
21
+ },
22
+ },
23
+ output: {
24
+ schema: {
25
+ type: 'object',
26
+ additionalProperties: false,
27
+ required: ['line', 'cny', 'usd'],
28
+ properties: {
29
+ line: { type: 'string' },
30
+ cny: { type: 'number' },
31
+ usd: { type: 'number' },
32
+ },
33
+ },
34
+ render: (_args, value) => [{ type: 'text', text: value.line }],
35
+ },
36
+ async execute(args) {
37
+ const settings = settingsOf()
38
+ const estimate = estimateCost(settings, { requirements: args.requirements ?? 8 })
39
+ // 每个模型都要标清楚这个价是怎么来的:估的就是估的,不能拿去对账。
40
+ const mark = row => CONFIDENCE_LABEL[row.confidence] ?? row.confidence
41
+ const estimatedCount = estimate.byStage.filter(row => row.confidence === 'family' || row.confidence === 'fallback').length
42
+ const lines = [
43
+ `开工前预估:约 ¥${estimate.cny}($${estimate.usd},汇率 ${settings.cnyRate})——这是「一次过」的账,不含返工`,
44
+ '',
45
+ '| 阶段 | 模型 | 单价 $/M(入·出) | 输入 token | 输出 token | 估算 | 价的来源 |',
46
+ '|---|---|---|---|---|---|---|',
47
+ ...estimate.byStage.map(row => `| ${row.label} | ${row.model} | ${row.priceInput}·${row.priceOutput} | ${row.inputTokens.toLocaleString()} | ${row.outputTokens.toLocaleString()} | ¥${row.cny} | ${mark(row)} |`),
48
+ '',
49
+ `返工一轮(重跑实施+质检)约再加 ¥${estimate.perRework.cny}。配置里返工上限 ${settings.maxRework} 次,真全用满最多约 ¥${(estimate.cny + estimate.perRework.cny * settings.maxRework).toFixed(2)}。`,
50
+ estimatedCount === 0
51
+ ? ''
52
+ : `其中 ${estimatedCount} 档的单价是按型号族估算的,不是厂商报价——按它算的预算要留余量;要精确就用 /flow-set 价格 模型名 输入价 输出价。`,
53
+ '',
54
+ estimate.note,
55
+ '跑起来之后,每阶结束会把真实 token 和分模型账单写进 state.json 的 cost,用 project_status 或 /flow-cost 看实际数。',
56
+ ].filter(line => line !== '')
57
+ return { line: lines.join('\n'), cny: estimate.cny, usd: estimate.usd }
58
+ },
59
+ })
60
+
61
+
62
+ return estimateTool
63
+ }