bridge.spec.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  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 LlmService from '@deepseek-ai/dsh-llm'
  8. import SessionStore, { type SessionEvent } from '@deepseek-ai/dsh-session'
  9. import SystemPrompt from '@deepseek-ai/dsh-system-prompt'
  10. import ToolRegistry, { defineTool } from '@deepseek-ai/dsh-tools'
  11. import AgentRegistry, { AgentId } from '@deepseek-ai/dsh-agent'
  12. import AgentLoop, { type ReactLoopAgent } from '@deepseek-ai/dsh-agent-loop'
  13. import { LocalBashExecutor } from '@deepseek-ai/dsh-bash-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: scripted mock MODEL + REAL loop + REAL bash +
  18. * REAL `dsh-hooks-codex` running REAL shell scripts from a temp `hooks.json`.
  19. * Codex dialect specifics exercised here: regex matcher (substring), block-only
  20. * decisions, 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): Promise<Context> {
  39. const ctx = new Context()
  40. await ctx.plugin(LlmService)
  41. await ctx.plugin(SessionStore)
  42. await ctx.plugin(SystemPrompt)
  43. await ctx.plugin(ToolRegistry)
  44. await ctx.plugin(AgentRegistry)
  45. await ctx.plugin(AgentLoop, { agents: [] })
  46. await ctx.plugin(LocalBashExecutor, { timeoutMs: 10_000 })
  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: ReactLoopAgent): Promise<void> {
  52. return new Promise((resolve) => {
  53. const dispose = ctx.on('agent/status', (subject, status) => {
  54. if (subject === agent && status === 'idle') { dispose(); resolve() }
  55. })
  56. })
  57. }
  58. function events(agent: ReactLoopAgent): SessionEvent[] { return [...agent.session.events] }
  59. /** Poll `predicate` until true or the deadline passes (detached hook effects can't be awaited directly). */
  60. async function waitFor(predicate: () => boolean, timeout = 5000, interval = 10): Promise<void> {
  61. const deadline = Date.now() + timeout
  62. while (!predicate()) {
  63. if (Date.now() > deadline) throw new Error('waitFor: condition not met before deadline')
  64. await new Promise(r => setTimeout(r, interval))
  65. }
  66. }
  67. describe('hooks-codex bridge', () => {
  68. it('a PreToolUse hook (exit 2) denies a tool the regex matcher matches as a substring', async () => {
  69. const dir = configDir()
  70. const deny = script(dir, 'deny.sh', '#!/usr/bin/env bash\necho "codex blocked it" >&2\nexit 2\n')
  71. // Codex regex matcher: "Bash" is /Bash/ — matches the tool name "Bash".
  72. writeHooks(dir, { PreToolUse: [{ matcher: 'Bash', hooks: [{ type: 'command', command: deny }] }] })
  73. const adapter = new MockAdapter([toolCallResponse('c1', 'Bash', { command: 'ls' }), textResponse('done')])
  74. const ctx = await harness(dir, adapter)
  75. let ran = false
  76. ctx.tools.register(defineTool({ name: 'Bash', description: 'b', parameters: { command: { type: 'string' } }, async execute() { ran = true; return [{ type: 'text', text: 'no' }] } }))
  77. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  78. agent.send([{ type: 'text', text: 'run ls' }])
  79. await waitForIdle(ctx, agent)
  80. expect(ran).toBe(false)
  81. const result = events(agent).find(e => e.type === 'tool/result')
  82. expect(result?.type === 'tool/result' && result.data.isError).toBe(true)
  83. expect(result?.type === 'tool/result' && result.data.content.some(b => b.type === 'text' && b.text.includes('codex blocked it'))).toBe(true)
  84. // recorded under the codex dialect
  85. expect(events(agent).some(e => e.type === 'hook/invoked' && e.data.dialect === 'codex' && e.data.point === 'PreToolUse')).toBe(true)
  86. })
  87. it('a Stop hook (exit 2) forces the turn to continue with the reason as steering', async () => {
  88. const dir = configDir()
  89. // Block exactly ONCE (a marker file), then allow — without a one-shot guard a
  90. // hook that always exits 2 would force-continue forever (the deferred
  91. // stop_hook_active loop-guard is the real fix; here we self-limit so the test
  92. // exercises the continue path without looping).
  93. const marker = join(dir, 'fired')
  94. 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`)
  95. writeHooks(dir, { Stop: [{ hooks: [{ type: 'command', command: cont }] }] })
  96. // Step 1 has no tool calls → would stop; the Stop hook forces step 2.
  97. const adapter = new MockAdapter([textResponse('first answer'), textResponse('second answer after goal')])
  98. const ctx = await harness(dir, adapter)
  99. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  100. agent.send([{ type: 'text', text: 'go' }])
  101. await waitForIdle(ctx, agent)
  102. // The Stop hook's reason became next-step steering → a second model request ran.
  103. expect(adapter.requests).toHaveLength(2)
  104. expect(JSON.stringify(adapter.requests[1]!.messages)).toContain('keep going: address the goal')
  105. })
  106. it('only the five Codex events are honored — a SubagentStop entry is ignored', async () => {
  107. const dir = configDir()
  108. const s = script(dir, 'x.sh', '#!/usr/bin/env bash\nexit 2\n')
  109. // SubagentStop is NOT a Codex event; it must be dropped (no crash, no effect).
  110. writeHooks(dir, { SubagentStop: [{ hooks: [{ type: 'command', command: s }] }] })
  111. const adapter = new MockAdapter([textResponse('fine')])
  112. const ctx = await harness(dir, adapter)
  113. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  114. agent.send([{ type: 'text', text: 'go' }])
  115. await waitForIdle(ctx, agent)
  116. // Ran normally; the unknown event was dropped at parse.
  117. expect(adapter.requests).toHaveLength(1)
  118. })
  119. it('a missing config registers no hooks and does not crash', async () => {
  120. const dir = configDir() // no hooks.json written
  121. const adapter = new MockAdapter([textResponse('ok')])
  122. const ctx = await harness(dir, adapter)
  123. const agent = ctx.agentLoop.create(AgentId('a1'), { model: 'mock' })
  124. agent.send([{ type: 'text', text: 'go' }])
  125. await waitForIdle(ctx, agent)
  126. expect(adapter.requests).toHaveLength(1)
  127. })
  128. it('disposing the bridge fiber removes its listeners (HMR safety)', async () => {
  129. const dir = configDir()
  130. // A BLOCKING UserPromptSubmit hook: if the listener leaked past dispose, it
  131. // would veto the prompt (0 model requests) and log a hook/invoked. After a
  132. // clean dispose the turn must proceed untouched — this fails loudly on a leak
  133. // (a no-op `true` hook would pass even with a leaked listener).
  134. const deny = script(dir, 'deny.sh', '#!/usr/bin/env bash\nexit 2\n')
  135. writeHooks(dir, { UserPromptSubmit: [{ hooks: [{ type: 'command', command: deny }] }] })
  136. const adapter = new MockAdapter([textResponse('ok')])
  137. const ctx = new Context()
  138. await ctx.plugin(LlmService)
  139. await ctx.plugin(SessionStore)
  140. await ctx.plugin(SystemPrompt)
  141. await ctx.plugin(ToolRegistry)
  142. await ctx.plugin(AgentRegistry)
  143. await ctx.plugin(AgentLoop, { agents: [] })
  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(AgentId('a1'), { model: 'mock' })
  149. agent.send([{ type: 'text', text: 'go' }])
  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 hook shell's PID and touch the marker FIRST so the test can
  159. // tell "the hook is genuinely mid-run", then sleep far past the suite
  160. // timeout. Dispose must KILL the process (the tracker's abort signal wired
  161. // through this bridge's runPoint), not await its exit.
  162. const slow = script(dir, 'slow.sh', `#!/usr/bin/env bash\necho $$ > "${pidFile}"\ntouch "${marker}"\nsleep 30\n`)
  163. writeHooks(dir, { SessionStart: [{ hooks: [{ type: 'command', command: slow }] }] })
  164. const ctx = new Context()
  165. await ctx.plugin(LlmService)
  166. await ctx.plugin(SessionStore)
  167. await ctx.plugin(SystemPrompt)
  168. await ctx.plugin(ToolRegistry)
  169. await ctx.plugin(AgentRegistry)
  170. await ctx.plugin(AgentLoop, { agents: [] })
  171. await ctx.plugin(LocalBashExecutor, { timeoutMs: 10_000 })
  172. const fiber = await ctx.plugin(HooksCodex, { configPath: join(dir, 'hooks.json'), model: 'm' })
  173. ctx.llm.registerAdapter(['mock'], new MockAdapter([]))
  174. const warn = vi.fn()
  175. ctx.logger.warn = warn as never
  176. ctx.agentLoop.create(AgentId('a1'), { model: 'mock' }) // fires agent/session-start
  177. await waitFor(() => existsSync(marker))
  178. const pid = Number(readFileSync(pidFile, 'utf8').trim())
  179. await fiber.dispose()
  180. // Quiescence, not just promptness: the drain resolves only after the run
  181. // settled, and the run settles only after the killed process was reaped —
  182. // so by the time dispose returns, the PID must be GONE (kill(pid, 0)
  183. // throws ESRCH). An untracked fire-and-forget regression would leave the
  184. // process alive (or unreaped) and fail this deterministically.
  185. expect(() => process.kill(pid, 0)).toThrow()
  186. // The aborted run resolves as a non-blocking error (runHook never rejects),
  187. // so the drained continuation must NOT have logged a failure.
  188. expect(warn).not.toHaveBeenCalledWith(expect.stringContaining('SessionStart hook failed'))
  189. })
  190. it('has the namespace-plugin export shape (no stray default) so the Loader keeps name/inject/apply', () => {
  191. expect('default' in HooksCodex).toBe(false)
  192. expect(HooksCodex.name).toBe('hooks-codex')
  193. expect(HooksCodex.inject).toEqual(['bash'])
  194. const loader = Object.create(Loader.prototype) as Loader
  195. const unwrapped = loader.unwrapExports(HooksCodex) as Record<string, unknown>
  196. expect(unwrapped).toBe(HooksCodex)
  197. expect(unwrapped.name).toBe('hooks-codex')
  198. expect(unwrapped.inject).toEqual(['bash'])
  199. expect(typeof unwrapped.apply).toBe('function')
  200. })
  201. })