escalation.e2e.ts 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  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 supplies machine policy. The subprocess
  28. * starts read-only, its first real bash write is denied, the model retries with
  29. * `sandbox_permissions` + `justification`, and the bridge prompts THIS client
  30. * over `session/request_permission`. An approved workspace-write retry must
  31. * then land ON DISK (world-verified).
  32. */
  33. const AGENT: AgentUnderTest = {
  34. binScript: fileURLToPath(new URL('../../../packages/examples/acp-demo/src/bin.ts', import.meta.url)),
  35. configPath: fileURLToPath(new URL('../cordis.yml', import.meta.url)),
  36. tsconfigPath: fileURLToPath(new URL('../../../tsconfig.json', import.meta.url)),
  37. }
  38. // A usable confining runner, probed the same way the executor suites do:
  39. // bwrap on Linux, Seatbelt's sandbox-exec on macOS. Without one the strict
  40. // attempt would fail closed (SANDBOX_UNAVAILABLE) instead of producing the
  41. // denial this flow starts from.
  42. const hasBwrap = spawnSync('bwrap', ['--ro-bind', '/', '/', '--dev', '/dev', '--proc', '/proc', '--die-with-parent', '--', 'true'], {
  43. timeout: 5_000,
  44. stdio: 'ignore',
  45. }).status === 0
  46. const hasSeatbelt = process.platform === 'darwin' && spawnSync('sandbox-exec', ['-p', '(version 1)(allow default)', 'true'], {
  47. timeout: 5_000,
  48. stdio: 'ignore',
  49. }).status === 0
  50. const hasRunner = hasBwrap || hasSeatbelt
  51. interface Spawned extends LaunchedAcpTestAgent {
  52. permissionRequests: RequestPermissionRequest[]
  53. }
  54. /** Boot the example with an optional sandbox override; the scripted client answers every permission prompt with `answer`. */
  55. function launchExampleAcpAgent(
  56. cwd: string,
  57. answer: 'allow-once' | 'reject-once',
  58. sandboxMode?: 'read-only' | 'workspace-write' | 'danger-full-access',
  59. ): Spawned {
  60. const permissionRequests: RequestPermissionRequest[] = []
  61. const launched = launchAcpTestAgent({
  62. agent: AGENT,
  63. cwd,
  64. // A dummy key lets the adapter boot keylessly; live tests carry the real key.
  65. env: {
  66. DEEPSEEK_API_KEY: process.env.DEEPSEEK_API_KEY ?? 'sk-dummy-for-boot',
  67. DSH_PERMISSION_MODE: sandboxMode,
  68. },
  69. requestPermission(params) {
  70. permissionRequests.push(params)
  71. const option = params.options.find(o => o.optionId === answer)
  72. // The scripted machine policy selects the requested option; an
  73. // unexpected request shape cancels (fail closed, never grants).
  74. if (option === undefined) return Promise.resolve({ outcome: { outcome: 'cancelled' } })
  75. return Promise.resolve({ outcome: { outcome: 'selected', optionId: option.optionId } })
  76. },
  77. })
  78. return Object.assign(launched, { permissionRequests })
  79. }
  80. function escalationPrompt(path: string, content: string): string {
  81. return `Create ${path} containing exactly ${JSON.stringify(content)} using bash, not filesystem tools. `
  82. + 'First try the command without sandbox_permissions. If the sandbox denies it, retry that exact command once '
  83. + 'with sandbox_permissions set to workspace-write and a one-sentence justification.'
  84. }
  85. let spawned: Spawned | undefined
  86. let workdir: string | undefined
  87. afterEach(async () => {
  88. const ownedSpawned = spawned
  89. const ownedWorkdir = workdir
  90. spawned = undefined
  91. workdir = undefined
  92. await cleanupAcpExampleTest(ownedSpawned, ownedWorkdir)
  93. })
  94. describe('default sandbox composition keyless smoke (real cordis.yml via the Loader)', () => {
  95. it('boots the tree — sandbox executor + approval service + bridge — and opens a session', async () => {
  96. workdir = await mkdtemp(join(tmpdir(), 'sandbox-acp-smoke-'))
  97. spawned = launchExampleAcpAgent(workdir, 'reject-once')
  98. const { client } = spawned
  99. // A dummy key boots the adapter; no prompt is ever sent, so no model call
  100. // and no sandbox runner probe happen. This drives the fiber tree the same
  101. // way an ACP caller would, which catches a broken export/inject shape.
  102. const init = await client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} })
  103. expect(init.protocolVersion).toBe(PROTOCOL_VERSION)
  104. expect(init.agentCapabilities).toEqual({
  105. promptCapabilities: { image: false, audio: false, embeddedContext: false },
  106. })
  107. const { sessionId } = await client.newSession({ cwd: workdir, mcpServers: [] })
  108. expect(sessionId.length).toBeGreaterThan(0)
  109. }, 30_000)
  110. })
  111. describe.skipIf(!process.env.DEEPSEEK_API_KEY || !hasRunner)('default sandbox composition e2e: the live approval loop', () => {
  112. it('denial → model escalation → machine allow-once → the retried write lands on disk', async () => {
  113. workdir = await mkdtemp(join(tmpdir(), 'sandbox-acp-e2e-'))
  114. spawned = launchExampleAcpAgent(workdir, 'allow-once', 'read-only')
  115. const { client, permissionRequests, updates } = spawned
  116. await client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} })
  117. const { sessionId } = await client.newSession({ cwd: workdir, mcpServers: [] })
  118. const res = await client.prompt({
  119. sessionId,
  120. prompt: [{
  121. type: 'text',
  122. text: `${escalationPrompt(join(workdir, 'escalated.txt'), 'ACP_ESCALATION_OK')} Then stop.`,
  123. }],
  124. })
  125. expect(['end_turn', 'max_tokens']).toContain(res.stopReason)
  126. expect(updates.every(update => update.sessionUpdate === 'agent_message_chunk')).toBe(true)
  127. // The WORLD: the approved escalated retry landed the write.
  128. const proof = await readFile(join(workdir, 'escalated.txt'), 'utf8')
  129. expect(proof).toContain('ACP_ESCALATION_OK')
  130. // The CHANNEL: the grant came through a real session/request_permission
  131. // request attached to the escalating tool call, offering exactly the
  132. // one-shot options.
  133. expect(permissionRequests.length).toBeGreaterThan(0)
  134. const prompt = permissionRequests[0]
  135. if (prompt === undefined) throw new Error('expected a permission request')
  136. expect(prompt.sessionId).toBe(sessionId)
  137. expect(typeof prompt.toolCall.toolCallId).toBe('string')
  138. expect(prompt.options.map(o => o.optionId).sort()).toEqual(['allow-once', 'reject-once'])
  139. }, 240_000)
  140. it('a rejected escalation stays denied: no write lands, the turn still ends', async () => {
  141. workdir = await mkdtemp(join(tmpdir(), 'sandbox-acp-e2e-'))
  142. spawned = launchExampleAcpAgent(workdir, 'reject-once', 'read-only')
  143. const { client, permissionRequests, updates } = spawned
  144. await client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} })
  145. const { sessionId } = await client.newSession({ cwd: workdir, mcpServers: [] })
  146. const res = await client.prompt({
  147. sessionId,
  148. prompt: [{
  149. type: 'text',
  150. text: `${escalationPrompt(join(workdir, 'refused.txt'), 'NO')} If approval is rejected, stop and say so.`,
  151. }],
  152. })
  153. expect(['end_turn', 'max_tokens']).toContain(res.stopReason)
  154. expect(updates.every(update => update.sessionUpdate === 'agent_message_chunk')).toBe(true)
  155. // The WORLD: rejected means the file never appeared.
  156. await expect(readFile(join(workdir, 'refused.txt'), 'utf8')).rejects.toThrow()
  157. // And the rejection flowed through the machine-policy channel.
  158. expect(permissionRequests.length).toBeGreaterThan(0)
  159. }, 240_000)
  160. })