run.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  1. /**
  2. * Process plumbing for the local bash executor: detached process-group spawn,
  3. * tail-keep output with spill files, and SIGTERM→SIGKILL escalation. This layer
  4. * reacts to an abort signal; the executor owns deadlines and classifies causes.
  5. * @module dsh-bash-local/run
  6. */
  7. import { type ChildProcessByStdio, spawn } from 'node:child_process'
  8. import type { Readable, Writable } from 'node:stream'
  9. import { randomBytes } from 'node:crypto'
  10. import { closeSync, mkdtempSync, openSync, writeSync } from 'node:fs'
  11. import { tmpdir } from 'node:os'
  12. import { join } from 'node:path'
  13. import type { CollectedOutput } from '@deepseek-ai/dsh-bash'
  14. /**
  15. * Model-friendly environment overrides: disable colors, pagers, and
  16. * interactive terminal features that would garble tool output (the same set
  17. * Codex hardcodes; Claude Code achieves it via TERM=dumb).
  18. */
  19. export const ENV_OVERRIDES = {
  20. NO_COLOR: '1',
  21. TERM: 'dumb',
  22. PAGER: 'cat',
  23. GIT_PAGER: 'cat',
  24. } as const
  25. /**
  26. * Credential-shaped env vars are NOT forwarded to commands (the harness's
  27. * own DEEPSEEK_API_KEY must not leak into `env` output, tool results, or
  28. * spill files). Same default pattern as Codex's env policy; a future config
  29. * can whitelist specific vars when a workflow genuinely needs one.
  30. */
  31. export const SENSITIVE_ENV_PATTERN = /KEY|SECRET|TOKEN/i
  32. /**
  33. * Build a child environment by scrubbing credential-shaped ambient variables,
  34. * applying model-friendly overrides, then merging trusted caller entries last.
  35. *
  36. * @param extra - caller-supplied entries merged last; an explicit entry wins even against the scrub and the overrides.
  37. * @returns the environment to hand to `spawn` for the child process.
  38. */
  39. export function childEnv(extra?: Record<string, string>): NodeJS.ProcessEnv {
  40. const env: NodeJS.ProcessEnv = {}
  41. for (const [key, value] of Object.entries(process.env)) {
  42. if (!SENSITIVE_ENV_PATTERN.test(key)) env[key] = value
  43. }
  44. return { ...env, ...ENV_OVERRIDES, ...extra }
  45. }
  46. /** What to run and under which limits (resolved — no defaults in here). */
  47. export interface SpawnSpec {
  48. command: string
  49. cwd: string
  50. /** Stdout in-memory cap; overflow spills to disk (tail kept in memory). */
  51. stdoutMaxBytes: number
  52. /** Stderr in-memory cap; overflow spills to disk (tail kept in memory). */
  53. stderrMaxBytes: number
  54. /** Grace period between the SIGTERM and the SIGKILL escalation on a kill. */
  55. graceMs: number
  56. /**
  57. * Abort signal — kills the process group when it fires. The executor owns
  58. * timing: `run()` passes a fused timeout/cancel deadline signal (see
  59. * `@deepseek-ai/dsh-timeout`), `start()` passes the bare upstream signal.
  60. * runBash only listens and kills; it does NOT classify why (the executor
  61. * reads the signal's reason afterward).
  62. */
  63. signal?: AbortSignal | undefined
  64. /**
  65. * Bytes to write to the child's stdin, then close it. Absent (or empty)
  66. * leaves stdin closed/empty. Set by in-process plugins (the hooks bridges);
  67. * the model-facing `dsh-tool-bash` tool does not thread model input here.
  68. */
  69. stdin?: string | undefined
  70. /**
  71. * Extra environment entries, merged onto the scrubbed env AFTER the
  72. * credential scrub and the model-friendly overrides (so an explicit entry
  73. * wins). Set by in-process plugins; the model-facing tool does not forward
  74. * model input here.
  75. */
  76. env?: Record<string, string> | undefined
  77. }
  78. /**
  79. * Raw outcome of one closed process (before result shaping). Deliberately
  80. * carries NO timeout/cancel classification: runBash kills on abort but does not
  81. * decide why — the executor's `run()`/`start()` reads the deadline signal it
  82. * owns to classify `timedOut`/`aborted` (see the package README).
  83. */
  84. export interface SpawnOutcome {
  85. exitCode: number | null
  86. signal: NodeJS.Signals | null
  87. stdout: CollectedOutput
  88. stderr: CollectedOutput
  89. }
  90. /** Injectable knobs so tests can exercise spill behavior without the OS tmpdir. */
  91. export interface RunInternals {
  92. /** Directory for spill files (defaults to the OS temp dir). */
  93. spillDir?: string
  94. }
  95. /** Default SIGTERM→SIGKILL grace period (the `graceMs` config; matches OpenCode's 3s). */
  96. export const DEFAULT_GRACE_MS = 3_000
  97. let spillCounter = 0
  98. let defaultSpillDir: string | undefined
  99. /**
  100. * The default spill location: a private (0700) per-process directory under
  101. * the OS tmpdir, created lazily. Predictable world-readable paths would let
  102. * other local users read command output or pre-create symlinks.
  103. */
  104. function privateSpillDir(): string {
  105. defaultSpillDir ??= mkdtempSync(join(tmpdir(), 'dsh-bash-'))
  106. return defaultSpillDir
  107. }
  108. /**
  109. * Collects one stream with a bounded in-memory tail. The FULL stream is
  110. * always recoverable: on first overflow a spill file is created and every
  111. * chunk (including those already collected) is appended there.
  112. *
  113. * Tail-keep rationale (pi/OpenCode): errors and final results cluster at the
  114. * end of command output; the spill file covers the head.
  115. */
  116. export class OutputCollector {
  117. private chunks: Buffer[] = []
  118. private bytes = 0
  119. private dropped = false
  120. private spillFd: number | undefined
  121. private spillFile: string | undefined
  122. /** Total bytes ever pushed (not just retained). */
  123. private total = 0
  124. constructor(
  125. private readonly maxBytes: number,
  126. private readonly label: string,
  127. private readonly spillDir: string,
  128. ) {}
  129. /**
  130. * Ingest one stream chunk, counting it toward the whole-stream total. On
  131. * first overflow of the in-memory cap a spill file is opened and every chunk
  132. * (already-collected ones included) is appended there from then on; the
  133. * in-memory tail then drops whole chunks from its head (or the head of a
  134. * single over-cap chunk) until it fits the cap again.
  135. * @param chunk - the raw bytes from one stream 'data' event.
  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. /**
  175. * Incremental read in whole-stream byte coordinates: returns everything
  176. * pushed since `fromByte`. When `fromByte` has already slid out of the
  177. * in-memory tail window, the read is `lossy` — it returns the whole
  178. * retained tail and the gap is only recoverable from the spill file.
  179. * @param fromByte - whole-stream offset to resume from (a prior read's `nextOffset`; 0 for the first read).
  180. * @returns the delta text, the offset for the next read, the `lossy` flag, and the spill path when one was created.
  181. */
  182. readFrom(fromByte: number): { text: string; nextOffset: number; lossy: boolean; spillPath?: string } {
  183. const windowStart = this.total - this.bytes
  184. const buffer = Buffer.concat(this.chunks)
  185. const lossy = fromByte < windowStart
  186. const slice = lossy ? buffer : buffer.subarray(fromByte - windowStart)
  187. return {
  188. text: slice.toString('utf8'),
  189. nextOffset: this.total,
  190. lossy,
  191. ...this.spillFile !== undefined ? { spillPath: this.spillFile } : {},
  192. }
  193. }
  194. /**
  195. * Close the spill file (if any) and return the final output. A failed close
  196. * (delayed writeback fault) stops advertising the spill path — the file may
  197. * be missing its tail — but still returns the in-memory result.
  198. * @returns the final collected output: tail text, truncation flag, and the spill path when intact.
  199. */
  200. finalize(): CollectedOutput {
  201. if (this.spillFd !== undefined) {
  202. try {
  203. closeSync(this.spillFd)
  204. } catch {
  205. // A delayed writeback failure makes the spill unreliable; keep finalize
  206. // total but stop advertising that file.
  207. this.spillFile = undefined
  208. }
  209. this.spillFd = undefined
  210. }
  211. return {
  212. text: Buffer.concat(this.chunks).toString('utf8'),
  213. truncated: this.dropped,
  214. ...this.spillFile !== undefined ? { spillPath: this.spillFile } : {},
  215. }
  216. }
  217. }
  218. /**
  219. * Send `sig` to a detached process group. Never throws: delivery races process
  220. * exit and may run in a timer callback, so failures are contained and a
  221. * non-positive pid is a no-op.
  222. * @param pid - the group leader's pid; non-positive means the spawn failed and the call is a no-op.
  223. * @param sig - the signal to deliver to the whole group.
  224. */
  225. export function killGroup(pid: number, sig: NodeJS.Signals): void {
  226. if (pid <= 0) return
  227. try {
  228. process.kill(-pid, sig)
  229. } catch {
  230. // Swallow: see contract above.
  231. }
  232. }
  233. /**
  234. * A live bash child process: the promise resolves when the process closes;
  235. * `kill()` starts the SIGTERM→grace→SIGKILL escalation on its group.
  236. */
  237. export interface RunningBash {
  238. /** Process id (group leader); -1 when the spawn itself failed. */
  239. readonly pid: number
  240. /** stdout/stderr collectors (live — background polling reads incrementally). */
  241. readonly stdout: OutputCollector
  242. readonly stderr: OutputCollector
  243. /** Resolves when the process closes; rejects only for spawn-level failures. */
  244. readonly done: Promise<SpawnOutcome>
  245. /** Begin SIGTERM→grace→SIGKILL on the process group. Idempotent. */
  246. kill(): void
  247. }
  248. /**
  249. * Spawn one isolated `bash -c` process group and collect its output.
  250. * Runtime exits resolve as {@link SpawnOutcome}; only spawn failures reject.
  251. * @param spec - fully resolved command, cwd, limits, and cancellation.
  252. * @param internals - test-only process and spill-directory overrides.
  253. * @returns live process handle and outcome promise.
  254. */
  255. // XXX(stateful-shell): evaluate persistent cwd or PTY sessions when workflows require shell state.
  256. export function runBash(spec: SpawnSpec, internals: RunInternals = {}): RunningBash {
  257. const spillDir = internals.spillDir ?? privateSpillDir()
  258. if (spec.signal?.aborted) {
  259. throw new Error(`aborted before spawn: ${String(spec.signal.reason ?? 'aborted')}`)
  260. }
  261. // Keep absent stdin as /dev/null; literal tuples preserve non-null output types.
  262. const env = childEnv(spec.env)
  263. const child: ChildProcessByStdio<Writable | null, Readable, Readable> = spec.stdin !== undefined
  264. ? spawn('bash', ['-c', spec.command], { cwd: spec.cwd, env, stdio: ['pipe', 'pipe', 'pipe'], detached: true })
  265. : spawn('bash', ['-c', spec.command], { cwd: spec.cwd, env, stdio: ['ignore', 'pipe', 'pipe'], detached: true })
  266. const stdout = new OutputCollector(spec.stdoutMaxBytes, 'stdout', spillDir)
  267. const stderr = new OutputCollector(spec.stderrMaxBytes, 'stderr', spillDir)
  268. child.stdout.on('data', (chunk: Buffer) => { stdout.push(chunk) })
  269. child.stderr.on('data', (chunk: Buffer) => { stderr.push(chunk) })
  270. let graceTimer: NodeJS.Timeout | undefined
  271. // Failed spawns use pid -1 so kill remains a no-op.
  272. const pid = child.pid ?? -1
  273. const kill = (): void => {
  274. if (graceTimer !== undefined) return // escalation already in flight
  275. killGroup(pid, 'SIGTERM')
  276. graceTimer = setTimeout(() => { killGroup(pid, 'SIGKILL') }, spec.graceMs)
  277. }
  278. // The executor owns timeout classification; this layer only reacts to abort.
  279. const onAbort = (): void => { kill() }
  280. spec.signal?.addEventListener('abort', onAbort, { once: true })
  281. // Stdin writes are best-effort; process exit and captured output remain authoritative.
  282. if (child.stdin !== null) {
  283. child.stdin.on('error', () => { /* stdin write is best-effort; outcome rides on exit/output. */ })
  284. child.stdin.end(spec.stdin)
  285. }
  286. const done = new Promise<SpawnOutcome>((resolve, reject) => {
  287. child.on('error', (error) => {
  288. // No meaningful close outcome follows a spawn failure.
  289. cleanup()
  290. reject(error)
  291. })
  292. child.on('close', (exitCode, signal) => {
  293. cleanup()
  294. resolve({
  295. exitCode,
  296. signal,
  297. stdout: stdout.finalize(),
  298. stderr: stderr.finalize(),
  299. })
  300. })
  301. function cleanup(): void {
  302. if (graceTimer !== undefined) clearTimeout(graceTimer)
  303. spec.signal?.removeEventListener('abort', onAbort)
  304. }
  305. })
  306. return { pid, stdout, stderr, done, kill }
  307. }