escalation.e2e.ts 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189
  1. import { spawn, spawnSync, type ChildProcessWithoutNullStreams } from 'node:child_process'
  2. import { Readable, Writable } from 'node:stream'
  3. import { mkdtemp, readFile, rm } 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. * Exercises the default ACP composition through the real bin and Loader. The
  20. * keyless leg boots sandbox, approval, permission, and bridge services, then
  21. * initializes and opens a session without a model call or runner probe. With a
  22. * key and usable runner, the prompt asserts a prior denial; the model requests
  23. * a wider retry with justification, and a scripted client grants or rejects it.
  24. * The filesystem must show that only the granted retry ran. Missing credentials
  25. * or runner support self-skip; real denial markers remain on sandbox e2e tiers.
  26. */
  27. const binScript = fileURLToPath(new URL('../../../packages/ui/acp-agent/src/bin.ts', import.meta.url))
  28. const configPath = fileURLToPath(new URL('../cordis.yml', import.meta.url))
  29. const tsxLoader = fileURLToPath(import.meta.resolve('tsx'))
  30. // The subprocess runs from a temp cwd outside the repo; point tsx at the repo
  31. // tsconfig so the unbuilt `paths` map resolves (see examples/AGENTS.md).
  32. const repoTsconfig = fileURLToPath(new URL('../../../tsconfig.json', import.meta.url))
  33. // Without a usable bwrap/Seatbelt runner, the strict attempt fails closed with
  34. // SANDBOX_UNAVAILABLE instead of producing the denial this flow requires.
  35. const hasBwrap = spawnSync('bwrap', ['--ro-bind', '/', '/', '--dev', '/dev', '--proc', '/proc', '--die-with-parent', '--', 'true'], {
  36. timeout: 5_000,
  37. stdio: 'ignore',
  38. }).status === 0
  39. const hasSeatbelt = process.platform === 'darwin' && spawnSync('sandbox-exec', ['-p', '(version 1)(allow default)', 'true'], {
  40. timeout: 5_000,
  41. stdio: 'ignore',
  42. }).status === 0
  43. const hasRunner = hasBwrap || hasSeatbelt
  44. interface Spawned {
  45. child: ChildProcessWithoutNullStreams
  46. client: ClientSideConnection
  47. updates: SessionNotification['update'][]
  48. permissionRequests: RequestPermissionRequest[]
  49. stderr: string[]
  50. }
  51. /** Boot the example as an ACP subprocess; the scripted client answers every permission prompt with `answer`. */
  52. function spawnAcpAgent(cwd: string, answer: 'allow-once' | 'reject-once'): Spawned {
  53. const child = spawn(
  54. process.execPath,
  55. ['--import', tsxLoader, binScript, '--config', configPath],
  56. {
  57. cwd,
  58. // A dummy key lets the deepseek adapter boot keyless (presence-checked at
  59. // apply, used only on a real model call); the with-key tests carry the
  60. // real key, so the fallback is inert there.
  61. env: { ...process.env, DEEPSEEK_API_KEY: process.env.DEEPSEEK_API_KEY ?? 'sk-dummy-for-boot', TSX_TSCONFIG_PATH: repoTsconfig },
  62. stdio: ['pipe', 'pipe', 'pipe'],
  63. },
  64. )
  65. const stderr: string[] = []
  66. child.stderr.setEncoding('utf8')
  67. child.stderr.on('data', (chunk: string) => stderr.push(chunk))
  68. const updates: SessionNotification['update'][] = []
  69. const permissionRequests: RequestPermissionRequest[] = []
  70. const stream = ndJsonStream(
  71. Writable.toWeb(child.stdin) as WritableStream<Uint8Array>,
  72. Readable.toWeb(child.stdout) as ReadableStream<Uint8Array>,
  73. )
  74. const makeClient = (_agent: AcpAgent): Client => ({
  75. sessionUpdate(params: SessionNotification): Promise<void> {
  76. updates.push(params.update)
  77. return Promise.resolve()
  78. },
  79. requestPermission(params: RequestPermissionRequest): Promise<RequestPermissionResponse> {
  80. permissionRequests.push(params)
  81. const option = params.options.find(o => o.optionId === answer)
  82. // An unexpected prompt shape cancels without granting.
  83. if (option === undefined) return Promise.resolve({ outcome: { outcome: 'cancelled' } })
  84. return Promise.resolve({ outcome: { outcome: 'selected', optionId: option.optionId } })
  85. },
  86. })
  87. const client = new ClientSideConnection(makeClient, stream)
  88. return { child, client, updates, permissionRequests, stderr }
  89. }
  90. let spawned: Spawned | undefined
  91. let workdir: string | undefined
  92. afterEach(async () => {
  93. if (spawned !== undefined && spawned.child.exitCode === null) spawned.child.kill('SIGKILL')
  94. spawned = undefined
  95. if (workdir !== undefined) await rm(workdir, { recursive: true, force: true })
  96. workdir = undefined
  97. })
  98. describe('default sandbox composition keyless smoke (real cordis.yml via the Loader)', () => {
  99. it('boots the tree — sandbox executor + approval service + bridge — and opens a session', async () => {
  100. workdir = await mkdtemp(join(tmpdir(), 'sandbox-acp-smoke-'))
  101. spawned = spawnAcpAgent(workdir, 'reject-once')
  102. const { client } = spawned
  103. const init = await client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} })
  104. expect(init.protocolVersion).toBe(PROTOCOL_VERSION)
  105. const { sessionId } = await client.newSession({ cwd: workdir, mcpServers: [] })
  106. expect(sessionId.length).toBeGreaterThan(0)
  107. }, 30_000)
  108. it('advertises the Permissions select and honors a switch end to end (no key, no model)', async () => {
  109. workdir = await mkdtemp(join(tmpdir(), 'sandbox-acp-config-'))
  110. spawned = spawnAcpAgent(workdir, 'reject-once')
  111. const { client } = spawned
  112. await client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} })
  113. const created = await client.newSession({ cwd: workdir, mcpServers: [] })
  114. const advertised = created.configOptions ?? []
  115. expect(advertised.map(option => [option.id, 'currentValue' in option ? option.currentValue : undefined]))
  116. .toEqual([['permission', 'workspace-write']])
  117. const afterFullAccess = await client.setSessionConfigOption({
  118. sessionId: created.sessionId, configId: 'permission', value: 'danger-full-access',
  119. })
  120. expect(afterFullAccess.configOptions?.find(option => option.id === 'permission'))
  121. .toMatchObject({ currentValue: 'danger-full-access' })
  122. const again = await client.setSessionConfigOption({
  123. sessionId: created.sessionId, configId: 'permission', value: 'danger-full-access',
  124. })
  125. expect((again.configOptions ?? []).map(option => [option.id, 'currentValue' in option ? option.currentValue : undefined]))
  126. .toEqual([['permission', 'danger-full-access']])
  127. await expect(client.setSessionConfigOption({
  128. sessionId: created.sessionId, configId: 'permission', value: 'plan',
  129. })).rejects.toThrow(/unknown permission value/)
  130. }, 30_000)
  131. })
  132. describe.skipIf(!process.env.DEEPSEEK_API_KEY || !hasRunner)('default sandbox composition e2e: the live approval loop', () => {
  133. it('denial → model escalation → editor prompt → allow-once → the retried write lands on disk', async () => {
  134. workdir = await mkdtemp(join(tmpdir(), 'sandbox-acp-e2e-'))
  135. spawned = spawnAcpAgent(workdir, 'allow-once')
  136. const { client, permissionRequests } = spawned
  137. await client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} })
  138. const { sessionId } = await client.newSession({ cwd: workdir, mcpServers: [] })
  139. const res = await client.prompt({
  140. sessionId,
  141. prompt: [{ type: 'text', text: `The sandbox already denied writing ${workdir}/escalated.txt. Create it now containing exactly "ACP_ESCALATION_OK": `
  142. + 'one single bash call with sandbox_permissions set to danger-full-access and a one-sentence justification, then stop.' }],
  143. })
  144. expect(['end_turn', 'max_tokens']).toContain(res.stopReason)
  145. // Verify the filesystem, not the model's report.
  146. const proof = await readFile(join(workdir, 'escalated.txt'), 'utf8')
  147. expect(proof).toContain('ACP_ESCALATION_OK')
  148. // Verify that ACP carried the grant with only one-shot choices.
  149. expect(permissionRequests.length).toBeGreaterThan(0)
  150. const prompt = permissionRequests[0]
  151. if (prompt === undefined) throw new Error('expected a permission request')
  152. expect(prompt.sessionId).toBe(sessionId)
  153. expect(typeof prompt.toolCall.toolCallId).toBe('string')
  154. expect(prompt.options.map(o => o.optionId).sort()).toEqual(['allow-once', 'reject-once'])
  155. }, 240_000)
  156. it('a rejected escalation stays denied: no write lands, the turn still ends', async () => {
  157. workdir = await mkdtemp(join(tmpdir(), 'sandbox-acp-e2e-'))
  158. spawned = spawnAcpAgent(workdir, 'reject-once')
  159. const { client, permissionRequests } = spawned
  160. await client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} })
  161. const { sessionId } = await client.newSession({ cwd: workdir, mcpServers: [] })
  162. const res = await client.prompt({
  163. sessionId,
  164. prompt: [{ type: 'text', text: `The sandbox already denied writing ${workdir}/refused.txt. Create it now containing "NO": `
  165. + 'one single bash call with sandbox_permissions set to danger-full-access and a one-sentence justification. If that is rejected, stop and say so.' }],
  166. })
  167. expect(['end_turn', 'max_tokens']).toContain(res.stopReason)
  168. await expect(readFile(join(workdir, 'refused.txt'), 'utf8')).rejects.toThrow()
  169. // Distinguish a user rejection from a missing approval channel.
  170. expect(permissionRequests.length).toBeGreaterThan(0)
  171. }, 240_000)
  172. })