dsh-project-flow 0.12.0 → 0.13.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.
- package/CHANGELOG.md +193 -0
- package/README.md +55 -8
- package/bin/flow.mjs +595 -0
- package/host/codex.mjs +587 -0
- package/package.json +8 -8
- package/runner/pipeline.mjs +38 -1
- package/tests/client-bundle.test.mjs +3 -3
- package/tests/codex-adapter.test.mjs +139 -0
- package/tests/codex-discovery.test.mjs +147 -0
- package/tests/e2e.mjs +1 -1
- package/tests/fixtures/fake-codex.mjs +49 -0
- package/tests/flow-cli.test.mjs +191 -0
- package/tests/flow-create.test.mjs +1 -1
- package/tests/flow-gate.test.mjs +1 -1
- package/tests/paths.mjs +27 -17
- package/tests/run-all.mjs +3 -0
package/host/codex.mjs
ADDED
|
@@ -0,0 +1,587 @@
|
|
|
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, mkdtempSync, readdirSync, rmSync, statSync, writeFileSync } from 'node:fs'
|
|
41
|
+
import { tmpdir } from 'node:os'
|
|
42
|
+
import { delimiter, isAbsolute, join } from 'node:path'
|
|
43
|
+
import { createInterface } from 'node:readline'
|
|
44
|
+
|
|
45
|
+
/** 缺省沙箱:能写工作区,但碰不到外面。 */
|
|
46
|
+
const DEFAULT_SANDBOX = 'workspace-write'
|
|
47
|
+
|
|
48
|
+
/** mediaType → 落盘扩展名。codex 的 `-i` 只吃真实文件,扩展名不对它不认。 */
|
|
49
|
+
const IMAGE_EXT = {
|
|
50
|
+
'image/png': 'png',
|
|
51
|
+
'image/jpeg': 'jpg',
|
|
52
|
+
'image/jpg': 'jpg',
|
|
53
|
+
'image/webp': 'webp',
|
|
54
|
+
'image/gif': 'gif',
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* 把一个 image 内容块抠成 `{ mediaType, base64 }`,认三种写法。
|
|
59
|
+
*
|
|
60
|
+
* DSH 那边给过的形状不止一种,而且中间改过。与其约定「必须是 source.type
|
|
61
|
+
* === 'base64'」然后对旧形状静默丢图,不如三种都认一遍——丢图是安静的,
|
|
62
|
+
* 用户只会看到「模型说没看到图片」,查半天。
|
|
63
|
+
*
|
|
64
|
+
* 抠不出来返回 undefined,由调用方计数并明说「这张没传过去」。
|
|
65
|
+
*/
|
|
66
|
+
function decodeImageBlock(block) {
|
|
67
|
+
// ① { image: 'data:image/png;base64,xxxx' }
|
|
68
|
+
const inline = block.image
|
|
69
|
+
if (typeof inline === 'string' && inline.startsWith('data:')) {
|
|
70
|
+
const matched = /^data:([^;,]+);base64,(.+)$/su.exec(inline)
|
|
71
|
+
if (matched !== null) return { mediaType: matched[1].toLowerCase(), base64: matched[2] }
|
|
72
|
+
}
|
|
73
|
+
// ② { source: { type: 'base64', mediaType, data } } —— DSH 的正式形状
|
|
74
|
+
const source = block.source
|
|
75
|
+
if (source !== null && typeof source === 'object' && typeof source.data === 'string') {
|
|
76
|
+
const mediaType = typeof source.mediaType === 'string' ? source.mediaType : 'image/png'
|
|
77
|
+
return { mediaType: mediaType.toLowerCase(), base64: source.data }
|
|
78
|
+
}
|
|
79
|
+
// ③ { data, mediaType }
|
|
80
|
+
if (typeof block.data === 'string') {
|
|
81
|
+
const mediaType = typeof block.mediaType === 'string' ? block.mediaType : 'image/png'
|
|
82
|
+
return { mediaType: mediaType.toLowerCase(), base64: block.data }
|
|
83
|
+
}
|
|
84
|
+
return undefined
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* 把内容块数组拆成文字和图片。
|
|
89
|
+
*
|
|
90
|
+
* 早先这里只取文字,图片块直接丢掉——文本任务看不出毛病,一到「看截图说
|
|
91
|
+
* 哪里错位了」这种活就整段能力消失,而且没有任何提示。现在图片会落盘、
|
|
92
|
+
* 用 `-i` 传给 codex;实在抠不出来的才跳过,并且由调用方喊一声。
|
|
93
|
+
*
|
|
94
|
+
* @returns {{ text: string, images: Array<{mediaType: string, base64: string}>, skipped: number }}
|
|
95
|
+
*/
|
|
96
|
+
export function promptPartsOf(content) {
|
|
97
|
+
if (typeof content === 'string') return { text: content, images: [], skipped: 0 }
|
|
98
|
+
if (!Array.isArray(content)) return { text: '', images: [], skipped: 0 }
|
|
99
|
+
|
|
100
|
+
const texts = []
|
|
101
|
+
const images = []
|
|
102
|
+
let skipped = 0
|
|
103
|
+
|
|
104
|
+
for (const block of content) {
|
|
105
|
+
if (block === null || typeof block !== 'object') continue
|
|
106
|
+
if (block.type === 'text') {
|
|
107
|
+
if (typeof block.text === 'string') texts.push(block.text)
|
|
108
|
+
continue
|
|
109
|
+
}
|
|
110
|
+
if (block.type === 'image') {
|
|
111
|
+
const decoded = decodeImageBlock(block)
|
|
112
|
+
if (decoded === undefined) skipped += 1
|
|
113
|
+
else images.push(decoded)
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
return { text: texts.join('\n\n'), images, skipped }
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/** 只要文字时用这个(日志、长度统计都按文字算)。 */
|
|
121
|
+
function promptTextOf(content) {
|
|
122
|
+
return promptPartsOf(content).text
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/**
|
|
126
|
+
* 图片落盘,返回文件路径。
|
|
127
|
+
*
|
|
128
|
+
* codex 的 `-i/--image` 只吃真实文件路径,没有 base64 入口,所以必须写一次
|
|
129
|
+
* 临时文件。目录单开一个 `mkdtemp`,跑完在 finish 里整棵删掉——不删的话
|
|
130
|
+
* 每次带图的任务都会在 %TEMP% 里留几张图,攒久了很脏。
|
|
131
|
+
*/
|
|
132
|
+
function spillImages(images) {
|
|
133
|
+
if (images.length === 0) return { files: [], dir: '' }
|
|
134
|
+
const dir = mkdtempSync(join(tmpdir(), 'pf-codex-img-'))
|
|
135
|
+
const files = []
|
|
136
|
+
for (let index = 0; index < images.length; index += 1) {
|
|
137
|
+
const image = images[index]
|
|
138
|
+
const ext = IMAGE_EXT[image.mediaType] ?? 'png'
|
|
139
|
+
const path = join(dir, `img-${index + 1}.${ext}`)
|
|
140
|
+
writeFileSync(path, Buffer.from(image.base64, 'base64'))
|
|
141
|
+
files.push(path)
|
|
142
|
+
}
|
|
143
|
+
return { files, dir }
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/** 把一条命令压成一行,给熔断日志用。 */
|
|
147
|
+
function briefCommand(command) {
|
|
148
|
+
const text = typeof command === 'string' ? command.replace(/\s+/gu, ' ').trim() : ''
|
|
149
|
+
return text.length > 80 ? `${text.slice(0, 80)}…` : text
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/**
|
|
153
|
+
* 造一个假 ctx。pipeline 只认 `subagents.startActivation` 这一个方法。
|
|
154
|
+
*
|
|
155
|
+
* @param bin codex 可执行文件绝对路径
|
|
156
|
+
* @param cwd 默认工作目录(spec.cwd 优先)
|
|
157
|
+
* @param model 留空表示用 codex 自己 config.toml 里的模型
|
|
158
|
+
* @param sandbox read-only / workspace-write / danger-full-access
|
|
159
|
+
* @param watchdog 守护器。事件直接喂给它——它天然对应「当前在跑的那一阶」,
|
|
160
|
+
* 不需要再做一次路由。
|
|
161
|
+
* @param onRun 可选:每次起子进程时回调,用来打印进度
|
|
162
|
+
* @param onImage 可选:图片处理结果回调(传了几张、丢了几张)
|
|
163
|
+
*/
|
|
164
|
+
export function createCodexCtx(options = {}) {
|
|
165
|
+
const {
|
|
166
|
+
bin,
|
|
167
|
+
// 放在 bin 前面的一串参数。正常用不到;测试时把 bin 指成 node、
|
|
168
|
+
// 这里放一个假 codex 脚本,就能把整条解析链跑一遍而不碰真模型。
|
|
169
|
+
binArgs = [],
|
|
170
|
+
cwd = process.cwd(),
|
|
171
|
+
model = '',
|
|
172
|
+
sandbox = DEFAULT_SANDBOX,
|
|
173
|
+
extraArgs = [],
|
|
174
|
+
watchdog,
|
|
175
|
+
onRun,
|
|
176
|
+
onImage,
|
|
177
|
+
} = options
|
|
178
|
+
|
|
179
|
+
if (typeof bin !== 'string' || bin === '') {
|
|
180
|
+
throw new Error('createCodexCtx 需要一个 codex 可执行文件路径')
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
// 累计真实 usage。插件的预算器是按字符估的(它拿不到 token 数),
|
|
184
|
+
// 而 codex 每个 turn 结束都会报真账。两个数放一起给人看,别让人以为
|
|
185
|
+
// 估算值就是账单。
|
|
186
|
+
const totalUsage = { input: 0, output: 0, cached: 0, turns: 0 }
|
|
187
|
+
|
|
188
|
+
return {
|
|
189
|
+
/** 宿主名字,给日志和证据包用。 */
|
|
190
|
+
host: { name: 'codex', model, sandbox },
|
|
191
|
+
|
|
192
|
+
/** 截至目前的真实 token 用量(来自 codex 的 turn.completed)。 */
|
|
193
|
+
usage() {
|
|
194
|
+
return { ...totalUsage }
|
|
195
|
+
},
|
|
196
|
+
|
|
197
|
+
subagents: {
|
|
198
|
+
/**
|
|
199
|
+
* 起一次 codex exec,返回 runStage 要的 activation。
|
|
200
|
+
*
|
|
201
|
+
* spec 里 runStage 会塞:provider / label / prompt / parent / signal /
|
|
202
|
+
* delivery / cwd / agentOptions。这里只用 prompt、cwd、signal 三样,
|
|
203
|
+
* 其余是 DSH 的东西,对 codex 没意义。
|
|
204
|
+
*/
|
|
205
|
+
async startActivation(spec = {}) {
|
|
206
|
+
const workdir = typeof spec.cwd === 'string' && spec.cwd !== '' ? spec.cwd : cwd
|
|
207
|
+
const parts = promptPartsOf(spec.prompt)
|
|
208
|
+
const prompt = parts.text
|
|
209
|
+
if (prompt === '' && parts.images.length === 0) {
|
|
210
|
+
return failedActivation('这一阶的 prompt 是空的:没有内容投给 codex,不能起空会话')
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
const label = typeof spec.label === 'string' ? spec.label : 'codex'
|
|
214
|
+
const spilled = spillImages(parts.images)
|
|
215
|
+
if (parts.skipped > 0) {
|
|
216
|
+
// 静默丢图是最坏的一种错:模型只会说「我没看到图」,人会以为是模型不行。
|
|
217
|
+
onImage?.({ sent: spilled.files.length, skipped: parts.skipped })
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
const args = [...binArgs, 'exec', '--json', '--skip-git-repo-check', '-C', workdir]
|
|
221
|
+
if (typeof model === 'string' && model !== '') args.push('-m', model)
|
|
222
|
+
if (typeof sandbox === 'string' && sandbox !== '') args.push('-s', sandbox)
|
|
223
|
+
for (const file of spilled.files) args.push('-i', file)
|
|
224
|
+
args.push(...extraArgs)
|
|
225
|
+
// 用 `-` 让 codex 从 stdin 读 prompt:中文、换行、引号全不用转义。
|
|
226
|
+
args.push('-')
|
|
227
|
+
|
|
228
|
+
onRun?.({
|
|
229
|
+
label,
|
|
230
|
+
workdir,
|
|
231
|
+
promptChars: prompt.length,
|
|
232
|
+
images: spilled.files.length,
|
|
233
|
+
skippedImages: parts.skipped,
|
|
234
|
+
})
|
|
235
|
+
|
|
236
|
+
const controller = new AbortController()
|
|
237
|
+
const forwardAbort = () => {
|
|
238
|
+
try { controller.abort() } catch { /* 已经 abort 过 */ }
|
|
239
|
+
}
|
|
240
|
+
if (spec.signal?.aborted === true) forwardAbort()
|
|
241
|
+
else spec.signal?.addEventListener('abort', forwardAbort, { once: true })
|
|
242
|
+
|
|
243
|
+
let child
|
|
244
|
+
try {
|
|
245
|
+
child = spawn(bin, args, {
|
|
246
|
+
cwd: workdir,
|
|
247
|
+
stdio: ['pipe', 'pipe', 'pipe'],
|
|
248
|
+
signal: controller.signal,
|
|
249
|
+
windowsHide: true,
|
|
250
|
+
// PATH 里找到的 codex 在 Windows 上通常是 .cmd 包装脚本,
|
|
251
|
+
// 不带 shell 直接 spawn 会 ENOENT/EINVAL。只在需要时开 shell,
|
|
252
|
+
// 别给 .exe 也套一层——那会把参数里的引号再解释一遍。
|
|
253
|
+
shell: needsShell(bin),
|
|
254
|
+
})
|
|
255
|
+
} catch (error) {
|
|
256
|
+
cleanup(spilled.dir)
|
|
257
|
+
return failedActivation(`codex 起不来:${error?.message ?? error}`)
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
// prompt 走 stdin。写失败(进程已经死了)不该抛到外面——下面的 close
|
|
261
|
+
// 事件会带着退出码回来,那才是结论。
|
|
262
|
+
try {
|
|
263
|
+
child.stdin.on('error', () => {})
|
|
264
|
+
child.stdin.end(prompt, 'utf8')
|
|
265
|
+
} catch { /* 见上 */ }
|
|
266
|
+
|
|
267
|
+
const openTools = new Set()
|
|
268
|
+
let lastMessage = ''
|
|
269
|
+
let stderrTail = ''
|
|
270
|
+
let usage = undefined
|
|
271
|
+
let sawTurnCompleted = false
|
|
272
|
+
let killedBySignal = false
|
|
273
|
+
|
|
274
|
+
child.stderr?.on('data', chunk => {
|
|
275
|
+
stderrTail = (stderrTail + chunk.toString('utf8')).slice(-4000)
|
|
276
|
+
})
|
|
277
|
+
|
|
278
|
+
const rl = createInterface({ input: child.stdout })
|
|
279
|
+
rl.on('line', line => {
|
|
280
|
+
const text = line.trim()
|
|
281
|
+
if (text === '') return
|
|
282
|
+
let event
|
|
283
|
+
try {
|
|
284
|
+
event = JSON.parse(text)
|
|
285
|
+
} catch {
|
|
286
|
+
// 不是 JSON 的行(进度条、彩色的杂音)直接忽略,但要顶一下心跳:
|
|
287
|
+
// 能吐字节就说明它还活着。
|
|
288
|
+
watchdog?.touch()
|
|
289
|
+
return
|
|
290
|
+
}
|
|
291
|
+
const type = typeof event?.type === 'string' ? event.type : ''
|
|
292
|
+
const item = event?.item
|
|
293
|
+
|
|
294
|
+
// 每一个事件都是活着的证据。codex 的流是有节奏的,比 DSH 外部后端
|
|
295
|
+
// 那种「一句话不说九分钟」强太多。
|
|
296
|
+
watchdog?.touch()
|
|
297
|
+
|
|
298
|
+
if (type === 'item.started' && item?.type === 'command_execution') {
|
|
299
|
+
openTools.add(item.id)
|
|
300
|
+
watchdog?.toolStart(briefCommand(item.command) || 'command_execution')
|
|
301
|
+
return
|
|
302
|
+
}
|
|
303
|
+
if (type === 'item.completed' && item?.type === 'command_execution') {
|
|
304
|
+
if (openTools.delete(item.id)) watchdog?.toolEnd()
|
|
305
|
+
return
|
|
306
|
+
}
|
|
307
|
+
if (type === 'item.completed' && item?.type === 'agent_message') {
|
|
308
|
+
if (typeof item.text === 'string' && item.text !== '') lastMessage = item.text
|
|
309
|
+
return
|
|
310
|
+
}
|
|
311
|
+
if (type === 'turn.completed') {
|
|
312
|
+
sawTurnCompleted = true
|
|
313
|
+
if (event.usage !== undefined) {
|
|
314
|
+
usage = event.usage
|
|
315
|
+
totalUsage.turns += 1
|
|
316
|
+
totalUsage.input += Number(event.usage.input_tokens ?? 0) || 0
|
|
317
|
+
totalUsage.output += Number(event.usage.output_tokens ?? 0) || 0
|
|
318
|
+
totalUsage.cached += Number(event.usage.cached_input_tokens ?? 0) || 0
|
|
319
|
+
}
|
|
320
|
+
return
|
|
321
|
+
}
|
|
322
|
+
if (type === 'error' && typeof event.message === 'string') {
|
|
323
|
+
// 重连提示不是失败:codex 会自己退到 HTTPS 再试。只留最后一条做诊断。
|
|
324
|
+
stderrTail = `${stderrTail}\n${event.message}`.slice(-4000)
|
|
325
|
+
}
|
|
326
|
+
})
|
|
327
|
+
|
|
328
|
+
const result = new Promise(resolve => {
|
|
329
|
+
const finish = (stopReason, diagnostic) => {
|
|
330
|
+
// 收尾时把没配对的工具全作废:被 kill 的命令不会再有 completed。
|
|
331
|
+
for (const _ of openTools) watchdog?.toolEnd()
|
|
332
|
+
openTools.clear()
|
|
333
|
+
try { rl.close() } catch { /* 已经关了 */ }
|
|
334
|
+
cleanup(spilled.dir)
|
|
335
|
+
resolve({
|
|
336
|
+
stopReason,
|
|
337
|
+
diagnostic,
|
|
338
|
+
usage,
|
|
339
|
+
// textOf 只认块数组,给字符串会静默变空串
|
|
340
|
+
output: lastMessage === '' ? [] : [{ type: 'text', text: lastMessage }],
|
|
341
|
+
})
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
child.on('error', error => {
|
|
345
|
+
killedBySignal = true
|
|
346
|
+
// spawn 带 signal 时,abort 会走 error 而不是 close(消息是
|
|
347
|
+
// "The operation was aborted")。不在这儿认一次的话,用户按了
|
|
348
|
+
// 停止却看到「codex 进程出错」,会以为插件坏了。
|
|
349
|
+
if (spec.signal?.aborted === true) {
|
|
350
|
+
finish('error', `${label}:已取消`)
|
|
351
|
+
return
|
|
352
|
+
}
|
|
353
|
+
finish('error', `${label}:codex 进程出错(${error?.message ?? error})`)
|
|
354
|
+
})
|
|
355
|
+
|
|
356
|
+
child.on('close', (code, signal) => {
|
|
357
|
+
const aborted = spec.signal?.aborted === true
|
|
358
|
+
if (aborted || killedBySignal) {
|
|
359
|
+
finish('error', `${label}:已取消`)
|
|
360
|
+
return
|
|
361
|
+
}
|
|
362
|
+
if (code === 0 && sawTurnCompleted) {
|
|
363
|
+
finish('completed', undefined)
|
|
364
|
+
return
|
|
365
|
+
}
|
|
366
|
+
const tail = stderrTail.trim().split(/\r?\n/u).slice(-6).join(' / ')
|
|
367
|
+
finish(
|
|
368
|
+
'error',
|
|
369
|
+
`${label}:codex 退出码 ${code ?? signal ?? '?'}`
|
|
370
|
+
+ (sawTurnCompleted ? '' : ',没跑到 turn.completed')
|
|
371
|
+
+ (tail === '' ? '' : `|${tail.slice(0, 400)}`),
|
|
372
|
+
)
|
|
373
|
+
})
|
|
374
|
+
})
|
|
375
|
+
|
|
376
|
+
return {
|
|
377
|
+
// external:不要给 handle.agent。runStage 看到 external 就不去挂事件监听,
|
|
378
|
+
// 那边的监听本来就是给 DSH 本地子会话准备的,这里没有。
|
|
379
|
+
kind: 'external',
|
|
380
|
+
result,
|
|
381
|
+
dispose: async () => {
|
|
382
|
+
spec.signal?.removeEventListener?.('abort', forwardAbort)
|
|
383
|
+
const alive = () => child.exitCode === null && child.signalCode === null
|
|
384
|
+
if (!alive()) {
|
|
385
|
+
cleanup(spilled.dir)
|
|
386
|
+
return
|
|
387
|
+
}
|
|
388
|
+
try { child.kill() } catch { /* 已经退了 */ }
|
|
389
|
+
// Windows 上 SIGTERM 不一定立刻生效,尤其对方是个不肯退的 node 进程。
|
|
390
|
+
// 等一小会儿还没死就硬杀——留在后台的 codex 会继续烧钱,那不是小事。
|
|
391
|
+
await new Promise(resolve => setTimeout(resolve, 150))
|
|
392
|
+
if (!alive()) {
|
|
393
|
+
cleanup(spilled.dir)
|
|
394
|
+
return
|
|
395
|
+
}
|
|
396
|
+
try { child.kill('SIGKILL') } catch { /* 系统不支持就直接算了 */ }
|
|
397
|
+
cleanup(spilled.dir)
|
|
398
|
+
},
|
|
399
|
+
}
|
|
400
|
+
},
|
|
401
|
+
},
|
|
402
|
+
}
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
/** 删临时目录,失败当没事。 */
|
|
406
|
+
function cleanup(dir) {
|
|
407
|
+
if (typeof dir !== 'string' || dir === '') return
|
|
408
|
+
try { rmSync(dir, { recursive: true, force: true }) } catch { /* 删不掉留给系统清 */ }
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
/**
|
|
412
|
+
* 这个路径要不要用 shell 起。
|
|
413
|
+
*
|
|
414
|
+
* Windows 上 `codex.cmd` / `codex.bat` 是批处理包装,`spawn` 不带 shell 会
|
|
415
|
+
* EINVAL。但 `.exe` 千万不能加——加了之后参数里那些引号会被 cmd 再解释一遍,
|
|
416
|
+
* 中文路径和判据命令都会碎。
|
|
417
|
+
*/
|
|
418
|
+
function needsShell(bin) {
|
|
419
|
+
return process.platform === 'win32' && /\.(cmd|bat)$/iu.test(bin)
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
function statOf(path) {
|
|
423
|
+
try { return statSync(path) } catch { return undefined }
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
function isFile(path) {
|
|
427
|
+
const stat = statOf(path)
|
|
428
|
+
return stat !== undefined && stat.isFile()
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
/** 目录名里抠 semver;抠不出返回 undefined(Codex 的 build 目录名是 hash)。 */
|
|
432
|
+
function versionOf(name) {
|
|
433
|
+
const matched = /(\d+)\.(\d+)\.(\d+)/u.exec(name)
|
|
434
|
+
if (matched === null) return undefined
|
|
435
|
+
return [Number(matched[1]), Number(matched[2]), Number(matched[3])]
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
function compareVersion(left, right) {
|
|
439
|
+
for (let index = 0; index < 3; index += 1) {
|
|
440
|
+
if (left[index] !== right[index]) return left[index] - right[index]
|
|
441
|
+
}
|
|
442
|
+
return 0
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
/**
|
|
446
|
+
* 从候选里挑最新的。
|
|
447
|
+
*
|
|
448
|
+
* 早先是 `found[found.length - 1]`——目录枚举顺序当版本顺序用。Windows 上
|
|
449
|
+
* `readdirSync` 的顺序既不是字母序也不是时间序,升级一次可能挑到旧的那个,
|
|
450
|
+
* 而且症状是「新功能没生效」,最难查的一种。
|
|
451
|
+
*
|
|
452
|
+
* 排序键三层,逐层比:
|
|
453
|
+
* 1. 目录名里能解析出版本号的优先(那是明确的版本,不是猜的)
|
|
454
|
+
* 2. 有版本号的之间按版本号降序
|
|
455
|
+
* 3. 都没有版本号时按 mtime 降序——Codex 的 `<build>` 是 hash,升级会换
|
|
456
|
+
* 一个新目录,新的那份 mtime 一定更新
|
|
457
|
+
*
|
|
458
|
+
* @param candidates [{ path, name, mtimeMs }]
|
|
459
|
+
*/
|
|
460
|
+
export function newestCandidate(candidates) {
|
|
461
|
+
if (candidates.length === 0) return ''
|
|
462
|
+
const scored = candidates.map(item => ({ ...item, version: versionOf(item.name) }))
|
|
463
|
+
scored.sort((left, right) => {
|
|
464
|
+
if ((left.version !== undefined) !== (right.version !== undefined)) {
|
|
465
|
+
return left.version !== undefined ? -1 : 1
|
|
466
|
+
}
|
|
467
|
+
if (left.version !== undefined && right.version !== undefined) {
|
|
468
|
+
const byVersion = compareVersion(right.version, left.version)
|
|
469
|
+
if (byVersion !== 0) return byVersion
|
|
470
|
+
}
|
|
471
|
+
return (right.mtimeMs ?? 0) - (left.mtimeMs ?? 0)
|
|
472
|
+
})
|
|
473
|
+
return scored[0].path
|
|
474
|
+
}
|
|
475
|
+
|
|
476
|
+
/** 在 PATH 里找。Windows 上要连同 PATHEXT 一起试。 */
|
|
477
|
+
function findOnPath(env, names) {
|
|
478
|
+
const raw = env.PATH ?? env.Path ?? env.path ?? ''
|
|
479
|
+
if (typeof raw !== 'string' || raw === '') return ''
|
|
480
|
+
for (const dir of raw.split(delimiter)) {
|
|
481
|
+
if (dir.trim() === '') continue
|
|
482
|
+
for (const name of names) {
|
|
483
|
+
const candidate = join(dir.trim(), name)
|
|
484
|
+
if (isFile(candidate)) return candidate
|
|
485
|
+
}
|
|
486
|
+
}
|
|
487
|
+
return ''
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
/** 各平台常见的安装位置。找不到 PATH 上那个时按这个兜底。 */
|
|
491
|
+
function knownDirs(env, home) {
|
|
492
|
+
if (process.platform === 'win32') {
|
|
493
|
+
const local = env.LOCALAPPDATA ?? (home === '' ? '' : join(home, 'AppData', 'Local'))
|
|
494
|
+
return local === '' ? [] : [join(local, 'OpenAI', 'Codex', 'bin')]
|
|
495
|
+
}
|
|
496
|
+
return [
|
|
497
|
+
home === '' ? '' : join(home, '.codex', 'bin'),
|
|
498
|
+
home === '' ? '' : join(home, '.local', 'bin'),
|
|
499
|
+
'/opt/homebrew/bin',
|
|
500
|
+
'/usr/local/bin',
|
|
501
|
+
].filter(dir => dir !== '')
|
|
502
|
+
}
|
|
503
|
+
|
|
504
|
+
function binaryNames() {
|
|
505
|
+
return process.platform === 'win32'
|
|
506
|
+
? ['codex.exe', 'codex.cmd', 'codex.bat']
|
|
507
|
+
: ['codex']
|
|
508
|
+
}
|
|
509
|
+
|
|
510
|
+
/**
|
|
511
|
+
* 找本机的 codex 可执行文件。
|
|
512
|
+
*
|
|
513
|
+
* 顺序(前一个命中就返回,不再往下猜):
|
|
514
|
+
*
|
|
515
|
+
* 1. `CODEX_CLI_PATH` —— 人明确指的那个,不猜
|
|
516
|
+
* 2. `PATH` 上的 `codex` —— 用户多半是用 `npm i -g` 或官方安装脚本装的,
|
|
517
|
+
* 这种装法本来就该能用,之前漏了它
|
|
518
|
+
* 3. `%LOCALAPPDATA%\OpenAI\Codex\bin\<build>\codex.exe` —— Codex 桌面版
|
|
519
|
+
* 自带的 CLI。`<build>` 是 hash,升级会换目录,所以按 mtime 取最新
|
|
520
|
+
* 4. macOS / Linux 的常见位置(`~/.codex/bin`、`~/.local/bin`、
|
|
521
|
+
* `/opt/homebrew/bin`、`/usr/local/bin`)
|
|
522
|
+
*
|
|
523
|
+
* 不去碰 `Program Files\WindowsApps\...`:那是桌面应用自带的副本,路径带
|
|
524
|
+
* 版本号还有 ACL 限制,拿来当 CLI 用是会踩坑的。
|
|
525
|
+
*
|
|
526
|
+
* @returns 找到的绝对路径;找不到返回空串,由调用方决定怎么报
|
|
527
|
+
*/
|
|
528
|
+
export function findCodexBinary(env = process.env) {
|
|
529
|
+
const home = env.USERPROFILE ?? env.HOME ?? ''
|
|
530
|
+
|
|
531
|
+
// ① 显式指定。相对路径按 HOME 展开,省得用户填一个只有自己 shell 认得的写法。
|
|
532
|
+
if (typeof env.CODEX_CLI_PATH === 'string' && env.CODEX_CLI_PATH !== '') {
|
|
533
|
+
const explicit = env.CODEX_CLI_PATH
|
|
534
|
+
const resolved = isAbsolute(explicit) || home === '' ? explicit : join(home, explicit)
|
|
535
|
+
const stat = statOf(resolved)
|
|
536
|
+
if (stat !== undefined && stat.isFile()) return resolved
|
|
537
|
+
}
|
|
538
|
+
|
|
539
|
+
// ② PATH。这是最该优先的一条:从 npm / brew 装的 codex 就在这儿。
|
|
540
|
+
const fromPath = findOnPath(env, binaryNames())
|
|
541
|
+
if (fromPath !== '') return fromPath
|
|
542
|
+
|
|
543
|
+
// ③④ 已知安装目录。同一层目录下可能有多个 build,挑最新的。
|
|
544
|
+
const names = binaryNames()
|
|
545
|
+
const candidates = []
|
|
546
|
+
for (const dir of knownDirs(env, home)) {
|
|
547
|
+
let entries
|
|
548
|
+
try {
|
|
549
|
+
if (!existsSync(dir)) continue
|
|
550
|
+
entries = readdirSync(dir, { withFileTypes: true })
|
|
551
|
+
} catch {
|
|
552
|
+
// 目录读不动就当没装
|
|
553
|
+
continue
|
|
554
|
+
}
|
|
555
|
+
for (const entry of entries) {
|
|
556
|
+
// 两种布局:<dir>/codex.exe(直接装)和 <dir>/<build>/codex.exe(桌面版)
|
|
557
|
+
if (entry.isFile()) {
|
|
558
|
+
if (names.includes(entry.name)) {
|
|
559
|
+
const path = join(dir, entry.name)
|
|
560
|
+
const stat = statOf(path)
|
|
561
|
+
if (stat !== undefined) candidates.push({ path, name: entry.name, mtimeMs: stat.mtimeMs })
|
|
562
|
+
}
|
|
563
|
+
continue
|
|
564
|
+
}
|
|
565
|
+
if (!entry.isDirectory()) continue
|
|
566
|
+
for (const name of names) {
|
|
567
|
+
const path = join(dir, entry.name, name)
|
|
568
|
+
const stat = statOf(path)
|
|
569
|
+
if (stat !== undefined && stat.isFile()) {
|
|
570
|
+
candidates.push({ path, name: entry.name, mtimeMs: stat.mtimeMs })
|
|
571
|
+
break
|
|
572
|
+
}
|
|
573
|
+
}
|
|
574
|
+
}
|
|
575
|
+
}
|
|
576
|
+
|
|
577
|
+
return newestCandidate(candidates)
|
|
578
|
+
}
|
|
579
|
+
|
|
580
|
+
/** 一起手就失败(比如 prompt 空)时用的占位 activation。 */
|
|
581
|
+
function failedActivation(message) {
|
|
582
|
+
return {
|
|
583
|
+
kind: 'external',
|
|
584
|
+
result: Promise.resolve({ stopReason: 'error', diagnostic: message, output: [] }),
|
|
585
|
+
dispose: async () => {},
|
|
586
|
+
}
|
|
587
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-project-flow",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.13.1",
|
|
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": {
|
|
@@ -97,13 +100,10 @@
|
|
|
97
100
|
}
|
|
98
101
|
},
|
|
99
102
|
"peerDependencies": {
|
|
100
|
-
"@deepseek-ai/schemastery": "*"
|
|
101
|
-
"@deepseek-ai/dsh-client-ui-conversation": "*"
|
|
103
|
+
"@deepseek-ai/schemastery": "*"
|
|
102
104
|
},
|
|
103
|
-
"
|
|
104
|
-
"
|
|
105
|
-
"optional": true
|
|
106
|
-
}
|
|
105
|
+
"bin": {
|
|
106
|
+
"flow": "./bin/flow.mjs"
|
|
107
107
|
},
|
|
108
108
|
"scripts": {
|
|
109
109
|
"bench": "node bench/run.mjs",
|
package/runner/pipeline.mjs
CHANGED
|
@@ -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
|
-
|
|
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
|
/**
|
|
@@ -53,10 +60,20 @@ export function createPipeline(ctx) {
|
|
|
53
60
|
}
|
|
54
61
|
const healedNote = healed.length === 0 ? '' : `自愈记录:${healed.join(';')}`
|
|
55
62
|
let snapshotNote = ''
|
|
63
|
+
/**
|
|
64
|
+
* 断言汇总。给外部入口(bin/flow.mjs)用:那边要打印「判据 5/5 过」,
|
|
65
|
+
* 而 gate / assertions 都是第 4 阶的局部变量。
|
|
66
|
+
*
|
|
67
|
+
* 放在这一层由 craft 兜一下,所有返回点都带得上,不用一个个调用点去传。
|
|
68
|
+
* 没跑到第 4 阶就停的时候保持 null——那是「还没验」,不是「零条验过」,
|
|
69
|
+
* 两者在报告里必须长得不一样。
|
|
70
|
+
*/
|
|
71
|
+
let assertionSummary = null
|
|
56
72
|
const craft = patch => ({
|
|
57
73
|
project,
|
|
58
74
|
artifacts,
|
|
59
75
|
issues: [],
|
|
76
|
+
assertions: assertionSummary,
|
|
60
77
|
...patch,
|
|
61
78
|
note: [patch.note, healedNote, snapshotNote, ...routeNotes]
|
|
62
79
|
.filter(part => typeof part === 'string' && part !== '')
|
|
@@ -913,6 +930,26 @@ export function createPipeline(ctx) {
|
|
|
913
930
|
tailChars: settings.checkStdoutTailChars,
|
|
914
931
|
})
|
|
915
932
|
const gate = gateAssertions(assertions)
|
|
933
|
+
// 一条要求可能挂好几条 check,全过才算这条过;判不了的(unverified)
|
|
934
|
+
// 和根本没有 check 的(uncovered)都不算过。给外部入口一个能直接印
|
|
935
|
+
// 「要求 3/3」的数字,别让它拿 check 数冒充要求数。
|
|
936
|
+
const failedReqs = new Set()
|
|
937
|
+
for (const item of gate.failed) failedReqs.add(item.req)
|
|
938
|
+
for (const item of gate.unverified) failedReqs.add(item.req)
|
|
939
|
+
for (const req of gate.uncovered) failedReqs.add(req)
|
|
940
|
+
const passedReqs = new Set()
|
|
941
|
+
for (const item of gate.passed) if (!failedReqs.has(item.req)) passedReqs.add(item.req)
|
|
942
|
+
assertionSummary = {
|
|
943
|
+
verdict: gate.verdict,
|
|
944
|
+
inPlay: criteriaInPlay(assertions),
|
|
945
|
+
requirements: { total: gate.total, passed: passedReqs.size },
|
|
946
|
+
checks: {
|
|
947
|
+
total: gate.checked,
|
|
948
|
+
passed: gate.passed.length,
|
|
949
|
+
failed: gate.failed.length,
|
|
950
|
+
unverified: gate.unverified.length + gate.uncovered.length,
|
|
951
|
+
},
|
|
952
|
+
}
|
|
916
953
|
if (Array.isArray(assertions) && assertions.length > 0) {
|
|
917
954
|
await logLine(cwd, project, criteriaInPlay(assertions)
|
|
918
955
|
? `断言:${gate.verdict}|过 ${gate.passed.length} / 未过 ${gate.failed.length} / 判不了 ${gate.unverified.length + gate.uncovered.length}`
|