1
0

runner.spec.ts 7.4 KB

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