ralphflow-dsh 0.1.1 → 2.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (68) hide show
  1. package/README.md +220 -167
  2. package/cordis.patch.yml +11 -0
  3. package/lib/create.d.ts +7 -11
  4. package/lib/create.js +132 -83
  5. package/lib/engine.d.ts +667 -262
  6. package/lib/engine.js +3583 -2579
  7. package/lib/index.d.ts +3 -4
  8. package/lib/index.js +222 -163
  9. package/lib/message-source.d.ts +25 -0
  10. package/lib/message-source.js +2 -0
  11. package/lib/reset.d.ts +40 -0
  12. package/lib/reset.js +147 -0
  13. package/lib/tools.d.ts +31 -14
  14. package/lib/tools.js +407 -684
  15. package/lib/verify.d.ts +57 -0
  16. package/lib/verify.js +326 -0
  17. package/lib/voting.d.ts +63 -0
  18. package/lib/voting.js +131 -0
  19. package/package.json +25 -44
  20. package/workflows/loop.yaml +21 -6
  21. package/workflows/spec.yaml +51 -46
  22. package/lib/actions.d.ts +0 -37
  23. package/lib/actions.js +0 -55
  24. package/lib/check-voting.d.ts +0 -54
  25. package/lib/check-voting.js +0 -289
  26. package/lib/check.d.ts +0 -64
  27. package/lib/check.js +0 -329
  28. package/lib/client/CommandCard.d.ts +0 -24
  29. package/lib/client/CommandCard.js +0 -69
  30. package/lib/client/HeaderAction.d.ts +0 -39
  31. package/lib/client/HeaderAction.js +0 -509
  32. package/lib/client/RunCard.d.ts +0 -27
  33. package/lib/client/RunCard.js +0 -375
  34. package/lib/client/client.d.ts +0 -3
  35. package/lib/client/client.js +0 -275
  36. package/lib/client/definition.d.ts +0 -126
  37. package/lib/client/definition.js +0 -259
  38. package/lib/client/hidden-runs.d.ts +0 -6
  39. package/lib/client/hidden-runs.js +0 -52
  40. package/lib/client/http-state.d.ts +0 -67
  41. package/lib/client/http-state.js +0 -81
  42. package/lib/client/markdown.d.ts +0 -26
  43. package/lib/client/markdown.js +0 -174
  44. package/lib/client/notify-watch.d.ts +0 -38
  45. package/lib/client/notify-watch.js +0 -98
  46. package/lib/client/notify.d.ts +0 -21
  47. package/lib/client/notify.js +0 -168
  48. package/lib/client/snapshots.d.ts +0 -8
  49. package/lib/client/snapshots.js +0 -101
  50. package/lib/client.js +0 -2361
  51. package/lib/commands.d.ts +0 -41
  52. package/lib/commands.js +0 -223
  53. package/lib/deps.d.ts +0 -17
  54. package/lib/deps.js +0 -19
  55. package/lib/done-detect.d.ts +0 -2
  56. package/lib/done-detect.js +0 -28
  57. package/lib/driver.d.ts +0 -32
  58. package/lib/driver.js +0 -248
  59. package/lib/events.d.ts +0 -35
  60. package/lib/events.js +0 -52
  61. package/lib/jobs.d.ts +0 -56
  62. package/lib/jobs.js +0 -355
  63. package/lib/mutex.d.ts +0 -9
  64. package/lib/mutex.js +0 -21
  65. package/lib/session-hygiene.d.ts +0 -25
  66. package/lib/session-hygiene.js +0 -205
  67. package/lib/voting-progress.d.ts +0 -37
  68. package/lib/voting-progress.js +0 -89
