executor.spec.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  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. })
  66. it('per-call timeout takes precedence under the cap and kills on expiry', async () => {
  67. const { bash } = await setup({ timeoutMs: 60_000 })
  68. const result = await bash.run(bash.resolve({ command: 'sleep 60', timeoutMs: 100 }))
  69. expect(result.timedOut).toBe(true)
  70. // Mutually exclusive: a timeout classifies as timedOut, never also aborted.
  71. expect(result.aborted).toBe(false)
  72. expect(result.timeoutMs).toBe(100)
  73. })
  74. it('propagates abort signals', async () => {
  75. const { bash } = await setup()
  76. const controller = new AbortController()
  77. const pending = bash.run(bash.resolve({ command: 'sleep 60', signal: controller.signal }))
  78. setTimeout(() => { controller.abort() }, 50)
  79. const result = await pending
  80. expect(result.aborted).toBe(true)
  81. // Mutually exclusive: an upstream cancel classifies as aborted, never also timedOut.
  82. expect(result.timedOut).toBe(false)
  83. })
  84. it('classifies a self-killed command as neither timed out nor aborted', async () => {
  85. // The command kills itself (SIGTERM) with no timeout and no upstream abort:
  86. // the deadline signal never fires, so both classifications are false — the
  87. // fused-signal classification reports the cause that cut the command short,
  88. // and here nothing the executor owns did.
  89. const { bash } = await setup({ timeoutMs: 60_000 })
  90. const result = await bash.run(bash.resolve({ command: 'kill -TERM $$' }))
  91. expect(result.signal).toBe('SIGTERM')
  92. expect(result.timedOut).toBe(false)
  93. expect(result.aborted).toBe(false)
  94. })
  95. it('rejects on spawn failure (bad workdir)', async () => {
  96. const { bash } = await setup()
  97. await expect(bash.run(bash.resolve({ command: 'true', workdir: '/nonexistent-dsh' }))).rejects.toThrow(/ENOENT/)
  98. })
  99. it('resolve() carries stdin/env onto the spec, and run() threads them to the command', async () => {
  100. const { bash } = await setup()
  101. const spec = bash.resolve({ command: 'cat; echo "[$DSH_SEAM_VAR]"', stdin: 'piped\n', env: { DSH_SEAM_VAR: 'env-ok' } })
  102. // resolve() keeps the stdin/env fields verbatim (optional, no default).
  103. expect(spec.stdin).toBe('piped\n')
  104. expect(spec.env).toEqual({ DSH_SEAM_VAR: 'env-ok' })
  105. const result = await bash.run(spec)
  106. expect(result.stdout.text).toBe('piped\n[env-ok]\n')
  107. })
  108. it('resolve() omits stdin/env when the request supplies neither', async () => {
  109. const { bash } = await setup()
  110. const spec = bash.resolve({ command: 'true' })
  111. expect('stdin' in spec).toBe(false)
  112. expect('env' in spec).toBe(false)
  113. })
  114. })
  115. describe('LocalBashExecutor.start (background process handles)', () => {
  116. it('start returns immediately with a running handle that settles as completed', async () => {
  117. const { bash } = await setup()
  118. const before = Date.now()
  119. const proc = bash.start(bash.resolve({ command: 'sleep 0.2; echo done' }))
  120. expect(Date.now() - before).toBeLessThan(150)
  121. expect(proc.status).toBe('running')
  122. await proc.done
  123. expect(proc.status).toBe('completed')
  124. expect(proc.exitCode).toBe(0)
  125. })
  126. it('threads stdin and extra env into a background process', async () => {
  127. const { bash } = await setup()
  128. const proc = bash.start(bash.resolve({
  129. command: 'cat; echo "[$DSH_BG_VAR]"',
  130. stdin: 'bg-stdin\n',
  131. env: { DSH_BG_VAR: 'bg-env' },
  132. }))
  133. const output = await readUntil(proc, '[bg-env]')
  134. expect(output).toContain('bg-stdin')
  135. await proc.done
  136. expect(proc.exitCode).toBe(0)
  137. })
  138. it('readOutput is consuming: increments are never re-delivered, and reads stay valid after exit', async () => {
  139. const { bash } = await setup()
  140. const proc = bash.start(bash.resolve({ command: 'echo first; sleep 1; echo second' }))
  141. const first = await readUntil(proc, 'first\n')
  142. expect(first).toBe('first\n')
  143. await proc.done
  144. // Read-after-exit returns the remaining buffered output — once.
  145. const second = proc.readOutput()
  146. expect(second.delta).toBe('second\n')
  147. expect(second.lossy).toBe(false)
  148. expect(proc.readOutput().delta).toBe('')
  149. })
  150. it('readOutput marks stderr sections', async () => {
  151. const { bash } = await setup()
  152. const proc = bash.start(bash.resolve({ command: 'echo out; echo err >&2' }))
  153. await proc.done
  154. expect(proc.readOutput().delta).toBe('out\n[stderr]\nerr\n')
  155. })
  156. it('readOutput reports stderr-only deltas without a leading newline', async () => {
  157. const { bash } = await setup()
  158. const proc = bash.start(bash.resolve({ command: 'echo err >&2' }))
  159. await proc.done
  160. expect(proc.readOutput().delta).toBe('[stderr]\nerr\n')
  161. })
  162. it('readOutput adds a separator only when stdout lacks a trailing newline', async () => {
  163. const { bash } = await setup()
  164. const proc = bash.start(bash.resolve({ command: 'printf out; echo err >&2' }))
  165. await proc.done
  166. expect(proc.readOutput().delta).toBe('out\n[stderr]\nerr\n')
  167. })
  168. it('readOutput flags lossy reads and reports stdout spill paths', async () => {
  169. const { bash } = await setup({ maxOutputBytes: 100 })
  170. const proc = bash.start(bash.resolve({ command: 'for i in $(seq 1 100); do printf "line-%04d\\n" $i; done' }))
  171. await proc.done
  172. const read = proc.readOutput()
  173. // Window slid past offset 0 → lossy, spill path points at the full stream.
  174. expect(read.lossy).toBe(true)
  175. expect(read.stdoutSpillPath).toBeDefined()
  176. })
  177. it('readOutput reports stderr spill paths', async () => {
  178. const { bash } = await setup({ maxOutputBytes: 100 })
  179. const proc = bash.start(bash.resolve({ command: 'for i in $(seq 1 100); do printf "line-%04d\\n" $i >&2; done' }))
  180. await proc.done
  181. const read = proc.readOutput()
  182. expect(read.lossy).toBe(true)
  183. expect(read.stderrSpillPath).toBeDefined()
  184. expect(read.delta).toContain('[stderr]')
  185. })
  186. it('kill() terminates the process group: true once, false after settlement', async () => {
  187. const { bash } = await setup()
  188. const proc = bash.start(bash.resolve({ command: 'sleep 60' }))
  189. expect(proc.kill()).toBe(true)
  190. await proc.done
  191. expect(proc.status).toBe('killed')
  192. expect(proc.signal).toBe('SIGTERM')
  193. expect(proc.kill()).toBe(false)
  194. })
  195. it('kill() returns false for a naturally completed process', async () => {
  196. const { bash } = await setup()
  197. const proc = bash.start(bash.resolve({ command: 'true' }))
  198. await proc.done
  199. expect(proc.status).toBe('completed')
  200. expect(proc.kill()).toBe(false)
  201. })
  202. it('kill escalation uses the configured graceMs (a TERM-trapping process dies by SIGKILL)', async () => {
  203. const { bash } = await setup() // setup pins graceMs: 200 via config
  204. // The child echoes AFTER arming the trap, so waiting for the marker
  205. // guarantees SIGTERM is already ignored when the kill lands (a fixed sleep
  206. // is load-flaky: a slow spawn would take the SIGTERM before the trap).
  207. const proc = bash.start(bash.resolve({ command: 'trap \'\' TERM; echo armed; sleep 60' }))
  208. await readUntil(proc, 'armed')
  209. proc.kill()
  210. await proc.done
  211. expect(proc.status).toBe('killed')
  212. expect(proc.signal).toBe('SIGKILL')
  213. })
  214. it('a spec.signal abort settles the handle as killed, not completed', async () => {
  215. const { bash } = await setup()
  216. const controller = new AbortController()
  217. const proc = bash.start(bash.resolve({ command: 'sleep 60', signal: controller.signal }))
  218. controller.abort()
  219. await proc.done
  220. expect(proc.status).toBe('killed')
  221. expect(proc.signal).toBe('SIGTERM')
  222. })
  223. it('a self-signal exit settles the handle as killed, not completed', async () => {
  224. const { bash } = await setup()
  225. const proc = bash.start(bash.resolve({ command: 'kill -TERM $$' }))
  226. await proc.done
  227. expect(proc.status).toBe('killed')
  228. expect(proc.exitCode).toBeNull()
  229. expect(proc.signal).toBe('SIGTERM')
  230. })
  231. it('a background spawn failure settles as killed with the error readable on stderr', async () => {
  232. const { bash } = await setup()
  233. const proc = bash.start(bash.resolve({ command: 'true', workdir: '/nonexistent-dsh' }))
  234. // done resolves (never rejects) even though the process never ran.
  235. await expect(proc.done).resolves.toBeUndefined()
  236. expect(proc.status).toBe('killed')
  237. expect(proc.readOutput().delta).toContain('spawn failed:')
  238. })
  239. })
  240. describe('LocalBashExecutor disposal', () => {
  241. it('disposing the fiber kills running processes and AWAITS their exit (no orphans, SIGKILL escalation included)', async () => {
  242. const ctx = new Context()
  243. const fiber = await ctx.plugin(LocalBashExecutor, { graceMs: 200 })
  244. const bash = ctx.bash as LocalBashExecutor
  245. bash.internals = { spillDir }
  246. // The child prints its own pid ($$ = the detached bash group leader) so
  247. // the test can probe liveness through the public read surface alone.
  248. const proc = bash.start(bash.resolve({ command: 'trap \'\' TERM; echo $$; sleep 60' }))
  249. const pid = Number((await readUntil(proc, '\n')).trim())
  250. expect(Number.isInteger(pid) && pid > 0).toBe(true)
  251. await fiber.dispose()
  252. // Disposal itself waited: the pid must already be gone, no grace left —
  253. // even for a TERM-trapping child held until the SIGKILL escalation landed.
  254. expect(() => process.kill(pid, 0)).toThrow()
  255. expect(proc.status).toBe('killed')
  256. await proc.done
  257. })
  258. it('settled processes already left the live map: dispose does not touch them', async () => {
  259. const ctx = new Context()
  260. const fiber = await ctx.plugin(LocalBashExecutor, { graceMs: 200 })
  261. const bash = ctx.bash as LocalBashExecutor
  262. bash.internals = { spillDir }
  263. const finished = bash.start(bash.resolve({ command: 'echo done' }))
  264. await finished.done
  265. expect(finished.status).toBe('completed')
  266. const running = bash.start(bash.resolve({ command: 'sleep 60' }))
  267. await fiber.dispose()
  268. // The teardown marks every LIVE entry killed; a settled process had
  269. // already left the map, so its status stays completed.
  270. expect(finished.status).toBe('completed')
  271. expect(running.status).toBe('killed')
  272. await running.done
  273. expect(running.signal).toBe('SIGTERM')
  274. })
  275. })