bridge.spec.ts 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  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 { defineTool } 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(defineTool({ 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.send([{ 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.send([{ 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('only the five bridge-supported Codex events are honored — a SubagentStop entry is ignored', async () => {
  96. const dir = configDir()
  97. const s = script(dir, 'x.sh', '#!/usr/bin/env bash\nexit 2\n')
  98. writeHooks(dir, { SubagentStop: [{ hooks: [{ type: 'command', command: s }] }] })
  99. const adapter = new MockAdapter([textResponse('fine')])
  100. const ctx = await harness(dir, adapter)
  101. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  102. agent.send([{ type: 'text', text: 'go' }])
  103. await waitForIdle(ctx, agent)
  104. expect(adapter.requests).toHaveLength(1)
  105. })
  106. it('a missing config registers no hooks and does not crash', async () => {
  107. const dir = configDir() // no hooks.json written
  108. const adapter = new MockAdapter([textResponse('ok')])
  109. const ctx = await harness(dir, adapter)
  110. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  111. agent.send([{ type: 'text', text: 'go' }])
  112. await waitForIdle(ctx, agent)
  113. expect(adapter.requests).toHaveLength(1)
  114. })
  115. it('disposing the bridge fiber removes its listeners (HMR safety)', async () => {
  116. const dir = configDir()
  117. // A leaked listener would let this blocking hook veto the prompt and log an invocation; a
  118. // no-op hook would pass even when leaked.
  119. const deny = script(dir, 'deny.sh', '#!/usr/bin/env bash\nexit 2\n')
  120. writeHooks(dir, { UserPromptSubmit: [{ hooks: [{ type: 'command', command: deny }] }] })
  121. const adapter = new MockAdapter([textResponse('ok')])
  122. const ctx = new Context()
  123. await mountAgentLoopTestDependencies(ctx)
  124. await ctx.plugin(AgentLoop, { agents: [] })
  125. await ctx.plugin(LocalBashExecutor, { timeoutMs: 10_000 })
  126. const fiber = await ctx.plugin(HooksCodex, { configPath: join(dir, 'hooks.json'), model: 'm' })
  127. await fiber.dispose()
  128. ctx.llm.registerAdapter(['mock'], adapter)
  129. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  130. agent.send([{ type: 'text', text: 'go' }])
  131. await waitForIdle(ctx, agent)
  132. expect(adapter.requests).toHaveLength(1) // not blocked → the listener is gone
  133. expect(events(agent).some(e => e.type === 'hook/invoked')).toBe(false) // no hook ran
  134. })
  135. it('disposing the bridge aborts a still-running SessionStart hook and drains to quiescence', async () => {
  136. const dir = configDir()
  137. const pidFile = join(dir, 'pid')
  138. const marker = join(dir, 'started')
  139. // Record the PID and marker before sleeping past the suite timeout. Disposal must abort the
  140. // tracked process through `runPoint`, not await its natural exit.
  141. const slow = script(dir, 'slow.sh', `#!/usr/bin/env bash\necho $$ > "${pidFile}"\ntouch "${marker}"\nsleep 30\n`)
  142. writeHooks(dir, { SessionStart: [{ hooks: [{ type: 'command', command: slow }] }] })
  143. const ctx = new Context()
  144. await mountAgentLoopTestDependencies(ctx)
  145. await ctx.plugin(AgentLoop, { agents: [] })
  146. await ctx.plugin(LocalBashExecutor, { timeoutMs: 10_000 })
  147. const fiber = await ctx.plugin(HooksCodex, { configPath: join(dir, 'hooks.json'), model: 'm' })
  148. ctx.llm.registerAdapter(['mock'], new MockAdapter([]))
  149. const warn = vi.fn()
  150. ctx.logger.warn = warn as never
  151. ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' }) // fires agent/session-start
  152. await waitFor(() => existsSync(marker))
  153. const pid = Number(readFileSync(pidFile, 'utf8').trim())
  154. await fiber.dispose()
  155. // Disposal reaches quiescence only after the aborted run settles and the process is reaped, so
  156. // `kill(pid, 0)` must report ESRCH. Untracked fire-and-forget work would remain.
  157. expect(() => process.kill(pid, 0)).toThrow()
  158. // runHook resolves an aborted run as a non-blocking error, so draining must
  159. // not log a rejected continuation.
  160. expect(warn).not.toHaveBeenCalledWith(expect.stringContaining('SessionStart hook failed'))
  161. })
  162. it('has the namespace-plugin export shape (no stray default) so the Loader keeps name/inject/apply', () => {
  163. expect('default' in HooksCodex).toBe(false)
  164. expect(HooksCodex.name).toBe('hooks-codex')
  165. expect(HooksCodex.inject).toEqual(['bash'])
  166. const loader = Object.create(Loader.prototype) as Loader
  167. const unwrapped = loader.unwrapExports(HooksCodex) as Record<string, unknown>
  168. expect(unwrapped).toBe(HooksCodex)
  169. expect(unwrapped.name).toBe('hooks-codex')
  170. expect(unwrapped.inject).toEqual(['bash'])
  171. expect(typeof unwrapped.apply).toBe('function')
  172. })
  173. })