bridge.spec.ts 13 KB

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