index.ts 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  1. /**
  2. * `LocalBashExecutor`: the local-subprocess implementation of the
  3. * `@deepseek-ai/dsh-bash` executor seam. Spawns `bash -c` per call in its
  4. * own process group (see `./run.ts` for the plumbing and the agent-tool
  5. * survey notes), tracks background tasks, and kills everything on dispose.
  6. *
  7. * TODO(permissions/sandbox): execution policy does NOT belong here — use
  8. * the `tools/pre-execute` deny/ask gate (see docs/architecture.md
  9. * § Extending The Harness) or implement a sandboxing `BashExecutor`.
  10. * Reference points:
  11. * Claude Code wraps commands in sandbox-exec/bubblewrap; Codex applies
  12. * seatbelt/landlock plus an execpolicy prefix-rule engine.
  13. *
  14. * @module @deepseek-ai/dsh-bash-local
  15. */
  16. import { Context } from 'cordis'
  17. import z from 'schemastery'
  18. import { BashExecutor, BashTaskId } from '@deepseek-ai/dsh-bash'
  19. import type { BashExecRequest, BashExecSpec, BashRunResult, BashTask, BashTaskRead, OwnerToken } from '@deepseek-ai/dsh-bash'
  20. import { clampTimeout, deadline, timeoutOf } from '@deepseek-ai/dsh-timeout'
  21. import { DEFAULT_GRACE_MS, runBash } from './run.ts'
  22. import type { RunInternals, RunningBash } from './run.ts'
  23. export { DEFAULT_GRACE_MS, ENV_OVERRIDES, killGroup, OutputCollector, runBash } from './run.ts'
  24. export type { RunInternals, RunningBash, SpawnOutcome, SpawnSpec } from './run.ts'
  25. /** Plugin config (all optional — `static Config` supplies the defaults). */
  26. export interface Config {
  27. /** Default working directory for commands (default: process.cwd()). */
  28. cwd?: string
  29. /** Default foreground timeout in milliseconds. */
  30. timeoutMs?: number
  31. /** Upper bound for per-call timeout overrides. */
  32. maxTimeoutMs?: number
  33. /** Per-stream in-memory output cap; overflow spills to a temp file. */
  34. maxOutputBytes?: number
  35. /** Grace period between the SIGTERM and the SIGKILL escalation on a kill. */
  36. graceMs?: number
  37. }
  38. /** The shape after schemastery applied the defaults (cwd has none). */
  39. type ResolvedConfig = Required<Omit<Config, 'cwd'>> & Pick<Config, 'cwd'>
  40. function assertPositiveFinite(name: string, value: number): void {
  41. if (!Number.isFinite(value) || value <= 0) {
  42. throw new Error(`bash-local: ${name} must be a positive finite number`)
  43. }
  44. }
  45. interface TrackedTask extends BashTask {
  46. running: RunningBash
  47. /** Whole-stream byte offsets already delivered via {@link LocalBashExecutor.readOutput}. */
  48. stdoutOffset: number
  49. stderrOffset: number
  50. /** Opaque owner token from the {@link BashExecSpec} (the consumer's isolation key). */
  51. owner: OwnerToken | undefined
  52. }
  53. /**
  54. * Local-subprocess bash executor. Defaults follow the agent-tool survey
  55. * consensus: 120s default / 600s max timeout (Claude Code, OpenCode), 64KB
  56. * in-memory output with full-stream spill files (pi, OpenCode),
  57. * process-group SIGTERM→SIGKILL kills with a 3s grace (OpenCode).
  58. */
  59. export class LocalBashExecutor extends BashExecutor {
  60. static Config: z<Config> = z.object({
  61. cwd: z.string(),
  62. timeoutMs: z.number().default(120_000),
  63. maxTimeoutMs: z.number().default(600_000),
  64. maxOutputBytes: z.number().default(64_000),
  65. graceMs: z.number().default(DEFAULT_GRACE_MS),
  66. })
  67. private tasks = new Map<BashTaskId, TrackedTask>()
  68. private nextTaskId = 1
  69. /** Test seam: spill knobs forwarded to runBash. */
  70. internals: RunInternals = {}
  71. /** Validated config (schemastery applied the defaults before construction). */
  72. readonly config: ResolvedConfig
  73. constructor(ctx: Context, config: Config) {
  74. super(ctx)
  75. // schemastery (static Config) has already filled the defaulted fields;
  76. // the cast records that runtime fact for exactOptionalPropertyTypes.
  77. this.config = config as ResolvedConfig
  78. assertPositiveFinite('timeoutMs', this.config.timeoutMs)
  79. assertPositiveFinite('maxTimeoutMs', this.config.maxTimeoutMs)
  80. assertPositiveFinite('maxOutputBytes', this.config.maxOutputBytes)
  81. assertPositiveFinite('graceMs', this.config.graceMs)
  82. ctx.effect(() => async () => {
  83. // Kill every live process group and WAIT for the processes to close so
  84. // nothing outlives the fiber (HMR safety) — a TERM-trapping child is
  85. // held until the SIGKILL escalation lands. The base class already
  86. // silenced listeners, so these kills complete without notices.
  87. const pending: Promise<void>[] = []
  88. for (const task of this.tasks.values()) {
  89. if (task.status === 'running') {
  90. task.status = 'killed'
  91. task.running.kill()
  92. pending.push(task.done)
  93. }
  94. }
  95. this.tasks.clear()
  96. await Promise.all(pending)
  97. }, 'local bash teardown')
  98. }
  99. /**
  100. * Resolve a request into a fully-specified spec: fill `workdir` from
  101. * `config.cwd` (else `process.cwd()`), and `timeoutMs` from
  102. * `config.timeoutMs`, capped at `config.maxTimeoutMs`. The tool layer calls
  103. * this before {@link run}/{@link start}, so those methods receive explicit
  104. * values and never re-default.
  105. */
  106. resolve(request: BashExecRequest): BashExecSpec {
  107. const timeoutMs = clampTimeout(
  108. request.timeoutMs,
  109. this.config.timeoutMs,
  110. this.config.maxTimeoutMs,
  111. 'bash-local: request.timeoutMs',
  112. )
  113. return {
  114. command: request.command,
  115. workdir: request.workdir ?? this.config.cwd ?? process.cwd(),
  116. timeoutMs,
  117. ...request.signal ? { signal: request.signal } : {},
  118. // Carry stdin/env through verbatim — optional, no config default (absent
  119. // means none). env merges AFTER the scrub in run.ts.
  120. ...request.stdin !== undefined ? { stdin: request.stdin } : {},
  121. ...request.env !== undefined ? { env: request.env } : {},
  122. // Carry the owner through verbatim (required-but-nullable on the spec):
  123. // the executor never interprets it — the consumer's access policy does.
  124. owner: request.owner,
  125. }
  126. }
  127. async run(spec: BashExecSpec): Promise<BashRunResult> {
  128. // One fused deadline drives both the timeout and upstream cancellation;
  129. // runBash listens on d.signal and runs the SIGTERM→grace→SIGKILL kill.
  130. // `using` clears the timer across the awaited process lifetime.
  131. using d = deadline(spec.signal, spec.timeoutMs, 'BASH_TIMEOUT')
  132. const outcome = await runBash({
  133. command: spec.command,
  134. cwd: spec.workdir,
  135. maxOutputBytes: this.config.maxOutputBytes,
  136. graceMs: this.config.graceMs,
  137. signal: d.signal,
  138. stdin: spec.stdin,
  139. env: spec.env,
  140. }, this.internals).done
  141. // Classify the FIRST abort reason: a BASH_TIMEOUT TimeoutReason means our
  142. // timeout cut the command short; any other abort — an upstream cancel, or a
  143. // foreign (outer) deadline's timeout under nesting — is aborted. Scoping to
  144. // our own code keeps a nested outer deadline from reading as our timeout.
  145. // Mutually exclusive by construction — the fused signal reports one cause.
  146. const timedOut = timeoutOf(d.signal, 'BASH_TIMEOUT') !== undefined
  147. const aborted = d.signal.aborted && !timedOut
  148. return { ...outcome, timedOut, aborted, timeoutMs: spec.timeoutMs }
  149. }
  150. start(spec: BashExecSpec): BashTask {
  151. // No timeout for background tasks (matches Claude Code, which detaches
  152. // the timeout when backgrounding); callers stop tasks via kill() — or
  153. // via spec.signal, which the seam contract honors for background runs
  154. // too (runBash wires it to the group kill). No deadline is created here,
  155. // so spec.timeoutMs is ignored by design — background tasks stay
  156. // timeout-free (see the timeout-library RFC).
  157. const running = runBash({
  158. command: spec.command,
  159. cwd: spec.workdir,
  160. maxOutputBytes: this.config.maxOutputBytes,
  161. graceMs: this.config.graceMs,
  162. signal: spec.signal,
  163. stdin: spec.stdin,
  164. env: spec.env,
  165. }, this.internals)
  166. const id = BashTaskId(`bash-${this.nextTaskId++}`)
  167. const task: TrackedTask = {
  168. id,
  169. command: spec.command,
  170. status: 'running',
  171. exitCode: null,
  172. signal: null,
  173. owner: spec.owner,
  174. running,
  175. stdoutOffset: 0,
  176. stderrOffset: 0,
  177. done: running.done.then((outcome) => {
  178. // Abort-killed tasks report as killed, not completed. Background runs
  179. // forward only the upstream signal (no timeout), so its aborted state
  180. // is the authoritative "was this cancelled" signal.
  181. if (task.status === 'running') task.status = spec.signal?.aborted === true ? 'killed' : 'completed'
  182. task.exitCode = outcome.exitCode
  183. task.signal = outcome.signal
  184. this.notifyTaskDone(task)
  185. }, (error: unknown) => {
  186. // Spawn-level failure (bad workdir, …): the task never ran. String()
  187. // suffices — runBash only rejects with Error instances.
  188. task.status = 'killed'
  189. task.running.stderr.push(Buffer.from(`spawn failed: ${String(error)}`))
  190. this.notifyTaskDone(task)
  191. }),
  192. }
  193. this.tasks.set(id, task)
  194. return task
  195. }
  196. get(id: BashTaskId): BashTask | undefined {
  197. return this.tasks.get(id)
  198. }
  199. ownerOf(id: BashTaskId): OwnerToken | undefined {
  200. // Unknown id and known-but-ownerless both read as undefined — the consumer
  201. // treats undefined as "open" and a truly unknown id fails at readOutput/kill.
  202. return this.tasks.get(id)?.owner
  203. }
  204. list(): BashTask[] {
  205. return [...this.tasks.values()]
  206. }
  207. readOutput(id: BashTaskId): BashTaskRead {
  208. const task = this.tasks.get(id)
  209. if (!task) throw new Error(`unknown bash task "${id}"`)
  210. const out = task.running.stdout.readFrom(task.stdoutOffset)
  211. const err = task.running.stderr.readFrom(task.stderrOffset)
  212. task.stdoutOffset = out.nextOffset
  213. task.stderrOffset = err.nextOffset
  214. // Single newline between sections: stdout chunks usually end with one
  215. // already; add it only when missing.
  216. const separator = out.text.length > 0 && !out.text.endsWith('\n') ? '\n' : ''
  217. const delta = out.text
  218. + (err.text.length > 0 ? `${separator}[stderr]\n${err.text}` : '')
  219. return {
  220. task,
  221. delta,
  222. lossy: out.lossy || err.lossy,
  223. ...out.spillPath !== undefined ? { stdoutSpillPath: out.spillPath } : {},
  224. ...err.spillPath !== undefined ? { stderrSpillPath: err.spillPath } : {},
  225. }
  226. }
  227. kill(id: BashTaskId): boolean {
  228. const task = this.tasks.get(id)
  229. if (!task) throw new Error(`unknown bash task "${id}"`)
  230. if (task.status !== 'running') return false
  231. task.status = 'killed'
  232. task.running.kill()
  233. return true
  234. }
  235. }
  236. export default LocalBashExecutor