run.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  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. /** Per-stream in-memory cap; overflow spills to disk (tail kept in memory). */
  51. maxOutputBytes: number
  52. /** Grace period between the SIGTERM and the SIGKILL escalation on a kill. */
  53. graceMs: number
  54. /**
  55. * Abort signal — kills the process group when it fires. The executor owns
  56. * timing: `run()` passes a fused timeout/cancel deadline signal (see
  57. * `@deepseek-ai/dsh-timeout`), `start()` passes the bare upstream signal.
  58. * runBash only listens and kills; it does NOT classify why (the executor
  59. * reads the signal's reason afterward).
  60. */
  61. signal?: AbortSignal | undefined
  62. /**
  63. * Bytes to write to the child's stdin, then close it. Absent (or empty)
  64. * leaves stdin closed/empty. Set by in-process plugins (the hooks bridges);
  65. * the model-facing `dsh-tool-bash` tool does not thread model input here.
  66. */
  67. stdin?: string | undefined
  68. /**
  69. * Extra environment entries, merged onto the scrubbed env AFTER the
  70. * credential scrub and the model-friendly overrides (so an explicit entry
  71. * wins). Set by in-process plugins; the model-facing tool does not forward
  72. * model input here.
  73. */
  74. env?: Record<string, string> | undefined
  75. }
  76. /**
  77. * Raw outcome of one closed process (before result shaping). Deliberately
  78. * carries NO timeout/cancel classification: runBash kills on abort but does not
  79. * decide why — the executor's `run()`/`start()` reads the deadline signal it
  80. * owns to classify `timedOut`/`aborted` (see the package README).
  81. */
  82. export interface SpawnOutcome {
  83. exitCode: number | null
  84. signal: NodeJS.Signals | null
  85. stdout: CollectedOutput
  86. stderr: CollectedOutput
  87. }
  88. /** Injectable knobs so tests can exercise spill behavior without the OS tmpdir. */
  89. export interface RunInternals {
  90. /** Directory for spill files (defaults to the OS temp dir). */
  91. spillDir?: string
  92. }
  93. /** Default SIGTERM→SIGKILL grace period (the `graceMs` config; matches OpenCode's 3s). */
  94. export const DEFAULT_GRACE_MS = 3_000
  95. let spillCounter = 0
  96. let defaultSpillDir: string | undefined
  97. /**
  98. * The default spill location: a private (0700) per-process directory under
  99. * the OS tmpdir, created lazily. Predictable world-readable paths would let
  100. * other local users read command output or pre-create symlinks.
  101. */
  102. function privateSpillDir(): string {
  103. defaultSpillDir ??= mkdtempSync(join(tmpdir(), 'dsh-bash-'))
  104. return defaultSpillDir
  105. }
  106. /**
  107. * Collects one stream with a bounded in-memory tail. The FULL stream is
  108. * always recoverable: on first overflow a spill file is created and every
  109. * chunk (including those already collected) is appended there.
  110. *
  111. * Tail-keep rationale (pi/OpenCode): errors and final results cluster at the
  112. * end of command output; the spill file covers the head.
  113. */
  114. export class OutputCollector {
  115. private chunks: Buffer[] = []
  116. private bytes = 0
  117. private dropped = false
  118. private spillFd: number | undefined
  119. private spillFile: string | undefined
  120. /** Total bytes ever pushed (not just retained). */
  121. private total = 0
  122. constructor(
  123. private readonly maxBytes: number,
  124. private readonly label: string,
  125. private readonly spillDir: string,
  126. ) {}
  127. /**
  128. * Ingest one stream chunk, counting it toward the whole-stream total. On
  129. * first overflow of the in-memory cap a spill file is opened and every chunk
  130. * (already-collected ones included) is appended there from then on; the
  131. * in-memory tail then drops whole chunks from its head (or the head of a
  132. * single over-cap chunk) until it fits the cap again.
  133. * @param chunk - the raw bytes from one stream 'data' event.
  134. */
  135. push(chunk: Buffer): void {
  136. this.total += chunk.length
  137. const overflows = this.bytes + chunk.length > this.maxBytes
  138. if (overflows || this.spillFd !== undefined) this.spillAll(chunk)
  139. this.chunks.push(chunk)
  140. this.bytes += chunk.length
  141. while (this.bytes > this.maxBytes && this.chunks.length > 1) {
  142. // Drop whole chunks from the head; pipe chunks are small (≤64KiB), so
  143. // the retained tail tracks the cap closely enough for a model-facing
  144. // truncation boundary. (length > 1 was just checked — shift() returns.)
  145. const head = this.chunks.shift() as Buffer
  146. this.bytes -= head.length
  147. this.dropped = true
  148. }
  149. if (this.bytes > this.maxBytes && this.chunks.length === 1) {
  150. // A single chunk larger than the cap: keep its tail.
  151. const only = this.chunks[0] as Buffer
  152. this.chunks[0] = only.subarray(only.length - this.maxBytes)
  153. this.bytes = this.maxBytes
  154. this.dropped = true
  155. }
  156. }
  157. /** Open the spill file lazily and append `chunk` (and any prior chunks once). */
  158. private spillAll(chunk: Buffer): void {
  159. if (this.spillFd === undefined) {
  160. // Random suffix + O_EXCL + no-follow-equivalent ('wx' fails on any
  161. // existing path, symlink or not) + owner-only mode: defeats spill-path
  162. // prediction and symlink planting in shared tmp dirs.
  163. this.spillFile = join(
  164. this.spillDir,
  165. `dsh-bash-${process.pid}-${++spillCounter}-${randomBytes(6).toString('hex')}-${this.label}.log`,
  166. )
  167. this.spillFd = openSync(this.spillFile, 'wx', 0o600)
  168. for (const prior of this.chunks) writeSync(this.spillFd, prior)
  169. }
  170. writeSync(this.spillFd, chunk)
  171. }
  172. // TODO(snapshot-scope): `snapshot()` has one internal caller (`finalize()` at
  173. // the bottom of this file) and `totalBytes` is read only by a test. The live
  174. // background-poll path goes through `readFrom()`, so inline snapshot() into
  175. // finalize() and drop or privatize the totalBytes getter.
  176. /**
  177. * Read the collected tail without finalizing (the final-result snapshot).
  178. * @returns the retained tail text, the truncation flag, and the spill path when one was created.
  179. */
  180. snapshot(): CollectedOutput {
  181. return {
  182. text: Buffer.concat(this.chunks).toString('utf8'),
  183. truncated: this.dropped,
  184. ...this.spillFile !== undefined ? { spillPath: this.spillFile } : {},
  185. }
  186. }
  187. /** Total bytes ever pushed (including bytes dropped from memory). */
  188. get totalBytes(): number {
  189. return this.total
  190. }
  191. /**
  192. * Incremental read in whole-stream byte coordinates: returns everything
  193. * pushed since `fromByte`. When `fromByte` has already slid out of the
  194. * in-memory tail window, the read is `lossy` — it returns the whole
  195. * retained tail and the gap is only recoverable from the spill file.
  196. * @param fromByte - whole-stream offset to resume from (a prior read's `nextOffset`; 0 for the first read).
  197. * @returns the delta text, the offset for the next read, the `lossy` flag, and the spill path when one was created.
  198. */
  199. readFrom(fromByte: number): { text: string; nextOffset: number; lossy: boolean; spillPath?: string } {
  200. const windowStart = this.total - this.bytes
  201. const buffer = Buffer.concat(this.chunks)
  202. const lossy = fromByte < windowStart
  203. const slice = lossy ? buffer : buffer.subarray(fromByte - windowStart)
  204. return {
  205. text: slice.toString('utf8'),
  206. nextOffset: this.total,
  207. lossy,
  208. ...this.spillFile !== undefined ? { spillPath: this.spillFile } : {},
  209. }
  210. }
  211. /**
  212. * Close the spill file (if any) and return the final output. A failed close
  213. * (delayed writeback fault) stops advertising the spill path — the file may
  214. * be missing its tail — but still returns the in-memory result.
  215. * @returns the final collected output: tail text, truncation flag, and the spill path when intact.
  216. */
  217. finalize(): CollectedOutput {
  218. if (this.spillFd !== undefined) {
  219. try {
  220. closeSync(this.spillFd)
  221. } catch {
  222. // A delayed writeback failure makes the spill unreliable; keep finalize
  223. // total but stop advertising that file.
  224. this.spillFile = undefined
  225. }
  226. this.spillFd = undefined
  227. }
  228. return this.snapshot()
  229. }
  230. }
  231. /**
  232. * Send `sig` to a detached process group. Never throws: delivery races process
  233. * exit and may run in a timer callback, so failures are contained and a
  234. * non-positive pid is a no-op.
  235. * @param pid - the group leader's pid; non-positive means the spawn failed and the call is a no-op.
  236. * @param sig - the signal to deliver to the whole group.
  237. */
  238. export function killGroup(pid: number, sig: NodeJS.Signals): void {
  239. if (pid <= 0) return
  240. try {
  241. process.kill(-pid, sig)
  242. } catch {
  243. // Swallow: see contract above.
  244. }
  245. }
  246. /**
  247. * A live bash child process: the promise resolves when the process closes;
  248. * `kill()` starts the SIGTERM→grace→SIGKILL escalation on its group.
  249. */
  250. export interface RunningBash {
  251. /** Process id (group leader); -1 when the spawn itself failed. */
  252. readonly pid: number
  253. /** stdout/stderr collectors (live — background polling reads incrementally). */
  254. readonly stdout: OutputCollector
  255. readonly stderr: OutputCollector
  256. /** Resolves when the process closes; rejects only for spawn-level failures. */
  257. readonly done: Promise<SpawnOutcome>
  258. /** Begin SIGTERM→grace→SIGKILL on the process group. Idempotent. */
  259. kill(): void
  260. }
  261. /**
  262. * Spawn one isolated `bash -c` process group and collect its output.
  263. * Runtime exits resolve as {@link SpawnOutcome}; only spawn failures reject.
  264. * @param spec - fully resolved command, cwd, limits, and cancellation.
  265. * @param internals - test-only process and spill-directory overrides.
  266. * @returns live process handle and outcome promise.
  267. */
  268. // XXX(stateful-shell): evaluate persistent cwd or PTY sessions when workflows require shell state.
  269. export function runBash(spec: SpawnSpec, internals: RunInternals = {}): RunningBash {
  270. const spillDir = internals.spillDir ?? privateSpillDir()
  271. if (spec.signal?.aborted) {
  272. throw new Error(`aborted before spawn: ${String(spec.signal.reason ?? 'aborted')}`)
  273. }
  274. // Keep absent stdin as /dev/null; literal tuples preserve non-null output types.
  275. const env = childEnv(spec.env)
  276. const child: ChildProcessByStdio<Writable | null, Readable, Readable> = spec.stdin !== undefined
  277. ? spawn('bash', ['-c', spec.command], { cwd: spec.cwd, env, stdio: ['pipe', 'pipe', 'pipe'], detached: true })
  278. : spawn('bash', ['-c', spec.command], { cwd: spec.cwd, env, stdio: ['ignore', 'pipe', 'pipe'], detached: true })
  279. const stdout = new OutputCollector(spec.maxOutputBytes, 'stdout', spillDir)
  280. const stderr = new OutputCollector(spec.maxOutputBytes, 'stderr', spillDir)
  281. child.stdout.on('data', (chunk: Buffer) => { stdout.push(chunk) })
  282. child.stderr.on('data', (chunk: Buffer) => { stderr.push(chunk) })
  283. let graceTimer: NodeJS.Timeout | undefined
  284. // Failed spawns use pid -1 so kill remains a no-op.
  285. const pid = child.pid ?? -1
  286. const kill = (): void => {
  287. if (graceTimer !== undefined) return // escalation already in flight
  288. killGroup(pid, 'SIGTERM')
  289. graceTimer = setTimeout(() => { killGroup(pid, 'SIGKILL') }, spec.graceMs)
  290. }
  291. // The executor owns timeout classification; this layer only reacts to abort.
  292. const onAbort = (): void => { kill() }
  293. spec.signal?.addEventListener('abort', onAbort, { once: true })
  294. // Stdin writes are best-effort; process exit and captured output remain authoritative.
  295. if (child.stdin !== null) {
  296. child.stdin.on('error', () => { /* stdin write is best-effort; outcome rides on exit/output. */ })
  297. child.stdin.end(spec.stdin)
  298. }
  299. const done = new Promise<SpawnOutcome>((resolve, reject) => {
  300. child.on('error', (error) => {
  301. // No meaningful close outcome follows a spawn failure.
  302. cleanup()
  303. reject(error)
  304. })
  305. child.on('close', (exitCode, signal) => {
  306. cleanup()
  307. resolve({
  308. exitCode,
  309. signal,
  310. stdout: stdout.finalize(),
  311. stderr: stderr.finalize(),
  312. })
  313. })
  314. function cleanup(): void {
  315. if (graceTimer !== undefined) clearTimeout(graceTimer)
  316. spec.signal?.removeEventListener('abort', onAbort)
  317. }
  318. })
  319. return { pid, stdout, stderr, done, kill }
  320. }