bridge.spec.ts 13 KB

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