dsh-project-flow 0.12.0 → 0.13.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/CHANGELOG.md CHANGED
@@ -14,6 +14,87 @@ dsh-project-flow 的版本变更。版本号遵循语义化版本。
14
14
 
15
15
  ---
16
16
 
17
+ ## [0.13.0] - 2026-12-05
18
+
19
+ ### 换宿主不需要重写流水,只需要换一处
20
+
21
+ 一直以为跨宿主是「把核心拆出来、写一堆适配器」的大工程。动手查了一遍才发现不是:
22
+
23
+ ```js
24
+ // pipeline.mjs 里 ctx 的全部用法
25
+ export function createPipeline(ctx) { … }
26
+ const collected = await runStage(ctx, stageOptions({ … }))
27
+ const planned = await runStage(ctx, stageOptions({ … }))
28
+ const built = await runStage(ctx, stageOptions({ … }))
29
+ const extra = await runStage(ctx, stageOptions({ … }))
30
+ const checked = await runStage(ctx, stageOptions({ … }))
31
+ ```
32
+
33
+ **ctx 只是路过的。** 真正用它的是 `runStage` 里那一句 `subagentsOf(ctx).startActivation(…)`。
34
+
35
+ 所以只要造一个假 ctx,实现 `startActivation` 的返回契约,整条四阶流水一行都不用改——快照、补丁台账、判据、问题闭环、返工、证据包全都白拿。
36
+
37
+ 分叉出第二套流水是这里最该避免的事:两边各有各的 bug,修一边漏一边,三个月后没人说得清哪个才是真的。
38
+
39
+ ### Codex 能拿来当子会话
40
+
41
+ `codex exec --json` 的输出比 DSH 的外部后端强一截:
42
+
43
+ ```
44
+ {"type":"item.started","item":{"id":"item_2","type":"command_execution",…,"status":"in_progress"}}
45
+ {"type":"item.completed","item":{"id":"item_2","type":"command_execution",…,"exit_code":0}}
46
+ {"type":"item.completed","item":{"id":"item_3","type":"agent_message","text":"…"}}
47
+ {"type":"turn.completed","usage":{"input_tokens":24504,…}}
48
+ ```
49
+
50
+ `item.started` 和 `item.completed` 成对出现、带 id,工具边界是**明确的观测**,不是猜。DSH 的外部后端连 agent 对象都没有,只能靠工作区文件 mtime 兜底——这一条正好补上那个洞。
51
+
52
+ 新增 `host/codex.mjs`:`createCodexCtx()` 把 `codex exec` 包成假 ctx。要点三个:
53
+
54
+ - **prompt 走 stdin**(`-`)。中文、换行、引号全不用转义,命令行长度也不用管。
55
+ - **output 必须是内容块数组** `[{type:'text',text}]`。`shared/util` 的 `textOf` 只认这个形状,给字符串会静默返回空串,**而且不报错**——这是个安静的错误。
56
+ - **abort 走的是 `error` 事件不是 `close`**(消息是 "The operation was aborted")。不单独认一次的话,用户按了停止却看到「codex 进程出错」。收尾还要等一小会儿再补一刀 `SIGKILL`:留在后台的 codex 会继续烧钱。
57
+
58
+ ### CLI 入口
59
+
60
+ 新增 `bin/flow.mjs`,在 DSH 之外跑同一套流水:
61
+
62
+ ```sh
63
+ flow run --spec task.json --cwd ./某项目 --mode quick
64
+ ```
65
+
66
+ `task.json` 里放 `intent` / `requirements` / `checks`,跟 `project_run` 的入参一样。
67
+
68
+ 两件小事但是真会挡路:
69
+
70
+ - **把 node 目录顶到 PATH 最前面**。判据里写 `node -e "…"` 是常态,但很多机器 PATH 上没有 node(本机就是,node 是 DSH 自带的)。
71
+ - **任务书读进来先剥 BOM**。记事本、PowerShell 的 `Set-Content -Encoding UTF8` 都会加 BOM,而 `JSON.parse` 见到它直接报「Unexpected token」,用户看到的是「我的 JSON 明明是对的」。
72
+
73
+ 另外 `runPipeline` 的入参给几个字段补了默认值(`requirements = []`、`healed = []`)。这些在 DSH 那边一定有,CLI 不经过那一层,少传一个就炸在 `healed.length` 上——外部入口不该被默认值问题挡住。
74
+
75
+ ### 真机验证
76
+
77
+ 在 `D:\flow-codex-test` 上跑了一个「创建 hello.txt 写 ok」的任务:
78
+
79
+ ```
80
+ 起子会话:hello-demo 规划(prompt 701 字)
81
+ 起子会话:hello-demo 实施(prompt 959 字)
82
+ 起子会话:hello-demo 质检(prompt 2537 字)
83
+
84
+ 结论:PASS(停在第 4 阶)
85
+ 完成证据包:…/Completion_Evidence.json
86
+ ```
87
+
88
+ 三个 codex 子会话、四阶走完、证据包生成、退出码 0。pipeline 一行没改。
89
+
90
+ ### 测试
91
+
92
+ 新增 `tests/codex-adapter.test.mjs`(8 条),配 `tests/fixtures/fake-codex.mjs` 假 codex,不花钱不联网:正常一轮拿文本和 usage、命令执行的前后报成工具开始/结束、没跑到 `turn.completed` 判失败、退出码非零带出 stderr、取消能收掉子进程、空 prompt 不起会话、`findCodexBinary` 找不到给空串、缺 bin 当场报错。
93
+
94
+ 全套 38 套变 39 套。
95
+
96
+ ---
97
+
17
98
  ## [0.12.0] - 2026-12-05
18
99
 
19
100
  ### 一件小事也走完整四阶,用户会觉得不如直接跟 agent 说话
package/README.md CHANGED
@@ -50,6 +50,32 @@ dsh plugin --profile <你的 profile> add dsh-project-flow
50
50
 
51
51
  需要 Node 20+、DSH 0.2.0+。装完重启 dsh。本机开发用 `file:` 装的要注意:pnpm 落地时是**复制**不是软链,改完源码得同步到 `node_modules` 副本再重载插件。
52
52
 
