bridge.spec.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  1. import { afterEach, describe, expect, it, vi } from 'vitest'
  2. import { chmodSync, existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
  3. import { tmpdir } from 'node:os'
  4. import { join } from 'node:path'
  5. import { Context } from 'cordis'
  6. import Loader from '@cordisjs/plugin-loader'
  7. import { SessionId, type SessionEvent } from '@deepseek-ai/dsh-session'
  8. import { defineContentToolFixture } from '@deepseek-ai/dsh-tools'
  9. import type { Agent } from '@deepseek-ai/dsh-agent'
  10. import AgentLoop from '@deepseek-ai/dsh-agent-loop'
  11. import { mountAgentLoopTestDependencies } from '@deepseek-ai/dsh-agent-loop-testkit'
  12. import { LocalBashExecutor } from '@deepseek-ai/dsh-bash-local'
  13. import * as HooksCodex from '@deepseek-ai/dsh-hooks-codex'
  14. import { MockAdapter, textResponse, toolCallResponse } from '../../../core/agent-loop/tests/mock-adapter.ts'
  15. /**
  16. * Full-loop Codex bridge tests with a mock model, the real loop and bash
  17. * executor, and shell hooks from a temporary config. Covers regex matching,
  18. * block-only decisions, and the five-event subset.
  19. */
  20. const dirs: string[] = []
  21. afterEach(() => { for (const d of dirs.splice(0)) rmSync(d, { recursive: true, force: true }) })
  22. function configDir(): string {
  23. const dir = mkdtempSync(join(tmpdir(), 'dsh-hooks-codex-'))
  24. dirs.push(dir)
  25. return dir
  26. }
  27. function script(dir: string, name: string, body: string): string {
  28. const path = join(dir, name)
  29. writeFileSync(path, body)
  30. chmodSync(path, 0o755)
  31. return path
  32. }
  33. function writeHooks(dir: string, hooks: unknown): void {
  34. writeFileSync(join(dir, 'hooks.json'), JSON.stringify({ hooks }))
  35. }
  36. async function harness(dir: string, adapter: MockAdapter): Promise<Context> {
  37. const ctx = new Context()
  38. await mountAgentLoopTestDependencies(ctx)
  39. await ctx.plugin(AgentLoop, { agents: [] })
  40. await ctx.plugin(LocalBashExecutor, { timeoutMs: 10_000 })
  41. await ctx.plugin(HooksCodex, { configPath: join(dir, 'hooks.json'), model: 'test-model' })
  42. ctx.llm.registerAdapter(['mock'], adapter)
  43. return ctx
  44. }
  45. function waitForIdle(ctx: Context, agent: Agent): Promise<void> {
  46. return new Promise((resolve) => {
  47. const dispose = ctx.on('agent/status', (subject, status) => {
  48. if (subject === agent && status === 'idle') { dispose(); resolve() }
  49. })
  50. })
  51. }
  52. function events(agent: Agent): SessionEvent[] { return [...agent.session.events] }
  53. /** Poll `predicate` until true or the deadline passes (detached hook effects can't be awaited directly). */
  54. async function waitFor(predicate: () => boolean, timeout = 5000, interval = 10): Promise<void> {
  55. const deadline = Date.now() + timeout
  56. while (!predicate()) {
  57. if (Date.now() > deadline) throw new Error('waitFor: condition not met before deadline')
  58. await new Promise(r => setTimeout(r, interval))
  59. }
  60. }
  61. describe('hooks-codex bridge', () => {
  62. it('a PreToolUse hook (exit 2) denies a tool the regex matcher matches as a substring', async () => {
  63. const dir = configDir()
  64. const deny = script(dir, 'deny.sh', '#!/usr/bin/env bash\necho "codex blocked it" >&2\nexit 2\n')
  65. // Codex regex matcher: "Bash" is /Bash/ — matches the tool name "Bash".
  66. writeHooks(dir, { PreToolUse: [{ matcher: 'Bash', hooks: [{ type: 'command', command: deny }] }] })
  67. const adapter = new MockAdapter([toolCallResponse('c1', 'Bash', { command: 'ls' }), textResponse('done')])
  68. const ctx = await harness(dir, adapter)
  69. let ran = false
  70. ctx.tools.register(defineContentToolFixture({ name: 'Bash', description: 'b', parameters: { command: { type: 'string' } }, async execute() { ran = true; return [{ type: 'text', text: 'no' }] } }))
  71. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  72. agent.followup([{ type: 'text', text: 'run ls' }])
  73. await waitForIdle(ctx, agent)
  74. expect(ran).toBe(false)
  75. const result = events(agent).find(e => e.type === 'tool/result')
  76. expect(result?.type === 'tool/result' && result.data.isError).toBe(true)
  77. expect(result?.type === 'tool/result' && result.data.content.some(b => b.type === 'text' && b.text.includes('codex blocked it'))).toBe(true)
  78. expect(events(agent).some(e => e.type === 'hook/invoked' && e.data.dialect === 'codex' && e.data.point === 'PreToolUse')).toBe(true)
  79. })
  80. it('a Stop hook (exit 2) forces the turn to continue with the reason as steering', async () => {
  81. const dir = configDir()
  82. // Block once with a marker; until the loop guard lands, an always-blocking
  83. // hook would never let this test finish.
  84. const marker = join(dir, 'fired')
  85. const cont = script(dir, 'cont.sh', `#!/usr/bin/env bash\nif [ -e "${marker}" ]; then exit 0; fi\ntouch "${marker}"\necho "keep going: address the goal" >&2\nexit 2\n`)
  86. writeHooks(dir, { Stop: [{ hooks: [{ type: 'command', command: cont }] }] })
  87. const adapter = new MockAdapter([textResponse('first answer'), textResponse('second answer after goal')])
  88. const ctx = await harness(dir, adapter)
  89. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  90. agent.followup([{ type: 'text', text: 'go' }])
  91. await waitForIdle(ctx, agent)
  92. expect(adapter.requests).toHaveLength(2)
  93. expect(JSON.stringify(adapter.requests[1]!.messages)).toContain('keep going: address the goal')
  94. })
  95. it('turn cancellation aborts and reaps a running UserPromptSubmit hook before idle', async () => {
  96. const dir = configDir()
  97. const pidFile = join(dir, 'pid')
  98. const marker = join(dir, 'started')
  99. const slow = script(dir, 'slow-prompt.sh', `#!/usr/bin/env bash\necho $$ > "${pidFile}"\ntouch "${marker}"\nsleep 30\n`)
  100. writeHooks(dir, { UserPromptSubmit: [{ hooks: [{ type: 'command', command: slow }] }] })
  101. const adapter = new MockAdapter([textResponse('must not run')])
  102. const ctx = await harness(dir, adapter)
  103. const agent = ctx.agentLoop.create(SessionId('cancel-prompt-hook'), { provider: 'mock', model: 'mock' })
  104. agent.followup([{ type: 'text', text: 'cancel the hook' }])
  105. await waitFor(() => existsSync(marker))
  106. const pid = Number(readFileSync(pidFile, 'utf8').trim())
  107. const idle = agent.whenIdle()
  108. agent.cancel({ kind: 'user' })
  109. await idle
  110. expect(() => process.kill(pid, 0)).toThrow()
  111. expect(adapter.requests).toHaveLength(0)
  112. expect(events(agent).findLast(event => event.type === 'turn/end')).toMatchObject({
  113. data: { reason: { kind: 'aborted' } },
  114. })
  115. expect(events(agent).some(event => event.type === 'hook/result' && event.data.point === 'UserPromptSubmit')).toBe(true)
  116. })
  117. it('only the five bridge-supported Codex events are honored — a SubagentStop entry is ignored', async () => {
  118. const dir = configDir()
  119. const s = script(dir, 'x.sh', '#!/usr/bin/env bash\nexit 2\n')
  120. writeHooks(dir, { SubagentStop: [{ hooks: [{ type: 'command', command: s }] }] })
  121. const adapter = new MockAdapter([textResponse('fine')])
  122. const ctx = await harness(dir, adapter)
  123. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  124. agent.followup([{ type: 'text', text: 'go' }])
  125. await waitForIdle(ctx, agent)
  126. expect(adapter.requests).toHaveLength(1)
  127. })
  128. it('a missing config registers no hooks and does not crash', async () => {
  129. const dir = configDir() // no hooks.json written
  130. const adapter = new MockAdapter([textResponse('ok')])
  131. const ctx = await harness(dir, adapter)
  132. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  133. agent.followup([{ type: 'text', text: 'go' }])
  134. await waitForIdle(ctx, agent)
  135. expect(adapter.requests).toHaveLength(1)
  136. })
  137. it('disposing the bridge fiber removes its listeners (HMR safety)', async () => {
  138. const dir = configDir()
  139. // A leaked listener would let this blocking hook veto the prompt and log an invocation; a
  140. // no-op hook would pass even when leaked.
  141. const deny = script(dir, 'deny.sh', '#!/usr/bin/env bash\nexit 2\n')
  142. writeHooks(dir, { UserPromptSubmit: [{ hooks: [{ type: 'command', command: deny }] }] })
  143. const adapter = new MockAdapter([textResponse('ok')])
  144. const ctx = new Context()
  145. await mountAgentLoopTestDependencies(ctx)
  146. await ctx.plugin(AgentLoop, { agents: [] })
  147. await ctx.plugin(LocalBashExecutor, { timeoutMs: 10_000 })
  148. const fiber = await ctx.plugin(HooksCodex, { configPath: join(dir, 'hooks.json'), model: 'm' })
  149. await fiber.dispose()
  150. ctx.llm.registerAdapter(['mock'], adapter)
  151. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  152. agent.followup([{ type: 'text', text: 'go' }])
  153. await waitForIdle(ctx, agent)
  154. expect(adapter.requests).toHaveLength(1) // not blocked → the listener is gone
  155. expect(events(agent).some(e => e.type === 'hook/invoked')).toBe(false) // no hook ran
  156. })
  157. it('disposing the bridge aborts a still-running SessionStart hook and drains to quiescence', async () => {
  158. const dir = configDir()
  159. const pidFile = join(dir, 'pid')
  160. const marker = join(dir, 'started')
  161. // Record the PID and marker before sleeping past the suite timeout. Disposal must abort the
  162. // tracked process through `runPoint`, not await its natural exit.
  163. const slow = script(dir, 'slow.sh', `#!/usr/bin/env bash\necho $$ > "${pidFile}"\ntouch "${marker}"\nsleep 30\n`)
  164. writeHooks(dir, { SessionStart: [{ hooks: [{ type: 'command', command: slow }] }] })
  165. const ctx = new Context()
  166. await mountAgentLoopTestDependencies(ctx)
  167. await ctx.plugin(AgentLoop, { agents: [] })
  168. await ctx.plugin(LocalBashExecutor, { timeoutMs: 10_000 })
  169. const fiber = await ctx.plugin(HooksCodex, { configPath: join(dir, 'hooks.json'), model: 'm' })
  170. ctx.llm.registerAdapter(['mock'], new MockAdapter([]))
  171. const warn = vi.fn()
  172. ctx.logger.warn = warn as never
  173. ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' }) // fires agent/session-start
  174. await waitFor(() => existsSync(marker))
  175. const pid = Number(readFileSync(pidFile, 'utf8').trim())
  176. await fiber.dispose()
  177. // Disposal reaches quiescence only after the aborted run settles and the process is reaped, so
  178. // `kill(pid, 0)` must report ESRCH. Untracked fire-and-forget work would remain.
  179. expect(() => process.kill(pid, 0)).toThrow()
  180. // runHook resolves an aborted run as a non-blocking error, so draining must
  181. // not log a rejected continuation.
  182. expect(warn).not.toHaveBeenCalledWith(expect.stringContaining('SessionStart hook failed'))
  183. })
  184. it('has the namespace-plugin export shape (no stray default) so the Loader keeps name/inject/apply', () => {
  185. expect('default' in HooksCodex).toBe(false)
  186. expect(HooksCodex.name).toBe('hooks-codex')
  187. expect(HooksCodex.inject).toEqual(['bash'])
  188. const loader = Object.create(Loader.prototype) as Loader
  189. const unwrapped = loader.unwrapExports(HooksCodex) as Record<string, unknown>
  190. expect(unwrapped).toBe(HooksCodex)
  191. expect(unwrapped.name).toBe('hooks-codex')
  192. expect(unwrapped.inject).toEqual(['bash'])
  193. expect(typeof unwrapped.apply).toBe('function')
  194. })
  195. })