run.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  1. /**
  2. * Process plumbing for the local bash executor: spawn, output collection
  3. * with tail-keep + spill-to-disk truncation, and process-group kill with
  4. * SIGTERM→SIGKILL escalation.
  5. *
  6. * Everything here is deliberately free of Cordis concepts so it can be unit
  7. * tested in isolation; `LocalBashExecutor` owns lifecycle and configuration.
  8. *
  9. * Design notes (surveyed against Claude Code, OpenCode, Codex, and pi — see
  10. * the package README): spawn-per-call with `detached: true` so the child
  11. * leads its own process group; kills target the group (`kill(-pid)`) so
  12. * pipelines and subshells die with the parent. SIGTERM first, SIGKILL after a
  13. * grace period (OpenCode's escalation; Codex/pi jump straight to SIGKILL).
  14. *
  15. * @module dsh-bash-local/run
  16. */
  17. import { type ChildProcessByStdio, spawn } from 'node:child_process'
  18. import type { Readable, Writable } from 'node:stream'
  19. import { randomBytes } from 'node:crypto'
  20. import { closeSync, mkdtempSync, openSync, writeSync } from 'node:fs'
  21. import { tmpdir } from 'node:os'
  22. import { join } from 'node:path'
  23. import type { CollectedOutput } from '@deepseek-ai/dsh-bash'
  24. /**
  25. * Model-friendly environment overrides: disable colors, pagers, and
  26. * interactive terminal features that would garble tool output (the same set
  27. * Codex hardcodes; Claude Code achieves it via TERM=dumb).
  28. */
  29. export const ENV_OVERRIDES = {
  30. NO_COLOR: '1',
  31. TERM: 'dumb',
  32. PAGER: 'cat',
  33. GIT_PAGER: 'cat',
  34. } as const
  35. /**
  36. * Credential-shaped env vars are NOT forwarded to commands (the harness's
  37. * own DEEPSEEK_API_KEY must not leak into `env` output, tool results, or
  38. * spill files). Same default pattern as Codex's env policy; a future config
  39. * can whitelist specific vars when a workflow genuinely needs one.
  40. */
  41. export const SENSITIVE_ENV_PATTERN = /KEY|SECRET|TOKEN/i
  42. /**
  43. * `process.env` minus credential-shaped vars, plus the model-friendly
  44. * overrides, plus any caller-supplied `extra` entries.
  45. *
  46. * Layering matters: the scrub drops `process.env` credentials, then
  47. * `ENV_OVERRIDES` forces the model-friendly terminal vars, then `extra` is
  48. * merged LAST so an explicit caller entry wins even when its name matches the
  49. * scrub pattern (the scrub is the control that stops the HARNESS's ambient
  50. * credentials leaking into a spawned command; a caller that explicitly sets a
  51. * var named a value it already holds, not that ambient secret). `extra` is set
  52. * by in-process plugins (the hooks bridges), not the model — `dsh-tool-bash`
  53. * builds its request from named fields only and does not forward model input
  54. * here (see its README, § "The tool builds its request from named args only").
  55. */
  56. export function childEnv(extra?: Record<string, string>): NodeJS.ProcessEnv {
  57. const env: NodeJS.ProcessEnv = {}
  58. for (const [key, value] of Object.entries(process.env)) {
  59. if (!SENSITIVE_ENV_PATTERN.test(key)) env[key] = value
  60. }
  61. return { ...env, ...ENV_OVERRIDES, ...extra }
  62. }
  63. /** What to run and under which limits (resolved — no defaults in here). */
  64. export interface SpawnSpec {
  65. command: string
  66. cwd: string
  67. /** Kill the process group after this many milliseconds. 0 = no timeout. */
  68. timeoutMs: number
  69. /** Per-stream in-memory cap; overflow spills to disk (tail kept in memory). */
  70. maxOutputBytes: number
  71. /** Grace period between the SIGTERM and the SIGKILL escalation on a kill. */
  72. graceMs: number
  73. /** Abort signal — kills the process group when fired. */
  74. signal?: AbortSignal | undefined
  75. /**
  76. * Bytes to write to the child's stdin, then close it. Absent (or empty)
  77. * leaves stdin closed/empty. Set by in-process plugins (the hooks bridges);
  78. * the model-facing `dsh-tool-bash` tool does not thread model input here.
  79. */
  80. stdin?: string | undefined
  81. /**
  82. * Extra environment entries, merged onto the scrubbed env AFTER the
  83. * credential scrub and the model-friendly overrides (so an explicit entry
  84. * wins). Set by in-process plugins; the model-facing tool does not forward
  85. * model input here.
  86. */
  87. env?: Record<string, string> | undefined
  88. }
  89. /** Raw outcome of one closed process (before result shaping). */
  90. export interface SpawnOutcome {
  91. exitCode: number | null
  92. signal: NodeJS.Signals | null
  93. timedOut: boolean
  94. aborted: boolean
  95. stdout: CollectedOutput
  96. stderr: CollectedOutput
  97. }
  98. /** Injectable knobs so tests can exercise spill behavior without the OS tmpdir. */
  99. export interface RunInternals {
  100. /** Directory for spill files (defaults to the OS temp dir). */
  101. spillDir?: string
  102. }
  103. /** Default SIGTERM→SIGKILL grace period (the `graceMs` config; matches OpenCode's 3s). */
  104. export const DEFAULT_GRACE_MS = 3_000
  105. let spillCounter = 0
  106. let defaultSpillDir: string | undefined
  107. /**
  108. * The default spill location: a private (0700) per-process directory under
  109. * the OS tmpdir, created lazily. Predictable world-readable paths would let
  110. * other local users read command output or pre-create symlinks.
  111. */
  112. function privateSpillDir(): string {
  113. defaultSpillDir ??= mkdtempSync(join(tmpdir(), 'dsh-bash-'))
  114. return defaultSpillDir
  115. }
  116. /**
  117. * Collects one stream with a bounded in-memory tail. The FULL stream is
  118. * always recoverable: on first overflow a spill file is created and every
  119. * chunk (including those already collected) is appended there.
  120. *
  121. * Tail-keep rationale (pi/OpenCode): errors and final results cluster at the
  122. * end of command output; the spill file covers the head.
  123. */
  124. export class OutputCollector {
  125. private chunks: Buffer[] = []
  126. private bytes = 0
  127. private dropped = false
  128. private spillFd: number | undefined
  129. private spillFile: string | undefined
  130. /** Total bytes ever pushed (not just retained). */
  131. private total = 0
  132. constructor(
  133. private readonly maxBytes: number,
  134. private readonly label: string,
  135. private readonly spillDir: string,
  136. ) {}
  137. push(chunk: Buffer): void {
  138. this.total += chunk.length
  139. const overflows = this.bytes + chunk.length > this.maxBytes
  140. if (overflows || this.spillFd !== undefined) this.spillAll(chunk)
  141. this.chunks.push(chunk)
  142. this.bytes += chunk.length
  143. while (this.bytes > this.maxBytes && this.chunks.length > 1) {
  144. // Drop whole chunks from the head; pipe chunks are small (≤64KiB), so
  145. // the retained tail tracks the cap closely enough for a model-facing
  146. // truncation boundary. (length > 1 was just checked — shift() returns.)
  147. const head = this.chunks.shift() as Buffer
  148. this.bytes -= head.length
  149. this.dropped = true
  150. }
  151. if (this.bytes > this.maxBytes && this.chunks.length === 1) {
  152. // A single chunk larger than the cap: keep its tail.
  153. const only = this.chunks[0] as Buffer
  154. this.chunks[0] = only.subarray(only.length - this.maxBytes)
  155. this.bytes = this.maxBytes
  156. this.dropped = true
  157. }
  158. }
  159. /** Open the spill file lazily and append `chunk` (and any prior chunks once). */
  160. private spillAll(chunk: Buffer): void {
  161. if (this.spillFd === undefined) {
  162. // Random suffix + O_EXCL + no-follow-equivalent ('wx' fails on any
  163. // existing path, symlink or not) + owner-only mode: defeats spill-path
  164. // prediction and symlink planting in shared tmp dirs.
  165. this.spillFile = join(
  166. this.spillDir,
  167. `dsh-bash-${process.pid}-${++spillCounter}-${randomBytes(6).toString('hex')}-${this.label}.log`,
  168. )
  169. this.spillFd = openSync(this.spillFile, 'wx', 0o600)
  170. for (const prior of this.chunks) writeSync(this.spillFd, prior)
  171. }
  172. writeSync(this.spillFd, chunk)
  173. }
  174. // TODO(snapshot-scope): `snapshot()` has one internal caller (`finalize()` at
  175. // the bottom of this file) and `totalBytes` is read only by a test. The live
  176. // background-poll path goes through `readFrom()`, so inline snapshot() into
  177. // finalize() and drop or privatize the totalBytes getter.
  178. /** Read the collected tail without finalizing (the final-result snapshot). */
  179. snapshot(): CollectedOutput {
  180. return {
  181. text: Buffer.concat(this.chunks).toString('utf8'),
  182. truncated: this.dropped,
  183. ...this.spillFile !== undefined ? { spillPath: this.spillFile } : {},
  184. }
  185. }
  186. /** Total bytes ever pushed (including bytes dropped from memory). */
  187. get totalBytes(): number {
  188. return this.total
  189. }
  190. /**
  191. * Incremental read in whole-stream byte coordinates: returns everything
  192. * pushed since `fromByte`. When `fromByte` has already slid out of the
  193. * in-memory tail window, the read is `lossy` — it returns the whole
  194. * retained tail and the gap is only recoverable from the spill file.
  195. */
  196. readFrom(fromByte: number): { text: string; nextOffset: number; lossy: boolean; spillPath?: string } {
  197. const windowStart = this.total - this.bytes
  198. const buffer = Buffer.concat(this.chunks)
  199. const lossy = fromByte < windowStart
  200. const slice = lossy ? buffer : buffer.subarray(fromByte - windowStart)
  201. return {
  202. text: slice.toString('utf8'),
  203. nextOffset: this.total,
  204. lossy,
  205. ...this.spillFile !== undefined ? { spillPath: this.spillFile } : {},
  206. }
  207. }
  208. /** Close the spill file (if any) and return the final output. */
  209. finalize(): CollectedOutput {
  210. if (this.spillFd !== undefined) {
  211. try {
  212. closeSync(this.spillFd)
  213. } catch {
  214. // close can surface delayed writeback failures (for example EIO/ENOSPC)
  215. // after writeSync appeared to succeed. Keep finalize total so runBash's
  216. // close handler still resolves, but stop advertising a spill file that
  217. // may be missing its tail.
  218. this.spillFile = undefined
  219. }
  220. this.spillFd = undefined
  221. }
  222. return this.snapshot()
  223. }
  224. }
  225. /**
  226. * Send `sig` to the process GROUP led by `pid` (requires the child to have
  227. * been spawned with `detached: true`). NEVER throws: kills race process exit
  228. * by design (ESRCH), and the other failure modes (EPERM from setuid
  229. * children, …) fire inside timer callbacks where a throw would crash the
  230. * host process — a kill that cannot be delivered is reported by the process
  231. * NOT dying, which callers already handle via escalation/timeouts. No-op for
  232. * non-positive pids (spawn never started a process).
  233. */
  234. export function killGroup(pid: number, sig: NodeJS.Signals): void {
  235. if (pid <= 0) return
  236. try {
  237. process.kill(-pid, sig)
  238. } catch {
  239. // Swallow: see contract above.
  240. }
  241. }
  242. /**
  243. * A live bash child process: the promise resolves when the process closes;
  244. * `kill()` starts the SIGTERM→grace→SIGKILL escalation on its group.
  245. */
  246. export interface RunningBash {
  247. /** Process id (group leader); -1 when the spawn itself failed. */
  248. readonly pid: number
  249. /** stdout/stderr collectors (live — background polling reads incrementally). */
  250. readonly stdout: OutputCollector
  251. readonly stderr: OutputCollector
  252. /** Resolves when the process closes; rejects only for spawn-level failures. */
  253. readonly done: Promise<SpawnOutcome>
  254. /** Begin SIGTERM→grace→SIGKILL on the process group. Idempotent. */
  255. kill(): void
  256. }
  257. /**
  258. * Spawn `bash -c <command>` in its own process group and collect output.
  259. *
  260. * Outcome semantics: the returned promise REJECTS only for spawn-level
  261. * failures (bad cwd → ENOENT, missing binary, pre-aborted signal); every
  262. * runtime outcome — nonzero exit, timeout kill, abort kill, signal death —
  263. * RESOLVES with a {@link SpawnOutcome} describing what happened, so callers
  264. * shape one consistent report for the model.
  265. *
  266. * XXX(stateful-shell): per the agent-tool survey there are two proven
  267. * stateful designs worth revisiting — Claude Code persists ONLY cwd between
  268. * calls (captures `pwd -P` after each command), and Codex keeps whole PTY
  269. * exec sessions addressable via session ids + stdin writes. We deliberately
  270. * spawn a fresh non-login `bash -c` per call for determinism (no rc files,
  271. * no inherited shell state); revisit when real workflows demand it.
  272. */
  273. export function runBash(spec: SpawnSpec, internals: RunInternals = {}): RunningBash {
  274. const spillDir = internals.spillDir ?? privateSpillDir()
  275. if (spec.signal?.aborted) {
  276. throw new Error(`aborted before spawn: ${String(spec.signal.reason ?? 'aborted')}`)
  277. }
  278. // stdin is a pipe ONLY when the caller supplied bytes; with none it is `ignore`
  279. // (fd 0 → /dev/null) — the exact pre-seam default. This matters: a spawn pipe
  280. // and /dev/null are NOT observationally identical (node's pipe is an AF_UNIX
  281. // socket, so a command that probes stdin's type — `test -c /dev/stdin`, `stat
  282. // /proc/self/fd/0` — sees a char device vs a socket), so the no-stdin path
  283. // (every model-driven call) must keep /dev/null rather than regress to a socket.
  284. // Two LITERAL `stdio` tuples (not one variable tuple): only a literal lets the
  285. // typed `spawn` overload infer non-null stdout/stderr, which the
  286. // `ChildProcessByStdio` annotation captures (stdin `Writable | null`; stdout/
  287. // stderr the non-null `Readable` the collectors attach to without a cast).
  288. const env = childEnv(spec.env)
  289. const child: ChildProcessByStdio<Writable | null, Readable, Readable> = spec.stdin !== undefined
  290. ? spawn('bash', ['-c', spec.command], { cwd: spec.cwd, env, stdio: ['pipe', 'pipe', 'pipe'], detached: true })
  291. : spawn('bash', ['-c', spec.command], { cwd: spec.cwd, env, stdio: ['ignore', 'pipe', 'pipe'], detached: true })
  292. const stdout = new OutputCollector(spec.maxOutputBytes, 'stdout', spillDir)
  293. const stderr = new OutputCollector(spec.maxOutputBytes, 'stderr', spillDir)
  294. child.stdout.on('data', (chunk: Buffer) => { stdout.push(chunk) })
  295. child.stderr.on('data', (chunk: Buffer) => { stderr.push(chunk) })
  296. let timedOut = false
  297. let aborted = false
  298. let killTimer: NodeJS.Timeout | undefined
  299. let graceTimer: NodeJS.Timeout | undefined
  300. // pid is undefined when the spawn itself fails (bad cwd, missing binary);
  301. // the 'error' handler rejects `done` and kills become no-ops via pid -1.
  302. const pid = child.pid ?? -1
  303. const kill = (): void => {
  304. if (graceTimer !== undefined) return // escalation already in flight
  305. killGroup(pid, 'SIGTERM')
  306. graceTimer = setTimeout(() => { killGroup(pid, 'SIGKILL') }, spec.graceMs)
  307. }
  308. if (spec.timeoutMs > 0) {
  309. killTimer = setTimeout(() => {
  310. timedOut = true
  311. kill()
  312. }, spec.timeoutMs)
  313. }
  314. const onAbort = (): void => {
  315. aborted = true
  316. kill()
  317. }
  318. spec.signal?.addEventListener('abort', onAbort, { once: true })
  319. // Write stdin and close it, but ONLY when the caller supplied bytes — with no
  320. // stdin, fd 0 is `ignore` (/dev/null) and `child.stdin` is null. The error
  321. // handler must exist whenever we write: an unhandled 'error' on the stream
  322. // would throw and crash the host. We swallow the error rather than reject
  323. // `done`, and that is correct for ANY stdin-write error, not just the common
  324. // one — the stdin write is BEST-EFFORT, while the command's authoritative
  325. // outcome is its exit code + captured output, which the `close` handler reports
  326. // regardless of whether the write landed. The expected case is EPIPE (the child
  327. // exited without reading, so closing our end of a still-full pipe fails); a rare
  328. // non-EPIPE pipe fault means the command ran with incomplete stdin, and it
  329. // surfaces that itself through its own exit/output (e.g. a hook that gets
  330. // truncated JSON errors out) — rejecting here would instead discard that real
  331. // output and turn it into an opaque infrastructure error, which is worse.
  332. if (child.stdin !== null) {
  333. child.stdin.on('error', () => { /* stdin write is best-effort; outcome rides on exit/output. */ })
  334. child.stdin.end(spec.stdin)
  335. }
  336. const done = new Promise<SpawnOutcome>((resolve, reject) => {
  337. child.on('error', (error) => {
  338. // Spawn-level failure (ENOENT cwd, EACCES, …): no close event with
  339. // meaningful output follows; clean up and reject.
  340. cleanup()
  341. reject(error)
  342. })
  343. child.on('close', (exitCode, signal) => {
  344. cleanup()
  345. resolve({
  346. exitCode,
  347. signal,
  348. timedOut,
  349. aborted,
  350. stdout: stdout.finalize(),
  351. stderr: stderr.finalize(),
  352. })
  353. })
  354. function cleanup(): void {
  355. if (killTimer !== undefined) clearTimeout(killTimer)
  356. if (graceTimer !== undefined) clearTimeout(graceTimer)
  357. spec.signal?.removeEventListener('abort', onAbort)
  358. }
  359. })
  360. return { pid, stdout, stderr, done, kill }
  361. }