ralphflow-dsh 0.1.0 → 2.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.
Files changed (67) hide show
  1. package/README.md +227 -158
  2. package/lib/create.d.ts +7 -11
  3. package/lib/create.js +132 -83
  4. package/lib/engine.d.ts +667 -262
  5. package/lib/engine.js +3583 -2579
  6. package/lib/index.d.ts +3 -4
  7. package/lib/index.js +222 -163
  8. package/lib/message-source.d.ts +25 -0
  9. package/lib/message-source.js +2 -0
  10. package/lib/reset.d.ts +40 -0
  11. package/lib/reset.js +147 -0
  12. package/lib/tools.d.ts +31 -14
  13. package/lib/tools.js +407 -684
  14. package/lib/verify.d.ts +57 -0
  15. package/lib/verify.js +326 -0
  16. package/lib/voting.d.ts +63 -0
  17. package/lib/voting.js +131 -0
  18. package/package.json +24 -45
  19. package/workflows/loop.yaml +21 -6
  20. package/workflows/spec.yaml +51 -46
  21. package/lib/actions.d.ts +0 -37
  22. package/lib/actions.js +0 -55
  23. package/lib/check-voting.d.ts +0 -54
  24. package/lib/check-voting.js +0 -289
  25. package/lib/check.d.ts +0 -64
  26. package/lib/check.js +0 -329
  27. package/lib/client/CommandCard.d.ts +0 -24
  28. package/lib/client/CommandCard.js +0 -69
  29. package/lib/client/HeaderAction.d.ts +0 -39
  30. package/lib/client/HeaderAction.js +0 -509
  31. package/lib/client/RunCard.d.ts +0 -27
  32. package/lib/client/RunCard.js +0 -375
  33. package/lib/client/client.d.ts +0 -3
  34. package/lib/client/client.js +0 -275
  35. package/lib/client/definition.d.ts +0 -126
  36. package/lib/client/definition.js +0 -259
  37. package/lib/client/hidden-runs.d.ts +0 -6
  38. package/lib/client/hidden-runs.js +0 -52
  39. package/lib/client/http-state.d.ts +0 -67
  40. package/lib/client/http-state.js +0 -81
  41. package/lib/client/markdown.d.ts +0 -26
  42. package/lib/client/markdown.js +0 -174
  43. package/lib/client/notify-watch.d.ts +0 -38
  44. package/lib/client/notify-watch.js +0 -98
  45. package/lib/client/notify.d.ts +0 -21
  46. package/lib/client/notify.js +0 -168
  47. package/lib/client/snapshots.d.ts +0 -8
  48. package/lib/client/snapshots.js +0 -101
  49. package/lib/client.js +0 -2361
  50. package/lib/commands.d.ts +0 -41
  51. package/lib/commands.js +0 -223
  52. package/lib/deps.d.ts +0 -17
  53. package/lib/deps.js +0 -19
  54. package/lib/done-detect.d.ts +0 -2
  55. package/lib/done-detect.js +0 -28
  56. package/lib/driver.d.ts +0 -32
  57. package/lib/driver.js +0 -248
  58. package/lib/events.d.ts +0 -35
  59. package/lib/events.js +0 -52
  60. package/lib/jobs.d.ts +0 -56
  61. package/lib/jobs.js +0 -355
  62. package/lib/mutex.d.ts +0 -9
  63. package/lib/mutex.js +0 -21
  64. package/lib/session-hygiene.d.ts +0 -25
  65. package/lib/session-hygiene.js +0 -205
  66. package/lib/voting-progress.d.ts +0 -37
  67. package/lib/voting-progress.js +0 -89
package/lib/tools.js CHANGED
@@ -1,716 +1,439 @@
1
1
  import { defineTool } from "@deepseek-ai/dsh-tools";
2
- import { isSubWorkflowStep, MANUAL_GATE_MARKER, DONE_TAG_MARKER } from "./engine.js";
3
- import { statusText, runCheckAndAdvance } from "./driver.js";
4
- import { createEmitter } from "./events.js";
5
- import { createCheckDeps } from "./deps.js";
6
- import { deleteVotingProgress, readVotingProgress } from "./voting-progress.js";
7
- import { withInstanceLock } from "./mutex.js";
8
- import { liveVerifierCount } from "./check.js";
9
- import { scanSessionLogs, unbrickSessions } from "./session-hygiene.js";
10
2
  import { CREATE_GUIDE } from "./create.js";
