dsh-workflow-execute 0.0.0-stage → 1.0.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.
@@ -0,0 +1,746 @@
1
+ 'use strict'
2
+
3
+ /**
4
+ * dsh-workflow-execute — 执行驱动(v0.2)。
5
+ *
6
+ * 发起运行 = 冻结工作流快照 + 建台账;驱动循环逐环节开全新 dsh 会话(可绑工作区/
7
+ * 指定模型),环节完成后代码层跑门禁(ai_criteria_review 裁判会话对照 min_score),
8
+ * 不过按 on_gate_fail 流转(break → awaiting 等人裁决;<id>/goto:<id> 回跳),
9
+ * max_rework 由代码计数封顶,max_step_executions 全程步数上限。
10
+ * 人可暂停/继续/停止/裁决 break(重试本环节=清零返工、跳过本环节、中止运行)。
11
+ *
12
+ * 会话创建沿 dsh-tasks / dsh-plugin-kit 的成熟路径(agents.create + standard
13
+ * preset + whenIdle + 事件泵收尾部输出),裁判用独立短会话。
14
+ */
15
+
16
+ const { randomUUID } = require('node:crypto')
17
+ const { makeAttempt, parseFlow, indexLinks, nextLinkAfter, firstLinkId, runSummary } = require('./runs.js')
18
+ const { collectWriteOps, resolveArtifactEntries } = require('./artifacts.js')
19
+ const { archiveArtifacts } = require('./archive.js')
20
+
21
+ const OUTPUT_TAIL_CAP = 8 * 1024
22
+
23
+ /** 会话事件列表:0.1.5 起 snapshotEvents()(events 属性移除);更早是 session.log / session.events 数组。 */
24
+ function sessionEventList(agent) {
25
+ try {
26
+ const ses = agent && agent.session
27
+ if (ses && typeof ses.snapshotEvents === 'function') return ses.snapshotEvents() || []
28
+ if (Array.isArray(ses && ses.log)) return ses.log
29
+ if (Array.isArray(ses && ses.events)) return ses.events
30
+ } catch { /* 会话对象缺席 */ }
31
+ return []
32
+ }
33
+ const PUMP_MS = 500
34
+ const TOUCH_THROTTLE_MS = 1500
35
+ const JUDGE_TIMEOUT_MS = 180000
36
+
37
+
38
+ /** 门禁评审输出 → {score, reason};解析失败按 0 分(fail-safe 走返工/裁决路径)。 */
39
+ function parseJudgeOutput(text) {
40
+ const s = String(text || '')
41
+ const fenced = s.match(/```(?:json)?\s*\n([\s\S]*?)```/)
42
+ const candidate = fenced ? fenced[1] : s
43
+ const brace = candidate.lastIndexOf('{')
44
+ if (brace >= 0) {
45
+ const end = candidate.indexOf('}', brace)
46
+ if (end > brace) {
47
+ try {
48
+ const j = JSON.parse(candidate.slice(brace, end + 1))
49
+ const score = Math.max(0, Math.min(100, Math.round(Number(j.score))))
50
+ if (Number.isFinite(score)) return { score, reason: String(j.reason || '').slice(0, 300) }
51
+ } catch { /* 落到默认 */ }
52
+ }
53
+ }
54
+ return { score: 0, reason: '评审输出无法解析,按不通过处理' }
55
+ }
56
+
57
+ /**
58
+ * 会话事件 → token 用量合计:assistant/message 事件逐步累加 usage
59
+ * (宿主 ≥0.1.5 在事件 data 上携带该步 {inputTokens,outputTokens,totalTokens};
60
+ * 每步 inputTokens 含该步全量 prompt,逐步求和 = API 实际计费口径)。
61
+ * 会话没有 usage 记录(旧宿主/适配器未上报)时返回 undefined。
62
+ */
63
+ function sumUsage(agent, firstSeq) {
64
+ let found = false
65
+ const total = { inputTokens: 0, outputTokens: 0, totalTokens: 0, calls: 0 }
66
+ for (const ev of sessionEventList(agent)) {
67
+ if (!ev || ev.seq < firstSeq) continue
68
+ const u = ev.type === 'assistant/message' && ev.data ? ev.data.usage : undefined
69
+ if (!u || typeof u !== 'object') continue
70
+ found = true
71
+ total.inputTokens += Number(u.inputTokens) || 0
72
+ total.outputTokens += Number(u.outputTokens) || 0
73
+ total.totalTokens += Number(u.totalTokens) || 0
74
+ total.calls += 1
75
+ }
76
+ return found ? total : undefined
77
+ }
78
+
79
+ /** 两份用量合并成新对象(a 可为 undefined)——运行合计 = 已累计 + 本次增量。 */
80
+ function addUsage(a, b) {
81
+ const base = a || { inputTokens: 0, outputTokens: 0, totalTokens: 0, calls: 0 }
82
+ return {
83
+ inputTokens: base.inputTokens + b.inputTokens,
84
+ outputTokens: base.outputTokens + b.outputTokens,
85
+ totalTokens: base.totalTokens + b.totalTokens,
86
+ calls: base.calls + b.calls,
87
+ }
88
+ }
89
+
90
+ /**
91
+ * 会话这一轮是怎么结束的:completed 正常结束,aborted = 用户点了终止,error = 会话出错。
92
+ * 只有 completed 才算「环节跑完了」,其余都不能往下流转。
93
+ */
94
+ function turnEndKind(events, fromSeq) {
95
+ for (let i = events.length - 1; i >= 0; i--) {
96
+ const ev = events[i]
97
+ if (!ev || ev.seq < fromSeq) continue
98
+ if (ev.type === 'turn/end') {
99
+ const reason = ev.data && ev.data.reason
100
+ return (reason && reason.kind) || 'unknown'
101
+ }
102
+ }
103
+ return undefined
104
+ }
105
+
106
+ /** 环节被中断(用户终止或会话出错):不进门禁、不流转,整条运行停下。 */
107
+ class LinkInterrupted extends Error {
108
+ constructor(message) {
109
+ super(message)
110
+ this.name = 'LinkInterrupted'
111
+ }
112
+ }
113
+
114
+ class ExecutionService {
115
+ /**
116
+ * @param {object} deps
117
+ * @param {object} deps.ctx 宿主上下文(agents / agentDefaultModel / workspaceRegistry)
118
+ * @param {import('./runs.js').RunStore} deps.runs
119
+ * @param {{get: Function}} deps.settings
120
+ * @param {object} [deps.logger]
121
+ */
122
+ constructor({ ctx, runs, settings, logger }) {
123
+ this.ctx = ctx
124
+ this.runs = runs
125
+ this.settings = settings
126
+ this.logger = logger || console
127
+ this.active = new Map() // runId → driveLoop promise
128
+ this.runSessions = new Map() // runId → { agent, sessionId }(sessionMode='single' 复用)
129
+ const parsed = Number.parseInt(process.env.DSH_WORKFLOW_EXECUTE_MAX_CONCURRENT ?? '', 10)
130
+ this.maxConcurrent = Number.isInteger(parsed) && parsed >= 1 ? parsed : 2
131
+ this.disposed = false
132
+ }
133
+
134
+ /** 宿主卸载/重启时置位:延迟 tick 与在飞收尾不得再碰 ctx。 */
135
+ dispose() { this.disposed = true }
136
+
137
+ /** 容量允许时从队列拉起运行;在 run 收尾后也要再 tick 一次。 */
138
+ tick() {
139
+ if (this.disposed) return
140
+ let agents
141
+ try { agents = this.ctx.agents } catch { return } // ctx 已失效(宿主重启后残留 tick):静默退出,绝不抛——这里抛错=整个 web 启动失败
142
+ if (!agents) return
143
+ const queued = this.runs.byStatus('queued')
144
+ for (const run of queued) {
145
+ if (this.active.size >= this.maxConcurrent) break
146
+ if (this.active.has(run.id)) continue
147
+ run.status = 'running'
148
+ run.startedAt = run.startedAt || Date.now()
149
+ this.runs.touch(run)
150
+ const p = this.driveLoop(run).catch((e) => {
151
+ this.logger.warn && this.logger.warn(`dsh-workflow-execute: run ${run.id} crashed: ${e && e.stack || e}`)
152
+ if (run.status === 'running') this.failRun(run, 'crashed', String(e && e.message || e))
153
+ }).finally(() => { this.active.delete(run.id); this.tick() })
154
+ this.active.set(run.id, p)
155
+ }
156
+ }
157
+
158
+ // ── 运行循环 ──────────────────────────────────────────────────────────
159
+
160
+ async driveLoop(run) {
161
+ const snap = run.snapshot
162
+ let cursor = run.current && run.current.linkId && indexLinks(snap).map.has(run.current.linkId)
163
+ ? run.current.linkId
164
+ : firstLinkId(snap)
165
+ if (!cursor) { this.finishRun(run, 'done', '工作流没有环节'); return }
166
+ run.current = { phaseId: undefined, linkId: cursor, attempt: (run.rework[cursor] || 0) + 1 }
167
+ this.runs.touch(run)
168
+
169
+ if (run.status !== 'running') { this.settleTrail(run); return }
170
+
171
+ // 每次运行只归档一次:把上一轮留下的产物整份复制到 <产物目录>/.history/<runId>/,
172
+ // 否则本轮同名文件会覆盖上一轮,留下的旧文件又会被当成本次产物。
173
+ if (!run.archiveDone) {
174
+ run.archiveDone = true
175
+ try {
176
+ const archived = await archiveArtifacts({ cwd: this.runCwd(run), snapshot: snap, runId: run.id, logger: this.logger })
177
+ if (archived.length > 0) run.artifactArchive = archived
178
+ } catch (error) {
179
+ if (this.logger && typeof this.logger.warn === 'function') this.logger.warn(`[dsh-workflow-execute] ${run.id} 归档旧产物失败:${String(error && error.message || error)}`)
180
+ }
181
+ this.runs.touch(run)
182
+ }
183
+
184
+ for (;;) {
185
+ if (run.status !== 'running') { this.settleTrail(run); return }
186
+ const { map } = indexLinks(snap)
187
+ const entry = map.get(cursor)
188
+ if (!entry) { this.failRun(run, 'bad_flow', `环节 "${cursor}" 在快照中不存在`); return }
189
+
190
+ const maxRework = Number.isInteger(entry.link.max_rework) && entry.link.max_rework >= 0 ? entry.link.max_rework : 3
191
+ const rework = run.rework[cursor] || 0
192
+ if (rework > maxRework) {
193
+ this.awaitBreak(run, cursor, { name: '返工上限', score: null, minScore: null, reason: '触发' },
194
+ `环节 "${cursor}" 超过 max_rework=${maxRework}`)
195
+ return
196
+ }
197
+ if (run.limits.maxStepExecutions !== null && run.limits.maxStepExecutions !== undefined
198
+ && run.stepCount >= run.limits.maxStepExecutions) {
199
+ this.failRun(run, 'capped_step', `达到步数上限 max_step_executions=${run.limits.maxStepExecutions}`)
200
+ return
201
+ }
202
+
203
+ run.current = { phaseId: entry.phase.id, linkId: cursor, attempt: rework + 1 }
204
+ const attempt = makeAttempt(entry.phase.id || entry.phase.name, cursor, rework + 1)
205
+ run.trail.push(attempt)
206
+ run.stepCount += 1
207
+ this.runs.touch(run)
208
+
209
+ try {
210
+ const output = await this.runLinkSession(run, entry, attempt)
211
+ // ── 人工审核(review_type: human):不做 AI 评分,环节做完了等人验收,
212
+ // 验收通过后由 actionResolveBreak 按 on_success 流转 ──
213
+ if ((entry.link.review_type || 'ai') === 'human') {
214
+ attempt.status = 'awaiting_review'
215
+ attempt.finishedAt = Date.now()
216
+ this.runs.touch(run)
217
+ this.awaitBreak(run, cursor, { name: '人工审核', score: null, minScore: null, reason: '等待人工审核' },
218
+ 'review_type: human', 'human')
219
+ return
220
+ }
221
+ // ── 门禁(全部通过才算过;取最严一分)──
222
+ const gates = Array.isArray(entry.link.gates) ? entry.link.gates : []
223
+ let failedGate = null
224
+ for (const gate of gates) {
225
+ if (!gate || typeof gate !== 'object') continue
226
+ const judge = await this.judgeGate(run, entry, gate, output)
227
+ if (judge.usage) {
228
+ attempt.gateUsage = addUsage(attempt.gateUsage, judge.usage)
229
+ run.usage = addUsage(run.usage, judge.usage)
230
+ }
231
+ if (!attempt.gate || (judge.score < (attempt.gate.score ?? 101))) attempt.gate = { name: gate.name || gate.type || 'gate', score: judge.score, minScore: gate.min_score ?? 0, reason: judge.reason }
232
+ const min = typeof gate.min_score === 'number' ? gate.min_score : 0
233
+ if (judge.score < min) { failedGate = { gate: { name: gate.name || gate.type || 'gate', score: judge.score, minScore: min, reason: judge.reason }, linkId: cursor }; break }
234
+ }
235
+ if (failedGate) {
236
+ attempt.status = 'gate_failed'
237
+ attempt.finishedAt = Date.now()
238
+ attempt.gate = failedGate.gate
239
+ run.rework[cursor] = (run.rework[cursor] || 0) + 1
240
+ const route = parseFlow(entry.link.on_gate_fail) || { jump: cursor }
241
+ if (route === 'break') {
242
+ this.awaitBreak(run, cursor, failedGate.gate, 'on_gate_fail: break')
243
+ return
244
+ }
245
+ cursor = route === 'next' ? (nextLinkAfter(snap, cursor) || cursor) : route.jump
246
+ run.current = { phaseId: undefined, linkId: cursor, attempt: (run.rework[cursor] || 0) + 1 }
247
+ this.runs.touch(run)
248
+ continue
249
+ }
250
+ attempt.status = 'done'
251
+ attempt.finishedAt = Date.now()
252
+ this.runs.touch(run)
253
+
254
+ // ── 成功流转 ──
255
+ const route = parseFlow(entry.link.on_success) || 'next'
256
+ if (route === 'end') { this.finishRun(run, 'done'); return }
257
+ if (route === 'break') { this.awaitBreak(run, cursor, null, 'on_success: break'); return }
258
+ cursor = route === 'next' ? nextLinkAfter(snap, cursor) : route.jump
259
+ if (!cursor || !map.has(cursor)) {
260
+ if (route === 'next') { this.finishRun(run, 'done'); return }
261
+ this.failRun(run, 'bad_flow', `流转目标 "${route.jump}" 不存在`)
262
+ return
263
+ }
264
+ run.current = { phaseId: undefined, linkId: cursor, attempt: (run.rework[cursor] || 0) + 1 }
265
+ this.runs.touch(run)
266
+ } catch (error) {
267
+ attempt.status = 'failed'
268
+ attempt.finishedAt = Date.now()
269
+ attempt.error = String(error && error.message || error)
270
+ this.settleTrail(run)
271
+ this.runs.touch(run)
272
+ // 中断(用户终止/会话出错)时运行已被置为 stopped,不再改写成 failed
273
+ if (error instanceof LinkInterrupted) return
274
+ this.failRun(run, 'link_failed', `环节 "${cursor}" 执行失败:${attempt.error}`)
275
+ return
276
+ }
277
+ }
278
+ }
279
+
280
+ settleTrail(run) {
281
+ for (const t of run.trail) if (t.status === 'running') { t.status = 'abandoned'; t.finishedAt = Date.now() }
282
+ }
283
+
284
+ finishRun(run, status, note) {
285
+ this.settleTrail(run)
286
+ run.status = status
287
+ run.finishedAt = Date.now()
288
+ run.current = null
289
+ if (note) run.error = note
290
+ this.runSessions.delete(run.id)
291
+ this.runs.touch(run)
292
+ }
293
+
294
+ failRun(run, code, message) { this.finishRun(run, 'failed', message) }
295
+
296
+ awaitBreak(run, linkId, gate, reason, kind = 'gate') {
297
+ this.settleTrail(run)
298
+ run.status = 'awaiting'
299
+ run.pendingBreak = { linkId, gate, reason, kind, at: Date.now() }
300
+ this.runs.touch(run)
301
+ }
302
+
303
+ // ── 会话驱动 ──────────────────────────────────────────────────────────
304
+
305
+ buildLinkPrompt(run, entry) {
306
+ const { link, phase } = entry
307
+ // 用户输入只给链路起点环节(回跳到起点也算):下游环节的输入是上游产出,见下方 upstreamBlock
308
+ const isStartLink = !!link && link.id === firstLinkId(run.snapshot)
309
+ const userBlock = isStartLink && run.userInput
310
+ ? ['【本次运行的用户需求】(这是用户这次真正要处理的事,本环节负责把它落成结论)', run.userInput, ''].join('\n')
311
+ : ''
312
+ // 产物名可留空:回退到路径里的文件名,再不行用环节名——不逼用户给每条产物起名
313
+ const artifactLabel = (a) => {
314
+ const p = a && a.path ? String(a.path) : ''
315
+ const named = a && a.name ? String(a.name) : ''
316
+ if (named) return p ? named + '(' + p + ')' : named
317
+ const base = p ? p.split(/[\\/]/).pop() : ''
318
+ const label = base || (link.name || link.id) + '(本环节产物)'
319
+ return p ? label + '(' + p + ')' : label
320
+ }
321
+ const artifacts = Array.isArray(link.expected_artifacts) && link.expected_artifacts.length > 0
322
+ ? link.expected_artifacts.map((a) => '- ' + artifactLabel(a)).join('\n')
323
+ : '(本环节未声明产物)'
324
+ // 上游产出:取 trail 里当前 attempt 之前、最近一条「别的环节」的尝试(跨阶段不重置)。
325
+ // 同一环节的上次失败不进这里,而由 reworkBlock 单独说明,避免两处重复。
326
+ const prevAttempts = Array.isArray(run.trail) ? run.trail.slice(0, -1) : []
327
+ const prev = prevAttempts.slice().reverse().find((t) => t && t.linkId !== link.id)
328
+ const linkNameOf = (id) => {
329
+ const m = indexLinks(run.snapshot).map.get(id)
330
+ return (m && m.link && (m.link.name || m.link.id)) || id
331
+ }
332
+ let upstreamBlock = ''
333
+ if (prev) {
334
+ const min = prev.gate && typeof prev.gate.minScore === 'number' ? prev.gate.minScore : 0
335
+ // 未通过时把评审原话带过去:回跳目标(如 goto:verify-01)只能看到「未通过 + 分数」是不够的
336
+ const prevPassed = prev.gate && typeof prev.gate.score === 'number' ? prev.gate.score >= min : null
337
+ const gateInfo = prevPassed === null
338
+ ? ''
339
+ : `,门禁「${prev.gate.name || '门禁'}」${prev.gate.score}/${min}${prevPassed ? '(通过)' : '(未通过)'}`
340
+ + (prevPassed ? '' : (prev.gate.reason ? ` —— 评审意见:${prev.gate.reason}` : ' —— 评审意见未记录'))
341
+ const files = Array.isArray(prev.artifacts) && prev.artifacts.length
342
+ ? prev.artifacts.map((a) => '- ' + (a.path || a.name || '(未命名)')
343
+ + (a.exists ? '' : '(文件不存在)')
344
+ + (typeof a.additions === 'number' ? ` +${a.additions}/-${a.deletions || 0}` : '')).join('\n')
345
+ : '(本环节未写入文件)'
346
+ upstreamBlock = [
347
+ `【上游环节产出】来自 ${prev.linkId}《${linkNameOf(prev.linkId)}》,状态 ${prev.status}${gateInfo}`,
348
+ '产物文件:',
349
+ files,
350
+ '上游输出原文(可能因引擎上限被截断,需要完整内容请直接打开上面的文件):',
351
+ prev.outputTail && String(prev.outputTail).trim() !== '' ? String(prev.outputTail) : '(无文字输出)',
352
+ '',
353
+ ].join('\n')
354
+ }
355
+ // 返工提示:本环节此前没过,附上次门禁原话,避免盲目重跑同一条指令
356
+ const reworkNo = run.rework && Number(run.rework[link.id]) ? Number(run.rework[link.id]) : 0
357
+ const lastFail = prevAttempts.slice().reverse()
358
+ .find((t) => t && t.linkId === link.id && t.gate && t.gate.reason)
359
+ const reworkBlock = reworkNo > 0
360
+ ? [
361
+ `【本次是返工(本环节第 ${reworkNo + 1} 次执行)】`,
362
+ lastFail
363
+ ? `上次未通过:门禁「${lastFail.gate.name || '门禁'}」${lastFail.gate.score}/${typeof lastFail.gate.minScore === 'number' ? lastFail.gate.minScore : 0} —— ${lastFail.gate.reason}`
364
+ : '上次未通过,原因未记录',
365
+ '先针对上面这条原因修复,再重做本环节;之前已经做对的部分不要推翻重来。',
366
+ '',
367
+ ].join('\n')
368
+ : ''
369
+ return [
370
+ userBlock,
371
+ `你正在执行工作流「${run.displayName || run.processName}」的一个环节,只做本环节的事,不要越界到其他环节。`,
372
+ `环节:${phase && phase.name ? `${phase.name} / ` : ''}${link.name || link.id}(id=${link.id})`,
373
+ link.expert_name || link.expert ? `建议以专家「${link.expert_name || link.expert}」的标准与视角执行。` : '',
374
+ Array.isArray(link.skills) && link.skills.length ? `可用技能:${link.skills.join(', ')}` : '',
375
+ '',
376
+ upstreamBlock,
377
+ reworkBlock,
378
+ '【环节指令】',
379
+ link.prompt || '(无指令,请根据环节名合理执行)',
380
+ '',
381
+ '【期望产物】',
382
+ artifacts,
383
+ link.acceptance_criteria ? `【环节验收标准】\n${link.acceptance_criteria}` : '',
384
+ '',
385
+ '完成后:在回答末尾输出执行报告,固定四段——①改动或结论(带文件路径与 文件:行)②验证方式与结果(命令 + 输出摘要)③遗留与未验证项④下一环节须知。门禁评审只看得到这段输出,证据必须写在这里。',
386
+ ].filter((x) => x !== '').join('\n')
387
+ }
388
+
389
+ /** 运行绑定的工作区(未绑定时 undefined)。 */
390
+ workspaceOf(run) {
391
+ return run.workspaceId && this.ctx.workspaceRegistry
392
+ ? this.ctx.workspaceRegistry.get(run.workspaceId)
393
+ : undefined
394
+ }
395
+
396
+ /** 运行工作目录:绑定工作区路径,没有绑定分区就用用户库根目录。 */
397
+ runCwd(run) {
398
+ const workspace = this.workspaceOf(run)
399
+ return workspace ? workspace.path : this.settings.get().userRoot
400
+ }
401
+
402
+ /** 会话模式:single=整条流程共用一个会话(含门禁评审);multi=每环节一个、门禁独立会话。 */
403
+ sessionMode(run) {
404
+ return run && run.sessionMode === 'single' ? 'single' : 'multi'
405
+ }
406
+
407
+ /**
408
+ * 取本次环节/门禁要用的会话。
409
+ * multi:每次新建(原行为)。single:复用本运行的第一个会话,门禁也用它。
410
+ */
411
+ /**
412
+ * 单会话模式下复用的会话是否还能写:宿主把会话从 SessionStore 摘掉后,
413
+ * 再 append 会抛 `session "…" cannot append outside a SessionStore`。
414
+ */
415
+ isSessionLive(entry) {
416
+ if (!entry || !entry.sessionId) return false
417
+ const store = this.ctx && this.ctx.sessions
418
+ if (!store || typeof store.get !== 'function') return !!entry.agent
419
+ try {
420
+ const live = store.get(entry.sessionId)
421
+ if (!live) return false
422
+ return !entry.agent || entry.agent.session === live
423
+ } catch {
424
+ return false
425
+ }
426
+ }
427
+
428
+ async getSession({ run, title, withTools = true }) {
429
+ if (this.sessionMode(run) !== 'single') return this.createSession({ run, title, withTools })
430
+ const cached = this.runSessions.get(run.id)
431
+ if (cached && this.isSessionLive(cached)) return cached
432
+ if (cached) {
433
+ this.runSessions.delete(run.id)
434
+ this.logger.warn && this.logger.warn(`[dsh-workflow-execute] ${run.id} 单会话 ${cached.sessionId} 已失效,本环节起改用新会话(上下文不再连续)`)
435
+ }
436
+ const made = await this.createSession({ run, title, withTools })
437
+ this.runSessions.set(run.id, made)
438
+ return made
439
+ }
440
+
441
+ async createSession({ run, title, withTools = true }) {
442
+ const selection = run.model
443
+ ? { provider: run.provider, model: run.model }
444
+ : this.ctx.agentDefaultModel.currentSelection()
445
+ const sessionId = 'session-' + randomUUID()
446
+ const workspace = this.workspaceOf(run)
447
+ if (run.workspaceId && !workspace) throw new Error(`workspace '${run.workspaceId}' not found`)
448
+ // 分区归属的判定是「会话 header.cwd === 分区路径」严格相等(dsh-workspace 的 attachSession /
449
+ // candidateMatches),所以会话头直接用分区路径;没有绑定分区时用用户库根目录。
450
+ const cwd = workspace ? workspace.path : this.settings.get().userRoot
451
+ const { agent } = await this.ctx.agents.create({
452
+ sessionId,
453
+ meta: { cwd },
454
+ agentOptions: { provider: selection.provider, model: selection.model },
455
+ // 关键:meta.agentPreset 只是会话头标签、不带任何工具——必须在 setup 里 mount
456
+ // 部署默认预设(web 网关/dsh-tasks/dsh-kb 同款),否则会话零工具,
457
+ // 模型只会干说「我无法执行」(真机抓过,见 dsh-kb v0.2 踩坑实录①)。
458
+ setup: async (agentCtx) => {
459
+ try {
460
+ const presets = typeof this.ctx.get === 'function' ? this.ctx.get('agentPresets') : undefined
461
+ if (withTools && presets && typeof presets.resolve === 'function' && typeof presets.mount === 'function') {
462
+ const resolved = await presets.resolve(undefined)
463
+ if (resolved && resolved.id) await presets.mount(agentCtx, resolved.id)
464
+ this.logger.info && this.logger.info(`[dsh-workflow-execute] preset mounted: ${resolved && resolved.id}`)
465
+ }
466
+ if (withTools) {
467
+ // 无人值守要写产物文件:沙箱 workspace-write + 审批 never(dsh-kb 同款旋钮)
468
+ agentCtx.session.append('sandbox/mode', { mode: 'workspace-write' })
469
+ agentCtx.session.append('approval/policy', { policy: 'never' })
470
+ }
471
+ } catch (e) { console.error(`[dsh-workflow-execute] setup 失败(会话将继续但可能无工具): ${e && e.stack || e}`) }
472
+ },
473
+ })
474
+ if (workspace && typeof workspace.attachSession === 'function') {
475
+ try {
476
+ await workspace.attachSession(sessionId)
477
+ } catch (e) {
478
+ // 分区归属的判定是「会话 header 的 cwd === 分区路径」(dsh-workspace 的 attachSession /
479
+ // candidateMatches 都做严格相等)。上面已按分区路径建会话,正常应当挂得上;
480
+ // 挂不上只会是路径形态不一致(盘符大小写、符号链接、8.3 短名)这类原因。
481
+ // 这里只记录原因,不阻塞执行(会话会独立成一个项目分组,界面上不属于所选分区)。
482
+ this.logger.warn && this.logger.warn(
483
+ `[dsh-workflow-execute] ${run.id} 会话 ${sessionId} 未能归入分区 ${workspace.path}:${(e && e.message) || e}`,
484
+ )
485
+ }
486
+ }
487
+ try {
488
+ agent.session.append('session/title', { title, messageSeqs: [], source: { kind: 'user' } })
489
+ } catch { /* 标题失败非致命 */ }
490
+ // 等会话运行时启动完成(kit 同款):立刻 followup 会丢消息(会话零事件、空转完成)
491
+ await agent.whenIdle()
492
+ return { agent, sessionId }
493
+ }
494
+
495
+ /** 执行一个环节:开会话 → followup → 事件泵收尾部 → whenIdle → 汇总报告文本。 */
496
+ async runLinkSession(run, entry, attempt) {
497
+ const prompt = this.buildLinkPrompt(run, entry)
498
+ const { agent, sessionId } = await this.getSession({
499
+ run,
500
+ // 会话标题带运行名(工作流名 · 需求摘要):同工作流多次运行的同名环节在会话列表里也能分开
501
+ title: `${run.runName || run.displayName || run.processName} · ${entry.link.name || entry.link.id}`,
502
+ })
503
+ attempt.sessionId = sessionId
504
+ this.runs.touch(run)
505
+
506
+ let tail = ''
507
+ let lastTouch = 0
508
+ const firstSeq = agent.session.seq
509
+ const seen = new Set()
510
+ let cancelSent = false
511
+ const liveLine = (text) => { tail = (tail + text).slice(-OUTPUT_TAIL_CAP) }
512
+ const eventList = () => sessionEventList(agent)
513
+ const pump = () => {
514
+ // 面板上点了停止:立刻打断当前会话,不等它自己跑完
515
+ if (!cancelSent && run.status !== 'running') {
516
+ cancelSent = true
517
+ try { if (typeof agent.cancel === 'function') agent.cancel({ kind: 'user' }) } catch { /* 会话可能已空闲 */ }
518
+ }
519
+ let changed = false
520
+ for (const ev of eventList()) {
521
+ if (ev.seq < firstSeq || seen.has(ev.seq)) continue
522
+ seen.add(ev.seq)
523
+ const d = ev.data || {}
524
+ if (ev.type === 'assistant/chunk' && d.chunk && typeof d.chunk.text === 'string' && (d.chunk.type === 'text-delta' || d.chunk.type === 'text')) { liveLine(d.chunk.text); changed = true }
525
+ else if (ev.type === 'tool/call') { liveLine(`\n[tool] ${String(d.name || '')} `); changed = true }
526
+ }
527
+ if (changed && Date.now() - lastTouch > TOUCH_THROTTLE_MS) { lastTouch = Date.now(); attempt.outputTail = tail; this.runs.touch(run) }
528
+ }
529
+ const timer = setInterval(pump, PUMP_MS)
530
+ if (typeof timer.unref === 'function') timer.unref()
531
+ try {
532
+ // v3 裸包装 {kind:'plugin', plugin:…} 在 format v4 宿主写路径抛 SessionFormatError
533
+ // (同 dsh-kb#1),必须用生产者自有写法 kind:'plugin:<名>'
534
+ agent.followup({ content: [{ type: 'text', text: prompt }], source: { kind: 'plugin:dsh-workflow-execute' } })
535
+ await agent.whenIdle()
536
+ } finally {
537
+ clearInterval(timer)
538
+ pump()
539
+ }
540
+ let output = tail.trim()
541
+ if (output === '') {
542
+ // 兜底:从最终 assistant 消息提取可见文本(kit 同款)
543
+ const list = eventList()
544
+ for (let i = list.length - 1; i >= 0; i--) {
545
+ const ev = list[i]
546
+ const msg = ev && ev.type === 'assistant/message' && ev.data ? ev.data.message : undefined
547
+ if (msg && msg.role === 'assistant' && Array.isArray(msg.content)) {
548
+ const text = msg.content.filter((b) => b && (b.type === 'text' || b.type === undefined) && typeof b.text === 'string').map((b) => b.text).join('')
549
+ if (text.trim() !== '') { output = text; break }
550
+ }
551
+ }
552
+ }
553
+ try { if (this.ctx.sessions && typeof this.ctx.sessions.flush === 'function') await this.ctx.sessions.flush(agent.session) } catch { /* 刷盘失败不致命 */ }
554
+
555
+ // 这一轮是怎么结束的:用户点了终止(turn/end.kind = aborted)或会话出错(error)时,
556
+ // 不能当成「环节跑完了」继续走门禁/流转——那会带着半截产物进入下一环节。
557
+ const endKind = turnEndKind(eventList(), firstSeq)
558
+ const stopped = run.status !== 'running'
559
+ if (stopped || endKind === 'aborted' || endKind === 'error') {
560
+ attempt.outputTail = output.slice(-OUTPUT_TAIL_CAP)
561
+ attempt.status = 'failed'
562
+ attempt.finishedAt = Date.now()
563
+ attempt.error = stopped ? '已停止运行,本环节作废' : `会话被中断(${endKind}),本环节作废`
564
+ this.runs.touch(run)
565
+ if (run.status === 'running') this.finishRun(run, 'stopped', attempt.error)
566
+ throw new LinkInterrupted(attempt.error)
567
+ }
568
+
569
+ attempt.outputTail = output.slice(-OUTPUT_TAIL_CAP)
570
+ // 环节 token 用量:全新会话 → 会话内逐步 usage 求和即本环节消耗
571
+ const usage = sumUsage(agent, firstSeq)
572
+ if (usage) {
573
+ attempt.usage = usage
574
+ run.usage = addUsage(run.usage, usage)
575
+ }
576
+ // 产物收集:只认会话里真实的写文件操作(write/edit 结果 meta.diffs、str-replace-editor
577
+ // 调用参数),按路径累计 +n/-n 与 diff;逐个 stat 出存在性
578
+ try {
579
+ attempt.artifacts = await resolveArtifactEntries({ cwd: this.runCwd(run), written: collectWriteOps(eventList(), firstSeq) })
580
+ } catch { /* stat 失败不致命:产物列表留空 */ }
581
+ return output
582
+ }
583
+
584
+ /** 评审超时(毫秒):gate.timeout_ms > limits.judge_timeout_ms > 默认 180s。 */
585
+ judgeTimeoutMs(run, gate) {
586
+ const limits = (run && run.snapshot && run.snapshot.limits) || {}
587
+ const pick = (v) => (Number.isFinite(Number(v)) && Number(v) >= 5000 ? Number(v) : null)
588
+ return pick(gate && gate.timeout_ms) ?? pick(limits.judge_timeout_ms) ?? JUDGE_TIMEOUT_MS
589
+ }
590
+
591
+ /** 门禁裁判:独立短会话按 ai_criteria_review 打分。 */
592
+ async judgeGate(run, entry, gate, output) {
593
+ const type = gate.type || 'ai_criteria_review'
594
+ // 评审口径:gate.review_prompt 优先于 link.review_prompt(该字段此前只落盘、从未生效)
595
+ const reviewPrompt = (gate && typeof gate.review_prompt === 'string' && gate.review_prompt.trim())
596
+ || (entry.link && typeof entry.link.review_prompt === 'string' && entry.link.review_prompt.trim())
597
+ || ''
598
+ const prompt = [
599
+ '你是工作流门禁评审员。对下面这次环节执行打分,只输出一个 JSON 对象:{"score": 0-100整数, "reason": "一句话理由"}。',
600
+ `门禁:${gate.name || '(未命名)'}(评审方式 ${type});通过分数线:${typeof gate.min_score === 'number' ? gate.min_score : 0}。`,
601
+ reviewPrompt ? `【评审口径】
602
+ ${reviewPrompt}` : '',
603
+ entry.link && entry.link.acceptance_criteria ? `【本环节验收标准】\n${entry.link.acceptance_criteria}` : '',
604
+ '',
605
+ `【环节指令】\n${entry.link.prompt || '(空)'}`,
606
+ `【执行报告】\n${output || '(无输出)'}`,
607
+ ].join('\n')
608
+ try {
609
+ const { agent } = await this.getSession({ run, title: `门禁评审 · ${run.runName || run.displayName || run.processName} · ${gate.name || gate.type}`, withTools: false })
610
+ await agent.whenIdle()
611
+ const firstSeq = agent.session.seq
612
+ const eventList = () => sessionEventList(agent)
613
+ agent.followup({ content: [{ type: 'text', text: prompt }], source: { kind: 'plugin:dsh-workflow-execute' } })
614
+ const idle = agent.whenIdle()
615
+ const timer = new Promise((resolve) => setTimeout(() => resolve('timeout'), this.judgeTimeoutMs(run, gate)))
616
+ const outcome = await Promise.race([idle.then(() => 'done'), timer])
617
+ const usage = sumUsage(agent, firstSeq)
618
+ if (outcome !== 'done') return { score: 0, reason: '评审超时,按不通过处理', usage }
619
+ const list = eventList()
620
+ let text = ''
621
+ for (let i = list.length - 1; i >= 0; i--) {
622
+ const ev = list[i]
623
+ if (ev.seq < firstSeq) continue
624
+ const msg = ev && ev.type === 'assistant/message' && ev.data ? ev.data.message : undefined
625
+ if (msg && msg.role === 'assistant' && Array.isArray(msg.content)) {
626
+ text = msg.content.filter((b) => b && (b.type === 'text' || b.type === undefined) && typeof b.text === 'string').map((b) => b.text).join('')
627
+ if (text.trim() !== '') break
628
+ }
629
+ }
630
+ return { ...parseJudgeOutput(text), usage }
631
+ } catch (error) {
632
+ return { score: 0, reason: `评审会话失败:${String(error && error.message || error)}` }
633
+ }
634
+ }
635
+
636
+ // ── 人的操作 ──────────────────────────────────────────────────────────
637
+
638
+ actionPause(id) {
639
+ const run = this.runs.get(id)
640
+ if (!run) throw new Error(`Error: not_found: ${id}`)
641
+ if (run.status !== 'running' && run.status !== 'queued') throw new Error('Error: invalid_transition: 只能暂停运行中/排队中的运行')
642
+ run.status = 'paused'
643
+ this.runs.touch(run)
644
+ return run
645
+ }
646
+
647
+ actionResume(id) {
648
+ const run = this.runs.get(id)
649
+ if (!run) throw new Error(`Error: not_found: ${id}`)
650
+ if (run.status !== 'paused') throw new Error('Error: invalid_transition: 只能继续已暂停的运行')
651
+ run.status = 'queued'
652
+ run.error = undefined
653
+ this.runs.touch(run)
654
+ this.tick()
655
+ return run
656
+ }
657
+
658
+ actionStop(id) {
659
+ const run = this.runs.get(id)
660
+ if (!run) throw new Error(`Error: not_found: ${id}`)
661
+ if (['done', 'stopped', 'failed'].includes(run.status)) throw new Error('Error: invalid_transition: 运行已结束')
662
+ // 先打断正在跑的那一轮会话(否则环节会跑完再停,白烧一次 token)
663
+ const cached = this.runSessions.get(run.id)
664
+ if (cached && cached.agent && typeof cached.agent.cancel === 'function') {
665
+ try { cached.agent.cancel({ kind: 'user' }) } catch { /* 会话已空闲 */ }
666
+ }
667
+ this.finishRun(run, 'stopped')
668
+ this.tick()
669
+ return run
670
+ }
671
+
672
+ /** break 裁决:retry(清零返工重跑本环节)/ skip(视为通过,按 on_success 走)/ stop。 */
673
+ actionResolveBreak(id, decision) {
674
+ const run = this.runs.get(id)
675
+ if (!run) throw new Error(`Error: not_found: ${id}`)
676
+ if (run.status !== 'awaiting' || !run.pendingBreak) throw new Error('Error: invalid_transition: 运行不在等待裁决状态')
677
+ const linkId = run.pendingBreak.linkId
678
+ const kind = run.pendingBreak.kind || 'gate'
679
+ // 人工审核(review_type: human)的裁决:通过 = 把该次尝试标记 approved 后按 on_success 走;
680
+ // 打回 = 清零返工重跑本环节。人工通过不补 skipped 记录——那不是「跳过环节」。
681
+ const markAwaitingReview = (status) => {
682
+ for (let i = run.trail.length - 1; i >= 0; i--) {
683
+ const t = run.trail[i]
684
+ if (t.linkId === linkId && t.status === 'awaiting_review') { t.status = status; t.finishedAt = Date.now(); return }
685
+ }
686
+ }
687
+ if (decision === 'stop') { run.pendingBreak = null; this.finishRun(run, 'stopped'); this.tick(); return run }
688
+ run.pendingBreak = null
689
+ if (decision === 'retry') {
690
+ if (kind === 'human') markAwaitingReview('rejected')
691
+ run.rework[linkId] = 0
692
+ run.current = { phaseId: undefined, linkId, attempt: 1 }
693
+ } else if (decision === 'skip') {
694
+ const { map } = indexLinks(run.snapshot)
695
+ const entry = map.get(linkId)
696
+ if (kind === 'human') markAwaitingReview('approved')
697
+ else run.trail.push(makeAttempt(entry ? entry.phase.id : undefined, linkId, (run.rework[linkId] || 0) + 1, { status: 'skipped', finishedAt: Date.now() }))
698
+ const route = parseFlow(entry && entry.link.on_success) || 'next'
699
+ const next = route === 'next' ? nextLinkAfter(run.snapshot, linkId) : route === 'end' ? null : route.jump
700
+ if (!next) { this.finishRun(run, 'done'); this.tick(); return run }
701
+ run.current = { phaseId: undefined, linkId: next, attempt: (run.rework[next] || 0) + 1 }
702
+ } else {
703
+ throw new Error('Error: invalid_input: decision 必须是 retry | skip | stop')
704
+ }
705
+ run.status = 'queued'
706
+ this.runs.touch(run)
707
+ this.tick()
708
+ return run
709
+ }
710
+
711
+ /** 跳过某个环节(仅暂停/等待裁决/失败态可用);retryLink 重跑某环节。 */
712
+ actionSkipLink(id, linkId) {
713
+ const run = this.runs.get(id)
714
+ if (!run) throw new Error(`Error: not_found: ${id}`)
715
+ if (run.status === 'running') throw new Error('Error: invalid_transition: 运行中请先暂停')
716
+ const { map } = indexLinks(run.snapshot)
717
+ const entry = map.get(linkId)
718
+ if (!entry) throw new Error('Error: invalid_input: 环节不存在')
719
+ run.trail.push(makeAttempt(entry.phase.id, linkId, (run.rework[linkId] || 0) + 1, { status: 'skipped', finishedAt: Date.now() }))
720
+ const route = parseFlow(entry.link.on_success) || 'next'
721
+ const next = route === 'next' ? nextLinkAfter(run.snapshot, linkId) : route === 'end' ? null : route.jump
722
+ if (!next) { this.finishRun(run, 'done'); this.tick(); return run }
723
+ run.current = { phaseId: undefined, linkId: next, attempt: (run.rework[next] || 0) + 1 }
724
+ if (run.status !== 'queued') run.status = 'queued'
725
+ this.runs.touch(run)
726
+ this.tick()
727
+ return run
728
+ }
729
+
730
+ actionRetryLink(id, linkId) {
731
+ const run = this.runs.get(id)
732
+ if (!run) throw new Error(`Error: not_found: ${id}`)
733
+ if (run.status === 'running') throw new Error('Error: invalid_transition: 运行中请先暂停')
734
+ const { map } = indexLinks(run.snapshot)
735
+ if (!map.has(linkId)) throw new Error('Error: invalid_input: 环节不存在')
736
+ run.rework[linkId] = 0
737
+ run.current = { phaseId: undefined, linkId, attempt: 1 }
738
+ run.status = 'queued'
739
+ run.error = undefined
740
+ this.runs.touch(run)
741
+ this.tick()
742
+ return run
743
+ }
744
+ }
745
+
746
+ module.exports = { ExecutionService, parseJudgeOutput, sumUsage, addUsage, runSummary }