runner.spec.ts 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149
  1. import { describe, expect, it } from 'vitest'
  2. import type { BashExecRequest, BashExecSpec, BashExecutor, BashRunResult } from '@deepseek-ai/dsh-bash'
  3. import { DEFAULT_HOOK_TIMEOUT_MS, runHook } from '@deepseek-ai/dsh-hook-protocol'
  4. /**
  5. * A minimal stand-in for the bits of {@link BashExecutor} that {@link runHook}
  6. * actually calls (`resolve` then `run`). `runHook` is pure plumbing over those
  7. * two methods, so a duck-typed recorder is the right test seam — the REAL
  8. * executor (dsh-bash-local) is exercised end-to-end by the hook-bridge plugins
  9. * that consume this library, not here.
  10. */
  11. function recordingBash(run: (spec: BashExecSpec) => Promise<BashRunResult>): {
  12. bash: BashExecutor
  13. specs: BashExecSpec[]
  14. } {
  15. const specs: BashExecSpec[] = []
  16. const bash = {
  17. resolve(request: BashExecRequest): BashExecSpec {
  18. // Carry the request through verbatim, defaulting the required spec fields —
  19. // exactly what dsh-bash-local's resolve does for the fields runHook sets.
  20. return {
  21. command: request.command,
  22. workdir: request.workdir ?? '/stub',
  23. timeoutMs: request.timeoutMs ?? 0,
  24. stdoutMaxBytes: request.stdoutMaxBytes ?? 64_000,
  25. ...request.signal ? { signal: request.signal } : {},
  26. ...request.stdin !== undefined ? { stdin: request.stdin } : {},
  27. ...request.env !== undefined ? { env: request.env } : {},
  28. sandboxMode: request.sandboxMode,
  29. }
  30. },
  31. async run(spec: BashExecSpec): Promise<BashRunResult> {
  32. specs.push(spec)
  33. return run(spec)
  34. },
  35. } as unknown as BashExecutor
  36. return { bash, specs }
  37. }
  38. function result(over: Partial<BashRunResult> = {}): BashRunResult {
  39. return {
  40. exitCode: 0,
  41. signal: null,
  42. timedOut: false,
  43. aborted: false,
  44. timeoutMs: 1000,
  45. stdout: { text: '', truncated: false },
  46. stderr: { text: '', truncated: false },
  47. ...over,
  48. }
  49. }
  50. const clock = () => { let t = 0; return () => (t += 5) } // +5ms per call → duration 5
  51. describe('runHook — payload + env + stdin plumbing', () => {
  52. it('serializes the payload to stdin (with trailing newline when requested)', async () => {
  53. const { bash, specs } = recordingBash(async () => result({ stdout: { text: '', truncated: false } }))
  54. await runHook(bash, { command: 'my-hook.sh' }, {
  55. payload: { hook_event_name: 'PreToolUse', tool_name: 'Bash' },
  56. defaultTimeoutMs: 60000,
  57. trailingNewline: true,
  58. }, clock())
  59. expect(specs[0]!.stdin).toBe(JSON.stringify({ hook_event_name: 'PreToolUse', tool_name: 'Bash' }) + '\n')
  60. expect(specs[0]!.command).toBe('my-hook.sh')
  61. })
  62. it('omits the trailing newline when trailingNewline is false (Codex)', async () => {
  63. const { bash, specs } = recordingBash(async () => result())
  64. await runHook(bash, { command: 'h' }, { payload: { a: 1 }, defaultTimeoutMs: 1000, trailingNewline: false }, clock())
  65. expect(specs[0]!.stdin).toBe('{"a":1}')
  66. })
  67. it('threads env and cwd into the request', async () => {
  68. const { bash, specs } = recordingBash(async () => result())
  69. await runHook(bash, { command: 'h' }, {
  70. payload: {}, env: { CLAUDE_PROJECT_DIR: '/proj' }, cwd: '/work',
  71. defaultTimeoutMs: 1000, trailingNewline: true,
  72. }, clock())
  73. expect(specs[0]!.env).toEqual({ CLAUDE_PROJECT_DIR: '/proj' })
  74. expect(specs[0]!.workdir).toBe('/work')
  75. })
  76. it('a per-hook timeoutSec (seconds) overrides the default (ms)', async () => {
  77. const { bash, specs } = recordingBash(async () => result())
  78. await runHook(bash, { command: 'h', timeoutSec: 3 }, { payload: {}, defaultTimeoutMs: 60000, trailingNewline: true }, clock())
  79. expect(specs[0]!.timeoutMs).toBe(3000)
  80. })
  81. it('falls back to the default timeout when the hook sets none', async () => {
  82. const { bash, specs } = recordingBash(async () => result())
  83. await runHook(bash, { command: 'h' }, { payload: {}, defaultTimeoutMs: 60000, trailingNewline: true }, clock())
  84. expect(specs[0]!.timeoutMs).toBe(60000)
  85. expect(DEFAULT_HOOK_TIMEOUT_MS).toBe(600_000) // the CC/Codex reference default (10 minutes)
  86. })
  87. it('passes the abort signal through', async () => {
  88. const controller = new AbortController()
  89. const { bash, specs } = recordingBash(async () => result())
  90. await runHook(bash, { command: 'h' }, { payload: {}, signal: controller.signal, defaultTimeoutMs: 1000, trailingNewline: true }, clock())
  91. expect(specs[0]!.signal).toBe(controller.signal)
  92. })
  93. })
  94. describe('runHook — outcome decoding + duration', () => {
  95. it('decodes a clean exit with structured stdout and reports a duration', async () => {
  96. const { bash } = recordingBash(async () => result({
  97. exitCode: 0, stdout: { text: JSON.stringify({ decision: 'block', reason: 'no' }), truncated: false },
  98. }))
  99. const { output, durationMs } = await runHook(bash, { command: 'h' }, { payload: {}, defaultTimeoutMs: 1000, trailingNewline: true }, clock())
  100. expect(output.decision).toBe('block')
  101. expect(output.reason).toBe('no')
  102. expect(durationMs).toBe(5)
  103. })
  104. it('a signal death (exitCode null) decodes as undefined exit (non-blocking error)', async () => {
  105. const { bash } = recordingBash(async () => result({ exitCode: null, signal: 'SIGKILL', stderr: { text: 'killed', truncated: false } }))
  106. const { output } = await runHook(bash, { command: 'h' }, { payload: {}, defaultTimeoutMs: 1000, trailingNewline: true }, clock())
  107. expect(output.exitCode).toBeUndefined()
  108. expect(output.decision).toBeUndefined()
  109. expect(output.stderr).toBe('killed')
  110. })
  111. it('an executor rejection (infra fault) becomes a non-blocking error, never throws', async () => {
  112. const { bash } = recordingBash(async () => { throw new Error('bad workdir: ENOENT') })
  113. const { output } = await runHook(bash, { command: 'h' }, { payload: {}, defaultTimeoutMs: 1000, trailingNewline: true }, clock())
  114. expect(output.exitCode).toBeUndefined()
  115. expect(output.stderr).toBe('bad workdir: ENOENT')
  116. expect(output.decision).toBeUndefined()
  117. })
  118. it('a non-Error rejection is stringified onto stderr', async () => {
  119. const { bash } = recordingBash(async () => { throw 'plain string fault' })
  120. const { output } = await runHook(bash, { command: 'h' }, { payload: {}, defaultTimeoutMs: 1000, trailingNewline: true }, clock())
  121. expect(output.stderr).toBe('plain string fault')
  122. })
  123. it('threads expectedEventName so a mismatched hookSpecificOutput block is discarded', async () => {
  124. const { bash } = recordingBash(async () => result({
  125. exitCode: 0,
  126. stdout: { text: JSON.stringify({ hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: 'deny' } }), truncated: false },
  127. }))
  128. const { output } = await runHook(bash, { command: 'h' }, {
  129. payload: {}, defaultTimeoutMs: 1000, trailingNewline: true, expectedEventName: 'Stop',
  130. }, clock())
  131. // A PreToolUse block on a Stop hook is malformed → its decision is discarded.
  132. expect(output.hookEventName).toBe('PreToolUse')
  133. expect(output.decision).toBeUndefined()
  134. })
  135. })