11
- import fs from "fs";
12
- import path from "path";
13
- import os from "os";
14
- /** 首次启动时附在返回文本后的引导块:告诉用户接下来的节奏与观察点 */
15
- const ONBOARDING = `\n\n---\n\n## 🧭 接下来会发生什么\n\n1. 模型在本对话执行当前步骤的任务,完成后输出 \`<promise>done</promise>\`。\n2. 完成后自动进入独立验证(多验证者投票),页面顶部 **Ralph Flow** 入口实时显示每一票与当前步骤。\n3. 验证失败会把原因自动发回给模型重做;标记了人工审查的步骤会停下等你批准(届时页头徽标变黄并弹通知)。多数时间你只需等待——随时 \`/ralphflow-status\` 看进度,或点页头入口展开任务列表。`;
3
+ /**
4
+ * 工作流机制说明(/ralphflow-start 与 /ralphflow-loop、/ralphflow-spec 等快捷命令共享,opencode 版 SHARED_MECHANISM 的 v0 裁剪版)。
5
+ * 让模型知道:两阶段协议、自动验证、手动审查的放行语义、暂停恢复、以及**阶段播报**(AI 交互友好的来源)。
6
+ */
7
+ const SHARED_MECHANISM = `## 工作流机制(每次启动都会生效)
8
+
9
+ 每个工作流步骤有两个阶段:
10
+
11
+ **DO 阶段(执行)**:
12
+ - 按收到的提示执行当前步骤的任务,完成实际工作(写代码、创建文件、运行命令)。
13
+ - 所有任务要求满足后,**调用 \`ralphflow_submit\` 工具交卷**(可在 \`summary\` 参数里简述做了什么)。
14
+ - 只在回复里说「完成了」**不会**触发验证——必须调用工具。
15
+ - 有 \`check\` / \`check_voting\` 的普通步骤到此为止——你空闲时系统会**自动**运行独立 CHECK,**不需要**调用其它工具。
16
+
17
+ **CHECK 阶段(仅本步有 \`check\` / \`check_voting\` 时)**:
18
+ - 交卷后,一个**独立验证者会话**(全新上下文,看不到本对话)依据该步骤的检查依据取证判定。你会收到「🔍 验证中」与验证结果消息。**没有 \`check\` / \`check_voting\` 的步骤不走这一阶段**(见下方「未配置 \`check\` / \`check_voting\` 的步骤」)。
19
+ - 步骤写的是 \`check_voting\`(多验证者投票)时:**N 个验证者并行**、各查一条检查依据、**全过才放行**;每票完成会各推一行进度。
20
+ - 验证是**异步**的:验证者(独立会话)会真的去读文件、跑命令取证,它在做什么你在会话里看得到;期间不需要你做任何操作,跑完会自动唤醒本会话。**不要给时长预估**——委派没有超时上界,任何时间承诺都是编的。
21
+ - **通过** → 工作流自动推进到下一步并注入下一条 DO 提示。
22
+ - **未通过** → 你收到失败原因并重做该步(自动重试,不会反复打扰用户)。
23
+
24
+ **手动步骤**(工作流 \`manual_step\` 列出的步骤,**且本步有 \`check\` / \`check_voting\`**):CHECK **通过后**系统停下等**用户**审查(会收到 🙋 消息)。用户的 \`/ralphflow-continue\` 是**放行**——直接进入下一步,不重复验证。用户要求修改时,你改完再次调用 \`ralphflow_submit\`,会再次自动验证,通过后再停下。
25
+
26
+ **未配置 \`check\` / \`check_voting\` 的步骤**(工作流定义声明本步免验证):**不做独立验证**——交卷后**跳过对抗性验证**,直接进入下一步;\`manual_step\` 的这类步骤则是**纯人工审查**(交卷后停在审查门,等用户 \`/ralphflow-continue\` 放行)。这类步骤务必自查产出是否满足任务要求。
27
+
28
+ **暂停与恢复**:某步验证失败达到 \`max_fail_count\` 时工作流暂停。用 \`/ralphflow-status\` 看失败原因,修复后 \`/ralphflow-continue\` 恢复(重置失败计数并重试)。
29
+
30
+ **重要**:\`ralphflow_continue\` 只用于 ① 批准手动审查 ② 恢复暂停 ③ 接管中断实例。**有 \`check\` / \`check_voting\` 的普通步骤不要调用它**——验证是自动的;没有检查依据的**普通步骤**交卷后也会自动继续,审查门步骤则按 ① 等你放行。
31
+
32
+ **阶段播报**:收到系统阶段通知时,简短地确认一下,让用户随时了解进度:
33
+ - DO 阶段:「已启动步骤 [X],正在处理 [任务]」
34
+ - CHECK 阶段(仅本步有 \`check\` / \`check_voting\` 时):「🔍 已交卷,独立验证者正在取证判定」(投票步:N 个验证者并行,全过才放行)
35
+ - 完成:「✅ 所有步骤完成,工作流结束」`;
36
+ /** 可用命令清单 —— 单一事实源:命令被拒绝时给模型转达的「还能用什么」与兜底回执共用同一份,避免两处各写一遍后走样。 */
37
+ const AVAILABLE_COMMANDS = "`/ralphflow-start`、`/ralphflow-list`、`/ralphflow-status`、`/ralphflow-continue`、`/ralphflow-reset`、`/ralphflow-rewind`、`/ralphflow-cancel`、`/ralphflow-create`、`/ralphflow-doctor`";
38
+ function sessionIdOf(agent) {
39
+ return agent?.session?.id ?? null;
40
+ }
41
+ // ─── 工具注册 ────────────────────────────────────────────────────────────────
16
42
  export function registerTools(deps) {
17
- const { ctx, engine, jobs } = deps;
18
- const tools = ctx.tools;
19
- const emit = createEmitter({ ctx, engine });
43
+ const { ctx } = deps;
20
44
  const handlers = new Map();
21
- const sessionIdOf = (agent) => agent?.session?.id ?? null;
45
+ const tools = ctx.tools;
22
46
  /**
23
- * 把实例的 UI 事件帧从执行日志重放到当前属主会话(接管场景专用)。
24
- * 返回是否发生了重放。失败绝不阻断接管流程本身。
25
- * 注:重放只落审计日志(宿主持久化不接受插件自定义会话帧);新会话的
26
- * 可视化档案由页头任务列表(HTTP 状态通道)承载。
47
+ * 会话 → 它所在工作区的引擎。**这是所有「发现面」的唯一入口。**
48
+ *
49
+ * 引擎的根就是会话工作区,所以列表、历史、doctor、自定义工作流查找天然落在对的地方。
50
+ * 以前这里是「一个引擎 + 全局索引」:引擎根是 dsh 进程的 cwd,而实例资产落在会话
51
+ * 工作区——真实 GUI 里两者必然不同(`dsh web` cwd = /home/yj,会话工作区 = 仓库),
52
+ * 于是自定义工作流加载不到、历史列表永远空、doctor 看不见残留。
27
53
  */
28
- function replayInstanceHistory(instId, emitter, eng) {
29
- try {
30
- const frames = eng.readUiEventFrames(instId);
31
- if (frames.length === 0)
32
- return false;
33
- for (const f of frames) {
34
- try {
35
- emitter.emit(instId, f.type, f.data);
36
- }
37
- catch { }
38
- }
39
- eng.logEvent(instId, "info", "history_replayed", { frames: frames.length });
40
- return true;
41
- }
42
- catch {
43
- return false;
44
- }
45
- }
46
- function makeDrive(agent, instId) {
47
- return {
48
- engine,
49
- deps: createCheckDeps({ ctx, engine, emit, getAgent: deps.getAgent, instId }),
50
- emit,
51
- parent: agent,
52
- };
53
- }
54
- // ─── ralphflow_start ────────────────────────────────────────────────────────
55
- const startHandler = async (args, agent) => {
56
- const { workflow, task, extra_dirs } = args ?? {};
57
- if (!workflow || !String(workflow).trim()) {
58
- return `缺少工作流名称。用法:\`ralphflow_start(workflow, task)\`,或 slash 命令 \`/ralphflow-start <工作流名> <任务描述>\`。可用工作流用 /ralphflow-list 查看。`;
59
- }
60
- if (task === undefined || task === null || !String(task).trim()) {
61
- return `缺少任务描述——请说明要完成什么。\n\n用法示例:\`/ralphflow-start loop 用 JWT 实现用户认证模块\`。`;
62
- }
54
+ const engineOf = (agent) => {
55
+ const sid = sessionIdOf(agent);
56
+ return deps.engineFor(sid ? deps.workspaceOfSession?.(sid) : undefined);
57
+ };
58
+ const startHandler = (args, agent) => {
63
59
  const sessionId = sessionIdOf(agent);
64
- const instances = engine.listInstances();
65
- const mine = sessionId != null ? instances.find((i) => i.owner === sessionId) : undefined;
66
- if (mine) {
67
- return `当前会话已有活跃工作流实例 \`${mine.id}\`(工作流: ${mine.state.workflow_name},步骤: ${mine.state.current_step})。\n\n使用 /ralphflow-continue 继续,或先用 /ralphflow-cancel 取消。`;
68
- }
69
- const problems = [];
70
- const workflowDef = engine.loadWorkflow(workflow, problems);
71
- if (!workflowDef) {
72
- if (problems.length > 0)
73
- return `工作流 "${workflow}" 定义无效,无法启动:\n${problems.map((p) => `- ${p}`).join("\n")}\n\n请修复工作流 YAML 后重试(可用 /ralphflow-doctor 看完整诊断)。`;
74
- const available = engine.listWorkflows();
75
- return available.length > 0
76
- ? `工作流 "${workflow}" 未找到。可用工作流:\n${available.map((w) => `- **${w.name}**: ${w.desc}`).join("\n")}`
77
- : "没有找到工作流。请在 <workspace>/ralph-flow/workflows/ 目录创建工作流定义文件。";
78
- }
79
- const firstStep = workflowDef.steps[0];
80
- if (!firstStep)
81
- return "工作流没有步骤。";
82
- const home = os.homedir() || "";
83
- const resolvedExtraDirs = [];
84
- for (const d of (extra_dirs || [])) {
85
- let p = String(d).trim();
86
- if (!p)
87
- continue;
88
- if (p === "~" || p.startsWith("~/"))
89
- p = path.join(home, p.slice(1));
90
- if (!path.isAbsolute(p))
91
- p = path.resolve(engine.projectDir, p);
92
- let st = null;
93
- try {
94
- st = fs.statSync(p);
95
- }
96
- catch { }
97
- if (!st || !st.isDirectory())
98
- return `extra_dirs 校验失败:\`${d}\`(解析为 \`${p}\`)不存在或不是目录。请修正后重新启动。`;
99
- resolvedExtraDirs.push(p);
100
- }
101
- const instId = engine.generateInstanceId(workflow);
102
- fs.mkdirSync(engine.getInstanceDir(instId), { recursive: true });
103
- engine.writeArtifactsDirName(instId, String(task));
104
- engine.writeExtraDirs(instId, resolvedExtraDirs);
105
- const othersNote = instances.length > 0 ? `\n\n> ℹ️ 本工作区下另有 ${instances.length} 个工作流实例,使用 /ralphflow-status 查看。` : "";
106
- const extraDirsNote = resolvedExtraDirs.length > 0 ? `\n\n验证器额外可读目录:${resolvedExtraDirs.map((d) => `\`${d}\``).join("、")}` : "";
107
- const baseState = { active: true, workflow_name: String(workflow), current_step: firstStep.id, current_phase: "do", fail_count: 0, user_task: String(task), paused: false, session_id: sessionId ?? undefined };
108
- const stepsOverview = () => workflowDef.steps.map((s, i) => ` ${i + 1}. **${s.id}**: ${s.desc}${isSubWorkflowStep(s) ? ` (子工作流: ${s.workflow})` : ""}${!isSubWorkflowStep(s) && s.no_check ? " (无独立验证)" : ""}${workflowDef.manual_step?.includes(s.id) ? " 📋人工审查" : ""}`).join("\n");
109
- if (isSubWorkflowStep(firstStep)) {
110
- engine.recordStepStart(instId, firstStep.id, "do");
111
- engine.logEvent(instId, "info", "step_start", { step: firstStep.id, phase: "do" });
112
- engine.writeState(baseState, instId);
113
- engine.pushState(baseState, instId);
114
- const subResult = engine.resolveSubWorkflowEntry(instId, firstStep.workflow, task, firstStep);
115
- if (subResult.error) {
116
- try {
117
- fs.rmSync(engine.getInstanceDir(instId), { recursive: true, force: true });
118
- }
119
- catch { }
120
- return subResult.text;
121
- }
122
- engine.markPromptDelivered(engine.readState(instId)?.current_step || firstStep.id, instId);
123
- engine.logEvent(instId, "info", "workflow_start", { workflow, instance: instId });
124
- emit.emit(instId, "tool-ralphflow/run-start", {
125
- runId: instId, workflow, task,
126
- steps: workflowDef.steps.map((s) => ({ id: s.id, desc: s.desc })),
127
- });
128
- jobs.ensure(instId);
129
- return `工作流 "${workflow}" 已启动(实例 \`${instId}\`)。\n\n任务:${task}\n\n## 步骤概览\n${stepsOverview()}\n\n启动子工作流:**${firstStep.id}** → ${firstStep.workflow}${extraDirsNote}${othersNote}\n\n---\n\n${subResult.text}${ONBOARDING}`;
130
- }
131
- engine.writeState(baseState, instId);
132
- engine.logEvent(instId, "info", "workflow_start", { workflow, instance: instId });
133
- engine.recordStepStart(instId, firstStep.id, "do");
134
- engine.logEvent(instId, "info", "step_start", { step: firstStep.id, phase: "do" });
135
- if (workflowDef.manual_step && workflowDef.manual_step.includes(firstStep.id)) {
136
- engine.writeManualStepMarker(instId);
137
- }
138
- engine.markPromptDelivered(firstStep.id, instId);
139
- emit.emit(instId, "tool-ralphflow/run-start", {
140
- runId: instId, workflow, task,
141
- steps: workflowDef.steps.map((s) => ({ id: s.id, desc: s.desc })),
142
- });
143
- jobs.ensure(instId);
144
- return `工作流 "${workflow}" 已启动(实例 \`${instId}\`)。\n\n任务:${task}\n\n## 步骤概览\n${stepsOverview()}\n\n开始:**${firstStep.id}** - ${firstStep.desc}${extraDirsNote}${othersNote}\n\n${engine.buildDoPrompt(instId, firstStep, String(task))}${ONBOARDING}`;
60
+ if (!sessionId)
61
+ return "找不到当前会话,无法启动工作流。";
62
+ return engineOf(agent).start(String(args?.workflow ?? ""), String(args?.task ?? ""), sessionId).text;
145
63
  };
