dsh-seal-scripts 0.0.0-stage → 0.4.7

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 (44) hide show
  1. package/LICENSE +21 -0
  2. package/README.en.md +318 -0
  3. package/README.md +342 -2
  4. package/cordis.patch.yml +6 -0
  5. package/index.js +12 -0
  6. package/lib/client.js +1465 -0
  7. package/lib/core/assembly.js +321 -0
  8. package/lib/core/catalog-snapshot.js +78 -0
  9. package/lib/core/diary.js +100 -0
  10. package/lib/core/health.js +72 -0
  11. package/lib/core/index.js +491 -0
  12. package/lib/core/inject.js +146 -0
  13. package/lib/core/lang.js +251 -0
  14. package/lib/core/locale.js +56 -0
  15. package/lib/core/memory-file.js +214 -0
  16. package/lib/core/migrate.js +97 -0
  17. package/lib/core/path-guard.js +43 -0
  18. package/lib/core/project-key.js +52 -0
  19. package/lib/core/render.js +228 -0
  20. package/lib/core/schema-runner.js +281 -0
  21. package/lib/core/schema-tools.js +794 -0
  22. package/lib/core/schema.js +493 -0
  23. package/lib/core/search.js +254 -0
  24. package/lib/core/settings.js +158 -0
  25. package/lib/core/store.js +408 -0
  26. package/lib/core/tool-transfer.js +249 -0
  27. package/lib/core/tool.js +602 -0
  28. package/lib/core/zip.js +226 -0
  29. package/lib/core/zstd-js.js +705 -0
  30. package/lib/core/zstd.js +103 -0
  31. package/lib/host/api.js +9 -0
  32. package/lib/host/capabilities.js +155 -0
  33. package/lib/host/compact-delete.js +76 -0
  34. package/lib/host/delete.js +136 -0
  35. package/lib/host/host-contract.js +73 -0
  36. package/lib/host/http-util.js +82 -0
  37. package/lib/host/lifecycle.js +66 -0
  38. package/lib/host/register.js +63 -0
  39. package/lib/host/routes/memories.js +102 -0
  40. package/lib/host/routes/options.js +46 -0
  41. package/lib/host/routes/sessions.js +194 -0
  42. package/lib/host/routes/tools.js +103 -0
  43. package/lib/host/summary.js +71 -0
  44. package/package.json +60 -4
