hooks.e2e.ts 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122
  1. import { spawn, type ChildProcessWithoutNullStreams } from 'node:child_process'
  2. import { Readable, Writable } from 'node:stream'
  3. import { mkdtemp, rm, writeFile, access } from 'node:fs/promises'
  4. import { tmpdir } from 'node:os'
  5. import { join } from 'node:path'
  6. import { fileURLToPath } from 'node:url'
  7. import { afterEach, describe, expect, it } from 'vitest'
  8. import {
  9. ClientSideConnection,
  10. ndJsonStream,
  11. PROTOCOL_VERSION,
  12. type Agent as AcpAgent,
  13. type Client,
  14. type RequestPermissionRequest,
  15. type RequestPermissionResponse,
  16. type SessionNotification,
  17. } from '@agentclientprotocol/sdk'
  18. /**
  19. * With-key e2e: the Claude Code hook bridge running against the REAL acp-agent
  20. * subprocess and the REAL model. The example `cordis.yml` loads `dsh-hooks-claude`
  21. * with a PROCESS-LEVEL `configPath` of `./hooks.json`, resolved once at load
  22. * against the ACP server's launch cwd (NOT per-session); this test sets that
  23. * launch cwd to the temp workspace and writes a `hooks.json` there with a
  24. * PreToolUse hook that BLOCKS every bash command, then asks the live model to
  25. * write a file — and verifies the WORLD (the file never appears on disk),
  26. * proving the hook actually intercepted execution rather than the agent merely
  27. * claiming it couldn't. (The hook itself then runs in the session cwd.)
  28. * Key-gated; owns and disposes its subprocess.
  29. *
  30. * A keyless companion lives in acp.e2e.ts (stdout purity + session/new); the
  31. * full hook-fires-end-to-end transcript is the keyless `hook-cc-promptsubmit-block`
  32. * snapshot scenario. This one closes the "green plumbing, broken product" gap:
  33. * only a real model deciding to call bash exercises the PreToolUse seam live.
  34. */
  35. const binScript = fileURLToPath(new URL('../../../packages/ui/acp-agent/src/bin.ts', import.meta.url))
  36. const configPath = fileURLToPath(new URL('../cordis.yml', import.meta.url))
  37. const tsxLoader = fileURLToPath(import.meta.resolve('tsx'))
  38. const repoTsconfig = fileURLToPath(new URL('../../../tsconfig.json', import.meta.url))
  39. interface Spawned {
  40. child: ChildProcessWithoutNullStreams
  41. client: ClientSideConnection
  42. updates: SessionNotification['update'][]
  43. stderr: string[]
  44. }
  45. function spawnAcpAgent(cwd: string): Spawned {
  46. const child = spawn(
  47. process.execPath,
  48. ['--import', tsxLoader, binScript, configPath],
  49. { cwd, env: { ...process.env, TSX_TSCONFIG_PATH: repoTsconfig }, stdio: ['pipe', 'pipe', 'pipe'] },
  50. )
  51. const stderr: string[] = []
  52. child.stderr.setEncoding('utf8')
  53. child.stderr.on('data', (chunk: string) => stderr.push(chunk))
  54. const updates: SessionNotification['update'][] = []
  55. const stream = ndJsonStream(
  56. Writable.toWeb(child.stdin) as WritableStream<Uint8Array>,
  57. Readable.toWeb(child.stdout) as ReadableStream<Uint8Array>,
  58. )
  59. const makeClient = (_agent: AcpAgent): Client => ({
  60. sessionUpdate(params: SessionNotification): Promise<void> {
  61. updates.push(params.update)
  62. return Promise.resolve()
  63. },
  64. requestPermission(_params: RequestPermissionRequest): Promise<RequestPermissionResponse> {
  65. return Promise.resolve({ outcome: { outcome: 'cancelled' } })
  66. },
  67. })
  68. const client = new ClientSideConnection(makeClient, stream)
  69. return { child, client, updates, stderr }
  70. }
  71. let spawned: Spawned | undefined
  72. let workdir: string | undefined
  73. afterEach(async () => {
  74. if (spawned) {
  75. spawned.child.kill('SIGKILL')
  76. spawned = undefined
  77. }
  78. if (workdir !== undefined) await rm(workdir, { recursive: true, force: true })
  79. workdir = undefined
  80. })
  81. describe.skipIf(!process.env.DEEPSEEK_API_KEY)('acp-agent e2e: a PreToolUse hook blocks bash (real model)', () => {
  82. it('denies every bash command, so the requested file is never written (verified on disk)', async () => {
  83. workdir = await mkdtemp(join(tmpdir(), 'acp-hooks-e2e-'))
  84. // A PreToolUse hook that blocks EVERY tool (exit 2, no matcher = match-all).
  85. // The session cwd is `workdir`, and the bridge resolves `./hooks.json` from
  86. // the process cwd (the launch dir = workdir), so this is the config it loads.
  87. await writeFile(join(workdir, 'hooks.json'), JSON.stringify({
  88. hooks: { PreToolUse: [{ hooks: [{ type: 'command', command: 'echo "bash blocked by policy" >&2; exit 2' }] }] },
  89. }))
  90. spawned = spawnAcpAgent(workdir)
  91. const { client, updates } = spawned
  92. await client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} })
  93. const { sessionId } = await client.newSession({ cwd: workdir, mcpServers: [] })
  94. const res = await client.prompt({
  95. sessionId,
  96. prompt: [{ type: 'text', text: 'Use the bash tool to write the exact text HOOK_FAIL into a file named proof.txt in the current directory. Then stop.' }],
  97. })
  98. // The turn completes normally (the block is a tool-result error fed back to
  99. // the model, not a turn failure).
  100. expect(['end_turn', 'max_tokens']).toContain(res.stopReason)
  101. // Verify the WORLD: the hook denied execution, so the file must NOT exist —
  102. // a keyword probe a "cheating" agent could fake in prose cannot pass this.
  103. await expect(access(join(workdir, 'proof.txt'))).rejects.toThrow()
  104. // The client still saw a tool_call stream (the model TRIED), and its result
  105. // carried the hook's block reason back as an error.
  106. const toolCalls = updates.filter(u => u.sessionUpdate === 'tool_call' || u.sessionUpdate === 'tool_call_update')
  107. expect(toolCalls.length).toBeGreaterThan(0)
  108. }, 180_000)
  109. })