executor.spec.ts 14 KB

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