53
+ ## 在 DSH 之外跑(Codex)
54
+
55
+ 四阶、快照、台账、判据、证据包跟「跑在哪个宿主上」没关系,绑定的是**怎么起一个子会话**这一件事。这件事现在可以换成 `codex exec`:
56
+
57
+ ```sh
58
+ flow run --spec task.json --cwd ./某项目
59
+ ```
60
+
61
+ `task.json`:
62
+
63
+ ```json
64
+ {
65
+ "intent": "把日志级别从 info 改成 debug",
66
+ "requirements": ["config.json 里的 log.level 是 debug"],
67
+ "checks": [{ "req": 1, "check": "node -e \"…\"", "checkExit": 0 }]
68
+ }
69
+ ```
70
+
71
+ 常用参数:`--model`(留空用 codex 自己的配置)、`--sandbox read-only|workspace-write|danger-full-access`(默认 workspace-write)、`--mode safe|quick`、`--max-rework`。
72
+
73
+ `--dry-run` 只检查环境,不起子会话、不花钱。
74
+
75
+ 退出码:0 = 验收通过,1 = 没过或出错,2 = 用法错误。
76
+
77
+ codex 自己会报真实 token 用量,跟插件的字符估算一起打印出来——两个数分开看,估算值不是账单。
78
+
53
79
  ## 用法
54
80
 
55
81
  ### 工具