@@ -0,0 +1,52 @@
1
+ /**
2
+ * 工作区目录编码 —— 照搬 DSH 会话存储的 projectKey 规则,
3
+ * 这样回顾目录和 $DSH_HOME/sessions/ 的目录名一一对应,肉眼就能对上。
4
+ *
5
+ * /sdcard/Download -> --sdcard-Download--
6
+ * /sdcard/Download/出图 -> --sdcard-Download-~51FA~56FE--
7
+ *
8
+ * 规则来源:dsh-session-persistence-jsonl/lib/index.js 的 projectKey()。
9
+ * 这里重新实现一份,是为了不依赖 DSH 内部未导出的函数。
10
+ */
11
+
12
+ /**
13
+ * 把路径分隔符换成减号,把不安全字符换成 ~XXXX。
14
+ * @param {string} cwd 会话的工作目录(绝对路径)
15
+ * @returns {string} 单段、可做目录名的 key
16
+ */
17
+ export function projectKey(cwd) {
18
+ if (typeof cwd !== 'string' || cwd.length === 0) {
19
+ throw new Error('cannot encode an empty project path')
20
+ }
21
+ let readable = ''
22
+ let separatorRun = false
23
+ for (let i = 0; i < cwd.length; i++) {
24
+ const code = cwd.charCodeAt(i)
25
+ const ch = String.fromCharCode(code)
26
+ if (ch === '/' || ch === '\\' || ch === ':') {
27
+ if (!separatorRun) readable += '-'
28
+ separatorRun = true
29
+ } else if (ch !== '~' && /^[A-Za-z0-9._-]$/.test(ch)) {
30
+ readable += ch
31
+ separatorRun = false
32
+ } else {
33
+ readable += '~' + code.toString(16).toUpperCase().padStart(4, '0')
34
+ separatorRun = false
35
+ }
36
+ }
37
+ const trimmed = readable.replace(/^-+/, '') || 'root'
38
+ return '--' + trimmed.slice(0, 251) + '--'
39
+ }
40
+
41
+ /**
42
+ * 反解:把 projectKey 还原成路径(只用于展示;有损,原路径里的 - 也会变回 /)。
43
+ * @param {string} key
44
+ * @returns {string}
45
+ */
46
+ export function decodeProjectKey(key) {
47
+ let s = key
48
+ if (s.startsWith('--')) s = s.slice(2)
49
+ if (s.endsWith('--')) s = s.slice(0, -2)
50
+ s = s.replace(/~([0-9A-Fa-f]{4})/g, (_, hex) => String.fromCharCode(parseInt(hex, 16)))
51
+ return '/' + s
52
+ }
@@ -0,0 +1,228 @@
1
+ /**
2
+ * 会话事件 -> 原文。
3
+ *
4
+ * 原文只有四种行首(见设计文档第三节):
5
+ * [用户] 用户说的
6
+ * [模型] 模型说的
7
+ * ▸ 工具发起
8
+ * ◂ 工具结果 / 报错
9
+ *
10
+ * 铁律:所有续行缩进两个空格。这样即便用户贴了一段以 [用户] 开头的文字,
11
+ * 它也只会是一条缩进的续行,骗不过行首匹配。
12
+ *
13
+ * 注意:压缩事件里的 shadowedSeqs 只列表面事件
14
+ * (user/message、assistant/message、tool/result),
15
+ * 独立的 tool/call 事件不在里面 —— 工具调用要从 assistant/message 的
16
+ * tool-call 内容块里取,否则工具足迹会整个丢掉。
17
+ *
18
+ * PTC 还有第三层:模型写的 run_code 里,代码自己调 tools.xxx(...)。
19
+ * 这些既不在 shadowedSeqs 里,也不在 assistant/message 的内容块里,
20
+ * 只有 tool/ptc-dispatch-start(发起)和 tool/ptc-dispatch(结果)两种独立事件。
21
+ * 不接住它们,内层调用就只剩代码文本里的一行字,谁调的、返回什么都查不到。
22
+ */
23
+
24
+ /** 用户消息里真正由用户说的那种 source.kind;其余都是系统注入。 */
25
+ const USER_KIND = 'user'
26
+
27
+ /* 工具参数不做任何压缩:日志删掉之后,回顾文件里的这份就是唯一原文。 */
28
+
29
+ /** 四个行首标记,别处也复用。 */
30
+ export const MARK = { user: '[用户] ', model: '[模型] ', call: '▸ ', result: '◂ ' }
31
+
32
+ /**
33
+ * 把工具参数摊成可读文本:换行、缩进、长度全部原样保留。
34
+ *
35
+ * 回顾文件是日志被删之后唯一的原文,所以这里不许截断、不许把空白压成空格——
36
+ * 压一次,那段命令就永久没了。
37
+ *
38
+ * 首行放主参数(下面 PICK 里的第一个),其余字段一行一个跟在后面 —— 全都要,
39
+ * 一个字段都不许丢:grep 的 pattern、write 的 content、edit 的 old_string
40
+ * 以前只因为「不是第一个命中的字段」就整段没进文件。
41
+ *
42
+ * 入参可能是 JSON 字符串(assistant/message 的 tool-call、tool/call 事件),
43
+ * 也可能已经是对象(tool/ptc-dispatch 的 arguments),两种都收。
44
+ * @param {string|object} raw
45
+ * @returns {string}
46
+ */
47
+ const PICK = ['command', 'code', 'file_path', 'pattern', 'path', 'url', 'query']
48
+
49
+ export function toolArgsText(raw) {
50
+ if (raw === undefined || raw === null) return ''
51
+ let obj
52
+ if (typeof raw === 'object') obj = raw
53
+ else if (typeof raw === 'string') { try { obj = JSON.parse(raw) } catch { obj = undefined } }
54
+ else return String(raw).replace(/\r\n/g, '\n')
55
+ if (!obj || typeof obj !== 'object' || Array.isArray(obj)) {
56
+ return String(raw).replace(/\r\n/g, '\n')
57
+ }
58
+ let key = PICK.find((k) => typeof obj[k] === 'string')
59
+ let text
60
+ if (key !== undefined) {
61
+ text = obj[key]
62
+ } else if (Array.isArray(obj.queries) && obj.queries.every((q) => typeof q === 'string')) {
63
+ key = 'queries'
64
+ text = obj.queries.join('\n')
65
+ } else {
66
+ // 一个主字段都对不上:整段带缩进的 JSON,不压成一行。
67
+ return JSON.stringify(obj, null, 2).replace(/\r\n/g, '\n')
68
+ }
69
+ const out = [String(text).replace(/\r\n/g, '\n')]
70
+ for (const [k, v] of Object.entries(obj)) {
71
+ if (k === key || v === undefined) continue
72
+ if (typeof v === 'string') {
73
+ const s = v.replace(/\r\n/g, '\n')
74
+ if (s.includes('\n')) out.push(k + ':', ...s.split('\n'))
75
+ else out.push(k + ': ' + s)
76
+ } else {
77
+ out.push(k + ': ' + JSON.stringify(v))
78
+ }
79
+ }
80
+ return out.join('\n')
81
+ }
82
+
83
+ /**
84
+ * 追加一个带行首标记的块:首行加前缀,其余行缩进两格。空文本什么也不写。
85
+ * @param {string[]} out
86
+ * @param {string} prefix
87
+ * @param {string} text
88
+ * @returns {boolean} 是否真的写了
89
+ */
90
+ function pushBlock(out, prefix, text) {
91
+ const lines = String(text ?? '').replace(/\r\n/g, '\n').split('\n')
92
+ while (lines.length > 0 && lines[lines.length - 1].trim() === '') lines.pop()
93
+ while (lines.length > 0 && lines[0].trim() === '') lines.shift()
94
+ if (lines.length === 0) return false
95
+ out.push(prefix + lines[0])
96
+ for (let i = 1; i < lines.length; i++) {
97
+ out.push(lines[i] === '' ? '' : ' ' + lines[i])
98
+ }
99
+ return true
100
+ }
101
+
102
+ /** 取内容块里的纯文本,忽略 reasoning / tool-call / 图片。 */
103
+ function textOf(blocks) {
104
+ if (!Array.isArray(blocks)) return ''
105
+ return blocks
106
+ .filter((b) => b && b.type === 'text' && typeof b.text === 'string')
107
+ .map((b) => b.text)
108
+ .join('\n')
109
+ }
110
+
111
+ /**
112
+ * 把一段会话事件渲染成原文。
113
+ * @param {Iterable<object>} events 该区间的事件,顺序即 seq 顺序
114
+ * @returns {string}
115
+ */
116
+ export function renderTranscript(events) {
117
+ const out = []
118
+ for (const event of events) {
119
+ if (!event || typeof event.type !== 'string') continue
120
+ const data = event.data ?? {}
121
+ switch (event.type) {
122
+ case 'user/message': {
123
+ // 只收用户本人说的话;agent-instructions / runtime-context /
124
+ // time-context / skill-catalog / compact-checkpoint 都是系统注入,不进原文。
125
+ if (data.source?.kind !== USER_KIND) break
126
+ pushBlock(out, MARK.user, textOf(data.content))
127
+ break
128
+ }
129
+ case 'assistant/message': {
130
+ // 按内容块原顺序走:reasoning 是草稿丢掉,text 是模型说的话,
131
+ // tool-call 是工具发起 —— 后者必须在这里取,工具事件不在 shadowedSeqs 里。
132
+ const blocks = Array.isArray(data.message?.content) ? data.message.content : []
133
+ for (const block of blocks) {
134
+ if (!block) continue
135
+ if (block.type === 'text') pushBlock(out, MARK.model, block.text)
136
+ else if (block.type === 'tool-call') {
137
+ const args = toolArgsText(block.arguments)
138
+ pushBlock(out, MARK.call, args ? String(block.name ?? '') + ': ' + args : String(block.name ?? ''))
139
+ }
140
+ }
141
+ break
142
+ }
143
+ case 'tool/call': {
144
+ // 兜底:万一某个后端把工具调用单独记成事件(而不是内容块),也接住。
145
+ // 同时存在两种记录时,assistant/message 那份总在前面,这里会重复,所以只在
146
+ // 没有 assistant 记录过的调用上生效 —— 由调用方按需传 dedupe。
147
+ const args = toolArgsText(data.arguments)
148
+ pushBlock(out, MARK.call, args ? String(data.name ?? '') + ': ' + args : String(data.name ?? ''))
149
+ break
150
+ }
151
+ case 'tool/ptc-dispatch-start': {
152
+ // PTC:代码里 tools.xxx(...) 的发起。参数在这里落一次,
153
+ // 配对的 tool/ptc-dispatch 再补结果。start 有 dispatch 无(执行中断)时也不丢参数。
154
+ const args = toolArgsText(data.arguments)
155
+ pushBlock(out, MARK.call, args ? String(data.name ?? '') + ': ' + args : String(data.name ?? ''))
156
+ break
157
+ }
158
+ case 'tool/ptc-dispatch': {
159
+ // 同一个 subCallId 的结果。发起已在 start 里写过,这里只写返回与成败。
160
+ const body = textOf(data.content)
161
+ if (body) pushBlock(out, ' ', body)
162
+ const err = data.error
163
+ if (err || data.isError) {
164
+ const reason = typeof err === 'string'
165
+ ? err
166
+ : [err?.name, err?.reason ?? err?.code].filter(Boolean).join(': ')
167
+ out.push(MARK.result + '报错:' + (reason || '未知错误'))
168
+ } else {
169
+ out.push(MARK.result + '完成')
170
+ }
171
+ break
172
+ }
173
+ case 'tool/result': {
174
+ const body = textOf(data.message?.content ?? data.content)
175
+ if (body) pushBlock(out, ' ', body)
176
+ const err = data.error
177
+ if (err) {
178
+ const reason = typeof err === 'string' ? err : [err.name, err.reason ?? err.code].filter(Boolean).join(': ')
179
+ out.push(MARK.result + '报错:' + (reason || '未知错误'))
180
+ } else {
181
+ out.push(MARK.result + '完成')
182
+ }
183
+ break
184
+ }
185
+ default:
186
+ break
187
+ }
188
+ }
189
+ return out.join('\n')
190
+ }
191
+
192
+ /**
193
+ * 只留对话(深度 3 时用):靠当前块类型判断,不逐行猜。
194
+ * 工具块、工具输出、报错整块丢弃;对话块内的续行原样保留。
195
+ * @param {string} body 原文
196
+ * @returns {string}
197
+ */
198
+ export function dialogueOnly(body) {
199
+ let kind = null
200
+ const out = []
201
+ for (const line of String(body).split('\n')) {
202
+ if (line.startsWith(MARK.user) || line.startsWith(MARK.model)) {
203
+ kind = 'say'
204
+ out.push(line)
205
+ } else if (line.startsWith(MARK.call) || line.startsWith(MARK.result)) {
206
+ kind = 'tool'
207
+ } else if (line.trim() === '') {
208
+ // 空行只是同一个块里的段落分隔,不是块的结束。
209
+ // 以前这里把 kind 清成 null,于是多段回复从第一个空行往后整段被丢掉
210
+ // (真实事故:注入里只剩「改好了,宝宝。」,后面的正文全没了)。
211
+ if (kind === 'say') out.push(line)
212
+ } else if (kind === 'say') {
213
+ out.push(line)
214
+ }
215
+ }
216
+ return out.join('\n')
217
+ }
218
+
219
+ /** 数原文里的工具调用次数与失败次数。 */
220
+ export function countTools(body) {
221
+ let calls = 0
222
+ let failures = 0
223
+ for (const line of String(body).split('\n')) {
224
+ if (line.startsWith(MARK.call)) calls++
225
+ else if (line.startsWith(MARK.result + '报错')) failures++
226
+ }
227
+ return { calls, failures }
228
+ }
@@ -0,0 +1,281 @@
1
+ /**
2
+ * 工具脚本执行(0.3.0):把一套里的某个脚本按 argv 数组跑起来。
3
+ *
4
+ * 三条硬规矩:
5
+ * 1. 不经过 shell 拼字符串 —— 参数是数组,模型给的 args 改不了命令行结构;
6
+ * 2. 只跑工具脚本目录里的文件,越界直接抛(resolveInside);
7
+ * 3. 跑之前对一遍 toolScript.json 里的 sha256,不一致就拒绝(除非调用方显式 allowDrift)。
8
+ *
9
+ * 输出:单条超过上限就溢写进 _runs/(写全量,不是写截断后的),返回前一段 + 溢写路径。
10
+ * 超时:先 SIGTERM,2 秒后 SIGKILL;Windows 上走 taskkill /T 把整棵进程树带走
11
+ * (cygwin 的 bash 会留一个 sleep 孙进程攥着管道,只杀父进程会白等到它自己结束)。
12
+ */
13
+
14
+ import { spawn } from 'node:child_process'
15
+ import fs from 'node:fs'
16
+ import path from 'node:path'
17
+ import { resolveInside, sha256OfFile, runsDir } from './schema.js'
18
+
19
+ /** 默认超时 120 秒,上限 600 秒(和 ops_bash 的上限对齐)。 */
20
+ export const DEFAULT_TIMEOUT_MS = 120000
21
+ export const MAX_TIMEOUT_MS = 600000
22
+
23
+ /** 单条输出上限 64 KB。 */
24
+ export const DEFAULT_MAX_OUTPUT = 64 * 1024
25
+
26
+ /** TERM 之后等多久再 KILL。 */
27
+ const KILL_GRACE_MS = 2000
28
+
29
+ /** 子进程退出后,等管道关闭的上限(孙进程攥着管道时不陪它等)。 */
30
+ const CLOSE_GRACE_MS = 600
31
+
32
+ /**
33
+ * 按 run 选解释器。node 用当前进程的可执行文件(不写死运行时路径),
34
+ * PowerShell 用系统自带的那个,bash 交给 PATH(找不到时由 runScript 说清楚)。
35
+ * @param {'bash'|'node'|'ps1'|'cmd'} run
36
+ * @returns {{cmd:string, args:string[]}}
37
+ */
38
+ export function interpreterOf(run) {
39
+ switch (run) {
40
+ case 'bash':
41
+ return { cmd: 'bash', args: [] }
42
+ case 'node':
43
+ return { cmd: process.execPath, args: [] }
44
+ case 'ps1': {
45
+ if (process.platform !== 'win32') return { cmd: 'pwsh', args: ['-NoProfile', '-File'] }
46
+ const root = process.env.SystemRoot || 'C:\\Windows'
47
+ return {
48
+ cmd: path.join(root, 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe'),
49
+ args: ['-NoProfile', '-ExecutionPolicy', 'Bypass', '-File']
50
+ }
51
+ }
52
+ case 'cmd': {
53
+ if (process.platform !== 'win32') return { cmd: 'sh', args: [] }
54
+ return { cmd: process.env.ComSpec || 'cmd.exe', args: ['/d', '/c'] }
55
+ }
56
+ default:
57
+ throw new Error('未知执行方式:' + String(run))
58
+ }
59
+ }
60
+
61
+ /**
62
+ * 跑一条。顺序、退出码、超时、截断都在这里收口。
63
+ * @param {object} p
64
+ * @param {string} p.dshHome
65
+ * @param {string} p.toolScriptId
66
+ * @param {string} p.dir 工具脚本目录
67
+ * @param {object} p.manifest toolScript.json 的内容
68
+ * @param {string} p.step 脚本文件名
69
+ * @param {string[]} [p.args] 脚本参数(argv,不经过 shell)
70
+ * @param {string} [p.stdin] 写进标准输入的内容(给了才写)
71
+ * @param {string} [p.cwd] 工作目录
72
+ * @param {number} [p.timeoutMs]
73
+ * @param {number} [p.maxOutputBytes]
74
+ * @param {boolean} [p.allowDrift]
75
+ * @returns {Promise<object>}
76
+ */
77
+ export async function runScript({
78
+ dshHome, toolScriptId, dir, manifest, step, args = [], stdin,
79
+ cwd, timeoutMs, maxOutputBytes, allowDrift = false
80
+ }) {
81
+ const name = String(step ?? '').trim()
82
+ const file = resolveInside(dir, name)
83
+ if (!fs.existsSync(file)) throw new Error('这个工具脚本里没有这个脚本:' + name)
84
+
85
+ const scripts = Array.isArray(manifest?.scripts) ? manifest.scripts : []
86
+ const meta = scripts.find((s) => s && s.name === name)
87
+ if (!meta) throw new Error('这个文件不在这个工具脚本的清单里:' + name)
88
+ const hashes = manifest && typeof manifest.hashes === 'object' && manifest.hashes !== null ? manifest.hashes : {}
89
+ const expected = typeof hashes[name] === 'string' ? hashes[name] : ''
90
+ const actual = sha256OfFile(file)
91
+ if (expected !== '' && expected !== actual && !allowDrift) {
92
+ throw new Error('脚本和清单里的 sha256 对不上,先不跑(' + name + ')。' +
93
+ '如果你刚手动改过它,重装这个工具脚本(session_tool_create_write + replace),或者这次显式传 allowDrift: true。')
94
+ }
95
+
96
+ const timeout = normalizeTimeout(timeoutMs === undefined ? (manifest?.timeoutMs ?? DEFAULT_TIMEOUT_MS) : timeoutMs)
97
+ const cap = normalizeMaxOutput(maxOutputBytes)
98
+ const interp = interpreterOf(meta.run)
99
+ const argv = [...interp.args, file, ...args.map((a) => String(a))]
100
+ const runCwd = cwd || path.resolve(dir)
101
+
102
+ const env = {
103
+ ...process.env,
104
+ TOOL_NAME: name,
105
+ TOOL_SCRIPT: String(toolScriptId),
106
+ TOOL_ROOT: path.resolve(dir),
107
+ DSH_HOME: String(dshHome ?? process.env.DSH_HOME ?? '')
108
+ }
109
+
110
+ const startedAt = Date.now()
111
+ const result = await spawnCollect({ cmd: interp.cmd, argv, cwd: runCwd, env, timeout, cap, stdin })
112
+ return {
113
+ toolScript: String(toolScriptId),
114
+ step: name,
115
+ run: meta.run,
116
+ argv,
117
+ cwd: runCwd,
118
+ drift: expected !== '' && expected !== actual,
119
+ durationMs: Date.now() - startedAt,
120
+ ...result
121
+ }
122
+ }
123
+
124
+ /** 时间收口:非数字给默认,越界夹到上限。 */
125
+ export function normalizeTimeout(value) {
126
+ const n = Number(value)
127
+ if (!Number.isFinite(n) || n <= 0) return DEFAULT_TIMEOUT_MS
128
+ return Math.min(Math.max(Math.trunc(n), 1000), MAX_TIMEOUT_MS)
129
+ }
130
+
131
+ /** 输出上限收口。 */
132
+ export function normalizeMaxOutput(value) {
133
+ const n = Number(value)
134
+ if (!Number.isFinite(n) || n <= 0) return DEFAULT_MAX_OUTPUT
135
+ return Math.min(Math.trunc(n), 1024 * 1024)
136
+ }
137
+
138
+ /**
139
+ * 真正跑一次子进程:收集 stdout/stderr,超上限就溢写。
140
+ * 不 resolve 成「成功」,只如实回 exitCode / signal / timedOut。
141
+ * @returns {Promise<{exitCode:number|null, signal:string|null, timedOut:boolean, stdout:string, stderr:string, truncated:boolean, spill:string}>}
142
+ */
143
+ function spawnCollect({ cmd, argv, cwd, env, timeout, cap, stdin }) {
144
+ return new Promise((resolve, reject) => {
145
+ const detached = process.platform !== 'win32'
146
+ let child
147
+ try {
148
+ child = spawn(cmd, argv, { cwd, env, windowsHide: true, stdio: ['pipe', 'pipe', 'pipe'], detached })
149
+ } catch (err) {
150
+ reject(new Error('起不来解释器 ' + cmd + ':' + (err?.message ?? err)))
151
+ return
152
+ }
153
+
154
+ const out = { stdout: [], stderr: [], bytes: 0, truncated: false }
155
+ let spillFile = ''
156
+ let spillFd = null
157
+ let killedByTimeout = false
158
+ let done = false
159
+ let exited = false
160
+ let code = null
161
+ let sig = null
162
+
163
+ // 溢写:第一次超限时把已经收到的头一段写进去,之后按到达顺序追加。
164
+ const openSpill = () => {
165
+ if (spillFile !== '') return
166
+ try {
167
+ const dir = runsDir(env.DSH_HOME || '')
168
+ fs.mkdirSync(dir, { recursive: true })
169
+ spillFile = path.join(dir, Date.now() + '-' + String(env.TOOL_SCRIPT || 'toolScript') + '-' +
170
+ String(env.TOOL_NAME || 'step') + '.log')
171
+ spillFd = fs.openSync(spillFile, 'w')
172
+ if (out.stdout.length > 0) fs.writeSync(spillFd, Buffer.concat(out.stdout))
173
+ fs.writeSync(spillFd, '\n----- stderr -----\n')
174
+ if (out.stderr.length > 0) fs.writeSync(spillFd, Buffer.concat(out.stderr))
175
+ fs.writeSync(spillFd, '\n----- 之后的内容按到达顺序 -----\n')
176
+ } catch {
177
+ spillFile = ''
178
+ spillFd = null
179
+ }
180
+ }
181
+
182
+ const take = (which, chunk) => {
183
+ if (spillFd !== null) {
184
+ try { fs.writeSync(spillFd, chunk) } catch { /* 盘满之类:算了,返回值还在 */ }
185
+ return
186
+ }
187
+ if (out.truncated) return
188
+ const room = cap - out.bytes
189
+ if (chunk.length <= room) {
190
+ out[which].push(chunk)
191
+ out.bytes += chunk.length
192
+ return
193
+ }
194
+ if (room > 0) out[which].push(chunk.subarray(0, room))
195
+ out.bytes = cap
196
+ out.truncated = true
197
+ openSpill()
198
+ const rest = room > 0 ? chunk.subarray(room) : chunk
199
+ if (spillFd !== null) {
200
+ try { fs.writeSync(spillFd, rest) } catch { /* 同上 */ }
201
+ }
202
+ }
203
+
204
+ const killTree = (signal) => {
205
+ if (!child.pid) return
206
+ try {
207
+ if (process.platform === 'win32') {
208
+ const k = spawn('taskkill', ['/pid', String(child.pid), '/T', '/F'], { windowsHide: true, stdio: 'ignore' })
209
+ k.on('error', () => {})
210
+ } else if (detached) {
211
+ try { process.kill(-child.pid, signal) } catch { child.kill(signal) }
212
+ } else {
213
+ child.kill(signal)
214
+ }
215
+ } catch { /* 进程已经没了 */ }
216
+ }
217
+
218
+ const timer = setTimeout(() => {
219
+ killedByTimeout = true
220
+ killTree('SIGTERM')
221
+ const graceTimer = setTimeout(() => killTree('SIGKILL'), KILL_GRACE_MS)
222
+ if (typeof graceTimer.unref === 'function') graceTimer.unref()
223
+ }, timeout)
224
+
225
+ const finish = () => {
226
+ if (done) return
227
+ done = true
228
+ clearTimeout(timer)
229
+ if (spillFd !== null) {
230
+ try { fs.closeSync(spillFd) } catch { /* 已经关了 */ }
231
+ spillFd = null
232
+ }
233
+ const stdout = Buffer.concat(out.stdout).toString('utf8')
234
+ const stderr = Buffer.concat(out.stderr).toString('utf8')
235
+ resolve({
236
+ exitCode: typeof code === 'number' ? code : null,
237
+ signal: sig ?? null,
238
+ timedOut: killedByTimeout,
239
+ stdout: out.truncated
240
+ ? stdout + '\n[输出超过单条上限(' + cap + ' 字节),完整内容在 ' + (spillFile || '(溢写失败,已丢)') + ']'
241
+ : stdout,
242
+ stderr,
243
+ truncated: out.truncated,
244
+ spill: spillFile
245
+ })
246
+ }
247
+
248
+ child.stdout?.on('data', (c) => take('stdout', c))
249
+ child.stderr?.on('data', (c) => take('stderr', c))
250
+
251
+ child.on('error', (err) => {
252
+ if (done) return
253
+ done = true
254
+ clearTimeout(timer)
255
+ if (spillFd !== null) { try { fs.closeSync(spillFd) } catch { /* 忽略 */ } }
256
+ const message = err && err.code === 'ENOENT'
257
+ ? '找不到解释器:' + cmd + (cmd === 'bash' ? '(这个工具脚本用 bash 写的;这台机器上 bash 不在 PATH 里,改写 node 脚本或先装 bash)' : '')
258
+ : '起不来:' + (err?.message ?? err)
259
+ reject(new Error(message))
260
+ })
261
+
262
+ // 子进程自己退了:最多再等 CLOSE_GRACE_MS 让管道收完,孙进程攥着管道也不陪它等。
263
+ child.on('exit', (c, s) => {
264
+ code = c
265
+ sig = s
266
+ exited = true
267
+ const finalTimer = setTimeout(finish, CLOSE_GRACE_MS)
268
+ if (typeof finalTimer.unref === 'function') finalTimer.unref()
269
+ })
270
+ child.on('close', (c, s) => {
271
+ if (!exited) { code = c; sig = s }
272
+ finish()
273
+ })
274
+
275
+ if (stdin !== undefined && stdin !== null) {
276
+ try { child.stdin?.end(String(stdin)) } catch { /* 子进程可能不看 stdin */ }
277
+ } else {
278
+ try { child.stdin?.end() } catch { /* 同上 */ }
279
+ }
280
+ })
281
+ }