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.
Files changed (60) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +196 -0
  3. package/lib/actions.d.ts +37 -0
  4. package/lib/actions.js +55 -0
  5. package/lib/check-voting.d.ts +54 -0
  6. package/lib/check-voting.js +289 -0
  7. package/lib/check.d.ts +64 -0
  8. package/lib/check.js +329 -0
  9. package/lib/client/CommandCard.d.ts +24 -0
  10. package/lib/client/CommandCard.js +69 -0
  11. package/lib/client/HeaderAction.d.ts +39 -0
  12. package/lib/client/HeaderAction.js +509 -0
  13. package/lib/client/RunCard.d.ts +27 -0
  14. package/lib/client/RunCard.js +375 -0
  15. package/lib/client/client.d.ts +3 -0
  16. package/lib/client/client.js +275 -0
  17. package/lib/client/definition.d.ts +126 -0
  18. package/lib/client/definition.js +259 -0
  19. package/lib/client/hidden-runs.d.ts +6 -0
  20. package/lib/client/hidden-runs.js +52 -0
  21. package/lib/client/http-state.d.ts +67 -0
  22. package/lib/client/http-state.js +81 -0
  23. package/lib/client/markdown.d.ts +26 -0
  24. package/lib/client/markdown.js +174 -0
  25. package/lib/client/notify-watch.d.ts +38 -0
  26. package/lib/client/notify-watch.js +98 -0
  27. package/lib/client/notify.d.ts +21 -0
  28. package/lib/client/notify.js +168 -0
  29. package/lib/client/snapshots.d.ts +8 -0
  30. package/lib/client/snapshots.js +101 -0
  31. package/lib/client.js +2361 -0
  32. package/lib/commands.d.ts +41 -0
  33. package/lib/commands.js +223 -0
  34. package/lib/create.d.ts +14 -0
  35. package/lib/create.js +98 -0
  36. package/lib/deps.d.ts +17 -0
  37. package/lib/deps.js +19 -0
  38. package/lib/done-detect.d.ts +2 -0
  39. package/lib/done-detect.js +28 -0
  40. package/lib/driver.d.ts +32 -0
  41. package/lib/driver.js +248 -0
  42. package/lib/engine.d.ts +306 -0
  43. package/lib/engine.js +2851 -0
  44. package/lib/events.d.ts +35 -0
  45. package/lib/events.js +52 -0
  46. package/lib/index.d.ts +11 -0
  47. package/lib/index.js +201 -0
  48. package/lib/jobs.d.ts +56 -0
  49. package/lib/jobs.js +355 -0
  50. package/lib/mutex.d.ts +9 -0
  51. package/lib/mutex.js +21 -0
  52. package/lib/session-hygiene.d.ts +25 -0
  53. package/lib/session-hygiene.js +205 -0
  54. package/lib/tools.d.ts +24 -0
  55. package/lib/tools.js +716 -0
  56. package/lib/voting-progress.d.ts +37 -0
  57. package/lib/voting-progress.js +89 -0
  58. package/package.json +73 -0
  59. package/workflows/loop.yaml +27 -0
  60. package/workflows/spec.yaml +105 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Ralph Flow for dsh contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,196 @@