package/bin/flow.mjs ADDED
@@ -0,0 +1,266 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * flow —— 在 DSH 之外跑同一套四阶流水。
4
+ *
5
+ * 用法
6
+ * ────
7
+ * node bin/flow.mjs run --spec task.json [--cwd <目录>] [--project <名字>]
8
+ * [--model <模型>] [--sandbox read-only|workspace-write|danger-full-access]
9
+ * [--mode safe|quick] [--max-rework 2] [--dry-run]
10
+ *
11
+ * task.json 长这样:
12
+ *
13
+ * {
14
+ * "intent": "把日志级别从 info 改成 debug",
15
+ * "requirements": ["config.json 里的 log.level 是 debug"],
16
+ * "checks": [{ "req": 1, "check": "node -e \"…\"", "checkExit": 0 }]
17
+ * }
18
+ *
19
+ * 为什么要有这个东西
20
+ * ──────────────
21
+ * 四阶、快照、台账、判据、证据包这些跟「跑在哪个宿主上」没关系,绑定的是
22
+ * 「怎么起一个子会话」这一件事。把那一件事换成 `codex exec`,其余的全都白拿。
23
+ *
24
+ * 这条入口存在的意义是证明那件事真的成立——而不是为了再维护一套产品。
25
+ */
26
+
27
+ import { readFileSync, existsSync } from 'node:fs'
28
+ import { basename, dirname, join, resolve } from 'node:path'
29
+ import { delimiter } from 'node:path'
30
+ import { configure, settingsOf } from '../config/settings.mjs'
31
+ import { createPipeline } from '../runner/pipeline.mjs'
32
+ import { createCodexCtx, findCodexBinary } from '../host/codex.mjs'
33
+ import { Watchdog } from '../watchdog.mjs'
34
+ import { stateDir, stripBom } from '../shared/util.mjs'
35
+
36
+ function usage(code = 0) {
37
+ const text = `flow —— 在 DSH 之外跑同一套四阶流水
38
+
39
+ node bin/flow.mjs run --spec <task.json> [选项]
40
+
41
+ 选项
42
+ --spec <文件> 任务书 JSON(必填)。字段:intent / requirements / checks
43
+ 可选:constraints / forbidden / mode
44
+ --cwd <目录> 工作目录,默认当前目录
45
+ --project <名字> 项目名,默认取工作目录名
46
+ --model <模型> 传给 codex 的模型,留空用 codex 自己的配置
47
+ --sandbox <模式> read-only / workspace-write / danger-full-access
48
+ 默认 workspace-write(能写工作区,碰不到外面)
49
+ --mode <模式> safe(默认,四阶)或 quick(跳过规划和质检子会话)
50
+ --max-rework <n> 最多返工几次,默认 2
51
+ --dry-run 只检查环境,不起子会话、不花钱
52
+ -h, --help 看这个
53
+
54
+ 退出码:0 = 验收通过,1 = 没过或出错,2 = 用法错误
55
+ `
56
+ process.stdout.write(text)
57
+ process.exit(code)
58
+ }
59
+
60
+ function parseArgs(argv) {
61
+ const out = { _: [] }
62
+ for (let i = 0; i < argv.length; i += 1) {
63
+ const token = argv[i]
64
+ if (!token.startsWith('--')) {
65
+ out._.push(token)
66
+ continue
67
+ }
68
+ const key = token.slice(2)
69
+ if (key === 'dry-run' || key === 'help') {
70
+ out[key] = true
71
+ continue
72
+ }
73
+ const value = argv[i + 1]
74
+ if (value === undefined || value.startsWith('--')) {
75
+ throw new Error(`--${key} 后面缺一个值`)
76
+ }
77
+ out[key] = value
78
+ i += 1
79
+ }
80
+ return out
81
+ }
82
+
83
+ function readSpec(path) {
84
+ // 带 BOM 的 UTF-8 在这里一定会踩:Windows 记事本、PowerShell 的
85
+ // Set-Content -Encoding UTF8 都会加 BOM,而 JSON.parse 见到它直接报
86
+ // 「Unexpected token」。用户看到的是「我的 JSON 明明是对的」。
87
+ const raw = stripBom(readFileSync(path, 'utf8'))
88
+ let spec
89
+ try {
90
+ spec = JSON.parse(raw)
91
+ } catch (error) {
92
+ throw new Error(`任务书不是合法 JSON:${error.message}`)
93
+ }
94
+ if (typeof spec?.intent !== 'string' || spec.intent.trim() === '') {
95
+ throw new Error('任务书缺 intent')
96
+ }
97
+ const requirements = Array.isArray(spec.requirements)
98
+ ? spec.requirements.filter(line => typeof line === 'string' && line.trim() !== '')
99
+ : []
100
+ if (requirements.length === 0) {
101
+ throw new Error('任务书里 requirements 是空的:一条要求都没有,验收无从谈起')
102
+ }
103
+ return {
104
+ intent: spec.intent.trim(),
105
+ requirements,
106
+ checks: Array.isArray(spec.checks) ? spec.checks : [],
107
+ constraints: typeof spec.constraints === 'string' ? spec.constraints : '',
108
+ forbidden: Array.isArray(spec.forbidden) ? spec.forbidden : [],
109
+ mode: spec.deliveryMode ?? spec.mode,
110
+ }
111
+ }
112
+
113
+ /** 把 pipeline 返回的东西压成给人看的一段。 */
114
+ function report(result) {
115
+ const lines = []
116
+ const badge = result.outcome === 'passed' ? 'PASS' : String(result.outcome ?? '?').toUpperCase()
117
+ lines.push('')
118
+ lines.push(`结论:${badge}(停在第 ${result.stage ?? '?'} 阶)`)
119
+ if (typeof result.verdict === 'string' && result.verdict !== '') lines.push(`判词:${result.verdict}`)
120
+ // 这些是质检给出的观察,不是「没闭环的问题」——只有返工那轮才算闭环与否。
121
+ // 一次就过的时候把它们叫成「没闭环」,读起来像这活还有毛病没修。
122
+ if (Array.isArray(result.issues) && result.issues.length > 0) {
123
+ lines.push(result.outcome === 'passed' ? '质检记下的几点:' : '还没解决的几条:')
124
+ for (const issue of result.issues.slice(0, 10)) lines.push(` - ${issue}`)
125
+ }
126
+ if (typeof result.note === 'string' && result.note.trim() !== '') {
127
+ lines.push('')
128
+ lines.push(result.note.trim())
129
+ }
130
+ return lines.join('\n')
131
+ }
132
+
133
+ async function main() {
134
+ const args = parseArgs(process.argv.slice(2))
135
+ if (args.help === true || args._[0] === 'help') usage(0)
136
+ if (args._[0] !== 'run') {
137
+ process.stderr.write(`不认识的子命令:${args._[0] ?? '(空)'}\n`)
138
+ usage(2)
139
+ }
140
+ if (typeof args.spec !== 'string') {
141
+ process.stderr.write('缺 --spec <task.json>\n')
142
+ usage(2)
143
+ }
144
+
145
+ const cwd = resolve(typeof args.cwd === 'string' ? args.cwd : process.cwd())
146
+ if (!existsSync(cwd)) {
147
+ process.stderr.write(`工作目录不存在:${cwd}\n`)
148
+ process.exit(2)
149
+ }
150
+ const project = typeof args.project === 'string' && args.project !== ''
151
+ ? args.project
152
+ : basename(cwd)
153
+
154
+ const spec = readSpec(resolve(args.spec))
155
+ const bin = findCodexBinary()
156
+ if (bin === '') {
157
+ process.stderr.write(
158
+ '找不到 codex 可执行文件。\n'
159
+ + '查过这两个位置:环境变量 CODEX_CLI_PATH、%USERPROFILE%\\AppData\\Local\\OpenAI\\Codex\\bin\\<build>\\codex.exe\n'
160
+ + '装了 Codex 桌面版的话,CLI 二进制一般就在上面那个目录里。\n',
161
+ )
162
+ process.exit(2)
163
+ }
164
+
165
+ // 判据命令里写 `node -e "…"` 是常态,但很多人的 PATH 里根本没有 node
166
+ // (本机就是这样:node 是 DSH 自带的,装在哪都不在 PATH 上)。
167
+ // 把自己所在目录顶到最前面,让那些 check 跑得起来。
168
+ const nodeDir = dirname(process.execPath)
169
+ const parts = (process.env.PATH ?? '').split(delimiter)
170
+ if (!parts.includes(nodeDir)) {
171
+ process.env.PATH = `${nodeDir}${delimiter}${process.env.PATH ?? ''}`
172
+ }
173
+
174
+ process.stdout.write(`宿主:codex(${bin})\n`)
175
+ process.stdout.write(`工作目录:${cwd}\n项目:${project}\n`)
176
+ process.stdout.write(`模型:${args.model ?? '(用 codex 自己的配置)'}\n`)
177
+ process.stdout.write(`沙箱:${args.sandbox ?? 'workspace-write'}\n`)
178
+ process.stdout.write(`模式:${args.mode ?? spec.mode ?? 'safe'}\n`)
179
+ process.stdout.write(`要求 ${spec.requirements.length} 条,判据 ${spec.checks.length} 条\n`)
180
+
181
+ if (args['dry-run'] === true) {
182
+ process.stdout.write('\n环境没问题(--dry-run:没起子会话,没花钱)\n')
183
+ return
184
+ }
185
+
186
+ // 读配置时别去碰 DSH 家的那一份:CLI 有自己的工作区,
187
+ // 用户为 DSH 配的 flowRoot、模型路由在这里全无意义。
188
+ process.env.DSH_HOME = join(cwd, '.flow-home')
189
+ configure({
190
+ deliveryMode: args.mode ?? spec.mode ?? 'safe',
191
+ maxRework: args['max-rework'] !== undefined ? Number(args['max-rework']) : 2,
192
+ watchdogEnabled: true,
193
+ // quick 模式下把窗口放得比默认更松一点:codex 的流本来就密,
194
+ // 会触发的多半是真卡住,不是渲染慢。
195
+ snapshotEnabled: true,
196
+ })
197
+ const settings = settingsOf()
198
+
199
+ const watchdog = new Watchdog({
200
+ cwd,
201
+ logPath: join(stateDir(cwd, project), 'Execution_Log.md'),
202
+ settings,
203
+ onTrip: fault => {
204
+ process.stderr.write(`\n守护器熔断:${fault.detail}\n`)
205
+ },
206
+ })
207
+
208
+ const ctx = createCodexCtx({
209
+ bin,
210
+ cwd,
211
+ model: typeof args.model === 'string' ? args.model : '',
212
+ sandbox: typeof args.sandbox === 'string' ? args.sandbox : 'workspace-write',
213
+ watchdog,
214
+ onRun: info => {
215
+ process.stdout.write(` 起子会话:${info.label}(prompt ${info.promptChars} 字)\n`)
216
+ },
217
+ })
218
+
219
+ // Ctrl+C 要能把子进程一起带走,不然 codex 会挂在后台继续烧钱
220
+ const interrupt = new AbortController()
221
+ process.on('SIGINT', () => {
222
+ process.stderr.write('\n收到中断,正在收尾…\n')
223
+ interrupt.abort()
224
+ })
225
+
226
+ const pipeline = createPipeline(ctx)
227
+ let result
228
+ try {
229
+ result = await pipeline.runPipeline({
230
+ cwd,
231
+ project,
232
+ intent: spec.intent,
233
+ requirements: spec.requirements,
234
+ checks: spec.checks,
235
+ constraints: spec.constraints,
236
+ forbidden: spec.forbidden,
237
+ settings,
238
+ watchdog,
239
+ signal: interrupt.signal,
240
+ mode: 'run',
241
+ })
242
+ } finally {
243
+ watchdog.dispose()
244
+ }
245
+
246
+ process.stdout.write(report(result))
247
+
248
+ // 两个花费数分开摆:插件的预算是按字符估的(它拿不到 token 数),
249
+ // codex 自己报的是真账。把估算值单独标出来,别让人以为那就是账单。
250
+ const usage = ctx.usage()
251
+ if (usage.turns > 0) {
252
+ process.stdout.write(
253
+ `\ncodex 实报用量:${usage.turns} 轮,输入 ${usage.input}(缓存命中 ${usage.cached})/ 输出 ${usage.output} token\n`,
254
+ )
255
+ }
256
+ if (result?.cost?.spentCny !== undefined) {
257
+ process.stdout.write(`插件估算花费:¥${result.cost.spentCny}(按字符估,仅供参考)\n`)
258
+ }
259
+ process.stdout.write(`\n产物:${stateDir(cwd, project)}\n`)
260
+ process.exit(result?.outcome === 'passed' ? 0 : 1)
261
+ }
262
+
263
+ main().catch(error => {
264
+ process.stderr.write(`\n出错了:${error?.stack ?? error}\n`)
265
+ process.exit(1)
266
+ })
package/host/codex.mjs ADDED
@@ -0,0 +1,338 @@
1
+ /**
2
+ * Codex 宿主适配器:把 `codex exec` 包成一个假的 DSH ctx。
3
+ *
4
+ * 为什么是「假 ctx」而不是重写一条流水
5
+ * ──────────────────────────────────
6
+ * `runner/pipeline.mjs` 对 ctx 的依赖只有一处:把 ctx 原样递给 runStage。
7
+ * 真正用 ctx 的只有 runStage 里的 `subagentsOf(ctx).startActivation(...)`。
8
+ * 所以只要这个假 ctx 实现了 startActivation 的返回契约,**整条四阶流水
9
+ * 一行都不用改**——快照、补丁台账、判据、问题闭环、返工、证据包全都白拿。
10
+ *
11
+ * 分叉出第二套流水是这里最该避免的事:两边各有各的 bug,修一边漏一边,
12
+ * 三个月后没人说得清哪个才是真的。
13
+ *
14
+ * 返回契约(runStage 的 settle 要的)
15
+ * ──────────────────────────────────
16
+ * { kind: 'external', result: Promise<{ stopReason, output, diagnostic }>, dispose() }
17
+ *
18
+ * `output` 必须是内容块数组 `[{ type: 'text', text }]`——shared/util 的 textOf
19
+ * 只认这个形状,给字符串会得到空串,而且不报错。这是个安静的错误,容易踩。
20
+ *
21
+ * 事件流
22
+ * ──────
23
+ * `codex exec --json` 每行一个 JSON:
24
+ *
25
+ * {"type":"thread.started","thread_id":"…"}
26
+ * {"type":"turn.started"}
27
+ * {"type":"item.started","item":{"id":"item_2","type":"command_execution",…,"status":"in_progress"}}
28
+ * {"type":"item.completed","item":{"id":"item_2","type":"command_execution",…,"exit_code":0}}
29
+ * {"type":"item.completed","item":{"id":"item_3","type":"agent_message","text":"…"}}
30
+ * {"type":"turn.completed","usage":{…}}
31
+ *
32
+ * 这一条比 DSH 那边强:`item.started` 和 `item.completed` 成对出现、带 id,
33
+ * 工具边界是明确的观测,不是猜。DSH 外部后端拿不到任何活跃信号(连 agent
34
+ * 对象都没有),只能靠文件 mtime 兜底。
35
+ *
36
+ * @module host/codex
37
+ */
38
+
39
+ import { spawn } from 'node:child_process'
40
+ import { existsSync, readdirSync } from 'node:fs'
41
+ import { join } from 'node:path'
42
+ import { createInterface } from 'node:readline'
43
+
44
+ /** 缺省沙箱:能写工作区,但碰不到外面。 */
45
+ const DEFAULT_SANDBOX = 'workspace-write'
46
+
47
+ /**
48
+ * 把内容块数组压成一段文本。
49
+ *
50
+ * runStage 传进来的 prompt 是 `[{type:'text',text},{type:'image',…}]` 这种形状。
51
+ * 图片块先跳过——codex 支持 `-i`,但需要真实文件路径,而 DSH 的图片块里
52
+ * 是 base64。要接的话得先落盘,那是下一步的事,不在这里假装支持。
53
+ */
54
+ function promptTextOf(content) {
55
+ if (typeof content === 'string') return content
56
+ if (!Array.isArray(content)) return ''
57
+ return content
58
+ .filter(block => block !== null && typeof block === 'object' && block.type === 'text')
59
+ .map(block => (typeof block.text === 'string' ? block.text : ''))
60
+ .join('\n\n')
61
+ }
62
+
63
+ /** 把一条命令压成一行,给熔断日志用。 */
64
+ function briefCommand(command) {
65
+ const text = typeof command === 'string' ? command.replace(/\s+/gu, ' ').trim() : ''
66
+ return text.length > 80 ? `${text.slice(0, 80)}…` : text
67
+ }
68
+
69
+ /**
70
+ * 造一个假 ctx。pipeline 只认 `subagents.startActivation` 这一个方法。
71
+ *
72
+ * @param bin codex 可执行文件绝对路径
73
+ * @param cwd 默认工作目录(spec.cwd 优先)
74
+ * @param model 留空表示用 codex 自己 config.toml 里的模型
75
+ * @param sandbox read-only / workspace-write / danger-full-access
76
+ * @param watchdog 守护器。事件直接喂给它——它天然对应「当前在跑的那一阶」,
77
+ * 不需要再做一次路由。
78
+ * @param onRun 可选:每次起子进程时回调,用来打印进度
79
+ */
80
+ export function createCodexCtx(options = {}) {
81
+ const {
82
+ bin,
83
+ // 放在 bin 前面的一串参数。正常用不到;测试时把 bin 指成 node、
84
+ // 这里放一个假 codex 脚本,就能把整条解析链跑一遍而不碰真模型。
85
+ binArgs = [],
86
+ cwd = process.cwd(),
87
+ model = '',
88
+ sandbox = DEFAULT_SANDBOX,
89
+ extraArgs = [],
90
+ watchdog,
91
+ onRun,
92
+ } = options
93
+
94
+ if (typeof bin !== 'string' || bin === '') {
95
+ throw new Error('createCodexCtx 需要一个 codex 可执行文件路径')
96
+ }
97
+
98
+ // 累计真实 usage。插件的预算器是按字符估的(它拿不到 token 数),
99
+ // 而 codex 每个 turn 结束都会报真账。两个数放一起给人看,别让人以为
100
+ // 估算值就是账单。
101
+ const totalUsage = { input: 0, output: 0, cached: 0, turns: 0 }
102
+
103
+ return {
104
+ /** 宿主名字,给日志和证据包用。 */
105
+ host: { name: 'codex', model, sandbox },
106
+
107
+ /** 截至目前的真实 token 用量(来自 codex 的 turn.completed)。 */
108
+ usage() {
109
+ return { ...totalUsage }
110
+ },
111
+
112
+ subagents: {
113
+ /**
114
+ * 起一次 codex exec,返回 runStage 要的 activation。
115
+ *
116
+ * spec 里 runStage 会塞:provider / label / prompt / parent / signal /
117
+ * delivery / cwd / agentOptions。这里只用 prompt、cwd、signal 三样,
118
+ * 其余是 DSH 的东西,对 codex 没意义。
119
+ */
120
+ async startActivation(spec = {}) {
121
+ const workdir = typeof spec.cwd === 'string' && spec.cwd !== '' ? spec.cwd : cwd
122
+ const prompt = promptTextOf(spec.prompt)
123
+ if (prompt === '') {
124
+ return failedActivation('这一阶的 prompt 是空的:没有内容投给 codex,不能起空会话')
125
+ }
126
+
127
+ const label = typeof spec.label === 'string' ? spec.label : 'codex'
128
+ const args = [...binArgs, 'exec', '--json', '--skip-git-repo-check', '-C', workdir]
129
+ if (typeof model === 'string' && model !== '') args.push('-m', model)
130
+ if (typeof sandbox === 'string' && sandbox !== '') args.push('-s', sandbox)
131
+ args.push(...extraArgs)
132
+ // 用 `-` 让 codex 从 stdin 读 prompt:中文、换行、引号全不用转义。
133
+ args.push('-')
134
+
135
+ onRun?.({ label, workdir, promptChars: prompt.length })
136
+
137
+ const controller = new AbortController()
138
+ const forwardAbort = () => {
139
+ try { controller.abort() } catch { /* 已经 abort 过 */ }
140
+ }
141
+ if (spec.signal?.aborted === true) forwardAbort()
142
+ else spec.signal?.addEventListener('abort', forwardAbort, { once: true })
143
+
144
+ let child
145
+ try {
146
+ child = spawn(bin, args, {
147
+ cwd: workdir,
148
+ stdio: ['pipe', 'pipe', 'pipe'],
149
+ signal: controller.signal,
150
+ windowsHide: true,
151
+ })
152
+ } catch (error) {
153
+ return failedActivation(`codex 起不来:${error?.message ?? error}`)
154
+ }
155
+
156
+ // prompt 走 stdin。写失败(进程已经死了)不该抛到外面——下面的 close
157
+ // 事件会带着退出码回来,那才是结论。
158
+ try {
159
+ child.stdin.on('error', () => {})
160
+ child.stdin.end(prompt, 'utf8')
161
+ } catch { /* 见上 */ }
162
+
163
+ const openTools = new Set()
164
+ let lastMessage = ''
165
+ let stderrTail = ''
166
+ let usage = undefined
167
+ let sawTurnCompleted = false
168
+ let killedBySignal = false
169
+
170
+ child.stderr?.on('data', chunk => {
171
+ stderrTail = (stderrTail + chunk.toString('utf8')).slice(-4000)
172
+ })
173
+
174
+ const rl = createInterface({ input: child.stdout })
175
+ rl.on('line', line => {
176
+ const text = line.trim()
177
+ if (text === '') return
178
+ let event
179
+ try {
180
+ event = JSON.parse(text)
181
+ } catch {
182
+ // 不是 JSON 的行(进度条、彩色的杂音)直接忽略,但要顶一下心跳:
183
+ // 能吐字节就说明它还活着。
184
+ watchdog?.touch()
185
+ return
186
+ }
187
+ const type = typeof event?.type === 'string' ? event.type : ''
188
+ const item = event?.item
189
+
190
+ // 每一个事件都是活着的证据。codex 的流是有节奏的,比 DSH 外部后端
191
+ // 那种「一句话不说九分钟」强太多。
192
+ watchdog?.touch()
193
+
194
+ if (type === 'item.started' && item?.type === 'command_execution') {
195
+ openTools.add(item.id)
196
+ watchdog?.toolStart(briefCommand(item.command) || 'command_execution')
197
+ return
198
+ }
199
+ if (type === 'item.completed' && item?.type === 'command_execution') {
200
+ if (openTools.delete(item.id)) watchdog?.toolEnd()
201
+ return
202
+ }
203
+ if (type === 'item.completed' && item?.type === 'agent_message') {
204
+ if (typeof item.text === 'string' && item.text !== '') lastMessage = item.text
205
+ return
206
+ }
207
+ if (type === 'turn.completed') {
208
+ sawTurnCompleted = true
209
+ if (event.usage !== undefined) {
210
+ usage = event.usage
211
+ totalUsage.turns += 1
212
+ totalUsage.input += Number(event.usage.input_tokens ?? 0) || 0
213
+ totalUsage.output += Number(event.usage.output_tokens ?? 0) || 0
214
+ totalUsage.cached += Number(event.usage.cached_input_tokens ?? 0) || 0
215
+ }
216
+ return
217
+ }
218
+ if (type === 'error' && typeof event.message === 'string') {
219
+ // 重连提示不是失败:codex 会自己退到 HTTPS 再试。只留最后一条做诊断。
220
+ stderrTail = `${stderrTail}\n${event.message}`.slice(-4000)
221
+ }
222
+ })
223
+
224
+ const result = new Promise(resolve => {
225
+ const finish = (stopReason, diagnostic) => {
226
+ // 收尾时把没配对的工具全作废:被 kill 的命令不会再有 completed。
227
+ for (const _ of openTools) watchdog?.toolEnd()
228
+ openTools.clear()
229
+ try { rl.close() } catch { /* 已经关了 */ }
230
+ resolve({
231
+ stopReason,
232
+ diagnostic,
233
+ usage,
234
+ // textOf 只认块数组,给字符串会静默变空串
235
+ output: lastMessage === '' ? [] : [{ type: 'text', text: lastMessage }],
236
+ })
237
+ }
238
+
239
+ child.on('error', error => {
240
+ killedBySignal = true
241
+ // spawn 带 signal 时,abort 会走 error 而不是 close(消息是
242
+ // "The operation was aborted")。不在这儿认一次的话,用户按了
243
+ // 停止却看到「codex 进程出错」,会以为插件坏了。
244
+ if (spec.signal?.aborted === true) {
245
+ finish('error', `${label}:已取消`)
246
+ return
247
+ }
248
+ finish('error', `${label}:codex 进程出错(${error?.message ?? error})`)
249
+ })
250
+
251
+ child.on('close', (code, signal) => {
252
+ const aborted = spec.signal?.aborted === true
253
+ if (aborted || killedBySignal) {
254
+ finish('error', `${label}:已取消`)
255
+ return
256
+ }
257
+ if (code === 0 && sawTurnCompleted) {
258
+ finish('completed', undefined)
259
+ return
260
+ }
261
+ const tail = stderrTail.trim().split(/\r?\n/u).slice(-6).join(' / ')
262
+ finish(
263
+ 'error',
264
+ `${label}:codex 退出码 ${code ?? signal ?? '?'}`
265
+ + (sawTurnCompleted ? '' : ',没跑到 turn.completed')
266
+ + (tail === '' ? '' : `|${tail.slice(0, 400)}`),
267
+ )
268
+ })
269
+ })
270
+
271
+ return {
272
+ // external:不要给 handle.agent。runStage 看到 external 就不去挂事件监听,
273
+ // 那边的监听本来就是给 DSH 本地子会话准备的,这里没有。
274
+ kind: 'external',
275
+ result,
276
+ dispose: async () => {
277
+ spec.signal?.removeEventListener?.('abort', forwardAbort)
278
+ const alive = () => child.exitCode === null && child.signalCode === null
279
+ if (!alive()) return
280
+ try { child.kill() } catch { /* 已经退了 */ }
281
+ // Windows 上 SIGTERM 不一定立刻生效,尤其对方是个不肯退的 node 进程。
282
+ // 等一小会儿还没死就硬杀——留在后台的 codex 会继续烧钱,那不是小事。
283
+ await new Promise(resolve => setTimeout(resolve, 150))
284
+ if (!alive()) return
285
+ try { child.kill('SIGKILL') } catch { /* 系统不支持就直接算了 */ }
286
+ },
287
+ }
288
+ },
289
+ },
290
+ }
291
+ }
292
+
293
+ /** 一起手就失败(比如 prompt 空)时用的占位 activation。 */
294
+ function failedActivation(message) {
295
+ return {
296
+ kind: 'external',
297
+ result: Promise.resolve({ stopReason: 'error', diagnostic: message, output: [] }),
298
+ dispose: async () => {},
299
+ }
300
+ }
301
+
302
+ /**
303
+ * 找本机的 codex 可执行文件。
304
+ *
305
+ * 顺序是有讲究的:
306
+ *
307
+ * 1. `CODEX_CLI_PATH` —— 用户或桌面应用明确指的那个,不猜
308
+ * 2. `AppData\Local\OpenAI\Codex\bin\<build>\codex.exe` —— 真正的 CLI 二进制。
309
+ * `<build>` 是版本号目录(比如 45e749ac65b97f3a),升级就会换一个,
310
+ * 所以得扫目录、取最新那个,不能写死。
311
+ *
312
+ * 不去碰 `Program Files\WindowsApps\...`:那是桌面应用自带的副本,路径带版本号
313
+ * 还有 ACL 限制,拿来当 CLI 用是会踩坑的。
314
+ *
315
+ * @returns 找到的绝对路径;找不到返回空串,由调用方决定怎么报
316
+ */
317
+ export function findCodexBinary(env = process.env) {
318
+ const home = env.USERPROFILE ?? env.HOME ?? ''
319
+
320
+ if (typeof env.CODEX_CLI_PATH === 'string' && env.CODEX_CLI_PATH !== '') {
321
+ try {
322
+ if (existsSync(env.CODEX_CLI_PATH)) return env.CODEX_CLI_PATH
323
+ } catch { /* 路径里有权限问题就当没配 */ }
324
+ }
325
+
326
+ if (home === '') return ''
327
+ const base = join(home, 'AppData', 'Local', 'OpenAI', 'Codex', 'bin')
328
+ try {
329
+ if (!existsSync(base)) return ''
330
+ const found = readdirSync(base)
331
+ .map(name => join(base, name, 'codex.exe'))
332
+ .filter(candidate => existsSync(candidate))
333
+ if (found.length > 0) return found[found.length - 1]
334
+ } catch {
335
+ // 目录读不动就当没装
336
+ }
337
+ return ''
338
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-project-flow",
3
- "version": "0.12.0",
3
+ "version": "0.13.0",
4
4
  "private": false,
5
5
  "description": "Delivery control for AI coding agents: every requirement gets a runnable check whose exit code decides the verdict, every write goes into a patch ledger so rollback can restore exactly that file, every round leaves a snapshot diff and a machine-readable completion evidence pack, and spend is capped before each call. Two paces: quick (one subagent) for small edits, safe (four gated stages) for long jobs.",
6
6
  "type": "module",
@@ -83,7 +83,10 @@
83
83
  "assets/*.png",
84
84
  "README.md",
85
85
  "CHANGELOG.md",
86
- "LICENSE"
86
+ "LICENSE",
87
+ "bin/",
88
+ "host/",
89
+ "tests/fixtures/"
87
90
  ],