package/lib/commands.d.ts DELETED
@@ -1,41 +0,0 @@
1
- /**
2
- * Ralph Flow for dsh — slash 命令(/ralphflow-*,与 opencode 命名一致)
3
- *
4
- * 命令通过 ctx.commands 注册;处理逻辑直接复用 tools.ts 中的工具实现。
5
- * 为复用工具逻辑,这里通过调用已注册的 tool 定义来执行,避免双份实现。
6
- *
7
- * 与 opencode 的关键架构差异及对齐手段:opencode 的 slash 命令是 prompt 模板
8
- * ($ARGUMENTS 注入后整段发给当前会话模型),命令执行天然驱动模型开工;dsh 的
9
- * 命令系统是 handler 型且 Log-only(command/run 永不进入模型上下文,返回文本只
10
- * 渲染给用户)。若不补一步注入,/ralphflow-start 之后 DO 阶段无人执行——工作流
11
- * 卡死在第一步。这里对会产生「轮到模型」结果的命令(start/continue/rewind/reset)
12
- * 用 agent.followup 把指令排队进当前会话并唤醒驱动(官方先例:dsh-cordis-host-
13
- * runner / dsh-subagent 均以 createUserMessage + inbox 投递驱动会话),对齐
14
- * opencode 版「start 后当前会话立即执行工作流」的行为。
15
- *
16
- * 反馈通道(重要架构约束):不再向会话 log 追加任何自定义事件帧——宿主持久化
17
- * 读路径(assertEventsSupported)只认识 KNOWN_SESSION_EVENT_TYPES,插件自定义
18
- * 类型落盘后整个会话会被 SessionFormatUnsupportedError 拒绝加载(会话变砖,无
19
- * ignorable 逃生门)。宿主对每条命令本身就会追加官方已知类型 command/run +
20
- * command/done(dsh-commands 的 execute 生命周期),client 端折叠这两个官方
21
- * 事件渲染命令结果卡,零持久化风险。
22
- */
23
- import type { Context } from "@deepseek-ai/cordis";
24
- import type { Engine } from "./engine.js";
25
- import type { RalphJobManager } from "./jobs.js";
26
- import type { Agent } from "@deepseek-ai/dsh-agent";
27
- export interface CommandContext {
28
- ctx: Context;
29
- engine: Engine;
30
- jobs: RalphJobManager;
31
- getAgent: (sessionId: string) => Agent | undefined;
32
- /** 已注册工具的执行器:name → (args, agent) => string | Promise<string> */
33
- runTool: (name: string, args: Record<string, unknown>, agent: Agent | undefined) => Promise<string> | string;
34
- }
35
- /**
36
- * 把工具结果作为插件消息投递进当前会话并唤醒模型驱动。失败绝不影响命令
37
- * 本身:结果卡已渲染给用户,注入失败时用户仍可手动让模型继续。
38
- */
39
- /** HTTP 动作端点(index.ts 审批/恢复/打回按钮直达通道)复用的同一注入桥 */
40
- export declare function deliverToModel(agent: Agent | undefined, command: string, text: string, logWarn?: (msg: string, err: unknown) => void): void;
41
- export declare function registerCommands(deps: CommandContext): void;
package/lib/commands.js DELETED
@@ -1,223 +0,0 @@
1
- import { createUserMessage } from "@deepseek-ai/dsh-llm";
2
- import { createUserGuideSummary } from "./create.js";
3
- const COMMAND_DEFS = [
4
- {
5
- name: "ralphflow-start",
6
- description: "启动工作流(工作流名 + 任务描述)",
7
- sample: "/ralphflow-start loop 实现用户认证",
8
- tool: "ralphflow_start",
9
- input: "<工作流名> <任务描述>",
10
- map: (raw) => {
11
- const [workflow, ...rest] = raw.trim().split(/\s+/);
12
- return { workflow, task: rest.join(" ") || undefined };
13
- },
14
- },
15
- {
16
- name: "ralphflow-continue",
17
- description: "批准手动审查 / 恢复暂停 / 接管实例",
18
- sample: "/ralphflow-continue [instance]",
19
- tool: "ralphflow_continue",
20
- input: "[instance]",
21
- map: (raw) => { const t = raw.trim(); return t ? { instance: t } : {}; },
22
- },
23
- {
24
- name: "ralphflow-status",
25
- description: "查看进度",
26
- sample: "/ralphflow-status [instance]",
27
- tool: "ralphflow_status",
28
- input: "[instance]",
29
- map: (raw) => { const t = raw.trim(); return t ? { instance: t } : {}; },
30
- },
31
- {
32
- name: "ralphflow-list",
33
- description: "列出工作流与活跃实例",
34
- sample: "/ralphflow-list",
35
- tool: "ralphflow_list",
36
- map: () => ({}),
37
- },
38
- {
39
- name: "ralphflow-cancel",
40
- description: "取消实例并归档报告",
41
- sample: "/ralphflow-cancel [instance]",
42
- tool: "ralphflow_cancel",
43
- input: "[instance]",
44
- map: (raw) => { const t = raw.trim(); return t ? { instance: t } : {}; },
45
- },
46
- {
47
- name: "ralphflow-rewind",
48
- description: "回退到已通过 CHECK 的上游步骤重做",
49
- sample: "/ralphflow-rewind <step> <reason> [instance]",
50
- tool: "ralphflow_rewind",
51
- input: "<step> <reason> [instance]",
52
- map: (raw) => {
53
- const parts = raw.trim().split(/\s+/);
54
- const step = parts[0];
55
- const reason = parts.slice(1).join(" ");
56
- return { step, reason };
57
- },
58
- },
59
- {
60
- name: "ralphflow-reset",
61
- description: "重置当前步上下文(当前会话内重新注入干净的 DO 提示重做当前步)",
62
- sample: "/ralphflow-reset [原因]",
63
- tool: "ralphflow_reset",
64
- input: "[reason]",
65
- map: (raw) => { const t = raw.trim(); return t ? { reason: t } : {}; },
66
- },
67
- {
68
- name: "ralphflow-doctor",
69
- description: "诊断工作流定义与实例状态",
70
- sample: "/ralphflow-doctor",
71
- tool: "ralphflow_doctor",
72
- map: () => ({}),
73
- },
74
- {
75
- name: "ralphflow-unbrick",
76
- description: "会话解砖(移除会话日志中的插件自定义事件帧,改前自动备份)",
77
- sample: "/ralphflow-unbrick",
78
- tool: "ralphflow_unbrick",
79
- map: () => ({}),
80
- },
81
- ];
82
- const CREATE_COMMAND = {
83
- name: "ralphflow-create",
84
- description: "创建自定义工作流(给出如何让模型引导你设计的说明)· 示例:/ralphflow-create 每天代码评审流程",
85
- input: { hint: "[想法描述]" },
86
- };
87
- /**
88
- * 返回文本可能携带「轮到模型执行」指令的命令:start 产出首个 DO 提示,
89
- * continue 批准门/恢复暂停/接管后产出下一步指引,reset/rewind 重注入 DO。
90
- * 查询类(status/list/cancel/doctor/create)只产生给人看的信息,不注入——
91
- * 免得模型为一行查询结果空转一轮。
92
- */
93
- const MODEL_FACING_COMMANDS = new Set(["ralphflow-start", "ralphflow-continue", "ralphflow-reset", "ralphflow-rewind"]);
94
- /**
95
- * 把工具结果作为插件消息投递进当前会话并唤醒模型驱动。失败绝不影响命令
96
- * 本身:结果卡已渲染给用户,注入失败时用户仍可手动让模型继续。
97
- */
98
- /** HTTP 动作端点(index.ts 审批/恢复/打回按钮直达通道)复用的同一注入桥 */
99
- export function deliverToModel(agent, command, text, logWarn) {
100
- if (!agent || typeof agent.followup !== "function")
101
- return;
102
- try {
103
- agent.followup(createUserMessage({
104
- content: [{
105
- type: "text",
106
- text: `[ralphflow] 用户刚通过 /${command} 触发了工作流操作,以下是执行结果与给你的后续指令。请遵循其中的指示行动;若它包含当前步骤的任务提示,现在就开始执行,完成实际工作后在回复最后一行单独输出 <promise>done</promise>。若它只是状态告知(如「验证进行中」),简短确认即可,不要输出 done 标记。\n\n---\n\n${text}`,
107
- }],
108
- source: { kind: "plugin", plugin: "ralphflow" },
109
- }));
110
- }
111
- catch (err) {
112
- logWarn?.("[ralphflow] followup inject failed:", err);
113
- }
114
- }
115
- /**
116
- * 命令结果的可视反馈由宿主自动追加的 command/run + command/done 官方事件承载
117
- * (client 折叠器渲染为对话内嵌卡),这里不再需要任何自定义帧写入。
118
- */
119
- /** 命令路径的空参校验(面向用户的用法提示;工具路径由工具自己校验) */
120
- const COMMAND_USAGE = {
121
- "ralphflow-start": (raw) => {
122
- const parts = raw.trim().split(/\s+/).filter(Boolean);
123
- if (parts.length < 2) {
124
- return `用法:/ralphflow-start <工作流名> <任务描述>\n\n示例:/ralphflow-start loop 用 JWT 实现用户认证模块\n\n用 /ralphflow-list 查看可用工作流。`;
125
- }
126
- return null;
127
- },
128
- "ralphflow-rewind": (raw) => {
129
- const parts = raw.trim().split(/\s+/).filter(Boolean);
130
- if (parts.length < 2) {
131
- return `用法:/ralphflow-rewind <步骤> <原因> [实例]\n\n示例:/ralphflow-rewind propose API 假设错了,改用 REST 轮询\n\n用 /ralphflow-status 查看可回退的步骤。`;
132
- }
133
- return null;
134
- },
135
- };
136
- export function registerCommands(deps) {
137
- const commands = deps.ctx.commands;
138
- for (const def of COMMAND_DEFS) {
139
- commands.register({
140
- name: def.name,
141
- description: `${def.description}(ralphflow)· 示例:${def.sample}`,
142
- ...(def.input ? { input: { hint: def.input } } : {}),
143
- handler: async (invocation) => {
144
- const agent = invocation.agent;
145
- try {
146
- const usageError = COMMAND_USAGE[def.name]?.(invocation.rawInput);
147
- if (usageError) {
148
- return { kind: "error", text: usageError };
149
- }
150
- const args = def.map(invocation.rawInput);
151
- const text = await deps.runTool(def.tool, args, agent);
152
- if (MODEL_FACING_COMMANDS.has(def.name)) {
153
- deliverToModel(agent, def.name.replace(/^ralphflow-/, ""), text, (m, e) => deps.ctx.logger?.warn?.(m, e));
154
- }
155
- return { kind: "success", text };
156
- }
157
- catch (err) {
158
- const msg = err instanceof Error ? err.message : String(err);
159
- return { kind: "error", text: msg };
160
- }
161
- },
162
- });
163
- }
164
- // ─── /ralphflow-create:用户侧创建入口(指引卡;设计过程由模型侧工具承载)──
165
- try {
166
- commands.register({
167
- name: CREATE_COMMAND.name,
168
- description: CREATE_COMMAND.description,
169
- input: CREATE_COMMAND.input,
170
- handler: async (invocation) => {
171
- const agent = invocation.agent;
172
- const text = createUserGuideSummary(invocation.rawInput ?? "");
173
- return { kind: "success", text };
174
- },
175
- });
176
- }
177
- catch (err) {
178
- deps.ctx.logger?.warn?.("[ralphflow] create command registration skipped:", err);
179
- }
180
- // ─── 动态工作流快捷命令(/loop、/spec……)────────────────────────────────────
181
- // 每个可启动的工作流各得到一个快捷 slash 命令(同 opencode 版语义),
182
- // 省去 list → start 的两步旅程。冲突策略:绝不覆盖——静态管理命令先注册,
183
- // 撞名/规范化后重名的工作流静默跳过,仍可用 /ralphflow-start <name> 启动。
184
- // 定义无效(invalid)的工作流不注册:启动必然失败,留给 /ralphflow-doctor 暴露。
185
- const taken = new Set(COMMAND_DEFS.map((d) => d.name));
186
- try {
187
- for (const wf of deps.engine.listWorkflows()) {
188
- if (wf.invalid)
189
- continue;
190
- const slug = String(wf.name).toLowerCase().replace(/[^a-z0-9-]+/g, "-").replace(/^-+|-+$/g, "");
191
- if (!slug || taken.has(slug))
192
- continue;
193
- taken.add(slug);
194
- const desc = wf.desc || `启动 ${wf.name} 工作流`;
195
- commands.register({
196
- name: slug,
197
- description: `(ralphflow) ${desc} · 示例:/${slug} <任务描述>`,
198
- input: { hint: "<任务描述>" },
199
- handler: async (invocation) => {
200
- const agent = invocation.agent;
201
- try {
202
- const task = invocation.rawInput.trim();
203
- if (!task) {
204
- const usage = `请给出任务描述:/${slug} <任务描述>`;
205
- return { kind: "error", text: usage };
206
- }
207
- const text = await deps.runTool("ralphflow_start", { workflow: wf.name, task }, agent);
208
- deliverToModel(agent, slug, text, (m, e) => deps.ctx.logger?.warn?.(m, e));
209
- return { kind: "success", text };
210
- }
211
- catch (err) {
212
- const msg = err instanceof Error ? err.message : String(err);
213
- return { kind: "error", text: msg };
214
- }
215
- },
216
- });
217
- }
218
- }
219
- catch (err) {
220
- // 同名命令已被注册(用户/其他插件):静默跳过,符合 opencode 版"绝不覆盖"语义
221
- deps.ctx.logger?.warn?.("[ralphflow] workflow shortcut registration skipped:", err);
222
- }
223
- }
package/lib/deps.d.ts DELETED
@@ -1,17 +0,0 @@
1
- /**
2
- * Ralph Flow for dsh — 共享依赖装配(check 调度依赖 + 事件发射)
3
- */
4
- import type { Context } from "@deepseek-ai/cordis";
5
- import type { Agent } from "@deepseek-ai/dsh-agent";
6
- import type { Engine } from "./engine.js";
7
- import type { CheckDeps } from "./check.js";
8
- import type { EventEmitter } from "./events.js";
9
- export interface CheckDepsOptions {
10
- ctx: Context;
11
- engine: Engine;
12
- emit: EventEmitter;
13
- getAgent: (sessionId: string) => Agent | undefined;
14
- /** 互斥段所属实例 id——提供后注册可 abort 的实例级信号(cancel 可中断在飞验证者) */
15
- instId?: string;
16
- }
17
- export declare function createCheckDeps(opts: CheckDepsOptions): CheckDeps;
package/lib/deps.js DELETED
@@ -1,19 +0,0 @@
1
- import { registerInstanceSignal } from "./check.js";
2
- export function createCheckDeps(opts) {
3
- if (opts.instId) {
4
- const reg = registerInstanceSignal(opts.instId);
5
- return {
6
- ctx: opts.ctx,
7
- engine: opts.engine,
8
- emit: (instId, type, data) => opts.emit.emit(instId, type, data),
9
- signal: reg.signal,
10
- dispose: reg.dispose,
11
- };
12
- }
13
- return {
14
- ctx: opts.ctx,
15
- engine: opts.engine,
16
- emit: (instId, type, data) => opts.emit.emit(instId, type, data),
17
- signal: new AbortController().signal,
18
- };
19
- }
@@ -1,2 +0,0 @@
1
- export declare function stripCodeBlocks(text: string): string;
2
- export declare function detectDoneTag(lastOutput: string): boolean;
@@ -1,28 +0,0 @@
1
- /**
2
- * done tag 检测(自 opencode 版 driver.ts 提取):模型在回复最后输出
3
- * <promise>done</promise> 表示 DO 阶段完成。代码围栏/行内代码里的标记被忽略。
4
- *
5
- * 匹配策略(兼顾两类误判):
6
- * - 标签必须落在文本末尾(允许尾随空白)——既容忍「完成。<promise>done</promise>」
7
- * 的同行写法,又排除正文提及(「…不要忘记输出 <promise>done</promise>」后面
8
- * 还跟实质内容时不会命中,避免提前触发验证白烧失败计数);
9
- * - 未闭合围栏:``` 成对替换后仍剩奇数个时,最后一个开围栏之后的内容整体按
10
- * 代码处理,围栏内的标记不参与检测。
11
- */
12
- const DONE_TAG_TAIL = /<promise>\s*done\s*<\/promise>[ \t]*$/i;
13
- export function stripCodeBlocks(text) {
14
- let result = text.replace(/```[\s\S]*?```/g, "");
15
- const openFences = result.split("```").length - 1;
16
- if (openFences % 2 === 1) {
17
- const idx = result.lastIndexOf("```");
18
- result = result.slice(0, idx);
19
- }
20
- result = result.replace(/`[^`\n]+`/g, "");
21
- return result;
22
- }
23
- export function detectDoneTag(lastOutput) {
24
- const text = stripCodeBlocks(lastOutput).trimEnd();
25
- if (!text)
26
- return false;
27
- return DONE_TAG_TAIL.test(text);
28
- }
package/lib/driver.d.ts DELETED
@@ -1,32 +0,0 @@
1
- /**
2
- * Ralph Flow for dsh — 状态机推进器(CHECK 编排 + 事件发射)
3
- *
4
- * 移植自 opencode 版 driver.ts 的 runCheckAndAdvance:opencode 通过 session.idle
5
- * 钩子 + injectPrompt 驱动;dsh 版由 job 内循环/工具调用触发本模块,把
6
- * "注入可见消息"替换为"发射 tool-ralphflow/* 事件帧"(client 端折叠成卡片),
7
- * 把"过渡文本"作为工具/命令的返回值返回给调用者(模型可见)。
8
- */
9
- import type { Engine, WorkflowDef, NormalStepDef, RalphFlowState } from "./engine.js";
10
- import { type CheckDeps } from "./check.js";
11
- import type { EventEmitter } from "./events.js";
12
- import type { Agent } from "@deepseek-ai/dsh-agent";
13
- export interface DriveContext {
14
- engine: Engine;
15
- deps: CheckDeps;
16
- emit: EventEmitter;
17
- /** 当前工作会话的 agent(验证者子代理的 parent);可能为 undefined(影子恢复) */
18
- parent: Agent | undefined;
19
- }
20
- export interface DriveResult {
21
- text: string;
22
- completed: boolean;
23
- paused: boolean;
24
- }
25
- /**
26
- * 对 DO 刚完成的步骤运行独立验证并推进状态机(do→check→on_pass/on_fail/暂停)。
27
- * 调用前置条件:实例状态为 do 阶段(done 已达成,或人工门已批准)。
28
- * 返回过渡文本(供工具/命令返回给模型),并发射全部 UI 事件帧。
29
- */
30
- export declare function runCheckAndAdvance(ctx: DriveContext, instId: string, workflow: WorkflowDef, step: NormalStepDef, state: RalphFlowState): Promise<DriveResult>;
31
- /** 供 tools/commands 复用的辅助:读单实例的状态快照文本(对齐 opencode 版信息量) */
32
- export declare function statusText(engine: Engine, instId: string, sessionId?: string | null): string;
package/lib/driver.js DELETED
@@ -1,248 +0,0 @@
1
- import { isSubWorkflowStep, MANUAL_GATE_MARKER, DEFAULT_ADVERSARIAL_TIMEOUT_MS } from "./engine.js";
2
- import { readFileSync } from "fs";
3
- import { adversarialCheck, liveVerifierCount } from "./check.js";
4
- import { runVotingCheck } from "./check-voting.js";
5
- import { readVotingProgress, deleteVotingProgress } from "./voting-progress.js";
6
- import { voterStatusLabel } from "./check-voting.js";
7
- function fmtVotingOverview(step) {
8
- if (!Array.isArray(step.check_voting) || step.check_voting.length === 0)
9
- return "";
10
- const n = step.check_voting.length;
11
- const rows = step.check_voting
12
- .map((e, i) => ` ${i + 1}/${n} ${String(e.check).split("\n")[0].trim().substring(0, 50)} · 模型:${typeof e.model === "string" ? e.model : e.model ? `${e.model.providerID}/${e.model.modelID}` : "默认"}`)
13
- .join("\n");
14
- return `[各验证者检查依据]\n${rows}`;
15
- }
16
- /**
17
- * 对 DO 刚完成的步骤运行独立验证并推进状态机(do→check→on_pass/on_fail/暂停)。
18
- * 调用前置条件:实例状态为 do 阶段(done 已达成,或人工门已批准)。
19
- * 返回过渡文本(供工具/命令返回给模型),并发射全部 UI 事件帧。
20
- */
21
- export async function runCheckAndAdvance(ctx, instId, workflow, step, state) {
22
- try {
23
- return await driveInner(ctx, instId, workflow, step, state);
24
- }
25
- finally {
26
- // 释放实例级 abort 注册(cancel 之后到达的本段信号不再保留)
27
- try {
28
- ctx.deps.dispose?.();
29
- }
30
- catch { }
31
- }
32
- }
33
- async function driveInner(ctx, instId, workflow, step, state) {
34
- const { engine, emit } = ctx;
35
- const sessionId = state.session_id ?? null;
36
- // do→check 转换(与 opencode 版一致:仅在真实边界记录 DO 完成)
37
- if (state.current_phase === "do") {
38
- engine.logEvent(instId, "info", "done_detected", { step: state.current_step });
39
- engine.addStepRecord(instId, state.current_step, "do", "passed", state.fail_count || 0, undefined, state.workflow_name);
40
- }
41
- engine.clearManualStepMarker(instId);
42
- engine.clearManualGate(instId);
43
- engine.clearReinjectCounter(instId);
44
- engine.clearDoPromptCache(instId);
45
- engine.clearDoneTagDetected(instId);
46
- engine.writeState({ ...state, current_phase: "check" }, instId);
47
- engine.recordStepStart(instId, state.current_step, "check");
48
- // ── no-check 步骤:未配置独立验证 → DO 完成即直通 on_pass ───────────────────
49
- if (step.no_check) {
50
- const noCheckReason = "本步骤未配置独立验证(no-check),完成即通过。";
51
- engine.addStepRecord(instId, step.id, "check", "passed", state.fail_count || 0, noCheckReason, state.workflow_name);
52
- emit.emit(instId, "tool-ralphflow/check-result", { runId: instId, step: step.id, passed: true, reason: noCheckReason });
53
- const result = engine.handleCheckPassed(instId, engine.readState(instId) ?? { ...state, current_phase: "check" }, workflow, step, { reason: noCheckReason }, true);
54
- return finishTransition(ctx, instId, workflow, state, result);
55
- }
56
- const isVoting = Array.isArray(step.check_voting) && step.check_voting.length > 0;
57
- const adversarialConfig = engine.getEffectiveAdversarialCheck(instId, workflow);
58
- engine.logEvent(instId, "info", "step_start", { step: state.current_step, phase: "check" });
59
- // 超时上限透传:UI 据此画「剩余时间」进度条,等待有了终点感
60
- const effectiveTimeoutMs = (isVoting && Array.isArray(step.check_voting)
61
- ? Math.max(...step.check_voting.map((v) => v.timeout_ms ?? adversarialConfig?.timeout_ms ?? 0), adversarialConfig?.timeout_ms ?? 0)
62
- : adversarialConfig?.timeout_ms) || DEFAULT_ADVERSARIAL_TIMEOUT_MS;
63
- emit.emit(instId, "tool-ralphflow/step-start", {
64
- runId: instId, step: state.current_step, phase: "check", failCount: state.fail_count || 0,
65
- ts: Date.now(),
66
- // 验证者总数:投票期首票落地前 UI 就能显示「已收 M/N 票」,不再静默
67
- voters: isVoting ? step.check_voting.length : 1,
68
- timeoutMs: effectiveTimeoutMs,
69
- });
70
- const checkPrompt = isVoting ? "" : engine.buildCheckPrompt(instId, step, state.user_task);
71
- let checkResult;
72
- try {
73
- if (isVoting && step.check_voting) {
74
- if (state.current_phase === "do") {
75
- deleteVotingProgress(engine, instId);
76
- }
77
- const progress = readVotingProgress(engine, instId);
78
- const outcome = await runVotingCheck(ctx.deps, engine, instId, sessionId, ctx.parent, step, state.user_task, step.check_voting, adversarialConfig, {
79
- phase: state.current_phase,
80
- workflowName: state.workflow_name,
81
- progress,
82
- // 投票进度通过 runSingleVoter 发射的 check-verdict 事件逐票推送,无需额外回调
83
- });
84
- if (outcome.kind === "cancelled") {
85
- engine.logEvent(instId, "warn", "voting_cancelled", { step: step.id });
86
- return { text: "工作流实例已被取消。", completed: false, paused: false };
87
- }
88
- if (outcome.kind === "infra_pause") {
89
- checkResult = { passed: false, infra: true, reason: outcome.reason };
90
- }
91
- else {
92
- checkResult = { passed: outcome.kind === "passed", reason: outcome.reason };
93
- }
94
- }
95
- else {
96
- const singleCheckConfig = step.check_model
97
- ? { ...(adversarialConfig || {}), model: step.check_model }
98
- : adversarialConfig;
99
- checkResult = await adversarialCheck(ctx.deps, sessionId, ctx.parent, instId, step, checkPrompt, state.user_task, singleCheckConfig);
100
- }
101
- }
102
- catch (err) {
103
- engine.logEvent(instId, "error", "adversarial_check_uncaught", { stepId: step.id, error: err.message });
104
- const st = engine.readState(instId);
105
- if (st && st.active && st.current_phase === "check" && st.current_step === state.current_step && st.workflow_name === state.workflow_name) {
106
- engine.writeState({ ...st, paused: true, pause_reason: "check_error", last_failure_reason: `对抗性检查崩溃:${err.message}` }, instId);
107
- }
108
- emit.emit(instId, "tool-ralphflow/check-result", { runId: instId, step: step.id, passed: false, reason: `对抗性检查崩溃:${err.message}`, infra: true });
109
- // 同 infra 暂停分支:绕过 finishTransition 的直接 return,补发暂停帧
110
- emit.emit(instId, "tool-ralphflow/run-end", { runId: instId, stopReason: "failed" });
111
- return {
112
- text: `⚠️ 验证未能运行 · 🙋 轮到你了\n\n对抗性检查崩溃:${err.message}\n\n这是验证程序自身的问题,不是你工作成果的问题——本次不计入失败次数,已完成的工作保持原样。\n\n👉 处理后运行 /ralphflow-continue 即可重新验证(无需重做任务),或 /ralphflow-cancel 放弃。`,
113
- completed: false, paused: true,
114
- };
115
- }
116
- // 状态竞争防御:验证期间实例被取消/接管/暂停则丢弃判定
117
- const cur = engine.readState(instId);
118
- if (!cur || !cur.active || cur.paused || cur.current_phase !== "check"
119
- || cur.workflow_name !== state.workflow_name || cur.current_step !== state.current_step) {
120
- engine.logEvent(instId, "warn", "check_result_discarded", { reason: cur?.paused ? "instance paused during check" : "state changed during check" });
121
- return { text: "", completed: false, paused: false };
122
- }
123
- if (checkResult.infra) {
124
- engine.writeState({ ...cur, paused: true, pause_reason: "check_error", last_failure_reason: checkResult.reason }, instId);
125
- engine.logEvent(instId, "warn", "workflow_paused", { workflow: cur.workflow_name, step: cur.current_step, reason: "check_infra_error" });
126
- emit.emit(instId, "tool-ralphflow/check-result", { runId: instId, step: step.id, passed: false, infra: true, reason: checkResult.reason });
127
- // 此分支直接 return 不经过 finishTransition——run-end failed 帧必须在这里
128
- // 补发,否则 client 卡片永远停在「验证中」、活体面板一直转(暂停语义在
129
- // UI 上不可见)。
130
- emit.emit(instId, "tool-ralphflow/run-end", { runId: instId, stopReason: "failed" });
131
- return {
132
- text: `⚠️ 验证未能运行 · 🙋 轮到你了\n\n${checkResult.reason}\n\n这是验证进程自身的问题(额度/API/超时),不是你工作成果的问题:本次不计入失败次数,已完成的工作无需重做。\n\n👉 问题解决后运行 /ralphflow-continue 直接重新验证,或 /ralphflow-cancel 放弃。`,
133
- completed: false, paused: true,
134
- };
135
- }
136
- emit.emit(instId, "tool-ralphflow/check-result", {
137
- runId: instId, step: step.id, passed: checkResult.passed, reason: checkResult.reason,
138
- aggregatedFails: checkResult.passed ? [] : [checkResult.reason],
139
- });
140
- engine.addStepRecord(instId, cur.current_step, "check", checkResult.passed ? "passed" : "failed", cur.fail_count || 0, checkResult.reason, cur.workflow_name);
141
- const result = checkResult.passed
142
- ? engine.handleCheckPassed(instId, cur, workflow, step, checkResult)
143
- : engine.handleCheckFailed(instId, cur, workflow, step, checkResult);
144
- return finishTransition(ctx, instId, workflow, state, result);
145
- }
146
- /**
147
- * 验证判定后的公共收尾:完成→报告+run-end;暂停→run-end failed;
148
- * 推进→step-start 事件 +(人工审查步骤只预告,真正停门发生在其 DO 完成时)。
149
- */
150
- function finishTransition(ctx, instId, workflow, state, result) {
151
- const { engine, emit } = ctx;
152
- if (result.completed) {
153
- // 工作流结束:报告已由 handleCheckPassed 归档,读取并发射报告/结束事件。
154
- // 实例此刻已被 destroyInstance 删除——用进入本段前锁定的属主会话发送,
155
- // 否则终态帧读不到 state.json 会被静默丢弃。
156
- const owner = state.session_id ?? null;
157
- const reportPath = engine.getReportPath(instId);
158
- let reportText = "";
159
- try {
160
- reportText = readFileSync(reportPath, "utf-8");
161
- }
162
- catch { }
163
- if (reportText) {
164
- emit.emitFinal(instId, owner, "tool-ralphflow/report", { runId: instId, text: reportText, reportPath });
165
- }
166
- emit.emitFinal(instId, owner, "tool-ralphflow/run-end", { runId: instId, stopReason: "done", reportId: instId });
167
- return { text: result.text, completed: true, paused: false };
168
- }
169
- if (result.paused) {
170
- emit.emit(instId, "tool-ralphflow/run-end", { runId: instId, stopReason: "failed" });
171
- return { text: result.text, completed: false, paused: true };
172
- }
173
- // 推进到下一步(do 阶段)——发射事件;人工审查步骤不发"已完成待审查"卡,
174
- // 审查门在其 DO 完成时由 job 触发(gate 帧此刻才真实)。
175
- const next = engine.readState(instId);
176
- if (next && next.active && next.current_phase === "do") {
177
- engine.clearDoneTagDetected(instId);
178
- engine.clearManualGate(instId);
179
- const nextWf = next.workflow_name === workflow.name ? workflow : engine.loadWorkflow(next.workflow_name);
180
- if (nextWf?.manual_step?.includes(next.current_step))
181
- engine.writeManualStepMarker(instId);
182
- engine.markPromptDelivered(next.current_step, instId);
183
- emit.emit(instId, "tool-ralphflow/step-start", {
184
- runId: instId, step: next.current_step, phase: "do", failCount: next.fail_count ?? 0,
185
- ts: Date.now(),
186
- });
187
- if (nextWf?.manual_step?.includes(next.current_step)) {
188
- return {
189
- text: `${result.text}\n\n---\n\n> 📋 下一步 **${next.current_step}** 是人工审查步骤:模型完成后会停下等你审查批准,届时对话里会出现审查卡片。`,
190
- completed: false,
191
- paused: false,
192
- };
193
- }
194
- }
195
- return { text: result.text, completed: false, paused: false };
196
- }
197
- /** 供 tools/commands 复用的辅助:读单实例的状态快照文本(对齐 opencode 版信息量) */
198
- export function statusText(engine, instId, sessionId) {
199
- const st = engine.readState(instId);
200
- if (!st)
201
- return `实例 ${instId} 不存在。`;
202
- const info = engine.listInstances().find((i) => i.id === instId);
203
- const line = [`实例 \`${instId}\`(工作流: ${st.workflow_name})`];
204
- line.push(`- 状态: ${info ? engine.instanceStatusLabel(info) : st.active ? (st.paused ? "⏸ 已暂停" : "🔨 执行中") : "已结束"}`);
205
- if (sessionId != null) {
206
- line.push(`- 属主会话: ${st.session_id === sessionId ? "🟢 本会话" : st.session_id ? `\`${st.session_id.slice(0, 8)}\`` : "无"}`);
207
- }
208
- else if (st.session_id) {
209
- line.push(`- 属主会话: \`${st.session_id.slice(0, 8)}\``);
210
- }
211
- line.push(`- 步骤: ${st.current_step} · 阶段: ${st.current_phase === "do" ? "DO 执行" : "CHECK 验证"} · 失败次数: ${st.fail_count ?? 0}`);
212
- if (info?.lastActivity)
213
- line.push(`- 最后活动: ${engine.formatLastActivity(info.lastActivity)}`);
214
- // 当前步骤详情
215
- const wf = engine.loadWorkflow(st.workflow_name);
216
- const step = wf ? engine.getStep(wf, st.current_step) : null;
217
- if (wf && step && !isSubWorkflowStep(step)) {
218
- const s = step;
219
- const detail = [];
220
- detail.push(`- 任务: ${(s.do || "").split("\n")[0].trim().slice(0, 80)}`);
221
- if ((st.fail_count ?? 0) >= s.max_fail_count)
222
- detail.push(` ⚠️ 已达最大失败次数 ${s.max_fail_count}`);
223
- line.push(...detail);
224
- }
225
- if (st.last_failure_reason) {
226
- const reason = st.last_failure_reason.length > 2000 ? st.last_failure_reason.slice(0, 2000) + "…" : st.last_failure_reason;
227
- line.push(`- 上次失败原因:\n\n ${reason.split("\n").join("\n ")}`);
228
- }
229
- // 人工门待审提示
230
- if (engine.markerExists(MANUAL_GATE_MARKER, instId)) {
231
- line.push(`\n> 📋 该实例停在人工审查门(步骤 \`${st.current_step}\`):确认无误后运行 \`/ralphflow-continue\` 批准进入验证;需返工则 \`/ralphflow-reset <意见>\` 打回重做。`);
232
- }
233
- // 验证中断检测:phase=check 且无任何登记中的验证者会话 → 进程曾在验证期间重启
234
- // (先清孤儿登记:kill -9 残留的 live 文件不能让这里永远报「验证进行中」)
235
- if (!st.paused && st.current_phase === "check" && liveVerifierCount(engine, instId) === 0) {
236
- line.push(`\n> ⏸ 验证似乎已中断(例如进程重启)。运行 \`/ralphflow-continue\` 恢复验证(已投出的票会保留)。`);
237
- }
238
- // 多验证者投票进度
239
- const progress = readVotingProgress(engine, instId);
240
- if (progress && progress.stepId === st.current_step && progress.entries.length > 0) {
241
- line.push(`\n**投票进度**(${progress.stepId}):`);
242
- for (const e of progress.entries) {
243
- const summary = (e.check || "").split("\n")[0].trim().slice(0, 40);
244
- line.push(` ${voterStatusLabel(e.status)} 验证者 ${e.index + 1}/${progress.entries.length}${e.model ? ` · ${e.model}` : ""} — ${summary}${e.reason ? `\n ${e.reason.split("\n")[0].slice(0, 120)}` : ""}`);
245
- }
246
- }
247
- return line.join("\n");
248
- }
package/lib/events.d.ts DELETED
@@ -1,35 +0,0 @@
1
- /**
2
- * Ralph Flow for dsh — 事件帧发射器(审计侧)
3
- *
4
- * 每个状态机步骤:1) 写 JSONL 审计日志(execution.log,100% 可控)。
5
- * 曾经通过 session.append 把 tool-ralphflow/* 帧发射到会话 log 供 client 折叠
6
- * 成对话内嵌卡——该通道已废弃(见 createEmitter 内的架构说明:自定义事件在
7
- * 宿主持久化读路径上会砖掉整个会话)。
8
- * 事件集(审计用途,与 client/definition.ts 的 match 对应):
9
- * run-start / step-start / check-voter-start / check-verdict / check-result /
10
- * gate / rewind / reset / report / run-end / run-detach
11
- */
12
- import type { Context } from "@deepseek-ai/cordis";
13
- import type { Engine } from "./engine.js";
14
- export interface EventEmitter {
15
- emit(instId: string, type: string, data: Record<string, unknown>): void;
16
- /**
17
- * 终态发射:实例已被销毁(完成/取消)后使用预先解析的属主会话发送。
18
- * 当前仅用于审计日志归属;不触碰会话 log。
19
- */
20
- emitFinal(instId: string, ownerSessionId: string | null | undefined, type: string, data: Record<string, unknown>): void;
21
- }
22
- export interface EmitterDeps {
23
- ctx: Context;
24
- engine: Engine;
25
- }
26
- export declare function createEmitter(deps: EmitterDeps): EventEmitter;
27
- /** 由引擎生成工作流快照,供 run 卡渲染(client 端亦可自行从事件折叠) */
28
- export declare function projectRunState(engine: Engine, instId: string): {
29
- workflow: string;
30
- currentStep: string;
31
- currentPhase: string;
32
- failCount: number;
33
- paused: boolean;
34
- status: "running" | "paused" | "failed" | "complete" | "cancelled";
35
- };