bridge.spec.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238
  1. import { createUserMessage } from '@deepseek-ai/dsh-llm'
  2. import { afterEach, describe, expect, it, vi } from 'vitest'
  3. import { chmodSync, existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
  4. import { tmpdir } from 'node:os'
  5. import { join } from 'node:path'
  6. import { Context } from '@deepseek-ai/cordis'
  7. import Loader from '@deepseek-ai/cordis-plugin-loader'
  8. import { SessionId, type SessionEvent } from '@deepseek-ai/dsh-session'
  9. import { defineContentToolFixture } from '@deepseek-ai/dsh-tools'
  10. import type { Agent } from '@deepseek-ai/dsh-agent'
  11. import AgentLoop from '@deepseek-ai/dsh-agent-loop'
  12. import { mountAgentLoopTestDependencies } from '@deepseek-ai/dsh-agent-loop-testkit'
  13. import { LocalBashExecutor } from '@deepseek-ai/dsh-bash-local'
  14. import LocalSubprocessRuntime from '@deepseek-ai/dsh-subprocess-local'
  15. import * as HooksCodex from '@deepseek-ai/dsh-hooks-codex'
  16. import { MockAdapter, textResponse, toolCallResponse } from '../../../core/agent-loop/tests/mock-adapter.ts'
  17. /**
  18. * Full-loop Codex bridge tests with a mock model, the real loop and bash
  19. * executor, and shell hooks from a temporary config. Covers regex matching,
  20. * block-only decisions, and the five-event subset.
  21. */
  22. const dirs: string[] = []
  23. afterEach(() => { for (const d of dirs.splice(0)) rmSync(d, { recursive: true, force: true }) })
  24. function configDir(): string {
  25. const dir = mkdtempSync(join(tmpdir(), 'dsh-hooks-codex-'))
  26. dirs.push(dir)
  27. return dir
  28. }
  29. function script(dir: string, name: string, body: string): string {
  30. const path = join(dir, name)
  31. writeFileSync(path, body)
  32. chmodSync(path, 0o755)
  33. return path
  34. }
  35. function writeHooks(dir: string, hooks: unknown): void {
  36. writeFileSync(join(dir, 'hooks.json'), JSON.stringify({ hooks }))
  37. }
  38. async function harness(dir: string, adapter: MockAdapter, beforeHooks?: (ctx: Context) => void): Promise<Context> {
  39. const ctx = new Context()
  40. await mountAgentLoopTestDependencies(ctx)
  41. await ctx.plugin(AgentLoop, { agents: [] })
  42. await ctx.plugin(LocalSubprocessRuntime)
  43. await ctx.plugin(LocalBashExecutor, { timeoutMs: 10_000 })
  44. beforeHooks?.(ctx)
  45. await ctx.plugin(HooksCodex, { configPath: join(dir, 'hooks.json'), model: 'test-model' })
  46. ctx.llm.registerAdapter(['mock'], adapter)
  47. return ctx
  48. }
  49. function waitForIdle(_ctx: Context, agent: Agent): Promise<void> {
  50. return agent.whenIdle()
  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(createUserMessage({ content: [{ type: 'text', text: 'run ls' }], source: { kind: 'user' } }))
  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.message.content[0].isError).toBe(true)
  77. expect(result?.type === 'tool/result' && result.data.message.content[0].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. // Stop ignores its malformed matcher field. Block once with a marker;
  83. // until the loop guard lands, an always-blocking hook would never 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: [{ matcher: '[', 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(createUserMessage({ content: [{ type: 'text', text: 'go' }], source: { kind: 'user' } }))
  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. }, 15_000) // Two real hook subprocesses and agent steps need startup and teardown headroom under load.
  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(createUserMessage({ content: [{ type: 'text', text: 'cancel the hook' }], source: { kind: 'user' } }))
  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).filter(event => event.type === 'turn/start' || event.type === 'hook/invoked'
  113. || event.type === 'hook/result' || event.type === 'turn/end').map(event => event.type))
  114. .toEqual(['turn/start', 'hook/invoked', 'hook/result', 'turn/end'])
  115. })
  116. it('only the five bridge-supported Codex events are honored — a SubagentStop entry is ignored', async () => {
  117. const dir = configDir()
  118. const s = script(dir, 'x.sh', '#!/usr/bin/env bash\nexit 2\n')
  119. writeHooks(dir, { SubagentStop: [{ hooks: [{ type: 'command', command: s }] }] })
  120. const adapter = new MockAdapter([textResponse('fine')])
  121. const ctx = await harness(dir, adapter)
  122. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  123. agent.followup(createUserMessage({ content: [{ type: 'text', text: 'go' }], source: { kind: 'user' } }))
  124. await waitForIdle(ctx, agent)
  125. expect(adapter.requests).toHaveLength(1)
  126. })
  127. it('a missing config registers no hooks and does not crash', async () => {
  128. const dir = configDir() // no hooks.json written
  129. const adapter = new MockAdapter([textResponse('ok')])
  130. const ctx = await harness(dir, adapter)
  131. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  132. agent.followup(createUserMessage({ content: [{ type: 'text', text: 'go' }], source: { kind: 'user' } }))
  133. await waitForIdle(ctx, agent)
  134. expect(adapter.requests).toHaveLength(1)
  135. })
  136. it('an invalid regex matcher is reported and registers no hooks', async () => {
  137. const dir = configDir()
  138. writeHooks(dir, {
  139. UserPromptSubmit: [{ hooks: [{ type: 'command', command: 'exit 2' }] }],
  140. PreToolUse: [{ matcher: '[', hooks: [{ type: 'command', command: 'exit 2' }] }],
  141. })
  142. const adapter = new MockAdapter([textResponse('ok')])
  143. const warn = vi.fn()
  144. const ctx = await harness(dir, adapter, (ctx) => { ctx.logger.warn = warn as never })
  145. const agent = ctx.agentLoop.create(SessionId('invalid-codex-matcher'), { provider: 'mock', model: 'mock' })
  146. agent.followup(createUserMessage({ content: [{ type: 'text', text: 'go' }], source: { kind: 'user' } }))
  147. await waitForIdle(ctx, agent)
  148. expect(adapter.requests).toHaveLength(1)
  149. expect(events(agent).some(event => event.type === 'hook/invoked')).toBe(false)
  150. expect(warn).toHaveBeenCalledWith(expect.stringContaining(
  151. 'invalid codex regex matcher "[" on event "PreToolUse"',
  152. ))
  153. })
  154. it('disposing the bridge fiber removes its listeners (HMR safety)', async () => {
  155. const dir = configDir()
  156. // A leaked listener would let this blocking hook veto the prompt and log an invocation; a
  157. // no-op hook would pass even when leaked.
  158. const deny = script(dir, 'deny.sh', '#!/usr/bin/env bash\nexit 2\n')
  159. writeHooks(dir, { UserPromptSubmit: [{ hooks: [{ type: 'command', command: deny }] }] })
  160. const adapter = new MockAdapter([textResponse('ok')])
  161. const ctx = new Context()
  162. await mountAgentLoopTestDependencies(ctx)
  163. await ctx.plugin(AgentLoop, { agents: [] })
  164. await ctx.plugin(LocalSubprocessRuntime)
  165. await ctx.plugin(LocalBashExecutor, { timeoutMs: 10_000 })
  166. const fiber = await ctx.plugin(HooksCodex, { configPath: join(dir, 'hooks.json'), model: 'm' })
  167. await fiber.dispose()
  168. ctx.llm.registerAdapter(['mock'], adapter)
  169. const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
  170. agent.followup(createUserMessage({ content: [{ type: 'text', text: 'go' }], source: { kind: 'user' } }))
  171. await waitForIdle(ctx, agent)
  172. expect(adapter.requests).toHaveLength(1) // not blocked → the listener is gone
  173. expect(events(agent).some(e => e.type === 'hook/invoked')).toBe(false) // no hook ran
  174. })
  175. it('disposing the bridge aborts a still-running SessionStart hook and drains to quiescence', async () => {
  176. const dir = configDir()
  177. const pidFile = join(dir, 'pid')
  178. const marker = join(dir, 'started')
  179. // Record the PID and marker before sleeping past the suite timeout. Disposal must abort the
  180. // tracked process through `runPoint`, not await its natural exit.
  181. const slow = script(dir, 'slow.sh', `#!/usr/bin/env bash\necho $$ > "${pidFile}"\ntouch "${marker}"\nsleep 30\n`)
  182. writeHooks(dir, { SessionStart: [{ hooks: [{ type: 'command', command: slow }] }] })
  183. const ctx = new Context()
  184. await mountAgentLoopTestDependencies(ctx)
  185. await ctx.plugin(AgentLoop, { agents: [] })
  186. await ctx.plugin(LocalSubprocessRuntime)
  187. await ctx.plugin(LocalBashExecutor, { timeoutMs: 10_000 })
  188. const fiber = await ctx.plugin(HooksCodex, { configPath: join(dir, 'hooks.json'), model: 'm' })
  189. ctx.llm.registerAdapter(['mock'], new MockAdapter([]))
  190. const warn = vi.fn()
  191. ctx.logger.warn = warn as never
  192. ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' }) // fires agent/session-start
  193. await waitFor(() => existsSync(marker))
  194. const pid = Number(readFileSync(pidFile, 'utf8').trim())
  195. await fiber.dispose()
  196. // Disposal reaches quiescence only after the aborted run settles and the process is reaped, so
  197. // `kill(pid, 0)` must report ESRCH. Untracked fire-and-forget work would remain.
  198. expect(() => process.kill(pid, 0)).toThrow()
  199. // runHook resolves an aborted run as a non-blocking error, so draining must
  200. // not log a rejected continuation.
  201. expect(warn).not.toHaveBeenCalledWith(expect.stringContaining('SessionStart hook failed'))
  202. })
  203. it('has the namespace-plugin export shape (no stray default) so the Loader keeps name/inject/apply', () => {
  204. expect('default' in HooksCodex).toBe(false)
  205. expect(HooksCodex.name).toBe('hooks-codex')
  206. expect(HooksCodex.inject).toEqual(['shell'])
  207. const loader = Object.create(Loader.prototype) as Loader
  208. const unwrapped = loader.unwrapExports(HooksCodex) as Record<string, unknown>
  209. expect(unwrapped).toBe(HooksCodex)
  210. expect(unwrapped.name).toBe('hooks-codex')
  211. expect(unwrapped.inject).toEqual(['shell'])
  212. expect(typeof unwrapped.apply).toBe('function')
  213. })
  214. })