88
91
  "dsh": {
89
92
  "bundle": {
@@ -105,6 +108,9 @@
105
108
  "optional": true
106
109
  }
107
110
  },
111
+ "bin": {
112
+ "flow": "./bin/flow.mjs"
113
+ },
108
114
  "scripts": {
109
115
  "bench": "node bench/run.mjs",
110
116
  "test": "node tests/run-all.mjs"
@@ -30,7 +30,14 @@ import { hitsForbidden, stageModelOf } from '../workspace/paths.mjs'
30
30
  export function createPipeline(ctx) {
31
31
 
32
32
  const runPipeline = async options => {
33
- const { cwd, project, intent, requirements, checks, constraints, confirmation, maxRework, parent, signal, seed, settings, healed, mode, watchdog } = options
33
+ // 这些字段本来由 DSH 那边的调用方给。CLI 入口(bin/flow.mjs)不经过那一层,
34
+ // 少传一个就炸在 `healed.length` 上——外部入口不该被这种默认值问题挡住,
35
+ // 所以能给默认值的都给上。
36
+ const {
37
+ cwd, project, intent, requirements = [], checks = [], constraints,
38
+ confirmation, maxRework, parent, signal, seed, settings,
39
+ healed = [], mode, watchdog,
40
+ } = options
34
41
  const artifacts = stateDir(cwd, project)
35
42
 
36
43
  /**
@@ -0,0 +1,139 @@
1
+ /**
2
+ * Codex 适配器:把 `codex exec` 包成假 ctx。
3
+ *
4
+ * 这一层的价值在于「pipeline 一行都不用改就能换个宿主」。所以测的也是这件事:
5
+ * 事件解不解得对、工具边界配不配得上、退出码翻不翻得成 stopReason。
6
+ *
7
+ * 用假 codex(tests/fixtures/fake-codex.mjs)跑,不花钱、不联网。
8
+ * 真机那一条已经在 D:\flow-codex-test 上跑通过了,那个不用天天跑。
9
+ */
10
+
11
+ import { test } from 'node:test'
12
+ import { sibling } from './paths.mjs'
13
+ import { pathToFileURL } from 'node:url'
14
+ import assert from 'node:assert/strict'
15
+ import { mkdtemp, rm } from 'node:fs/promises'
16
+ import { tmpdir } from 'node:os'
17
+ import { join } from 'node:path'
18
+
19
+ const { createCodexCtx, findCodexBinary } = await import(
20
+ pathToFileURL(sibling('host/codex.mjs')).href + `?t=${Date.now()}`
21
+ )
22
+
23
+ const FAKE = sibling('tests/fixtures/fake-codex.mjs')
24
+ const NODE = process.execPath
25
+
26
+ /** 用假 codex 造一个 ctx。剧本走环境变量,用完还原。 */
27
+ async function withFake(script, fn) {
28
+ const cwd = await mkdtemp(join(tmpdir(), 'flow-codex-'))
29
+ const previous = process.env.FAKE_CODEX_SCRIPT
30
+ process.env.FAKE_CODEX_SCRIPT = script
31
+ const ctx = createCodexCtx({ bin: NODE, binArgs: [FAKE], cwd, model: 'fake-model', sandbox: 'read-only' })
32
+ try {
33
+ await fn(ctx, cwd)
34
+ } finally {
35
+ if (previous === undefined) delete process.env.FAKE_CODEX_SCRIPT
36
+ else process.env.FAKE_CODEX_SCRIPT = previous
37
+ // 子进程刚被杀掉时 Windows 还会占一小会儿目录,直接 rm 会 EBUSY。
38
+ // 这跟适配器无关,是文件系统的结算延迟。
39
+ await rm(cwd, { recursive: true, force: true, maxRetries: 6, retryDelay: 150 })
40
+ }
41
+ }
42
+
43
+ test('正常一轮:拿到文本、收到 usage', async () => {
44
+ await withFake('ok', async (ctx, cwd) => {
45
+ const activation = await ctx.subagents.startActivation({
46
+ label: '测试阶',
47
+ prompt: [{ type: 'text', text: '跑一下' }],
48
+ cwd,
49
+ })
50
+ assert.equal(activation.kind, 'external', '必须报 external:本地会话那套事件监听在这里没有对象可挂')
51
+ const result = await activation.result
52
+ assert.equal(result.stopReason, 'completed')
53
+ // output 必须是块数组。给字符串的话 textOf 会静默返回空串,而且不报错。
54
+ assert.ok(Array.isArray(result.output), 'output 要是内容块数组')
55
+ assert.match(result.output[0].text, /hello\.txt/u)
56
+ const usage = ctx.usage()
57
+ assert.equal(usage.turns, 1)
58
+ assert.equal(usage.input, 1000)
59
+ assert.equal(usage.output, 50)
60
+ assert.equal(usage.cached, 200)
61
+ })
62
+ })
63
+
64
+ test('命令执行的前后会被报成工具开始 / 结束', async () => {
65
+ await withFake('ok', async (ctx, cwd) => {
66
+ const events = []
67
+ const watchdog = {
68
+ touch: () => events.push('touch'),
69
+ toolStart: label => events.push(`start:${label}`),
70
+ toolEnd: () => events.push('end'),
71
+ }
72
+ const ctx2 = createCodexCtx({ bin: NODE, binArgs: [FAKE], cwd, watchdog })
73
+ const activation = await ctx2.subagents.startActivation({ label: 'x', prompt: '跑一下', cwd })
74
+ await activation.result
75
+
76
+ assert.ok(events.includes('start:echo hi'), `要报出工具开始并带上命令,实际:${events.join(',')}`)
77
+ // start 必须排在 end 前面,配不上就是泄漏或者永久 busy
78
+ const startAt = events.indexOf('start:echo hi')
79
+ const endAt = events.indexOf('end')
80
+ assert.ok(startAt >= 0 && endAt > startAt, `start/end 顺序不对:${events.join(',')}`)
81
+ assert.ok(events.filter(e => e === 'touch').length >= 3, '每个事件都该顶一下心跳')
82
+ void ctx
83
+ })
84
+ })
85
+
86
+ test('没跑到 turn.completed 要判失败,不能当成功', async () => {
87
+ await withFake('noturn', async (ctx, cwd) => {
88
+ const activation = await ctx.subagents.startActivation({ label: 'x', prompt: '跑一下', cwd })
89
+ const result = await activation.result
90
+ assert.equal(result.stopReason, 'error', '断了半截还给 completed,等于把没干完的活当成功')
91
+ assert.match(result.diagnostic, /turn\.completed/u, '要说清是没跑到收尾,而不是笼统一句失败')
92
+ })
93
+ })
94
+
95
+ test('退出码非零要把 stderr 带出来', async () => {
96
+ await withFake('fail', async (ctx, cwd) => {
97
+ const activation = await ctx.subagents.startActivation({ label: '实施', prompt: '跑一下', cwd })
98
+ const result = await activation.result
99
+ assert.equal(result.stopReason, 'error')
100
+ assert.match(result.diagnostic, /退出码 1/u)
101
+ assert.match(result.diagnostic, /something went wrong/u, '不带 stderr 的话用户只能盯着一个退出码猜')
102
+ })
103
+ })
104
+
105
+ test('取消能真的把子进程收掉', async () => {
106
+ await withFake('hang', async (ctx, cwd) => {
107
+ const controller = new AbortController()
108
+ const activation = await ctx.subagents.startActivation({
109
+ label: 'x',
110
+ prompt: '跑一下',
111
+ cwd,
112
+ signal: controller.signal,
113
+ })
114
+ setTimeout(() => controller.abort(), 300)
115
+ const result = await activation.result
116
+ assert.equal(result.stopReason, 'error')
117
+ assert.match(result.diagnostic, /已取消/u)
118
+ await activation.dispose()
119
+ })
120
+ })
121
+
122
+ test('prompt 是空的时候不许起空会话', async () => {
123
+ await withFake('ok', async (ctx, cwd) => {
124
+ const activation = await ctx.subagents.startActivation({ label: 'x', prompt: [], cwd })
125
+ const result = await activation.result
126
+ assert.equal(result.stopReason, 'error')
127
+ assert.match(result.diagnostic, /prompt 是空的/u, '空 prompt 起 codex 会白烧一次调用')
128
+ })
129
+ })
130
+
131
+ test('findCodexBinary 找不到时给空串,不抛', () => {
132
+ const got = findCodexBinary({ USERPROFILE: 'Z:\\definitely-not-here', HOME: 'Z:\\definitely-not-here' })
133
+ assert.equal(got, '')
134
+ assert.equal(typeof got, 'string')
135
+ })
136
+
137
+ test('createCodexCtx 缺 bin 要当场报错', () => {
138
+ assert.throws(() => createCodexCtx({}), /codex 可执行文件路径/u)
139
+ })
@@ -0,0 +1,49 @@
1
+ /**
2
+ * 假的 codex:输出一串预设的 JSONL,用来测解析链。
3
+ *
4
+ * 真 codex 要花钱、要联网、要几十秒。而适配器里真正容易错的是
5
+ * 「事件怎么解、工具边界怎么配对、退出码怎么翻成 stopReason」——这些
6
+ * 只要事件流一样就能验,不必真调模型。
7
+ *
8
+ * 剧本从环境变量 FAKE_CODEX_SCRIPT 读,取值:
9
+ * ok 正常一轮,带一次命令执行
10
+ * noturn 没有 turn.completed(模拟中途断线)
11
+ * fail 退出码 1
12
+ * hang 一直不说话(测超时/取消)
13
+ */
14
+ const mode = process.env.FAKE_CODEX_SCRIPT ?? 'ok'
15
+
16
+ function emit(obj) {
17
+ process.stdout.write(`${JSON.stringify(obj)}\n`)
18
+ }
19
+
20
+ emit({ type: 'thread.started', thread_id: 'fake-thread' })
21
+ emit({ type: 'turn.started' })
22
+
23
+ if (mode === 'ok') {
24
+ emit({ type: 'item.completed', item: { id: 'i0', type: 'agent_message', text: '我来看一下工作目录。' } })
25
+ emit({
26
+ type: 'item.started',
27
+ item: { id: 'i1', type: 'command_execution', command: 'echo hi', aggregated_output: '', exit_code: null, status: 'in_progress' },
28
+ })
29
+ // 故意中间停一会儿:真 codex 跑命令就是这个节奏,这里要验的是
30
+ // 「命令已经 started、还没 completed」这段时间能不能被认出来。
31
+ setTimeout(() => {
32
+ emit({
33
+ type: 'item.completed',
34
+ item: { id: 'i1', type: 'command_execution', command: 'echo hi', aggregated_output: 'hi\n', exit_code: 0, status: 'completed' },
35
+ })
36
+ emit({ type: 'item.completed', item: { id: 'i2', type: 'agent_message', text: '做完了,hello.txt 里写的是 ok。' } })
37
+ emit({ type: 'turn.completed', usage: { input_tokens: 1000, output_tokens: 50, cached_input_tokens: 200 } })
38
+ process.exit(0)
39
+ }, 120)
40
+ } else if (mode === 'noturn') {
41
+ emit({ type: 'item.completed', item: { id: 'i0', type: 'agent_message', text: '说到一半' } })
42
+ process.exit(0)
43
+ } else if (mode === 'fail') {
44
+ process.stderr.write('something went wrong\n')
45
+ process.exit(1)
46
+ } else if (mode === 'hang') {
47
+ // 什么都不发,等被杀
48
+ setInterval(() => {}, 1000)
49
+ }
package/tests/run-all.mjs CHANGED
@@ -33,6 +33,7 @@ const SUITES = [
33
33
  ['命令把话送到模型', 'steer-command.test.mjs'],
34
34
  ['工作流目录门控', 'flow-gate.test.mjs'],
35
35
  ['交付模式', 'delivery-mode.test.mjs'],
36
+ ['Codex 适配器', 'codex-adapter.test.mjs'],
36
37
  ['状态栏看哪个目录', 'watch-root.test.mjs'],
37
38
  ['质检读预览图的路径', 'preview-path.test.mjs'],
38
39
  ['diff / 停机说明 / 盲区记忆', 'feedback.test.mjs'],