146
- handlers.set("ralphflow_start", startHandler);
147
- // ─── ralphflow_continue ─────────────────────────────────────────────────────
148
- const continueHandler = async (args, agent) => {
149
- const instance = args?.instance;
64
+ const continueHandler = (args, agent) => {
150
65
  const sessionId = sessionIdOf(agent);
151
- // 预解析仅为取得锁 key(纯读);接管与全部推进在锁内完成
152
- const pre = engine.resolveInstance(instance, sessionId);
153
- if (!pre.ok)
154
- return pre.text;
155
- // 以下分支可能触发异步推进——整段放入实例互斥锁,双会话并发 continue 时串行化
156
- return withInstanceLock(pre.id, async () => {
157
- // 锁内重新解析 + 接管:排队期间实例可能已被取消/易主
158
- const resolution = engine.resolveInstance(instance, sessionId);
159
- if (!resolution.ok)
160
- return resolution.text;
161
- const instId = resolution.id;
162
- const attached = resolution.attached;
163
- if (attached) {
164
- const other = engine.listInstances().find((i) => i.id !== instId && i.owner === sessionId);
165
- if (other)
166
- return `当前会话已有活跃工作流实例 \`${other.id}\`。先 /ralphflow-cancel 它,或为该实例指定 \`instance\` 参数接管。`;
167
- // 转交通知:接管后终态帧只会发给新会话,旧会话那张卡若不显式释放
168
- // 会永远停在「运行中」变成僵尸(用户看到的「明明跑完了还在转」)。
169
- const previousOwner = engine.readState(instId)?.session_id ?? null;
170
- engine.claimOwnership(instId, sessionId);
171
- if (previousOwner && previousOwner !== sessionId) {
172
- try {
173
- emit.emitFinal(instId, previousOwner, "tool-ralphflow/run-detach", {
174
- runId: instId, workflow: engine.readState(instId)?.workflow_name ?? "",
175
- reason: "已在另一个会话继续",
176
- });
177
- }
178
- catch { }
179
- }
180
- // 接管即历史重放:本实例的事件帧全发到了旧会话,新会话的对话里没有
181
- // 任何可导航的卡片。从执行日志回放 UI 帧(client 折叠器幂等),用户
182
- // 接手的是一本有目录的档案——哪几步过了、谁投的票、为何中断一目了然。
183
- replayInstanceHistory(instId, emit, engine);
184
- }
185
- let state = engine.readState(instId);
186
- if (!state)
187
- return `实例 ${instId} 不存在。`;
188
- // 工作流定义在锁内加载:排队期间用户可能编辑过 YAML
189
- const workflow = engine.loadWorkflow(state.workflow_name);
190
- if (!workflow)
191
- return `工作流 "${state.workflow_name}" 未找到。`;
192
- // 0. archive_failed pause → 上轮完成时报告归档失败(destroyInstance 拒绝
193
- // 销毁、现场完整保留):这里只重试归档+销毁并补发终态帧——所有步骤
194
- // 均已通过,绝不能走重跑验证路径白烧 token。
195
- if (state.paused && state.pause_reason === "archive_failed") {
196
- const reportPath = engine.destroyInstance(instId, "completed");
197
- if (!reportPath) {
198
- engine.logEvent(instId, "error", "complete_archive_retry_failed", { workflow: state.workflow_name });
199
- return `## ⚠️ 报告归档仍失败\n\n实例 \`${instId}\` 的最终报告依然写入失败(磁盘满或权限不足)。实例与执行记录继续原样保留。\n\n👉 再次排查磁盘/权限后重试 \`/ralphflow-continue\`;或 \`/ralphflow-cancel\` 放弃归档直接结束。`;
200
- }
201
- // 实例已销毁:与 finishTransition 正常完成一致,用锁内快照的属主会话
202
- // emitFinal 补发 report + run-end done,UI 卡片从「⏸ 已暂停」翻转为完成态。
203
- const owner = state.session_id ?? null;
204
- let reportText = "";
205
- try {
206
- reportText = fs.readFileSync(reportPath, "utf-8");
207
- }
208
- catch { }
209
- if (reportText) {
210
- emit.emitFinal(instId, owner, "tool-ralphflow/report", { runId: instId, text: reportText, reportPath });
211
- }
212
- emit.emitFinal(instId, owner, "tool-ralphflow/run-end", { runId: instId, stopReason: "done", reportId: instId });
213
- jobs.kill(instId);
214
- engine.logEvent(instId, "info", "workflow_end", { workflow: state.workflow_name, via: "archive_retry" });
215
- return `## 🎉 工作流完成!\n\n报告归档已重试成功,无需再操作。\n\n执行报告:${path.relative(engine.projectDir, reportPath)}`;
216
- }
217
- // 1. check_error pause → 恢复并重跑验证
218
- if (state.paused && state.pause_reason === "check_error" && state.current_phase === "check") {
219
- const step = engine.getStep(workflow, state.current_step);
220
- if (step && !isSubWorkflowStep(step)) {
221
- engine.writeState({ ...state, paused: false, pause_reason: undefined }, instId);
222
- engine.logEvent(instId, "info", "check_retry_after_infra_error", { workflow: state.workflow_name, step: step.id });
223
- jobs.reobserve(instId);
224
- const result = await runCheckAndAdvance(makeDrive(agent, instId), instId, workflow, step, engine.readState(instId));
225
- return result.text || "验证基础设施故障已清除,工作流恢复。";
226
- }
227
- }
228
- // 2. manual gate → 批准后立即跑验证
229
- if (engine.markerExists(MANUAL_GATE_MARKER, instId)) {
230
- engine.clearManualStepMarker(instId);
231
- engine.clearManualGate(instId);
232
- engine.logEvent(instId, "info", "manual_gate_approved", { step: state.current_step });
233
- jobs.reobserve(instId);
234
- const step = engine.getStep(workflow, state.current_step);
235
- if (step && !isSubWorkflowStep(step)) {
236
- const result = await runCheckAndAdvance(makeDrive(agent, instId), instId, workflow, step, engine.readState(instId));
237
- return result.text || `## ✅ 审查通过\n\n步骤 \`${state.current_step}\` 已批准,验证已自动运行。`;
238
- }
239
- if (step && isSubWorkflowStep(step)) {
240
- // 子工作流的人工门(标在其内部最后一步上):批准后重新进入该子工作流的推进
241
- const subResult = engine.resolveSubWorkflowEntry(instId, step.workflow, state.user_task, step);
242
- if (subResult.error) {
243
- engine.writeState({ ...state, paused: true, pause_reason: "config_error", last_failure_reason: subResult.text }, instId);
244
- return subResult.text;
245
- }
246
- engine.markPromptDelivered(engine.readState(instId)?.current_step || step.id, instId);
247
- return `## ✅ 审查通过\n\n---\n\n${subResult.text}`;
248
- }
249
- return `## ✅ 审查通过\n\n步骤 \`${state.current_step}\` 已批准。验证会自动运行。`;
250
- }
251
- // 3. paused → 恢复并重发 DO(复合步骤则重新进入子工作流)
252
- if (state.paused) {
253
- const previousFailCount = state.fail_count;
254
- const previousReason = state.last_failure_reason;
255
- engine.clearReinjectCounter(instId);
256
- engine.clearDoneTagDetected(instId);
257
- engine.clearManualGate(instId);
258
- engine.writeState({ ...state, current_phase: "do", paused: false, pause_reason: undefined, fail_count: 0 }, instId);
259
- engine.logEvent(instId, "info", "workflow_resumed", { workflow: state.workflow_name, step: state.current_step });
260
- const step = engine.getStep(workflow, state.current_step);
261
- if (!step)
262
- return `已恢复。当前步骤:${state.current_step}`;
263
- jobs.reobserve(instId);
264
- if (isSubWorkflowStep(step)) {
265
- const subResult = engine.resolveSubWorkflowEntry(instId, step.workflow, state.user_task, step, undefined, previousReason, previousFailCount);
266
- if (subResult.error) {
267
- engine.writeState({ ...engine.readState(instId), paused: true, pause_reason: "config_error", last_failure_reason: subResult.text }, instId);
268
- return subResult.text;
269
- }
270
- engine.markPromptDelivered(engine.readState(instId)?.current_step || step.id, instId);
271
- return `## 工作流已恢复\n\n---\n\n${subResult.text}`;
272
- }
273
- if (workflow.manual_step && workflow.manual_step.includes(step.id))
274
- engine.writeManualStepMarker(instId);
275
- const doPrompt = engine.buildDoPrompt(instId, step, state.user_task, previousReason, previousFailCount);
276
- engine.markPromptDelivered(step.id, instId);
277
- return `## 工作流已恢复\n\n---\n\n${doPrompt}`;
278
- }
279
- // 4. crash recovery:卡在 check 无活跃验证
280
- if (state.current_phase !== "do") {
281
- if (state.current_phase === "check") {
282
- // 先清理孤儿登记(进程 kill -9 后 finally 不执行残留的 live 文件),
283
- // 否则这里会永远认为「验证进行中」而死等。
284
- if (liveVerifierCount(engine, instId) > 0) {
285
- return `## ⏳ 验证进行中\n\n步骤 **${state.current_step}** 的独立验证仍在运行。\n\n请等待完成(进度见对话卡与 /ralphflow-status),或使用 /ralphflow-cancel 取消工作流。`;
286
- }
287
- // 有本步的投票进度文件(进程曾在验证期间重启)→ 不回退 DO,
288
- // 直接恢复验证:已投出的票保留,只补跑未完成的票。
289
- const progress = readVotingProgress(engine, instId);
290
- const step = engine.getStep(workflow, state.current_step);
291
- if (progress && progress.stepId === state.current_step && step && !isSubWorkflowStep(step)) {
292
- engine.logEvent(instId, "warn", "check_resume_after_restart", { step: state.current_step, kept_votes: progress.entries.filter((e) => e.status === "passed").length });
293
- jobs.reobserve(instId);
294
- const result = await runCheckAndAdvance(makeDrive(agent, instId), instId, workflow, step, { ...engine.readState(instId), current_phase: "check" });
295
- return result.text || "验证已从上次中断处恢复。";
296
- }
297
- // 单 check 路径的中断无法续跑 → 回 DO 重做
298
- const orphans = engine.readAdversarialSessions(instId);
299
- engine.clearAdversarialSession(instId);
300
- deleteVotingProgress(engine, instId);
301
- engine.logEvent(instId, "warn", "crash_recovery", { step: state.current_step, orphan_sessions: orphans.length });
302
- state = { ...state, current_phase: "do" };
303
- engine.writeState(state, instId);
304
- engine.clearReinjectCounter(instId);
305
- engine.clearManualStepMarker(instId);
306
- engine.clearManualGate(instId);
307
- engine.clearDoneTagDetected(instId);
308
- if (!step)
309
- return `崩溃恢复:步骤 "${state.current_step}" 在工作流中未找到。`;
310
- jobs.reobserve(instId);
311
- if (isSubWorkflowStep(step)) {
312
- const subResult = engine.resolveSubWorkflowEntry(instId, step.workflow, state.user_task, step, undefined, "之前的验证被中断(进程崩溃)。请重新执行任务。", state.fail_count || 0);
313
- if (subResult.error) {
314
- engine.writeState({ ...engine.readState(instId), paused: true, pause_reason: "config_error", last_failure_reason: subResult.text }, instId);
315
- return subResult.text;
316
- }
317
- engine.markPromptDelivered(engine.readState(instId)?.current_step || step.id, instId);
318
- return `## ⚠️ 崩溃恢复\n\n进程在验证期间崩溃。DO 阶段已重置。\n\n---\n\n${subResult.text}`;
319
- }
320
- if (workflow.manual_step && workflow.manual_step.includes(step.id))
321
- engine.writeManualStepMarker(instId);
322
- const prompt = engine.buildDoPrompt(instId, step, state.user_task, "之前的验证被中断(进程崩溃)。请重新执行任务。", state.fail_count || 0);
323
- engine.markPromptDelivered(step.id, instId);
324
- return `## ⚠️ 崩溃恢复\n\n进程在验证期间崩溃。DO 阶段已重置。\n\n---\n\n${prompt}`;
325
- }
326
- return `当前阶段是 "${state.current_phase}",不是 "do"。工作流已在处理中。`;
327
- }
328
- const step = engine.getStep(workflow, state.current_step);
329
- if (!step)
330
- return `步骤 "${state.current_step}" 未找到。`;
331
- // 5. attach 接管中断的 DO → 重发 DO(复合步骤重新进入子工作流)
332
- if (attached && !engine.markerExists(DONE_TAG_MARKER, instId) && !engine.markerExists(MANUAL_GATE_MARKER, instId)) {
333
- jobs.reobserve(instId);
334
- if (isSubWorkflowStep(step)) {
335
- const subResult = engine.resolveSubWorkflowEntry(instId, step.workflow, state.user_task, step, undefined, state.last_failure_reason, state.fail_count || 0);
336
- if (subResult.error) {
337
- engine.writeState({ ...state, paused: true, pause_reason: "config_error", last_failure_reason: subResult.text }, instId);
338
- return subResult.text;
339
- }
340
- engine.markPromptDelivered(engine.readState(instId)?.current_step || step.id, instId);
341
- engine.logEvent(instId, "info", "instance_attached_resume_do", { instance: instId, step: step.id });
342
- return `## 已接管工作流实例 \`${instId}\`\n\n该实例中断于 DO 阶段,继续执行当前步骤。\n\n---\n\n${subResult.text}`;
343
- }
344
- if (workflow.manual_step && workflow.manual_step.includes(step.id))
345
- engine.writeManualStepMarker(instId);
346
- const prompt = engine.buildDoPrompt(instId, step, state.user_task, state.last_failure_reason, state.fail_count || 0);
347
- engine.markPromptDelivered(step.id, instId);
348
- engine.logEvent(instId, "info", "instance_attached_resume_do", { instance: instId, step: step.id });
349
- return `## 已接管工作流实例 \`${instId}\`\n\n该实例中断于 DO 阶段,继续执行当前步骤。\n\n---\n\n${prompt}`;
350
- }
351
- // 6. do 阶段无门无暂停 → 无操作
352
- engine.markPromptDelivered(step.id, instId);
353
- if (isSubWorkflowStep(step)) {
354
- return `步骤 \`${state.current_step}\` 是子工作流(复合)步骤,仍在进行中。验证只在内部步骤完成后才开始。`;
355
- }
356
- return `步骤 \`${state.current_step}\` 仍在 **DO 阶段**(没有待批准的审查、没有暂停、没有中断的实例),本工具无需操作。验证只在 DO 阶段结束后才开始。\n\n${engine.buildDoNudge(instId, state.current_step)}`;
357
- });
66
+ if (!sessionId)
67
+ return "找不到当前会话。";
68
+ return engineOf(agent).continueInstance(sessionId, args?.instance ? String(args.instance) : undefined).text;
358
69
  };
359
- handlers.set("ralphflow_continue", continueHandler);
360
- // ─── ralphflow_status ───────────────────────────────────────────────────────
361
70
  const statusHandler = (args, agent) => {
362
- const instance = args?.instance;
363
71
  const sessionId = sessionIdOf(agent);
364
- if (instance) {
365
- const resolution = engine.resolveInstance(instance, sessionId);
366
- if (!resolution.ok)
367
- return resolution.text;
368
- return statusText(engine, resolution.id, sessionId);
369
- }
370
- const instances = engine.listInstances();
371
- if (instances.length === 0)
372
- return "当前没有活跃的工作流实例。";
373
- // 单实例优先详情(与 opencode 版一致);多实例逐个详情
374
- return instances.map((i) => statusText(engine, i.id, sessionId)).join("\n\n");
375
- };
376
- handlers.set("ralphflow_status", statusHandler);
377
- // ─── ralphflow_list ─────────────────────────────────────────────────────────
378
- const listHandler = () => {
379
- const workflows = engine.listWorkflows();
380
- const instances = engine.listInstances();
381
- const sections = [];
382
- if (workflows.length > 0) {
383
- sections.push("## 可用工作流");
384
- sections.push(workflows.map((w) => `- **${w.name}**: ${w.desc}`).join("\n"));
385
- sections.push(`> 启动:\`/ralphflow-start <工作流名> <任务描述>\`;自定义工作流放到 \`<workspace>/ralph-flow/workflows/<名字>.yaml\`(模板可复制内置定义)。`);
386
- }
387
- else {
388
- sections.push("## 可用工作流\n(无)\n\n把工作流 YAML 放到 `<workspace>/ralph-flow/workflows/`(或全局 `~/.dsh/ralph-flow/workflows/`)即可被识别;内置 loop/spec 应始终可用——若缺失请运行 /ralphflow-doctor 诊断。");
389
- }
390
- if (instances.length > 0) {
391
- sections.push("## 活跃实例");
392
- sections.push(instances.map((i) => `- **${i.id}** · ${i.state.workflow_name} · ${i.state.current_step} · ${i.state.paused ? "暂停" : i.state.current_phase === "check" ? "验证中" : "进行中"}`).join("\n"));
393
- }
394
- return sections.join("\n\n");
72
+ if (!sessionId)
73
+ return "找不到当前会话。";
74
+ return engineOf(agent).statusOf(sessionId, args?.instance ? String(args.instance) : undefined).text;
395
75
  };
396
- handlers.set("ralphflow_list", listHandler);
397
- // ─── ralphflow_cancel ───────────────────────────────────────────────────────
76
+ const listHandler = (_args, agent) => engineOf(agent).listAll().text;
398
77
  const cancelHandler = (args, agent) => {
399
- const instance = args?.instance;
400
78
  const sessionId = sessionIdOf(agent);
401
- const resolution = engine.resolveInstance(instance, sessionId);
402
- if (!resolution.ok)
403
- return resolution.text;
404
- // 与锁内推进互斥:取消不能插在 do→check 写入中间(否则状态与已发射帧脱节)
405
- return withInstanceLock(resolution.id, async () => {
406
- // 锁内重新解析:排队期间实例可能已被取消/完成
407
- const re = engine.resolveInstance(instance, sessionId);
408
- if (!re.ok)
409
- return re.text;
410
- const instId = re.id;
411
- const state = engine.readState(instId);
412
- const ownerNote = re.attached && state?.session_id
413
- ? `\n\n> ⚠️ 该实例原属另一个会话(\`${state.session_id.slice(0, 8)}\`),你已将其取消。`
414
- : "";
415
- engine.logEvent(instId, "warn", "workflow_cancelled", { by_session: sessionId ?? undefined });
416
- const owner = state?.session_id ?? null;
417
- // 取消者会话:终态帧必须同时到达实例属主与执行取消的会话——两者经常
418
- // 不是同一个(接管场景 owner=B、人在 A 取消),只发 owner 会让取消者
419
- // 自己的对话里那张卡永远收不到收尾。
420
- const cancellerSession = sessionId ?? null;
421
- const reportPath = engine.destroyInstance(instId, "cancelled");
422
- if (!reportPath) {
423
- // 归档失败 → destroyInstance 已拒绝销毁,现场(含执行记录)完整保留。
424
- // 但绝不能就此 return:job 不 kill 会悬挂、UI 无帧会永久滞留。让实例
425
- // 停下来(暂停 + 杀守护 job,kill 内部会中止在飞验证者),并如实发射
426
- // run-end failed 帧——client 将其折叠为可恢复的「⏸ 已暂停」态。
427
- if (state) {
428
- engine.writeState({ ...state, paused: true, pause_reason: "cancel_archive_failed", last_failure_reason: "最终报告归档失败(磁盘满/权限不足?),取消已中止。" }, instId);
429
- }
430
- jobs.kill(instId);
431
- emit.emit(instId, "tool-ralphflow/run-end", { runId: instId, stopReason: "failed" });
432
- if (cancellerSession && cancellerSession !== engine.readState(instId)?.session_id) {
433
- emit.emitFinal(instId, cancellerSession, "tool-ralphflow/run-end", { runId: instId, stopReason: "failed" });
434
- }
435
- engine.logEvent(instId, "error", "cancel_archive_failed", { workflow: state?.workflow_name });
436
- return `## ⚠️ 取消未完成\n\n实例 \`${instId}\` 的最终报告归档失败(磁盘满或权限不足),实例与执行记录已原样保留,本次未取消。工作流已暂停。\n\n👉 排查磁盘/权限后重试 \`/ralphflow-cancel\` 彻底删除;改变主意可用 \`/ralphflow-continue\` 放弃取消、恢复运行。`;
437
- }
438
- emit.emitFinal(instId, owner, "tool-ralphflow/run-end", { runId: instId, stopReason: "cancelled" });
439
- if (cancellerSession && cancellerSession !== owner) {
440
- // 取消者不在属主会话:给取消者也补一帧收尾(去重由 events 层保证)
441
- emit.emitFinal(instId, cancellerSession, "tool-ralphflow/run-end", { runId: instId, stopReason: "cancelled" });
442
- }
443
- jobs.kill(instId);
444
- return `## 已取消\n\n实例 \`${instId}\` 已取消并归档报告:${path.relative(engine.projectDir, reportPath)}。${ownerNote}`;
445
- });
79
+ if (!sessionId)
80
+ return "找不到当前会话。";
81
+ return engineOf(agent).cancelInstance(sessionId, args?.instance ? String(args.instance) : undefined, args?.reason ? String(args.reason) : undefined).text;
446
82
  };
447
- handlers.set("ralphflow_cancel", cancelHandler);
448
- // ─── ralphflow_rewind ───────────────────────────────────────────────────────
449
- const rewindHandler = (args, agent) => {
450
- const { step: targetStep, reason, keep_session, instance } = args ?? {};
451
- const sessionId = sessionIdOf(agent);
452
- if (!reason || !String(reason).trim()) {
453
- return `回退需要一个原因:为什么回退、重做时要注意什么。\n\n用法:\`/ralphflow-rewind <步骤> <原因>\`,例如 \`/ralphflow-rewind propose API 假设错了,改用 REST 轮询\`。`;
454
- }
455
- const reasonStr = String(reason).trim();
456
- if (!targetStep || !String(targetStep).trim()) {
457
- return "请指定要回退到的目标步骤 `step`。可用 `/ralphflow-status` 查看当前进度。";
83
+ const createHandler = (args, agent) => {
84
+ const idea = args?.idea ? String(args.idea).trim() : "";
85
+ // 写意图:把工作流目录建好,模型随后才写得进 <workspace>/.dsh/ralph-flow/workflows/
86
+ try {
87
+ engineOf(agent).ensureLayout();
458
88
  }
459
- const targetStepId = String(targetStep).trim();
460
- const resolution = engine.resolveInstance(instance, sessionId);
461
- if (!resolution.ok)
462
- return resolution.text;
463
- // 与锁内推进互斥:回退的「读快照→校验→写回 do」绝不能与在飞验证/推进交错
464
- return withInstanceLock(resolution.id, async () => {
465
- // 锁内重新解析 + 重读:排队期间实例可能已被取消/易主/推进
466
- const re = engine.resolveInstance(instance, sessionId);
467
- if (!re.ok)
468
- return re.text;
469
- const instId = re.id;
470
- const attached = re.attached;
471
- const state = engine.readState(instId);
472
- if (!state || !state.active)
473
- return "没有活跃的工作流。使用 `/ralphflow-start` 启动一个。";
474
- if (attached)
475
- return "该实例的属主是另一个会话。只有属主会话可以回退。先运行 `/ralphflow-continue` 接管该实例,再操作。";
476
- if (engine.readStateStack(instId).length > 0) {
477
- return `当前实例在子工作流内运行(工作流 \`${state.workflow_name}\`,步骤 \`${state.current_step}\`)。本版本不支持跨子工作流栈帧回退——请先完成或取消该子工作流(\`/ralphflow-continue\` 或 \`/ralphflow-cancel\`),再回退到父工作流的步骤。`;
478
- }
479
- if (!state.paused && state.current_phase !== "do") {
480
- return `当前阶段是 \`${state.current_phase}\`(独立 CHECK 进行中)。回退只能在 DO 阶段或暂停时操作——请稍候验证完成,或运行 \`/ralphflow-cancel\` 放弃。`;
481
- }
482
- if (state.paused && state.current_phase === "check") {
483
- if (liveVerifierCount(engine, instId) > 0) {
484
- return `步骤 \`${state.current_step}\` 的独立验证仍在运行。请稍候完成,或运行 \`/ralphflow-cancel\` 放弃后再回退。`;
485
- }
486
- }
487
- const workflow = engine.loadWorkflow(state.workflow_name);
488
- if (!workflow)
489
- return `工作流 "${state.workflow_name}" 未找到。`;
490
- const target = engine.getStep(workflow, targetStepId);
491
- if (!target)
492
- return `步骤 \`${targetStepId}\` 不在工作流 "${state.workflow_name}" 中。`;
493
- if (isSubWorkflowStep(target))
494
- return `步骤 \`${targetStepId}\` 是子工作流(复合)步骤,没有 DO/CHECK 阶段,不能回退到它。`;
495
- if (targetStepId === state.current_step)
496
- return `\`${targetStepId}\` 就是当前步骤——重做当前步用 \`/ralphflow-reset\`;rewind 是回退到**上游**已通过步骤。`;
497
- const passed = engine.passedStepIds(instId, state.workflow_name);
498
- if (!passed.includes(targetStepId)) {
499
- const list = passed.length > 0 ? passed.map((s) => `\`${s}\``).join("、") : "(暂无——本工作流还没有步骤通过独立验证)";
500
- return `只能回退到**本工作流里已通过独立验证**的步骤,\`${targetStepId}\` 不在此列。\n\n本工作流已通过验证的步骤:${list}\n\n可用 \`/ralphflow-status\` 查看当前进度。`;
501
- }
502
- const fromStep = state.current_step;
503
- const wasPaused = state.paused;
504
- const newState = {
505
- ...state,
506
- current_step: targetStepId,
507
- current_phase: "do",
508
- fail_count: 0,
509
- paused: false,
510
- pause_reason: undefined,
511
- last_failure_reason: undefined,
512
- };
513
- engine.writeState(newState, instId);
514
- engine.clearManualGate(instId);
515
- engine.clearManualStepMarker(instId);
516
- engine.clearDoneTagDetected(instId);
517
- engine.clearReinjectCounter(instId);
518
- deleteVotingProgress(engine, instId);
519
- engine.recordStepStart(instId, targetStepId, "do");
520
- engine.logEvent(instId, "info", "step_start", { step: targetStepId, phase: "do" });
521
- engine.logEvent(instId, "info", "rewind", { from: fromStep, to: targetStepId, keep_session: !!keep_session, was_paused: !!wasPaused });
522
- if (workflow.manual_step && workflow.manual_step.includes(targetStepId))
523
- engine.writeManualStepMarker(instId);
524
- emit.emit(instId, "tool-ralphflow/rewind", { runId: instId, fromStep, toStep: targetStepId, reason: reasonStr });
525
- const header = wasPaused
526
- ? `## 已从暂停恢复并回退到步骤 \`${targetStepId}\`\n\n**原因:** ${reasonStr}`
527
- : `## 已回退到步骤 \`${targetStepId}\`\n\n**原因:** ${reasonStr}`;
528
- const prompt = engine.buildDoPrompt(instId, target, state.user_task, reasonStr, 0);
529
- engine.markPromptDelivered(targetStepId, instId);
530
- jobs.reobserve(instId);
531
- return `${header}\n\n---\n\n${prompt}`;
532
- });
89
+ catch { }
90
+ return idea ? `你要创建的工作流:**${idea}**\n\n---\n\n${CREATE_GUIDE}` : CREATE_GUIDE;
533
91
  };
534
- handlers.set("ralphflow_rewind", rewindHandler);
535
- // ─── ralphflow_reset ────────────────────────────────────────────────────────
536
- const resetHandler = (args, agent) => {
537
- const { reason, instance } = args ?? {};
92
+ const doctorHandler = (_args, agent) => engineOf(agent).diagnose().text;
93
+ /**
94
+ * DO 阶段交卷(dsh 原生方式:工具调用即事实,不靠正则扫自由文本)。
95
+ * `concludeTurn` 由注册处调用,让本次工具结果结束当前回合。
96
+ */
97
+ const submitHandler = (args, agent) => {
538
98
  const sessionId = sessionIdOf(agent);
539
- const resolution = engine.resolveInstance(instance, sessionId);
540
- if (!resolution.ok)
541
- return resolution.text;
542
- // 与锁内推进互斥:重置的清标记/发帧不能插在推进中间
543
- return withInstanceLock(resolution.id, async () => {
544
- const re = engine.resolveInstance(instance, sessionId);
545
- if (!re.ok)
546
- return re.text;
547
- const instId = re.id;
548
- if (re.attached)
549
- return "该实例的属主是另一个会话。只有属主会话可以重置。先运行 `/ralphflow-continue` 接管该实例,再操作。";
550
- const state = engine.readState(instId);
551
- if (!state)
552
- return `实例 ${instId} 不存在。`;
553
- if (state.paused) {
554
- return `实例当前处于暂停状态(${state.pause_reason || "未知原因"})。重置不会解除暂停。\n\n请先运行 /ralphflow-continue 恢复;恢复后若仍想重做当前步,再运行 /ralphflow-reset。想回退到上游已通过步骤改方向,用 /ralphflow-rewind(它会解除暂停)。`;
555
- }
556
- if (state.current_phase !== "do") {
557
- return `当前处于 ${state.current_phase} 阶段,不能重置(只有 DO 阶段可重置)。等验证结束后再试。`;
558
- }
559
- const workflow = engine.loadWorkflow(state.workflow_name);
560
- if (!workflow)
561
- return `工作流 "${state.workflow_name}" 未找到。`;
562
- const step = engine.getStep(workflow, state.current_step);
563
- if (!step || isSubWorkflowStep(step))
564
- return `步骤 "${state.current_step}" 无法重置。`;
565
- engine.clearDoneTagDetected(instId);
566
- engine.clearReinjectCounter(instId);
567
- engine.clearManualGate(instId);
568
- deleteVotingProgress(engine, instId);
569
- const transitionText = `## 🔄 当前步将重新执行\n\n步骤 \`${state.current_step}\` 会带着下方干净的任务提示重新执行(会话上下文不变,失败计数不清零)${reason ? `\n\n**原因:** ${reason}` : ""}`;
570
- const prompt = engine.buildDoPrompt(instId, step, state.user_task, reason, state.fail_count || 0);
571
- engine.markPromptDelivered(step.id, instId);
572
- emit.emit(instId, "tool-ralphflow/reset", { runId: instId, step: state.current_step, reason });
573
- jobs.reobserve(instId);
574
- return `${transitionText}\n\n---\n\n${prompt}`;
575
- });
99
+ if (!sessionId)
100
+ return "找不到当前会话,无法交卷。";
101
+ const summary = args?.summary !== undefined ? String(args.summary) : undefined;
102
+ return engineOf(agent).onSubmit(sessionId, summary).text;
576
103
  };
577
- handlers.set("ralphflow_reset", resetHandler);
578
- // ─── ralphflow_doctor ───────────────────────────────────────────────────────
579
- const doctorHandler = () => {
580
- const report = engine.buildDoctorReport();
581
- // 资源占用(只读提醒):reports/artifacts/instances/logs/history 都是
582
- // 只增不减的增长面,长期使用需要人知道积了多大。
583
- let resourceSection = "";
584
- try {
585
- const rfDir = path.join(engine.projectDir, "ralph-flow");
586
- const walkCount = (d) => {
587
- let files = 0, bytes = 0;
588
- const walk = (dir) => {
589
- let entries;
104
+ const toolDefs = [
105
+ {
106
+ name: "ralphflow_start",
107
+ description: "启动一个 Ralph Flow 工作流:模型执行当前步骤;有 `check` / `check_voting` 的步骤交卷后由独立验证者取证判定(投票步 N 票并行、全过才放行),失败自动返工;没有 `check` / `check_voting` 的步骤跳过对抗性验证。启动结果会给出本步的 DO 提示与交卷方式。",
108
+ params: {
109
+ workflow: { type: "string", required: true, description: "工作流名(loop / spec,或自定义 YAML 名)。" },
110
+ task: { type: "string", required: true, description: "要完成的任务描述。" },
111
+ },
112
+ handler: startHandler,
113
+ },
114
+ {
115
+ name: "ralphflow_submit",
116
+ description: "【DO 阶段交卷】本步工作完成后调用。有 `check` / `check_voting` 的步骤:独立验证者随即取证判定(投票步 N 票并行、全过才放行);没有 `check` / `check_voting` 的步骤:跳过对抗性验证直接继续(`manual_step` 则停在审查门等放行)。不交卷则工作流不会推进。",
117
+ params: {
118
+ summary: { type: "string", description: "可选:简述本步做了什么。**验证者看不到它**(T1:验证请求不含执行者自述),它只留在实例状态里;验证者只独立取证。" },
119
+ },
120
+ handler: submitHandler,
121
+ concludeTurn: true,
122
+ },
123
+ {
124
+ name: "ralphflow_continue",
125
+ description: "推进工作流:放行审查门 / 解除暂停 / 接管实例(**只在无属主时自动接管**;有属主的实例必须显式给 `instance`)。判定未通过时拒绝推进。",
126
+ params: {
127
+ instance: { type: "string", description: "要接管/推进的实例 ID(可前缀)。带它 = 用户显式指定 —— 有属主的实例只走这条显式路径。" },
128
+ },
129
+ handler: continueHandler,
130
+ },
131
+ {
132
+ name: "ralphflow_status",
133
+ description: "查看工作流状态、本轮判定、多验证者投票的每票进度与最近轨迹;实例已结束并销毁时指向它的历史报告。**无参且本会话没有活跃实例时,给出全部活跃实例的概览(含属主会话)**。",
134
+ params: {
135
+ instance: { type: "string", description: "实例 ID(可前缀);缺省看当前会话实例,本会话没有就给全部活跃实例的概览。" },
136
+ },
137
+ handler: statusHandler,
138
+ },
139
+ {
140
+ name: "ralphflow_list",
141
+ description: "列出可用工作流与活跃实例(已结束的运行只给报告目录,不逐个列出)。",
142
+ params: {},
143
+ handler: listHandler,
144
+ },
145
+ {
146
+ name: "ralphflow_cancel",
147
+ description: "取消当前会话(或指定)的活跃实例:中止在飞验证者、归档报告到精确路径并销毁实例目录(报告归档失败时保留不销毁)。",
148
+ params: {
149
+ instance: { type: "string", description: "实例 ID(可前缀)。" },
150
+ reason: { type: "string", description: "取消原因(可选)。" },
151
+ },
152
+ handler: cancelHandler,
153
+ },
154
+ {
155
+ name: "ralphflow_create",
156
+ description: "获取自定义工作流的交互式设计指引(模型与用户一轮问清流程 → 呈现步骤图 → 写 YAML → doctor 校验到全部 ✅ 且无告警)。",
157
+ params: {
158
+ idea: { type: "string", description: "用户想自动化的流程想法(可选,有则附在指引前)。" },
159
+ },
160
+ handler: createHandler,
161
+ },
162
+ {
163
+ name: "ralphflow_doctor",
164
+ description: "诊断工作流定义与实例状态:坏文件说人话、列出阻塞项,修完重跑直到全部 ✅。",
165
+ params: {},
166
+ handler: doctorHandler,
167
+ },
168
+ ];
169
+ for (const def of toolDefs) {
170
+ handlers.set(def.name, def.handler);
171
+ tools.register(defineTool({
172
+ name: def.name,
173
+ description: def.description,
174
+ parameters: def.params,
175
+ output: { schema: { type: "string" }, render: (_args, value) => [{ type: "text", text: value }] },
176
+ async execute(args, exec) {
177
+ const out = await def.handler(args ?? {}, exec?.agent);
178
+ // 交卷工具用宿主原生的 concludeTurn 结束本回合
179
+ // (与 dsh-subagent-in-process-driver 的 structured_output 同款机制)。
180
+ if (def.concludeTurn && typeof exec?.concludeTurn === "function") {
590
181
  try {
591
- entries = fs.readdirSync(dir, { withFileTypes: true });
592
- }
593
- catch {
594
- return;
595
- }
596
- for (const e of entries) {
597
- const p = path.join(dir, e.name);
598
- if (e.isDirectory()) {
599
- walk(p);
600
- continue;
601
- }
602
- files++;
603
- try {
604
- bytes += fs.statSync(p).size;
605
- }
606
- catch { }
182
+ exec.concludeTurn();
607
183
  }
184
+ catch { }
185
+ }
186
+ return out;
187
+ },
188
+ }));
189
+ }
190
+ // `/ralphflow-rewind` 与 `/ralphflow-reset` 一样**不注册为工具**:注册了就等于给模型一个
191
+ // 可调用、会返回内容的实现,与「命令面固定 + 不给模型可调用的修复入口」的边界冲突
192
+ // (design §10.10)。两者的机械动作都由命令处理器直接驱动引擎完成,见下面的 `run` 分支。
193
+ // 「未实现」的占位处理函数因此不再需要:命令面从今日起没有任何「只声明不实现」的命令。
194
+ return handlers;
195
+ }
196
+ // ─── 命令注册 ────────────────────────────────────────────────────────────────
197
+ export function registerCommands(deps) {
198
+ const { ctx } = deps;
199
+ const commands = ctx.commands;
200
+ /** 每条命令 = 触发词:不直接渲染工具返回值,而是给模型一条指令,由模型调用工具并自然回复(claude/opencode 语义)。 */
201
+ const defs = [
202
+ {
203
+ name: "ralphflow-start",
204
+ description: "启动工作流:模型执行 → 有 `check` / `check_voting` 的步骤交独立验证(投票步 N 票并行、全过才放行),失败自动返工;没有 `check` / `check_voting` 的步骤跳过对抗性验证。示例:/ralphflow-start loop 修复登录模块的空指针",
205
+ input: { hint: "<工作流> <任务描述>" },
206
+ shim: (inv) => {
207
+ const parts = inv.rawInput.trim().split(/\s+/).filter(Boolean);
208
+ if (parts.length < 2) {
209
+ // 用法错误也交回 AI:像 opencode 一样由模型说明用法并追问缺失信息
210
+ return {
211
+ kind: "directive",
212
+ text: "用户执行了 /ralphflow-start 但参数不完整(需要工作流名 + 任务描述)。**不要调用任何工具**,先用自然语言向用户说明用法并询问缺少的信息:只有任务没有工作流 → 问用哪个工作流;只有工作流没有任务 → 问要做什么;都没有 → 两者都问。必要时用 ralphflow_list 查看可用工作流供用户选择。",
213
+ };
214
+ }
215
+ const workflow = parts[0];
216
+ const task = parts.slice(1).join(" ");
217
+ return {
218
+ kind: "directive",
219
+ text: `用户通过 /ralphflow-start 启动了 ralphflow 工作流。请调用 \`ralphflow_start\` 工具:workflow = \`${workflow}\`,task = \`${task}\`。若工具报错,如实转达;若成功,按它返回的指示执行并遵循下面的机制。\n\n${SHARED_MECHANISM}`,
608
220
  };
609
- walk(d);
610
- return { files, bytes };
611
- };
612
- const fmtBytes = (b) => (b >= 1 << 20 ? `${(b / (1 << 20)).toFixed(1)} MB` : `${Math.round(b / 1024)} KB`);
613
- const reports = walkCount(path.join(rfDir, "reports"));
614
- const artifacts = walkCount(path.join(rfDir, "artifacts"));
615
- const instances = walkCount(path.join(rfDir, "instances"));
616
- let historyLines = 0;
617
- try {
618
- historyLines = fs.readFileSync(path.join(rfDir, "history.jsonl"), "utf-8").split("\n").filter(Boolean).length;
619
- }
620
- catch { }
621
- let logBytes = 0;
622
- try {
623
- logBytes = fs.statSync(path.join(rfDir, "logs", "execution.log")).size;
624
- }
625
- catch { }
626
- resourceSection = `\n\n## 资源占用\n\n- 报告归档:${reports.files} 个文件(${fmtBytes(reports.bytes)})\n- 任务产物:${artifacts.files} 个文件(${fmtBytes(artifacts.bytes)})\n- 活跃实例:${instances.files} 个文件\n- 历史索引:${historyLines} 条 · 运行日志:${fmtBytes(logBytes)}\n\n> reports/artifacts 只增不减,完成后不再被引用——需要时手工归档或删除旧目录。`;
627
- }
628
- catch { }
629
- // 会话卫生:历史版本 session.append 的自定义帧会砖会话——扫描当前全部
630
- // 会话存储,把待砖清单并入诊断(防止「会话突然打不开」时才后知后觉)。
631
- let hygieneSection = "";
221
+ },
222
+ },
223
+ {
224
+ name: "ralphflow-continue",
225
+ description: "推进工作流:放行审查门 / 解除暂停 / 接管实例。示例:/ralphflow-continue <实例ID>",
226
+ input: { hint: "[实例ID]" },
227
+ shim: (inv) => {
228
+ const parts = inv.rawInput.trim().split(/\s+/).filter(Boolean);
229
+ const instance = parts[0] ? `,instance = \`${parts[0]}\`` : "";
230
+ return {
231
+ kind: "directive",
232
+ text: `用户执行了 /ralphflow-continue。\`ralphflow_continue\` 只用于三种情况:**批准手动审查**(🙋 步骤停下等你放行:有 \`check\` / \`check_voting\` 的是已通过独立验证,没有 \`check\` / \`check_voting\` 的是已跳过对抗性验证的纯人工审查——两者都直接放行进入下一步,不重复验证)、**恢复暂停**(先看 \`/ralphflow-status\` 的失败原因,修复后调用,重置失败计数并重试;投票步的基础设施故障恢复只重跑未通过的票,已通过的保留)、**接管中断/他人实例**。有 \`check\` / \`check_voting\` 的普通步骤推进是自动的,不要调用它。
233
+
234
+ 请调用 \`ralphflow_continue\` 工具${instance}。若不带实例 id 且本会话没有活跃实例,工具**只在恰好一个无属主实例时自动接管**;否则会列出候选(含属主会话)并要求显式指定 —— 把它展示给用户并询问接管哪个,再带 \`instance\` 调用。按工具结果行动:进入 DO 就执行该步任务;验证中就简短说明;完成就说「工作流结束」;暂停就说明原因与下一步。`,
235
+ };
236
+ },
237
+ },
238
+ {
239
+ name: "ralphflow-status",
240
+ description: "查看实例状态与判定。示例:/ralphflow-status",
241
+ input: { hint: "[实例ID]" },
242
+ shim: (inv) => {
243
+ const parts = inv.rawInput.trim().split(/\s+/).filter(Boolean);
244
+ const instance = parts[0] ? `,instance = \`${parts[0]}\`` : "";
245
+ return {
246
+ kind: "directive",
247
+ text: `用户执行了 /ralphflow-status,想了解工作流进度。请调用 \`ralphflow_status\` 工具${instance}(不带参数时若本会话无实例,应显示项目里所有活跃实例的概览)。然后向用户清晰说明:工作流与当前步骤、状态(执行中/验证中/待放行/暂停及原因)、失败次数,以及**属主会话**——属于其他或已关闭会话的实例可通过 \`/ralphflow-continue <实例ID>\` 接管。若工具说该实例**已结束并销毁**,就把报告路径给用户(历史在报告里,不要在列表里找)。`,
248
+ };
249
+ },
250
+ },
251
+ {
252
+ name: "ralphflow-list",
253
+ description: "列出可用工作流与活跃实例。示例:/ralphflow-list",
254
+ shim: () => ({
255
+ kind: "directive",
256
+ text: "用户执行了 /ralphflow-list。请调用 `ralphflow_list` 工具获取数据,然后把「可用工作流」整理成**表格**(列:工作流 | 用途描述),把「活跃实例」按工具返回的字段简要列给用户(实例 id、工作流、任务、步骤、状态、属主),并转达工具给的「已结束的运行」报告目录。数据以工具返回为准,不要编造;没有就直说。工作流解析顺序:工作区自定义 `.dsh/ralph-flow/workflows/` > 全局 `~/.dsh/ralph-flow/workflows/` > 插件内置。",
257
+ }),
258
+ },
259
+ {
260
+ name: "ralphflow-cancel",
261
+ description: "取消活跃实例:归档报告并销毁实例目录。示例:/ralphflow-cancel",
262
+ input: { hint: "[实例ID] [原因]" },
263
+ shim: (inv) => {
264
+ const parts = inv.rawInput.trim().split(/\s+/).filter(Boolean);
265
+ const instance = parts[0] ? `,instance = \`${parts[0]}\`` : "";
266
+ const reason = parts.length > 1 ? `,reason = \`${parts.slice(1).join(" ")}\`` : "";
267
+ return {
268
+ kind: "directive",
269
+ text: `用户执行了 /ralphflow-cancel,要取消工作流实例${instance}。请调用 \`ralphflow_cancel\` 工具${reason}——它会中止任何在飞的独立验证会话、把最终报告归档到精确路径(\`.dsh/ralph-flow/reports/<实例ID>.md\`)并销毁实例目录;产出目录保留。若报告归档失败,它会保留实例目录不销毁并告警,请如实转达。然后向用户简短确认已取消(或转达错误),并把报告路径给用户。`,
270
+ };
271
+ },
272
+ },
273
+ {
274
+ name: "ralphflow-create",
275
+ description: "交互式创建自定义工作流(模型引导设计 → 写 YAML → doctor 校验)。示例:/ralphflow-create 把 C 代码迁移到 Rust",
276
+ input: { hint: "[流程想法]" },
277
+ shim: (inv) => ({
278
+ kind: "directive",
279
+ text: `用户想${inv.rawInput.trim() ? `创建一个工作流:${inv.rawInput.trim()}` : "创建自定义 Ralph Flow 工作流"}。请调用 \`ralphflow_create\` 工具获取完整设计指引,然后按指引与用户交互:一轮问清流程阶段与审查门位置(用户没说清楚才问)→ 呈现步骤图 → 写 YAML 到 \`.dsh/ralph-flow/workflows/\` → 调用 \`ralphflow_doctor\` 校验到全部 ✅ 且无告警 → 交接运行方式。`,
280
+ }),
281
+ },
282
+ {
283
+ name: "ralphflow-doctor",
284
+ description: "诊断工作流定义与实例状态。示例:/ralphflow-doctor",
285
+ shim: () => ({
286
+ kind: "directive",
287
+ text: "用户执行了 /ralphflow-doctor,想诊断工作流与实例。请调用 `ralphflow_doctor` 工具,然后把诊断为 ❌ 的每一项用通俗语言向用户说明原因与修复建议;全部 ✅ 就简短说「一切正常」。",
288
+ }),
289
+ },
290
+ {
291
+ name: "ralphflow-reset",
292
+ description: "重做当前步:只换干净上下文(失败计数保留,不赦免失败);暂停中请用 /ralphflow-continue。示例:/ralphflow-reset",
293
+ run: async (inv) => {
294
+ const sid = messageSessionId(inv.agent);
295
+ if (!sid)
296
+ return { kind: "error", text: "当前会话已离线,无法重置上下文。请刷新后重试。" };
297
+ // 机械动作在**命令处理器**里完成(不经过模型调工具):重置是程序的职责,
298
+ // 「不赦免失败」也只有在程序手里才守得住。失败绝不抛,如实回。
299
+ const res = deps.engineFor(deps.workspaceOfSession?.(sid)).resetCurrent(sid);
300
+ if (res.ok) {
301
+ // 成功:引擎已在**空闲窗口**排入整段替换,并会把当前步 DO 重投 + 发一条可见告知。
302
+ // 不给程序化卡片(命令语义 = 触发词,回复由模型/引擎消息承担)。
303
+ return { kind: "success" };
304
+ }
305
+ // 拒绝:把原因交回模型自然语言转达,并叫停重复尝试(命令语义不变)。
306
+ deps.deliver(sid, `[ralphflow] 用户执行了 /ralphflow-reset,但**被拒绝**:${res.text}\n\n请用自然语言如实向用户说明拒绝原因与下一步(暂停中指向 \`/ralphflow-continue\`;验证/审查门中请等结果)。**不要调用任何工具**,不要替用户重试重置。`);
307
+ return { kind: "success" };
308
+ },
309
+ },
310
+ {
311
+ name: "ralphflow-rewind",
312
+ description: "回退到更早的步骤并换方向:清暂停与失败计数、作废本轮判定,属主会话上下文整段替换成交接稿,目标步 DO 带着原因重投。示例:/ralphflow-rewind design 改用另一种方案(回退只去当前步**之前**的步骤;目标步与原因都必填)",
313
+ input: { hint: "<步骤> <原因>" },
314
+ run: async (inv) => {
315
+ const sid = messageSessionId(inv.agent);
316
+ if (!sid)
317
+ return { kind: "error", text: "当前会话已离线,无法回退。请刷新后重试。" };
318
+ // 参数解析:`<步骤> <原因>` 两个都必填;原因是自由文本(可含空格),所以第一段是步骤、
319
+ // 其余整段是原因。
320
+ const parts = inv.rawInput.trim().split(/\s+/).filter(Boolean);
321
+ if (parts.length < 2) {
322
+ // 缺参数**交回模型自然语言追问**(与 /ralphflow-start 同款:像 opencode 一样由模型
323
+ // 说明用法并问清缺失信息),不在这里给程序化卡片。
324
+ const have = parts.length === 1 ? `用户已给出目标步骤 \`${parts[0]}\`,缺的是**回退原因**。` : "目标步骤与回退原因两者都缺。";
325
+ deps.deliver(sid, `[ralphflow] 用户执行了 /ralphflow-rewind 但参数不完整(用法:\`/ralphflow-rewind <步骤> <原因>\`,两个都必填):${have}\n\n**不要调用任何工具**,先用自然语言向用户说明用法并询问缺少的信息(要回到哪个更早的步骤、以及为什么要换方向——原因会写进目标步的 DO 提示词,接手这一步的模型一定看得到)。必要时用 \`ralphflow_status\` 看当前步与工作流的步骤列表,供用户选择。`);
326
+ return { kind: "success" };
327
+ }
328
+ const stepId = parts[0];
329
+ const reasonText = parts.slice(1).join(" ");
330
+ // 机械动作在**命令处理器**里完成(不经过模型调工具):状态机倒退 + 清暂停/失败计数
331
+ // + 强制整段替换上下文 + 重投目标步 DO,必须与机械程序的决定原子发生,不能要求模型记得去调。
332
+ const res = deps.engineFor(deps.workspaceOfSession?.(sid)).rewindTo(sid, stepId, reasonText);
333
+ if (res.ok) {
334
+ // 成功:引擎已在**空闲窗口**排入整段替换,并会把目标步 DO(带着原因)+ 可见告知投出。
335
+ // 不给程序化卡片(命令语义 = 触发词,回复由模型/引擎消息承担)。
336
+ return { kind: "success" };
337
+ }
338
+ // 拒绝:把原因交回模型自然语言转达(调用点 / 未来步 / 当前步 / 不存在 / 已交卷…每条
339
+ // 都是具体理由),并叫停重复尝试(命令语义不变)。
340
+ deps.deliver(sid, `[ralphflow] 用户执行了 /ralphflow-rewind ${stepId} ${reasonText},但**被拒绝**:${res.text}\n\n请用自然语言如实向用户说明拒绝原因与下一步(已交卷 / 验证中请等验证结果;想重做**当前步**用 \`/ralphflow-reset\`;想放行审查门或恢复暂停用 \`/ralphflow-continue\`)。当前可用命令:${AVAILABLE_COMMANDS}。**不要调用任何工具**,不要替用户重试回退。`);
341
+ return { kind: "success" };
342
+ },
343
+ },
344
+ ];
345
+ for (const def of defs) {
632
346
  try {
633
- const infected = scanSessionLogs();
634
- hygieneSection = infected.length === 0
635
- ? "\n\n## 会话卫生\n\n✅ 所有会话日志干净(无插件自定义事件帧,无砖化风险)。"
636
- : `\n\n## 会话卫生\n\n⚠️ 以下 ${infected.length} 个会话日志含插件自定义事件帧,重启 dsh 后可能无法打开:\n${infected.map((e) => `- \`${path.relative(path.join(os.homedir(), ".dsh"), e.file)}\`:${e.count} 帧(${e.types.join("、")})`).join("\n")}\n\n→ 运行 \`/ralphflow-unbrick\` 一键备份并移除(风险:改前自动备份)。`;
347
+ commands.register({
348
+ name: def.name,
349
+ description: def.description,
350
+ ...(def.input ? { input: { hint: def.input.hint } } : {}),
351
+ handler: async (inv) => {
352
+ try {
353
+ // 机械命令:处理器直接驱动引擎,结果交回模型自然回复(零程序化卡片返回)
354
+ if (def.run)
355
+ return await def.run({ rawInput: inv.rawInput, agent: inv.agent, signal: inv.signal });
356
+ const out = def.shim({ rawInput: inv.rawInput, agent: inv.agent, signal: inv.signal });
357
+ if (out.kind === "directive") {
358
+ const sid = messageSessionId(inv.agent);
359
+ if (sid) {
360
+ deps.deliver(sid, `[ralphflow] ${out.text}`);
361
+ // 回复留给模型(claude/opencode 语义),命令卡不渲染任何程序文本
362
+ return { kind: "success" };
363
+ }
364
+ // 找不到会话(罕见兜底):卡片展示,避免用户什么反馈都没有
365
+ return { kind: "error", text: "当前会话已离线,无法交给模型处理。请刷新后重试。" };
366
+ }
367
+ return { kind: "success", text: out.text };
368
+ }
369
+ catch (err) {
370
+ return { kind: "error", text: err instanceof Error ? err.message : String(err) };
371
+ }
372
+ },
373
+ });
637
374
  }
638
- catch (e) {
639
- hygieneSection = `\n\n> 会话卫生检查失败:${e instanceof Error ? e.message : String(e)}`;
375
+ catch (err) {
376
+ ctx.logger?.warn?.("[ralphflow] command registration skipped:", err);
640
377
  }
641
- return `${report}${resourceSection}${hygieneSection}`;
642
- };
643
- handlers.set("ralphflow_doctor", doctorHandler);
644
- // ─── ralphflow_unbrick ──────────────────────────────────────────────────────
645
- // 会话解砖:备份并移除会话日志中的插件自定义事件帧(历史版本 session.append
646
- // 的遗留;继续留存的帧会在下次重启 dsh 时让整个会话无法加载)。
647
- const unbrickHandler = () => {
378
+ }
379
+ // ─── 动态工作流快捷命令:/ralphflow-<工作流名>(与 claude code 版看齐)────────
380
+ // claude 版:cmdName = SLASH_COMMAND_PREFIX("ralphflow-") + wf.name,且只对
381
+ // 名字安全(^[a-zA-Z0-9_-]+$)的工作流注册。这里同款,另加 dsh 命令名约束
382
+ // (小写、^[a-z][a-z0-9_-]*$)与静态命令撞名保护(如工作流叫 start → ralphflow-start 已占用则跳过)。
383
+ //
384
+ // **引擎按工作区惰性创建**,所以这里返回一个登记器而不是一次性注册:每新建一个引擎,
385
+ // 就把该工作区新出现的工作流补登记成快捷命令(同名先到先得,与「绝不覆盖」语义一致)。
386
+ const taken = new Set(defs.map((d) => d.name));
387
+ return function registerWorkflowShortcuts(workflows) {
648
388
  try {
649
- const infected = scanSessionLogs();
650
- if (infected.length === 0) {
651
- return "✅ 所有会话日志干净,无需解砖。";
389
+ for (const wf of workflows) {
390
+ const rawName = String(wf.name);
391
+ if (!/^[a-zA-Z0-9_-]+$/.test(rawName))
392
+ continue;
393
+ const cmd = `ralphflow-${rawName.toLowerCase()}`;
394
+ if (!/^[a-z][a-z0-9_-]*$/.test(cmd))
395
+ continue;
396
+ if (taken.has(cmd))
397
+ continue;
398
+ taken.add(cmd);
399
+ const desc = wf.desc || `启动 ${wf.name} 工作流`;
400
+ try {
401
+ commands.register({
402
+ name: cmd,
403
+ description: `(ralphflow) ${desc} · 示例:/${cmd} <任务描述>`,
404
+ input: { hint: "<任务描述>" },
405
+ handler: async (inv) => {
406
+ try {
407
+ const task = inv.rawInput.trim();
408
+ const sid = messageSessionId(inv.agent);
409
+ if (!task) {
410
+ // 缺任务也交回 AI:先说明用法再等任务(claude 版同款:先问要完成什么)
411
+ if (sid) {
412
+ deps.deliver(sid, `[ralphflow] 用户执行了 /${cmd}(\`${wf.name}\` 工作流)但没有附带任务描述。**不要调用任何工具**,先用自然语言说明用法:\`/${cmd} <任务描述>\`,并请用户补上要完成的任务。`);
413
+ }
414
+ return { kind: "success" };
415
+ }
416
+ if (sid) {
417
+ deps.deliver(sid, `[ralphflow] 用户通过 /${cmd} 启动了 \`${wf.name}\` 工作流。请调用 \`ralphflow_start\` 工具:workflow = \`${wf.name}\`,task = \`${task}\`。若工具报错,如实转达;若成功,按它返回的指示执行并遵循下面的机制。\n\n${SHARED_MECHANISM}`);
418
+ }
419
+ return { kind: "success" };
420
+ }
421
+ catch (err) {
422
+ return { kind: "error", text: err instanceof Error ? err.message : String(err) };
423
+ }
424
+ },
425
+ });
426
+ }
427
+ catch {
428
+ // 与其它插件撞名:静默跳过,与 claude/opencode 版"绝不覆盖"语义一致
429
+ }
652
430
  }
653
- const result = unbrickSessions();
654
- const head = result.fixed > 0
655
- ? `已修复 ${result.fixed} 个会话(备份在 \`${result.backupRoot}\`):\n${result.fixedFiles.map((f) => `- ${f}`).join("\n")}`
656
- : "没有可修复的会话(检查失败的见下)。";
657
- const errors = result.errors.length > 0
658
- ? `\n\n⚠️ 注意:\n${result.errors.map((e) => `- ${e}`).join("\n")}`
659
- : "";
660
- const note = "重启 dsh 后这些会话应可正常打开。若仍有问题,用备份目录还原。";
661
- return `${head}${errors}\n\n${note}`;
662
431
  }
663
- catch (e) {
664
- return `解砖失败:${e instanceof Error ? e.message : String(e)}`;
432
+ catch (err) {
433
+ ctx.logger?.warn?.("[ralphflow] workflow shortcut registration skipped:", err);
665
434
  }
666
435
  };
667
- handlers.set("ralphflow_unbrick", unbrickHandler);
668
- // ─── ralphflow_create ───────────────────────────────────────────────────────
669
- // 模型侧入口:返回完整设计指引(dsh 命令通道 log-only,指引只能经工具到达模型)
670
- const createHandler = () => CREATE_GUIDE;
671
- handlers.set("ralphflow_create", createHandler);
672
- // ─── 注册为 dsh 工具 ────────────────────────────────────────────────────────
673
- const register = (name, description, parameters, handler) => {
674
- tools.register(defineTool({
675
- name,
676
- description,
677
- parameters,
678
- output: {
679
- schema: { type: "string" },
680
- render: (args, value) => [{ type: "text", text: value }],
681
- },
682
- async execute(args, exec) {
683
- return handler(args ?? {}, exec?.agent);
684
- },
685
- }));
686
- };
687
- register("ralphflow_start", "启动一个工作流实例。需提供工作流名称和任务描述。同一工作区下多个会话可各自运行自己的实例。", {
688
- workflow: { type: "string", required: true, description: "工作流名称(用 ralphflow_list 查看可用工作流)" },
689
- task: { type: "string", required: true, description: "任务描述——需要完成什么" },
690
- extra_dirs: { type: "array", items: { type: "string" }, description: "任务源材料所在的、项目目录之外的目录(绝对路径或 ~/...)。验证者会获得只读访问;每个目录必须存在,否则拒绝启动。" },
691
- }, startHandler);
692
- register("ralphflow_continue", "批准手动审查 / 恢复暂停的工作流 / 接管中断的实例。验证由后台 job 自动进行。(可选实例 id,支持唯一前缀。)", {
693
- instance: { type: "string", description: "实例 id(支持唯一前缀)。仅在从新会话接管特定实例时需要。" },
694
- }, continueHandler);
695
- register("ralphflow_status", "查看本会话的实例、指定实例,或全部实例。", {
696
- instance: { type: "string", description: "实例 id(支持唯一前缀)。不传时显示全部活跃实例。" },
697
- }, statusHandler);
698
- register("ralphflow_list", "列出可用工作流与活跃实例。", {}, listHandler);
699
- register("ralphflow_cancel", "取消实例(先归档报告)。", {
700
- instance: { type: "string", description: "实例 id(支持唯一前缀)。" },
701
- }, cancelHandler);
702
- register("ralphflow_rewind", "回退到一个在本工作流里已通过独立 CHECK 的上游步骤,重做该步及后续。状态机倒退、fail_count 归零、清除暂停;下游已落盘产物保留(不删除)。reason 必填。", {
703
- step: { type: "string", required: true, description: "目标步骤 id——必须是本工作流里已通过独立 CHECK 的上游步骤(用 /ralphflow-status 查看)" },
704
- reason: { type: "string", required: true, description: "回退原因(必填):为什么回退、重做时要注意什么。会拼到新会话首条 DO 提示前。" },
705
- keep_session: { type: "boolean", description: "可选,默认 false;dsh 版始终在当前会话继续,此参数保留兼容。仅倒退状态机。" },
706
- instance: { type: "string", description: "实例 id(支持唯一前缀)。" },
707
- }, rewindHandler);
708
- register("ralphflow_reset", "当前会话上下文脏了/跑偏时,只重置当前步的上下文——重新注入干净的 DO 提示重做当前步(状态机不动,失败计数不赦免)。", {
709
- reason: { type: "string", description: "可选的重置原因——来自用户,说明为什么重置、重做时要注意什么。会拼到新会话首条 DO 提示前。" },
710
- instance: { type: "string", description: "实例 id(支持唯一前缀)。" },
711
- }, resetHandler);
712
- register("ralphflow_doctor", "诊断所有工作流定义和实例状态:完整的校验错误列表、被静默跳过的步骤、不可达步骤、无法解析的模板记号、损坏的子工作流引用与环、项目/插件遮蔽、被忽略的非工作流 YAML,以及损坏的实例状态。另含会话卫生检查:扫描会话日志中的插件自定义事件帧(重启后可能打不开会话的隐患)。只读。", {}, doctorHandler);
713
- register("ralphflow_create", "交互式创建一个自定义工作流:返回完整的设计指引(YAML 结构、硬规则、最佳实践)。当用户想新建工作流时调用,然后按指引与用户逐步确认设计、写入 YAML 并用 ralphflow_doctor 校验到可启动。", {}, createHandler);
714
- register("ralphflow_unbrick", "会话解砖:备份并移除会话日志中的插件自定义事件帧(历史版本 session.append 的遗留——继续留存会在下次重启 dsh 时让整个会话无法加载)。改前自动备份到 sessions/ralphflow-unbrick-backup-<ts>/。", {}, unbrickHandler);
715
- return handlers;
436
+ }
437
+ function messageSessionId(agent) {
438
+ return agent?.session?.id ?? "";
716
439
  }