index.ts 9.2 KB

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