ralphflow-dsh 0.1.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.
- package/LICENSE +21 -0
- package/README.md +196 -0
- package/lib/actions.d.ts +37 -0
- package/lib/actions.js +55 -0
- package/lib/check-voting.d.ts +54 -0
- package/lib/check-voting.js +289 -0
- package/lib/check.d.ts +64 -0
- package/lib/check.js +329 -0
- package/lib/client/CommandCard.d.ts +24 -0
- package/lib/client/CommandCard.js +69 -0
- package/lib/client/HeaderAction.d.ts +39 -0
- package/lib/client/HeaderAction.js +509 -0
- package/lib/client/RunCard.d.ts +27 -0
- package/lib/client/RunCard.js +375 -0
- package/lib/client/client.d.ts +3 -0
- package/lib/client/client.js +275 -0
- package/lib/client/definition.d.ts +126 -0
- package/lib/client/definition.js +259 -0
- package/lib/client/hidden-runs.d.ts +6 -0
- package/lib/client/hidden-runs.js +52 -0
- package/lib/client/http-state.d.ts +67 -0
- package/lib/client/http-state.js +81 -0
- package/lib/client/markdown.d.ts +26 -0
- package/lib/client/markdown.js +174 -0
- package/lib/client/notify-watch.d.ts +38 -0
- package/lib/client/notify-watch.js +98 -0
- package/lib/client/notify.d.ts +21 -0
- package/lib/client/notify.js +168 -0
- package/lib/client/snapshots.d.ts +8 -0
- package/lib/client/snapshots.js +101 -0
- package/lib/client.js +2361 -0
- package/lib/commands.d.ts +41 -0
- package/lib/commands.js +223 -0
- package/lib/create.d.ts +14 -0
- package/lib/create.js +98 -0
- package/lib/deps.d.ts +17 -0
- package/lib/deps.js +19 -0
- package/lib/done-detect.d.ts +2 -0
- package/lib/done-detect.js +28 -0
- package/lib/driver.d.ts +32 -0
- package/lib/driver.js +248 -0
- package/lib/engine.d.ts +306 -0
- package/lib/engine.js +2851 -0
- package/lib/events.d.ts +35 -0
- package/lib/events.js +52 -0
- package/lib/index.d.ts +11 -0
- package/lib/index.js +201 -0
- package/lib/jobs.d.ts +56 -0
- package/lib/jobs.js +355 -0
- package/lib/mutex.d.ts +9 -0
- package/lib/mutex.js +21 -0
- package/lib/session-hygiene.d.ts +25 -0
- package/lib/session-hygiene.js +205 -0
- package/lib/tools.d.ts +24 -0
- package/lib/tools.js +716 -0
- package/lib/voting-progress.d.ts +37 -0
- package/lib/voting-progress.js +89 -0
- package/package.json +73 -0
- package/workflows/loop.yaml +27 -0
- package/workflows/spec.yaml +105 -0
package/lib/tools.js
ADDED
|
@@ -0,0 +1,716 @@
|
|
|
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
|
+
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\` 看进度,或点页头入口展开任务列表。`;
|
|
16
|
+
export function registerTools(deps) {
|
|
17
|
+
const { ctx, engine, jobs } = deps;
|
|
18
|
+
const tools = ctx.tools;
|
|
19
|
+
const emit = createEmitter({ ctx, engine });
|
|
20
|
+
const handlers = new Map();
|
|
21
|
+
const sessionIdOf = (agent) => agent?.session?.id ?? null;
|
|
22
|
+
/**
|
|
23
|
+
* 把实例的 UI 事件帧从执行日志重放到当前属主会话(接管场景专用)。
|
|
24
|
+
* 返回是否发生了重放。失败绝不阻断接管流程本身。
|
|
25
|
+
* 注:重放只落审计日志(宿主持久化不接受插件自定义会话帧);新会话的
|
|
26
|
+
* 可视化档案由页头任务列表(HTTP 状态通道)承载。
|
|
27
|
+
*/
|
|
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
|
+
}
|
|
63
|
+
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}`;
|
|
145
|
+
};
|
|
146
|
+
handlers.set("ralphflow_start", startHandler);
|
|
147
|
+
// ─── ralphflow_continue ─────────────────────────────────────────────────────
|
|
148
|
+
const continueHandler = async (args, agent) => {
|
|
149
|
+
const instance = args?.instance;
|
|
150
|
+
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
|
+
});
|
|
358
|
+
};
|
|
359
|
+
handlers.set("ralphflow_continue", continueHandler);
|
|
360
|
+
// ─── ralphflow_status ───────────────────────────────────────────────────────
|
|
361
|
+
const statusHandler = (args, agent) => {
|
|
362
|
+
const instance = args?.instance;
|
|
363
|
+
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");
|
|
395
|
+
};
|
|
396
|
+
handlers.set("ralphflow_list", listHandler);
|
|
397
|
+
// ─── ralphflow_cancel ───────────────────────────────────────────────────────
|
|
398
|
+
const cancelHandler = (args, agent) => {
|
|
399
|
+
const instance = args?.instance;
|
|
400
|
+
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
|
+
});
|
|
446
|
+
};
|
|
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` 查看当前进度。";
|
|
458
|
+
}
|
|
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
|
+
});
|
|
533
|
+
};
|
|
534
|
+
handlers.set("ralphflow_rewind", rewindHandler);
|
|
535
|
+
// ─── ralphflow_reset ────────────────────────────────────────────────────────
|
|
536
|
+
const resetHandler = (args, agent) => {
|
|
537
|
+
const { reason, instance } = args ?? {};
|
|
538
|
+
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
|
+
});
|
|
576
|
+
};
|
|
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;
|
|
590
|
+
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 { }
|
|
607
|
+
}
|
|
608
|
+
};
|
|
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 = "";
|
|
632
|
+
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\` 一键备份并移除(风险:改前自动备份)。`;
|
|
637
|
+
}
|
|
638
|
+
catch (e) {
|
|
639
|
+
hygieneSection = `\n\n> 会话卫生检查失败:${e instanceof Error ? e.message : String(e)}`;
|
|
640
|
+
}
|
|
641
|
+
return `${report}${resourceSection}${hygieneSection}`;
|
|
642
|
+
};
|
|
643
|
+
handlers.set("ralphflow_doctor", doctorHandler);
|
|
644
|
+
// ─── ralphflow_unbrick ──────────────────────────────────────────────────────
|
|
645
|
+
// 会话解砖:备份并移除会话日志中的插件自定义事件帧(历史版本 session.append
|
|
646
|
+
// 的遗留;继续留存的帧会在下次重启 dsh 时让整个会话无法加载)。
|
|
647
|
+
const unbrickHandler = () => {
|
|
648
|
+
try {
|
|
649
|
+
const infected = scanSessionLogs();
|
|
650
|
+
if (infected.length === 0) {
|
|
651
|
+
return "✅ 所有会话日志干净,无需解砖。";
|
|
652
|
+
}
|
|
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
|
+
}
|
|
663
|
+
catch (e) {
|
|
664
|
+
return `解砖失败:${e instanceof Error ? e.message : String(e)}`;
|
|
665
|
+
}
|
|
666
|
+
};
|
|
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;
|
|
716
|
+
}
|