1
+ # Ralph Flow for DeepSeek Harness (dsh)
2
+
3
+ > 插件名 **ralphflow** —— slash 命令与工具命名和 opencode 版**一字不差**,opencode 用户零学习成本。
4
+ > 目标:把 ralphflow 的 DO/CHECK 状态机工作流引擎做成 dsh 的原生插件,像 dsh 本来就有的功能。
5
+
6
+ ## 这是什么
7
+
8
+ dsh 版的 ralphflow:同一个 DO → CHECK → 人工门 → 验证 → 报告 状态机,但 UI 全部是 dsh 原生形态(对话内嵌卡 + 页头入口),不引入独立大页面(无 Studio/Dashboard/Runs 表格页)。
9
+
10
+ - 插件名:`ralphflow`
11
+ - slash 命令:`/ralphflow-start` `/ralphflow-continue` `/ralphflow-status` `/ralphflow-list` `/ralphflow-cancel` `/ralphflow-rewind` `/ralphflow-reset` `/ralphflow-doctor` `/ralphflow-unbrick`
12
+ - 工具:`ralphflow_start` `ralphflow_continue` `ralphflow_status` `ralphflow_list` `ralphflow_cancel` `ralphflow_rewind` `ralphflow_reset` `ralphflow_doctor` `ralphflow_create` `ralphflow_unbrick`(10 个,除 create/unbrick 外与 opencode 同名同参)
13
+ - 工作流快捷命令:`/loop` `/spec` 等(按工作流目录动态注册)
14
+
15
+ ## 安装
16
+
17
+ ### 从 npm 安装(发布后)
18
+
19
+ ```bash
20
+ dsh plugin --profile web add ralphflow-dsh # pnpm 从 registry 解析并装入 profile
21
+ ```
22
+
23
+ 然后照常三步:`cordis.patch.yml` 追加 `insert: [{ id: ralphflow, name: ralphflow-dsh }]`,重启 dsh。npm 包名 `ralphflow-dsh`(`ralphflow` 已被其它项目占用);插件名保持 `ralphflow`(命令/工具命名与 opencode 版一致)。
24
+
25
+ ### 本地源码安装
26
+
27
+ 构建产物在 `lib/`(host: `lib/index.js`,client: `lib/client/client.js`)。
28
+
29
+ ```bash
30
+ cd ~/ralph-flow-dsh
31
+ npm install # 安装构建依赖
32
+ npm run build # 产出 lib/(host 端 tsc + client 端 esbuild bundle)
33
+ ```
34
+
35
+ 构建分两步:`build:host`(tsc 编译 host 引擎)与 `build:client`(`scripts/build-client.mjs` 用 esbuild 把 `src/client/**` 打成 dsh 官方 client bundle 单文件 `lib/client.js`)。client bundle 格式与官方 `@deepseek-ai/dsh-client-ui-workflow-run/lib/client.js` 同构:`window.__ModuleLoader__.load({ id, factory: (require) => {...} })`,外部依赖(react、`@deepseek-ai/*`)走 factory 参数 `require` 由 dsh 浏览器运行时解析,不做任何跨插件值导入。
36
+
37
+ 把插件装进 dsh profile(以 web profile 为例)并启用:
38
+
39
+ ```bash
40
+ # 1) 安装到 profile(pnpm link,包名 ralphflow-dsh)
41
+ dsh plugin --profile web add ~/ralph-flow-dsh
42
+
43
+ # 2) 在 ~/.dsh/profiles/web/cordis.patch.yml 里追加:
44
+ # - insert:
45
+ # - id: ralphflow
46
+ # name: ralphflow-dsh
47
+
48
+ # 3) 重启 dsh
49
+ dsh --profile web
50
+ ```
51
+
52
+ 插件加载验证:dsh 启动后浏览器控制台 Network 面板可见 `/plugins/ralphflow/client.js`(client 端组合成功);对话里执行 `/ralphflow-list` 能列出工作流即 host 端就绪。
53
+
54
+ ### 可重复验证(无模型也可跑)
55
+
56
+ 模型配额 429 时,真实模型链路(DO 执行 / 验证者 subagent)无法在线跑通。除引擎层等价脚本外,还有**真实 dsh 运行时**与**真实浏览器**验证:
57
+
58
+ ```bash
59
+ npm run build
60
+
61
+ # A. 真实 dsh 进程内端到端(真实 ctx + 真实 ralphflow_start 工具 + 真实落盘 + 重启接管 + 权限)
62
+ RALPHFLOW_WORKSPACE=/home/yj/ralph-flow-dsh dsh --profile headless-e2e "noop"
63
+ # → 结果在 e2e-harness/result.json(33 项断言,真实 dsh 运行时)
64
+
65
+ # B. 真实 chromium 浏览器 UI(client.js 加载 + 渲染 + 截图)
66
+ dsh --profile web & # 先启动 web(建议 RALPHFLOW_WORKSPACE=<插件工作区> 指定工作流目录)
67
+ node e2e-harness/ui-browser.mjs
68
+ # → 结果在 e2e-harness/ui-result.json + ui-home.png
69
+
70
+ # B2. 真实浏览器执行 slash 命令(补全面板点选 /ralphflow-list → 输出渲染 diff)
71
+ node e2e-harness/ui-cmd-browser.mjs
72
+ # → 结果在 e2e-harness/cmd-ui-result.json + cmd-ui-after.png
73
+
74
+ # C. 引擎层/折叠逻辑单元级补充(不依赖模型)
75
+ node --experimental-strip-types smoke-host.mts
76
+ node --experimental-strip-types smoke-client.mts
77
+ node --experimental-strip-types e2e-verify.mts
78
+ node --experimental-strip-types ui-verify.mts
79
+ ```
80
+
81
+ `headless-e2e` 是一个专门用于验证的 dsh profile(bundle 同 headless,patch 注入 ralphflow + e2e-harness);`e2e-harness/` 是真实 cordis/dsh 插件,在真实 dsh 进程内通过真实 `ctx.tools` 调用 `ralphflow_start` 创建真实实例并推进。完整报告见工作流产出 `verification.md`。
82
+
83
+ ### 依赖解析说明
84
+
85
+ 本插件 peerDependencies 指向 dsh 官方包(`@deepseek-ai/dsh-*`,版本 `^0.1.0-rc.7`)。这些包随 dsh 一起安装于 `/usr/lib/deepseek-harness/node_modules/@deepseek-ai/`。构建时若 npm 无法解析,可用符号链接指向 dsh 自带包:
86
+
87
+ ```bash
88
+ mkdir -p node_modules
89
+ ln -s /usr/lib/deepseek-harness/node_modules/@deepseek-ai node_modules/@deepseek-ai
90
+ ln -s /usr/lib/deepseek-harness/node_modules/cordis node_modules/cordis
91
+ ln -s /usr/lib/deepseek-harness/node_modules/react node_modules/react
92
+ ```
93
+
94
+ ## 使用
95
+
96
+ ```text
97
+ /ralphflow-start loop 用 JWT 实现用户认证模块
98
+ /ralphflow-start spec 修复登录模块的空指针
99
+ /ralphflow-continue # 批准人工审查 / 恢复暂停 / 接管实例
100
+ /ralphflow-status # 查看进度
101
+ /ralphflow-list # 工作流 + 活跃实例
102
+ /ralphflow-rewind propose 第二步的技术文档 API 假设错了,重新设计
103
+ /ralphflow-reset 模型跑偏了,换干净上下文重做当前步
104
+ /ralphflow-cancel # 取消并归档报告
105
+ /ralphflow-doctor # 诊断工作流定义与实例状态(含会话卫生检查)
106
+ /ralphflow-unbrick # 会话解砖(备份并移除会话日志中的插件自定义帧)
107
+ ```
108
+
109
+ - 启动后模型在对话里执行 DO;完成时输出 `<promise>done</promise>`,后台 job 自动转入独立验证(多验证者投票)。
110
+ - 实时 UI 挂在**页面顶部 Ralph Flow 入口**(HTTP 状态通道轮询,2.5s 刷新):活跃/待审查/已暂停徽标(trigger 微缩含当前步骤与耗时)、任务列表(「待处理」与「运行中」分区)、验证票进度(本地化状态 + 语义色 + 票飞行时长)、**CHECK 剩余时间进度条**(超时上限给了等待一个终点)、失败原因全文、暂停原因、审查材料、属主;审查门可**一键通过**(POST 直连 host),打回附意见内联发送后模型带意见返工,暂停实例直接「继续」恢复,**取消**两步确认防误触;「已结束」区带**报告按钮**直接打开最终报告。
111
+ - 通知是**全局模块级监视**(不依赖任何页面组件):审查门到达 / 暂停 / 完成都弹系统通知 + 标题闪烁,任意页面(含空态页)都提醒;历史完成记录预填游标,切页/刷新不历史轰炸;同标签去重(sessionStorage)+ 跨标签协调(localStorage 短窗口),多开标签页只响一次。
112
+ - 命令结果卡折叠**官方 `command/run` + `command/done` 事件**渲染在对话流(宿主动态词汇表成员,持久化安全)——插件不再向会话日志写任何自定义帧(第三方自定义事件类型无 ignorable 逃生门,落盘会让整个会话无法加载,历史版本因此砖过会话,`/ralphflow-unbrick` 一键修复)。
113
+ - 人工审查门(`manual_step`)的步骤:DO 完成后停下,页头徽标变「待审查」,在抽屉点「通过」或 `/ralphflow-continue` 批准后进入验证。
114
+ - 跨会话/重启后:任何会话 `/ralphflow-continue` 可接管实例;插件加载时自动扫描实例目录恢复任务视图(影子 registry)。
115
+
116
+ ## 与 opencode 版的功能对照
117
+
118
+ | 能力 | opencode 版 | dsh 版(本插件) |
119
+ |---|---|---|
120
+ | 命令/工具命名 | `/ralphflow-*` + `ralphflow_*` | 完全一致 |
121
+ | DO/CHECK 状态机 | 引擎驱动 | 引擎移植复用,驱动换 dsh jobs + 会话事件流 |
122
+ | 多验证者投票 | `check_voting` 并行投票 | 相同,验证者改 dsh 子代理 |
123
+ | 人工审查门 | `manual_step` 暂停等待 | 相同,抽屉一键通过/打回(POST 直连) |
124
+ | 实例持久化 | `.opencode/ralph-flow/instances/` | `<workspace>/ralph-flow/instances/`(同布局) |
125
+ | 跨会话接管 | 任意会话 continue | 相同(jobs + 影子 registry) |
126
+ | 崩溃恢复 | idle 重跑 + 孤儿清理 | job 重建 + 状态文件恢复 |
127
+ | UI | TUI + 自绘 | dsh 原生插槽:页头任务列表 + 对话内命令结果卡(官方 command/done 事件折叠) |
128
+ | 主题 | 自绘 | dsh `--dsw-*` token |
129
+ | 独立大页面(Studio/Dashboard 等) | 有(原型) | **无**(评审结论:会话中心不引入全局面板) |
130
+
131
+ ## 对 plugin-design.md 的实现偏离(留痕)
132
+
133
+ 0. **2025-08 dsh 契合度修复批次**(诊断 + 修复,目标:完美契合 dsh 的 ralphflow):
134
+ - **会话砖化根除**:移除命令路径的 `session.append("tool-ralphflow/command-result")`(宿主持久化读路径只认 KNOWN_SESSION_EVENT_TYPES,第三方自定义类型落盘后整个会话拒绝加载,无 ignorable 逃生门——历史因此砖过两个真实会话,`~/.dsh/unbrick-backup-*` 有备份为证)。命令结果卡改为折叠宿主自动追加的官方已知类型 `command/run` + `command/done`(dsh-commands 的 execute 生命周期,落盘重放安全)。
135
+ - **抽屉中心化**:run 帧通道废弃后对话内不再折叠 run 卡——通知/快照/审批全部迁到页头任务列表(HTTP 状态通道数据源):审查门/暂停/完成到达弹系统通知 + 标题闪烁(全局模块级监视,不依赖组件挂载;sessionStorage 去重 + localStorage 跨标签协调)、「通过/继续/取消(两步确认)」POST 直连 host 动作端点(webServer 路由,逻辑抽到 actions.ts 可单测)、「打回」抽屉内联意见发送、CHECK 剩余时间进度条(timeoutMs/checkStartedAt 透出)、验证票本地化状态 + 飞行时长(voterProgress 带 startedAt)、「状态详情」抽屉展开(任务/审查材料/失败原因全文/属主)、「已结束」区报告按钮(recentEnded 带 reportPath)。回退守卫:POST 失败自动退回命令注入链路。
136
+ - **会话卫生自愈**:新增 `ralphflow_unbrick` 工具 + `/ralphflow-unbrick` 命令(备份后按 dsh 多帧 zstd 格式重写,自实现不依赖外部脚本);`/ralphflow-doctor` 增加会话卫生节 + 资源占用节(reports/artifacts/instances/history/logs 增长报告)。
137
+ - **成本与安全**:DO/CHECK prompt 长文本截断(任务 4k / 步骤正文 8k / 输入输出 2k,截断处明确标注);markdown 链接协议白名单(https/mailto/file/相对路径,拒绝 javascript:/data:);删除死导出 `RALPH_CHECK_AGENT_PERMISSION`;`get_agent_missing_session` 降噪为 info(影子恢复的正常降级)。
138
+ - **文案对齐**:ONBOARDING/README/对照表改为抽屉 + 命令卡的真实能力描述。
139
+ - HTTP GET 通道 payload 增加 `workflows`(命令卡折叠器识别 /loop /spec)与 `recentEnded`(完成通知与报告按钮数据源)。
140
+
141
+ 0b. **2025-08 UX 评审修复批次**(4 路独立评审:对齐/用户旅程/健壮性/UI,汇总 40+ 问题后迭代):
142
+ - **人工审查门接线修复**:此前 jobs 检测的是恒不存在的 `.manual-gate` → manual 步 DO 完成后直接自动进验证,门形同虚设;且 gate 卡在步骤开始前就弹出并谎称「DO 已完成」。现改为:DO 完成检测点真实写 `.manual-gate` + 发 gate 帧 + 停下等待;推进预告只提示「完成后会停下等你审查」;`e2e-verify.mts` 的伪断言替换为 stub 验证者驱动的全链路真断言。
143
+ - **「验证进行中」防线生效**:`.adversarial-session` 此前从未被写入(读侧防线全部恒假)。现在每个验证者子代理启动/结束时登记/移除该文件——CHECK 运行中不再被重复触发或误判为崩溃恢复。
144
+ - **终态帧可达**:实例销毁后 report/run-end 帧因读不到 state.json 属主而被静默丢弃(UI 永远停在旧状态)。新增 `emitFinal(instId, owner, ...)` 在销毁前锁定属主会话发送。
145
+ - **审批按钮行为拆分**:「✗ 打回」此前与「✓ 通过」绑定同一动作。现打回填入 `/ralphflow-reset `(附意见回车返工)、通过填入 `/ralphflow-continue` 并尝试代提交;两种结果都有可见反馈,绝不静默。命令错误结果同样发可见卡(error 视觉态),不再落入不可见的日志行。
146
+ - 其余:no_check 步骤保留直通(不再静默丢弃);continue 的 paused/crash/attach 分支补齐子工作流重入;status 输出对齐 opencode 版信息量(属主/最后活动/失败原因全文/投票进度/友好暂停文案);start 空 task 拒绝 + 启动引导块;实例级互斥锁(双会话并发 continue 串行化);cancel 真正中止在飞验证者(AbortSignal registry)并补日志/kill job;writeVotingProgress 防复活已销毁目录;崩溃重启后 continue 保留已投出的票只补跑;doctor 移除幽灵命令引用与占位符泄漏;client 终态冻结/verdict upsert 幂等/runId 丢帧/虚构 token 修正/条件 hook 修复/页头徽标状态换色/任务行改传实例 id。
147
+ - **create 双端落地**:dsh 命令通道 log-only(never model surface,见 dsh-commands "without sending it to the model"),opencode 式模板命令无注入模型的通道。改为:host 工具 `ralphflow_create` 承载完整设计指引(模型被调用后引导用户设计 YAML 并 doctor 校验),`/ralphflow-create [想法]` 命令作用户侧入口(展示如何唤起模型 + 引导卡)。
148
+ - **卡片运行耗时**:step-start 帧携带 `ts` 时间戳,client 折叠为 `stepStartedAt`,卡片头部显示当前步骤「⏱ 已运行 Xm」。
149
+ - **i18n 补全**:HeaderAction 状态标签与 aria 接入 locale 词典(zh/en status.* 键),RunCard/HeaderAction 均接收 slot 注入的 `t`。
150
+
151
+ 1. **reset/rewind 的"换新会话"语义**:设计稿提出复用 opencode 的"新顶级会话"路径;实现改为工具返回完整过渡文本、在当前会话继续重做。理由:dsh 没有 opencode 的 TUI session 导航;跨会话接管由 `/ralphflow-continue` 承担,与 dsh 会话心智一致。
152
+ 2. **验证者沙箱**:设计稿建议子代理会话 `read-only` sandbox。当前实现以 `toolFilter` 白名单(read/bash/grep/glob/read_image)+ system prompt 铁律实现 edit 硬拒;子代理 sandbox 继承依赖 in-process provider 的会话配置,若宿主未配置 read-only 继承,则文件写入仍可能被工具白名单之外的途径阻塞——README 记录此约束,待真机验证后按宿主能力收紧。
153
+ 3. **事件帧收敛**:`onVoteProgress` 不再注入可见消息,改由每个验证者的 `check-verdict` 事件帧逐票推送(client 卡片实时刷新),避免消息风暴。
154
+ 4. **全局工作流目录**:opencode 版在 `~/.config/opencode/ralph-flow/workflows/`;dsh 版改在 `~/.dsh/ralph-flow/workflows/`(尊重 `$DSH_HOME`),doctor/list 文案同步。
155
+ 5. **工作流快捷命令**:`/loop` `/spec` 等动态注册移植自 opencode 版,撞名/无效定义静默跳过(同 opencode 规则);dsh 命令注册冲突会抛错,故冲突时捕获跳过。
156
+ 6. **验证者模型与工具白名单**:设计稿的"验证者沙箱"以 dsh 原生 `toolFilter`(allow: read/bash/grep/glob/read_image)+ 验证 prompt 铁律落地;模型解析用 dsh 的 `AgentOptions`(provider/model 分字段,来自工作会话或全局默认),与 opencode 版"会话模型"同源。命令 handler 严格遵循 dsh 的 `CommandInvocation`(rawInput/agent/signal)契约。
157
+ 6a. **验证者必须携带 parent agent**:dsh-subagent 的 `start` 内部强制读 `parent.options`(无 parent 即抛 `reading 'options'`)。因此插件 host 入口 `inject` 必须含 `agents`,`getAgent(sessionId)` 经 `ctx.agents.get` 解析工作会话 agent 作为验证者子代理的 parent;缺失时验证者全部失败并 `check_error` 暂停(e2e 已覆盖)。
158
+ 6b. **验证者模型解析保留 provider**:工作会话 `agent.options` 的 `provider`/`model` 分字段存在时,须组合为 `"provider/model"` 传给子代理 `agentOptions`(单独给 model 会丢 provider,请求路由错误)。
159
+ 6c. **命令的 opencode 式反馈**:早期实现向会话追加 `tool-ralphflow/command-result` 帧渲染结果卡(见 batch 0a 的砖化教训);现已改为折叠宿主自动追加的官方 `command/run` + `command/done` 事件(kind `ralphflow-command`),既保留显眼结果卡又零持久化风险。6d 起同下。
160
+ 6d. **client chat.node 槽组件签名**:dsh 的 keyed Chat Node 组件接收 `{ node, renderSlot, t }`,数据在 `node.data`(与官方 CommandNodeView 一致),不能用 `{ data }`;页头组件用 `useSessions` 必须在组件顶层调用(不得包进 useMemo,违反 hooks 规则会让 React 崩溃 `reading 'length'`)。
161
+ 6e. **命令必须声明 `input.hint` 才能"命令+参数"**:dsh 输入机的 `matchEnter` 对带参数的命令——若命令未声明 `CommandDefinition.input`,返回 undefined 把整行当普通消息发给模型(`/ralphflow-start loop 任务` 会变成模型提示而不是启动工作流)。声明 `input: { hint }` 后:裸命令 Enter 进入 claim(输入框保留 `/name `)可继续输入;带参数 Enter 作为命令执行。ralphflow-* 与快捷命令(/loop、/spec)均已声明。
162
+ 7. **client bundle 打包**:设计稿要求"client 端与 host 端双入口"。dsh 要求 client bundle 是单文件 `__ModuleLoader__.load({id, factory})` CJS 格式(tsdown/官方打包产物),直接 `tsc` 的多文件 ESM 产物在经典 `<script>` 加载下必然抛错且相对导入 404。故 `build:client` 用 esbuild 打成官方同构单文件,`exports["./client"]` 指向 `lib/client.js`;`lib/client/*.js`(tsc 产物)仅作类型/开发引用。已在真实浏览器加载链路验证(`/plugins/ralphflow/client.js` HTTP 200 + VM 实执 factory)。
163
+ 8. **主题 token**:设计稿要求"全部消费 dsh 主题 token(design-platform.css 变量)"。初版误用虚构 token 名(`--dsw-alias-surface-l2`/`text-primary`/`border-default` 等),官方 CSS 无定义,运行时落到硬编码 fallback。已全部替换为官方真实 token(`--dsw-alias-bg-layer-1/3`、`border-l1/l2`、`label-primary/secondary/tertiary`、`state-success/error/warn/business-*` 等,逐一核对 `dsh-client-ui-theme/lib/styles/design-platform.css` 有定义),删除所有硬编码非 token 色值。
164
+ 9. **会话事件订阅 API**:opencode 版监听 `session.idle`/会话事件驱动状态机;dsh 的 `Session` 类**没有** `.on` 方法(真实运行时 `typeof session.on === 'undefined'`),会话事件由 `SessionStore` 经 `ctx.on("session/event", (session, event) => …)` 分发(`emitCtx` 即 store 的 ctx,carrier 的 filter 对无 scope 的 ctx 放行)。job 守护者(`src/jobs.ts`)改用该官方同构写法订阅、按 session id 过滤事件,do→check→advance 由 `assistant/message` 中的 `<promise>done</promise>` 触发(见官方 `dsh-agent-instructions/lib/index.js:1255`)。订阅随 job `run()`(`start()` 内同步调用)注册,cancel 时解除。
165
+
166
+ ## 目录结构
167
+
168
+ ```
169
+ src/
170
+ ├── index.ts # host 入口(apply/inject + HTTP 状态/动作通道)
171
+ ├── engine.ts # 状态机引擎(移植自 opencode 版,去 .opencode 硬编码)
172
+ ├── driver.ts # CHECK 编排 + 事件发射(移植自 driver.ts)
173
+ ├── check.ts # 验证者调度(dsh 子代理)
174
+ ├── check-voting.ts # 多验证者投票(移植)
175
+ ├── voting-progress.ts# 投票进度持久化(移植)
176
+ ├── jobs.ts # jobs 生产者 + 影子 registry
177
+ ├── events.ts # 事件帧发射(tool-ralphflow/*,仅审计落盘)
178
+ ├── tools.ts # 10 个工具(defineTool)
179
+ ├── commands.ts # slash 命令(结果反馈走官方 command/run+done,零自定义帧)
180
+ ├── session-hygiene.ts# 会话卫生:扫描/解砖(备份并移除插件自定义事件帧)
181
+ ├── deps.ts # 共享依赖装配
182
+ ├── done-detect.ts # <promise>done</promise> 检测
183
+ └── client/
184
+ ├── client.ts # client 入口(apply/inject)
185
+ ├── definition.ts # 事件折叠器(kind ralphflow-run 遗留 / ralphflow-command 官方帧)
186
+ ├── RunCard.tsx # 遗留 run 节点渲染(历史折叠产物)
187
+ ├── CommandCard.tsx # 命令结果卡(command/run + command/done)
188
+ └── HeaderAction.tsx # 页头入口:任务列表/通知/审批(POST 直连)/详情
189
+ scripts/
190
+ └── build-client.mjs # client bundle 打包(esbuild → lib/client.js,官方同构格式)
191
+ workflows/ # 内置工作流(loop / spec)
192
+ ```
193
+
194
+ ## 许可
195
+
196
+ MIT
@@ -0,0 +1,37 @@
1
+ /**
2
+ * Ralph Flow for dsh — 抽屉动作分发(POST 动作端点的心智,独立可单测)
3
+ *
4
+ * 页头抽屉的「通过 / 继续 / 打回 / 取消」按钮 → POST /ralphflow/instances →
5
+ * 本模块按白名单动作执行对应工具并(需要时)followup 注入模型。与 index.ts
6
+ * 的 HTTP 壳解耦:纯逻辑可用 e2e 单测覆盖(工具执行/超时/注入/日志四件事)。
7
+ *
8
+ * 语义:
9
+ * - approve:人工门/check_error/archive_failed 恢复——验证由后台 subagent 跑,
10
+ * 模型无需介入,fire 后台推进(不阻塞 HTTP 响应);
11
+ * - resume:暂停恢复——DO 提示需要模型接管,await 后 followup;
12
+ * - return:打回——意见必填,reset 带意见后 followup;
13
+ * - cancel:取消实例(先归档)——快路径,await 返回结果文本。
14
+ */
15
+ import type { Agent } from "@deepseek-ai/dsh-agent";
16
+ import type { Engine } from "./engine.js";
17
+ import type { ToolHandlers } from "./tools.js";
18
+ export interface ActionRequest {
19
+ action: string;
20
+ sessionId?: string;
21
+ runId?: string;
22
+ reason?: string;
23
+ }
24
+ export interface ActionDeps {
25
+ engine: Engine;
26
+ handlers: ToolHandlers;
27
+ getAgent: (sessionId: string) => Agent | undefined;
28
+ deliverToModel: (agent: Agent | undefined, command: string, text: string, warn?: (m: string, e: unknown) => void) => void;
29
+ warn?: (m: string, e: unknown) => void;
30
+ }
31
+ export interface ActionResult {
32
+ ok: boolean;
33
+ text: string;
34
+ /** approve 的后台推进(调用方 void 掉并追加 catch,不阻塞响应) */
35
+ fire?: Promise<string>;
36
+ }
37
+ export declare function dispatchAction(deps: ActionDeps, req: ActionRequest): Promise<ActionResult>;
package/lib/actions.js ADDED
@@ -0,0 +1,55 @@
1
+ export async function dispatchAction(deps, req) {
2
+ const action = String(req?.action ?? "");
3
+ const sessionId = String(req?.sessionId ?? "");
4
+ const runId = typeof req?.runId === "string" && req.runId ? String(req.runId) : undefined;
5
+ const reason = typeof req?.reason === "string" && req.reason.trim()
6
+ ? String(req.reason).trim().slice(0, 4000)
7
+ : undefined;
8
+ const agent = sessionId ? deps.getAgent(sessionId) : undefined;
9
+ if (!agent)
10
+ return { ok: false, text: "会话 agent 不可用(sessionId 无效或会话已结束)。" };
11
+ const run = (name, args) => {
12
+ const h = deps.handlers.get(name);
13
+ if (!h)
14
+ return Promise.resolve(`工具 ${name} 未注册。`);
15
+ return Promise.resolve(h(args, agent));
16
+ };
17
+ const withTimeout = (p, ms) => Promise.race([
18
+ p,
19
+ new Promise((_, rej) => {
20
+ const t = setTimeout(() => rej(new Error("处理超时(可能因实例互斥锁排队),请稍后查看状态。")), ms);
21
+ void t.unref?.();
22
+ }),
23
+ ]);
24
+ switch (action) {
25
+ case "approve": {
26
+ deps.engine.logEvent("", "info", "action_approve", { runId, sessionId });
27
+ const fire = run("ralphflow_continue", runId ? { instance: runId } : {}).catch((e) => {
28
+ deps.engine.logEvent("", "error", "action_approve_failed", { runId, error: e instanceof Error ? e.message : String(e) });
29
+ return "";
30
+ });
31
+ return { ok: true, text: "已提交审批:验证即将在后台运行,进度在页头任务列表实时更新。", fire };
32
+ }
33
+ case "resume": {
34
+ deps.engine.logEvent("", "info", "action_resume", { runId, sessionId });
35
+ const text = await withTimeout(run("ralphflow_continue", runId ? { instance: runId } : {}), 10_000).catch((e) => String(e?.message ?? e));
36
+ deps.deliverToModel(agent, "continue", text, deps.warn);
37
+ return { ok: true, text: "已恢复并让模型继续执行。" };
38
+ }
39
+ case "return": {
40
+ if (!reason)
41
+ return { ok: false, text: "打回需要填写修改意见。" };
42
+ deps.engine.logEvent("", "info", "action_return", { runId, sessionId });
43
+ const text = await withTimeout(run("ralphflow_reset", { ...(runId ? { instance: runId } : {}), reason }), 10_000).catch((e) => String(e?.message ?? e));
44
+ deps.deliverToModel(agent, "reset", text, deps.warn);
45
+ return { ok: true, text: "已打回并让模型按意见返工。" };
46
+ }
47
+ case "cancel": {
48
+ deps.engine.logEvent("", "info", "action_cancel", { runId, sessionId });
49
+ const text = await withTimeout(run("ralphflow_cancel", runId ? { instance: runId } : {}), 10_000).catch((e) => String(e?.message ?? e));
50
+ return { ok: true, text };
51
+ }
52
+ default:
53
+ return { ok: false, text: `未知动作:${action}` };
54
+ }
55
+ }
@@ -0,0 +1,54 @@
1
+ /**
2
+ * Multi-voter CHECK (check_voting) — parallel voting + aggregation + infra retry.
3
+ *
4
+ * Semantics (design §4.3/§4.4/§5.3):
5
+ * - Aggregation priority: cancelled > failed > infra > all-pass.
6
+ * - All must pass. failed beats infra (a known work problem is never masked
7
+ * by infra votes; the infra vote re-runs on the next cross-round anyway).
8
+ * - infra auto-retry: at most 1 retry per pause-session; a vote that is still
9
+ * infra after retry → check_error pause (progress file kept, vote marked
10
+ * infra_failed). User continue resets infra_failed → pending (new pardon).
11
+ * - Progress is persisted per-instance via voting-progress.ts; any single
12
+ * vote completion updates the file. The state machine is only touched by
13
+ * the driver after this function returns.
14
+ */
15
+ import { type CheckDeps } from "./check.js";
16
+ import type { Engine, CheckVotingEntry, NormalStepDef, AdversarialCheckConfig } from "./engine.js";
17
+ import type { Agent } from "@deepseek-ai/dsh-agent";
18
+ import { type VotingProgress, type VoterStatus } from "./voting-progress.js";
19
+ export interface VoterVerdict {
20
+ index: number;
21
+ status: "passed" | "failed" | "infra" | "cancelled";
22
+ reason: string;
23
+ }
24
+ export interface VotingOutcome {
25
+ kind: "passed" | "failed" | "infra_pause" | "cancelled";
26
+ reason: string;
27
+ verdicts: VoterVerdict[];
28
+ /** true when the progress file must be kept (infra_pause). */
29
+ keepProgress: boolean;
30
+ }
31
+ export interface RunVotingCheckOptions {
32
+ /** Entry phase: "do" = fresh round (delete progress), "check" = resume. */
33
+ phase: string;
34
+ workflowName: string;
35
+ /** Current persisted progress (null when none). */
36
+ progress: VotingProgress | null;
37
+ /** Per-vote completion callback — the driver uses it to push live progress
38
+ * to the user (design: 投票进度推送). Fired in completion order. */
39
+ onVoteProgress?: (message: string) => void;
40
+ }
41
+ /**
42
+ * Run the full voting flow for a step: decide which votes to run (fresh vs
43
+ * resume), run them concurrently, auto-retry infra once, aggregate.
44
+ * Never touches the state machine; returns an outcome for the driver.
45
+ */
46
+ export declare function runVotingCheck(deps: CheckDeps, engine: Engine, instId: string, ownerSessionId: string | null, parent: Agent | undefined, step: NormalStepDef, userTask: string | undefined, entries: CheckVotingEntry[], effective: AdversarialCheckConfig | undefined, opts: RunVotingCheckOptions): Promise<VotingOutcome>;
47
+ /** Aggregate failure feedback for DO (design §4.5). */
48
+ export declare function formatVotingFailureReason(verdicts: VoterVerdict[], entries: CheckVotingEntry[]): string;
49
+ /** Aggregate pass feedback (design §4.6). */
50
+ export declare function formatVotingPassReason(verdicts: VoterVerdict[], entries: CheckVotingEntry[]): string;
51
+ /** Infra pause reason for the user (design §9 scenario 3). */
52
+ export declare function formatVotingInfraReason(infraVotes: VoterVerdict[], entries: CheckVotingEntry[]): string;
53
+ /** Status letter for TUI/status summaries. */
54
+ export declare function voterStatusLabel(status: VoterStatus): string;