escalation.e2e.ts 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185
  1. import { spawnSync } from 'node:child_process'
  2. import { mkdtemp, readFile } from 'node:fs/promises'
  3. import { tmpdir } from 'node:os'
  4. import { join } from 'node:path'
  5. import { fileURLToPath } from 'node:url'
  6. import { afterEach, describe, expect, it } from 'vitest'
  7. import {
  8. PROTOCOL_VERSION,
  9. type RequestPermissionRequest,
  10. } from '@agentclientprotocol/sdk'
  11. import {
  12. launchAcpTestAgent,
  13. type AgentUnderTest,
  14. type LaunchedAcpTestAgent,
  15. } from '@deepseek-ai/dsh-acp-snapshot'
  16. import { cleanupAcpExampleTest } from './cleanup.ts'
  17. /**
  18. * The default ACP composition (`cordis.yml`) end to end.
  19. *
  20. * Keyless smoke: boot the REAL `cordis.yml` through the `dsh-acp-agent` bin as
  21. * an ACP subprocess and drive initialize + session/new — the real-Loader-path
  22. * guard (postmortem 0001) for THIS tree's export shapes, which now include the
  23. * sandbox executor AND the approval service. No prompt is sent, so neither the
  24. * model nor a sandbox runner is ever exercised.
  25. *
  26. * With-key escalation flow (self-skips without DEEPSEEK_API_KEY or a usable
  27. * platform runner): a scripted ACP client plays the human. The prompt asserts
  28. * a prior denial (the organic denial→marker path lives on the sandbox e2e
  29. * legs and unit tiers), the real model escalates with `sandbox_permissions` +
  30. * `justification`, the bridge prompts THIS client over
  31. * `session/request_permission`, the client answers `allow-once`, and the
  32. * retried write must land ON DISK (world-verified) — under the granted mode,
  33. * a temp-dir session cwd is writable either way.
  34. */
  35. const AGENT: AgentUnderTest = {
  36. binScript: fileURLToPath(new URL('../../../packages/examples/acp-demo/src/bin.ts', import.meta.url)),
  37. configPath: fileURLToPath(new URL('../cordis.yml', import.meta.url)),
  38. tsconfigPath: fileURLToPath(new URL('../../../tsconfig.json', import.meta.url)),
  39. }
  40. // A usable confining runner, probed the same way the executor suites do:
  41. // bwrap on Linux, Seatbelt's sandbox-exec on macOS. Without one the strict
  42. // attempt would fail closed (SANDBOX_UNAVAILABLE) instead of producing the
  43. // denial this flow starts from.
  44. const hasBwrap = spawnSync('bwrap', ['--ro-bind', '/', '/', '--dev', '/dev', '--proc', '/proc', '--die-with-parent', '--', 'true'], {
  45. timeout: 5_000,
  46. stdio: 'ignore',
  47. }).status === 0
  48. const hasSeatbelt = process.platform === 'darwin' && spawnSync('sandbox-exec', ['-p', '(version 1)(allow default)', 'true'], {
  49. timeout: 5_000,
  50. stdio: 'ignore',
  51. }).status === 0
  52. const hasRunner = hasBwrap || hasSeatbelt
  53. interface Spawned extends LaunchedAcpTestAgent {
  54. permissionRequests: RequestPermissionRequest[]
  55. }
  56. /** Boot the example as an ACP subprocess; the scripted client answers every permission prompt with `answer`. */
  57. function launchExampleAcpAgent(cwd: string, answer: 'allow-once' | 'reject-once'): Spawned {
  58. const permissionRequests: RequestPermissionRequest[] = []
  59. const launched = launchAcpTestAgent({
  60. agent: AGENT,
  61. cwd,
  62. // A dummy key lets the adapter boot keylessly; live tests carry the real key.
  63. env: { DEEPSEEK_API_KEY: process.env.DEEPSEEK_API_KEY ?? 'sk-dummy-for-boot' },
  64. requestPermission(params) {
  65. permissionRequests.push(params)
  66. const option = params.options.find(o => o.optionId === answer)
  67. // The scripted human: pick the requested option when the prompt offers
  68. // it; an unexpected prompt shape cancels (fail closed, never grants).
  69. if (option === undefined) return Promise.resolve({ outcome: { outcome: 'cancelled' } })
  70. return Promise.resolve({ outcome: { outcome: 'selected', optionId: option.optionId } })
  71. },
  72. })
  73. return Object.assign(launched, { permissionRequests })
  74. }
  75. let spawned: Spawned | undefined
  76. let workdir: string | undefined
  77. afterEach(async () => {
  78. const ownedSpawned = spawned
  79. const ownedWorkdir = workdir
  80. spawned = undefined
  81. workdir = undefined
  82. await cleanupAcpExampleTest(ownedSpawned, ownedWorkdir)
  83. })
  84. describe('default sandbox composition keyless smoke (real cordis.yml via the Loader)', () => {
  85. it('boots the tree — sandbox executor + approval service + bridge — and opens a session', async () => {
  86. workdir = await mkdtemp(join(tmpdir(), 'sandbox-acp-smoke-'))
  87. spawned = launchExampleAcpAgent(workdir, 'reject-once')
  88. const { client } = spawned
  89. // A dummy key boots the adapter; no prompt is ever sent, so no model call
  90. // and no sandbox runner probe happen. This drives the fiber tree the same
  91. // way an editor would, which is what catches a broken export/inject shape.
  92. const init = await client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} })
  93. expect(init.protocolVersion).toBe(PROTOCOL_VERSION)
  94. const { sessionId } = await client.newSession({ cwd: workdir, mcpServers: [] })
  95. expect(sessionId.length).toBeGreaterThan(0)
  96. }, 30_000)
  97. it('advertises the Permissions select and honors a switch end to end (no key, no model)', async () => {
  98. workdir = await mkdtemp(join(tmpdir(), 'sandbox-acp-config-'))
  99. spawned = launchExampleAcpAgent(workdir, 'reject-once')
  100. const { client } = spawned
  101. await client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} })
  102. // This tree composes the permission presets over bash-sandbox + approval →
  103. // ONE select advertises, current from the configured default preset.
  104. const created = await client.newSession({ cwd: workdir, mcpServers: [] })
  105. const advertised = created.configOptions ?? []
  106. expect(advertised.map(option => [option.id, 'currentValue' in option ? option.currentValue : undefined]))
  107. .toEqual([['permission', 'workspace-write']])
  108. // A switch responds with the COMPLETE refreshed state (the spec contract),
  109. // and the new current survives in the response of a second switch.
  110. const afterFullAccess = await client.setSessionConfigOption({
  111. sessionId: created.sessionId, configId: 'permission', value: 'danger-full-access',
  112. })
  113. expect(afterFullAccess.configOptions?.find(option => option.id === 'permission'))
  114. .toMatchObject({ currentValue: 'danger-full-access' })
  115. const again = await client.setSessionConfigOption({
  116. sessionId: created.sessionId, configId: 'permission', value: 'danger-full-access',
  117. })
  118. expect((again.configOptions ?? []).map(option => [option.id, 'currentValue' in option ? option.currentValue : undefined]))
  119. .toEqual([['permission', 'danger-full-access']])
  120. // An out-of-vocabulary value is a protocol error, never a silent default.
  121. await expect(client.setSessionConfigOption({
  122. sessionId: created.sessionId, configId: 'permission', value: 'plan',
  123. })).rejects.toThrow(/unknown permission value/)
  124. }, 30_000)
  125. })
  126. describe.skipIf(!process.env.DEEPSEEK_API_KEY || !hasRunner)('default sandbox composition e2e: the live approval loop', () => {
  127. it('denial → model escalation → editor prompt → allow-once → the retried write lands on disk', async () => {
  128. workdir = await mkdtemp(join(tmpdir(), 'sandbox-acp-e2e-'))
  129. spawned = launchExampleAcpAgent(workdir, 'allow-once')
  130. const { client, permissionRequests } = spawned
  131. await client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} })
  132. const { sessionId } = await client.newSession({ cwd: workdir, mcpServers: [] })
  133. const res = await client.prompt({
  134. sessionId,
  135. prompt: [{ type: 'text', text: `The sandbox already denied writing ${workdir}/escalated.txt. Create it now containing exactly "ACP_ESCALATION_OK": `
  136. + 'one single bash call with sandbox_permissions set to danger-full-access and a one-sentence justification, then stop.' }],
  137. })
  138. expect(['end_turn', 'max_tokens']).toContain(res.stopReason)
  139. // The WORLD: the approved escalated retry landed the write.
  140. const proof = await readFile(join(workdir, 'escalated.txt'), 'utf8')
  141. expect(proof).toContain('ACP_ESCALATION_OK')
  142. // The CHANNEL: the grant came through a real session/request_permission
  143. // prompt attached to the escalating tool call, offering exactly the
  144. // one-shot options.
  145. expect(permissionRequests.length).toBeGreaterThan(0)
  146. const prompt = permissionRequests[0]
  147. if (prompt === undefined) throw new Error('expected a permission request')
  148. expect(prompt.sessionId).toBe(sessionId)
  149. expect(typeof prompt.toolCall.toolCallId).toBe('string')
  150. expect(prompt.options.map(o => o.optionId).sort()).toEqual(['allow-once', 'reject-once'])
  151. }, 240_000)
  152. it('a rejected escalation stays denied: no write lands, the turn still ends', async () => {
  153. workdir = await mkdtemp(join(tmpdir(), 'sandbox-acp-e2e-'))
  154. spawned = launchExampleAcpAgent(workdir, 'reject-once')
  155. const { client, permissionRequests } = spawned
  156. await client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} })
  157. const { sessionId } = await client.newSession({ cwd: workdir, mcpServers: [] })
  158. const res = await client.prompt({
  159. sessionId,
  160. prompt: [{ type: 'text', text: `The sandbox already denied writing ${workdir}/refused.txt. Create it now containing "NO": `
  161. + '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.' }],
  162. })
  163. expect(['end_turn', 'max_tokens']).toContain(res.stopReason)
  164. // The WORLD: rejected means the file never appeared.
  165. await expect(readFile(join(workdir, 'refused.txt'), 'utf8')).rejects.toThrow()
  166. // And the rejection really flowed through a prompt (not a missing channel).
  167. expect(permissionRequests.length).toBeGreaterThan(0)
  168. }, 240_000)
  169. })