executor.spec.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  1. import { mkdtempSync } from 'node:fs'
  2. import { tmpdir } from 'node:os'
  3. import { join } from 'node:path'
  4. import { describe, expect, it } from 'vitest'
  5. import { Context } from 'cordis'
  6. import { LocalBashExecutor } from '@deepseek-ai/dsh-bash-local'
  7. import type { BashProcess } from '@deepseek-ai/dsh-bash'
  8. const spillDir = mkdtempSync(join(tmpdir(), 'dsh-bash-exec-spec-'))
  9. async function setup(config: ConstructorParameters<typeof LocalBashExecutor>[1] = {}) {
  10. const ctx = new Context()
  11. // A short kill grace via the REAL config path, so escalation tests stay fast.
  12. await ctx.plugin(LocalBashExecutor, { graceMs: 200, ...config })
  13. const bash = ctx.bash as LocalBashExecutor
  14. bash.internals = { spillDir }
  15. return { ctx, bash }
  16. }
  17. /**
  18. * Poll a handle's consuming readOutput until the ACCUMULATED delta contains
  19. * `expected`; returns the accumulation (reads never re-deliver, so the caller
  20. * gets everything produced up to the match).
  21. */
  22. async function readUntil(proc: BashProcess, expected: string, timeoutMs = 5_000): Promise<string> {
  23. const deadline = Date.now() + timeoutMs
  24. let all = ''
  25. while (Date.now() < deadline) {
  26. all += proc.readOutput().delta
  27. if (all.includes(expected)) return all
  28. await new Promise(resolve => setTimeout(resolve, 20))
  29. }
  30. throw new Error(`process output did not include ${JSON.stringify(expected)}; accumulated ${JSON.stringify(all)}`)
  31. }
  32. describe('LocalBashExecutor.run', () => {
  33. it('resolves with output and the effective timeout', async () => {
  34. const { bash } = await setup({ timeoutMs: 5_000 })
  35. const result = await bash.run(bash.resolve({ command: 'echo hi' }))
  36. expect(result.exitCode).toBe(0)
  37. expect(result.stdout.text).toBe('hi\n')
  38. expect(result.timeoutMs).toBe(5_000)
  39. })
  40. it('uses config cwd, overridable per call', async () => {
  41. const { bash } = await setup({ cwd: '/tmp' })
  42. const fromConfig = await bash.run(bash.resolve({ command: 'pwd' }))
  43. expect(fromConfig.stdout.text.trim()).toMatch(/\/tmp$/)
  44. const fromCall = await bash.run(bash.resolve({ command: 'pwd', workdir: '/' }))
  45. expect(fromCall.stdout.text.trim()).toBe('/')
  46. })
  47. it('defaults cwd to process.cwd()', async () => {
  48. const { bash } = await setup()
  49. const result = await bash.run(bash.resolve({ command: 'pwd' }))
  50. expect(result.stdout.text.trim()).toBe(process.cwd())
  51. })
  52. it('caps per-call timeouts at maxTimeoutMs', async () => {
  53. const { bash } = await setup({ timeoutMs: 1_000, maxTimeoutMs: 2_000 })
  54. const result = await bash.run(bash.resolve({ command: 'true', timeoutMs: 99_999 }))
  55. expect(result.timeoutMs).toBe(2_000)
  56. })
  57. it('rejects invalid numeric config and timeout overrides', async () => {
  58. await expect(setup({ timeoutMs: Number.NaN })).rejects.toThrow(/timeoutMs/)
  59. await expect(setup({ maxTimeoutMs: 0 })).rejects.toThrow(/maxTimeoutMs/)
  60. await expect(setup({ maxOutputBytes: -1 })).rejects.toThrow(/maxOutputBytes/)
  61. await expect(setup({ graceMs: 0 })).rejects.toThrow(/graceMs/)
  62. const { bash } = await setup()
  63. expect(() => bash.resolve({ command: 'true', timeoutMs: Number.NaN })).toThrow(/request\.timeoutMs/)
  64. expect(() => bash.resolve({ command: 'true', timeoutMs: -1 })).toThrow(/request\.timeoutMs/)
  65. expect(() => bash.resolve({ command: 'true', stdoutMaxBytes: Number.NaN })).toThrow(/request\.stdoutMaxBytes/)
  66. expect(() => bash.resolve({ command: 'true', stdoutMaxBytes: -1 })).toThrow(/request\.stdoutMaxBytes/)
  67. })
  68. it('defaults stdoutMaxBytes to maxOutputBytes and lets foreground callers raise stdout only', async () => {
  69. const { bash } = await setup({ maxOutputBytes: 100 })
  70. expect(bash.resolve({ command: 'true' }).stdoutMaxBytes).toBe(100)
  71. const result = await bash.run(bash.resolve({
  72. command: 'printf "%.0sx" $(seq 1 500); printf "%.0se" $(seq 1 500) >&2',
  73. stdoutMaxBytes: 500,
  74. }))
  75. expect(result.stdout.truncated).toBe(false)
  76. expect(result.stdout.text).toBe('x'.repeat(500))
  77. expect(result.stderr.truncated).toBe(true)
  78. expect(result.stderr.text.length).toBeLessThanOrEqual(100)
  79. })
  80. it('per-call timeout takes precedence under the cap and kills on expiry', async () => {
  81. const { bash } = await setup({ timeoutMs: 60_000 })
  82. const result = await bash.run(bash.resolve({ command: 'sleep 60', timeoutMs: 100 }))
  83. expect(result.timedOut).toBe(true)
  84. // Mutually exclusive: a timeout classifies as timedOut, never also aborted.
  85. expect(result.aborted).toBe(false)
  86. expect(result.timeoutMs).toBe(100)
  87. })
  88. it('propagates abort signals', async () => {
  89. const { bash } = await setup()
  90. const controller = new AbortController()
  91. const pending = bash.run(bash.resolve({ command: 'sleep 60', signal: controller.signal }))
  92. setTimeout(() => { controller.abort() }, 50)
  93. const result = await pending
  94. expect(result.aborted).toBe(true)
  95. // Mutually exclusive: an upstream cancel classifies as aborted, never also timedOut.
  96. expect(result.timedOut).toBe(false)
  97. })
  98. it('classifies a self-killed command as neither timed out nor aborted', async () => {
  99. // The command kills itself (SIGTERM) with no timeout and no upstream abort:
  100. // the deadline signal never fires, so both classifications are false — the
  101. // fused-signal classification reports the cause that cut the command short,
  102. // and here nothing the executor owns did.
  103. const { bash } = await setup({ timeoutMs: 60_000 })
  104. const result = await bash.run(bash.resolve({ command: 'kill -TERM $$' }))
  105. expect(result.signal).toBe('SIGTERM')
  106. expect(result.timedOut).toBe(false)
  107. expect(result.aborted).toBe(false)
  108. })
  109. it('rejects on spawn failure (bad workdir)', async () => {
  110. const { bash } = await setup()
  111. await expect(bash.run(bash.resolve({ command: 'true', workdir: '/nonexistent-dsh' }))).rejects.toThrow(/ENOENT/)
  112. })
  113. it('resolve() carries stdin/env/dshEnv onto the spec, and run() threads them to the command', async () => {
  114. const { bash } = await setup()
  115. const spec = bash.resolve({
  116. command: 'cat; echo "[$SEAM_VAR][$DSH_SEAM_VAR]"',
  117. stdin: 'piped\n',
  118. env: { SEAM_VAR: 'env-ok' },
  119. dshEnv: { DSH_SEAM_VAR: 'dsh-ok' },
  120. })
  121. // resolve() keeps the optional input/environment fields verbatim.
  122. expect(spec.stdin).toBe('piped\n')
  123. expect(spec.env).toEqual({ SEAM_VAR: 'env-ok' })
  124. expect(spec.dshEnv).toEqual({ DSH_SEAM_VAR: 'dsh-ok' })
  125. const result = await bash.run(spec)
  126. expect(result.stdout.text).toBe('piped\n[env-ok][dsh-ok]\n')
  127. })
  128. it('resolve() omits stdin/env/dshEnv when the request supplies none', async () => {
  129. const { bash } = await setup()
  130. const spec = bash.resolve({ command: 'true' })
  131. expect('stdin' in spec).toBe(false)
  132. expect('env' in spec).toBe(false)
  133. expect('dshEnv' in spec).toBe(false)
  134. })
  135. })
  136. describe('LocalBashExecutor.start (background process handles)', () => {
  137. it('start returns immediately with a running handle that settles as completed', async () => {
  138. const { bash } = await setup()
  139. const before = Date.now()
  140. const proc = bash.start(bash.resolve({ command: 'sleep 0.2; echo done' }))
  141. expect(Date.now() - before).toBeLessThan(150)
  142. expect(proc.status).toBe('running')
  143. await proc.done
  144. expect(proc.status).toBe('completed')
  145. expect(proc.exitCode).toBe(0)
  146. })
  147. it('threads stdin and extra env into a background process', async () => {
  148. const { bash } = await setup()
  149. const proc = bash.start(bash.resolve({
  150. command: 'cat; echo "[$BG_VAR][$DSH_BG_VAR]"',
  151. stdin: 'bg-stdin\n',
  152. env: { BG_VAR: 'bg-env' },
  153. dshEnv: { DSH_BG_VAR: 'bg-dsh-env' },
  154. }))
  155. const output = await readUntil(proc, '[bg-env][bg-dsh-env]')
  156. expect(output).toContain('bg-stdin')
  157. await proc.done
  158. expect(proc.exitCode).toBe(0)
  159. })
  160. it('readOutput is consuming: increments are never re-delivered, and reads stay valid after exit', async () => {
  161. const { bash } = await setup()
  162. const proc = bash.start(bash.resolve({ command: 'echo first; sleep 1; echo second' }))
  163. const first = await readUntil(proc, 'first\n')
  164. expect(first).toBe('first\n')
  165. await proc.done
  166. // Read-after-exit returns the remaining buffered output — once.
  167. const second = proc.readOutput()
  168. expect(second.delta).toBe('second\n')
  169. expect(second.lossy).toBe(false)
  170. expect(proc.readOutput().delta).toBe('')
  171. })
  172. it('readOutput marks stderr sections', async () => {
  173. const { bash } = await setup()
  174. const proc = bash.start(bash.resolve({ command: 'echo out; echo err >&2' }))
  175. await proc.done
  176. expect(proc.readOutput().delta).toBe('out\n[stderr]\nerr\n')
  177. })
  178. it('readOutput reports stderr-only deltas without a leading newline', async () => {
  179. const { bash } = await setup()
  180. const proc = bash.start(bash.resolve({ command: 'echo err >&2' }))
  181. await proc.done
  182. expect(proc.readOutput().delta).toBe('[stderr]\nerr\n')
  183. })
  184. it('readOutput adds a separator only when stdout lacks a trailing newline', async () => {
  185. const { bash } = await setup()
  186. const proc = bash.start(bash.resolve({ command: 'printf out; echo err >&2' }))
  187. await proc.done
  188. expect(proc.readOutput().delta).toBe('out\n[stderr]\nerr\n')
  189. })
  190. it('readOutput flags lossy reads and reports stdout spill paths', async () => {
  191. const { bash } = await setup({ maxOutputBytes: 100 })
  192. const proc = bash.start(bash.resolve({ command: 'for i in $(seq 1 100); do printf "line-%04d\\n" $i; done' }))
  193. await proc.done
  194. const read = proc.readOutput()
  195. // Window slid past offset 0 → lossy, spill path points at the full stream.
  196. expect(read.lossy).toBe(true)
  197. expect(read.stdoutSpillPath).toBeDefined()
  198. })
  199. it('readOutput reports stderr spill paths', async () => {
  200. const { bash } = await setup({ maxOutputBytes: 100 })
  201. const proc = bash.start(bash.resolve({ command: 'for i in $(seq 1 100); do printf "line-%04d\\n" $i >&2; done' }))
  202. await proc.done
  203. const read = proc.readOutput()
  204. expect(read.lossy).toBe(true)
  205. expect(read.stderrSpillPath).toBeDefined()
  206. expect(read.delta).toContain('[stderr]')
  207. })
  208. it('kill() terminates the process group: true once, false after settlement', async () => {
  209. const { bash } = await setup()
  210. const proc = bash.start(bash.resolve({ command: 'sleep 60' }))
  211. expect(proc.kill()).toBe(true)
  212. await proc.done
  213. expect(proc.status).toBe('killed')
  214. expect(proc.signal).toBe('SIGTERM')
  215. expect(proc.kill()).toBe(false)
  216. })
  217. it('kill() returns false for a naturally completed process', async () => {
  218. const { bash } = await setup()
  219. const proc = bash.start(bash.resolve({ command: 'true' }))
  220. await proc.done
  221. expect(proc.status).toBe('completed')
  222. expect(proc.kill()).toBe(false)
  223. })
  224. it('kill escalation uses the configured graceMs (a TERM-trapping process dies by SIGKILL)', async () => {
  225. const { bash } = await setup() // setup pins graceMs: 200 via config
  226. // The child echoes AFTER arming the trap, so waiting for the marker
  227. // guarantees SIGTERM is already ignored when the kill lands (a fixed sleep
  228. // is load-flaky: a slow spawn would take the SIGTERM before the trap).
  229. const proc = bash.start(bash.resolve({ command: 'trap \'\' TERM; echo armed; sleep 60' }))
  230. await readUntil(proc, 'armed')
  231. proc.kill()
  232. await proc.done
  233. expect(proc.status).toBe('killed')
  234. expect(proc.signal).toBe('SIGKILL')
  235. })
  236. it('a spec.signal abort settles the handle as killed, not completed', async () => {
  237. const { bash } = await setup()
  238. const controller = new AbortController()
  239. const proc = bash.start(bash.resolve({ command: 'sleep 60', signal: controller.signal }))
  240. controller.abort()
  241. await proc.done
  242. expect(proc.status).toBe('killed')
  243. expect(proc.signal).toBe('SIGTERM')
  244. })
  245. it('a self-signal exit settles the handle as killed, not completed', async () => {
  246. const { bash } = await setup()
  247. const proc = bash.start(bash.resolve({ command: 'kill -TERM $$' }))
  248. await proc.done
  249. expect(proc.status).toBe('killed')
  250. expect(proc.exitCode).toBeNull()
  251. expect(proc.signal).toBe('SIGTERM')
  252. })
  253. it('a background spawn failure settles as killed with the error readable on stderr', async () => {
  254. const { bash } = await setup()
  255. const proc = bash.start(bash.resolve({ command: 'true', workdir: '/nonexistent-dsh' }))
  256. // done resolves (never rejects) even though the process never ran.
  257. await expect(proc.done).resolves.toBeUndefined()
  258. expect(proc.status).toBe('killed')
  259. expect(proc.readOutput().delta).toContain('spawn failed:')
  260. })
  261. })
  262. describe('LocalBashExecutor disposal', () => {
  263. it('disposing the fiber kills running processes and AWAITS their exit (no orphans, SIGKILL escalation included)', async () => {
  264. const ctx = new Context()
  265. const fiber = await ctx.plugin(LocalBashExecutor, { graceMs: 200 })
  266. const bash = ctx.bash as LocalBashExecutor
  267. bash.internals = { spillDir }
  268. // The child prints its own pid ($$ = the detached bash group leader) so
  269. // the test can probe liveness through the public read surface alone.
  270. const proc = bash.start(bash.resolve({ command: 'trap \'\' TERM; echo $$; sleep 60' }))
  271. const pid = Number((await readUntil(proc, '\n')).trim())
  272. expect(Number.isInteger(pid) && pid > 0).toBe(true)
  273. await fiber.dispose()
  274. // Disposal itself waited: the pid must already be gone, no grace left —
  275. // even for a TERM-trapping child held until the SIGKILL escalation landed.
  276. expect(() => process.kill(pid, 0)).toThrow()
  277. expect(proc.status).toBe('killed')
  278. await proc.done
  279. })
  280. it('settled processes already left the live map: dispose does not touch them', async () => {
  281. const ctx = new Context()
  282. const fiber = await ctx.plugin(LocalBashExecutor, { graceMs: 200 })
  283. const bash = ctx.bash as LocalBashExecutor
  284. bash.internals = { spillDir }
  285. const finished = bash.start(bash.resolve({ command: 'echo done' }))
  286. await finished.done
  287. expect(finished.status).toBe('completed')
  288. const running = bash.start(bash.resolve({ command: 'sleep 60' }))
  289. await fiber.dispose()
  290. // The teardown marks every LIVE entry killed; a settled process had
  291. // already left the map, so its status stays completed.
  292. expect(finished.status).toBe('completed')
  293. expect(running.status).toBe('killed')
  294. await running.done
  295. expect(running.signal).toBe('SIGTERM')
  296. })
  297. })