bridge.spec.ts 11 KB

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