escalation.e2e.ts 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208
  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 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 human: pick the requested option when the prompt offers
  73. // it; an unexpected prompt 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. function includesReadOnlyDenial(updates: LaunchedAcpTestAgent['updates']): boolean {
  86. return updates.some(update => update.sessionUpdate === 'tool_call_update'
  87. && JSON.stringify(update.content).includes('[sandbox: file access denied under read-only mode]'))
  88. }
  89. let spawned: Spawned | undefined
  90. let workdir: string | undefined
  91. afterEach(async () => {
  92. const ownedSpawned = spawned
  93. const ownedWorkdir = workdir
  94. spawned = undefined
  95. workdir = undefined
  96. await cleanupAcpExampleTest(ownedSpawned, ownedWorkdir)
  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 = launchExampleAcpAgent(workdir, 'reject-once')
  102. const { client } = spawned
  103. // A dummy key boots the adapter; no prompt is ever sent, so no model call
  104. // and no sandbox runner probe happen. This drives the fiber tree the same
  105. // way an editor would, which is what catches a broken export/inject shape.
  106. const init = await client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} })
  107. expect(init.protocolVersion).toBe(PROTOCOL_VERSION)
  108. const { sessionId } = await client.newSession({ cwd: workdir, mcpServers: [] })
  109. expect(sessionId.length).toBeGreaterThan(0)
  110. }, 30_000)
  111. it('advertises model and Permissions selects and honors a permission switch without a model call', async () => {
  112. workdir = await mkdtemp(join(tmpdir(), 'sandbox-acp-config-'))
  113. spawned = launchExampleAcpAgent(workdir, 'reject-once')
  114. const { client } = spawned
  115. await client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} })
  116. // This tree composes the permission presets over bash-sandbox + approval →
  117. // ONE select advertises, current from the configured default preset.
  118. const created = await client.newSession({ cwd: workdir, mcpServers: [] })
  119. const advertised = created.configOptions ?? []
  120. const modelValue = JSON.stringify(['deepseek', 'deepseek-v4-pro'])
  121. expect(advertised.map(option => [option.id, 'currentValue' in option ? option.currentValue : undefined]))
  122. .toEqual([['model', modelValue], ['permission', 'workspace-write']])
  123. // A switch responds with the COMPLETE refreshed state (the spec contract),
  124. // and the new current survives in the response of a second switch.
  125. const afterFullAccess = await client.setSessionConfigOption({
  126. sessionId: created.sessionId, configId: 'permission', value: 'danger-full-access',
  127. })
  128. expect(afterFullAccess.configOptions?.find(option => option.id === 'permission'))
  129. .toMatchObject({ currentValue: 'danger-full-access' })
  130. const again = await client.setSessionConfigOption({
  131. sessionId: created.sessionId, configId: 'permission', value: 'danger-full-access',
  132. })
  133. expect((again.configOptions ?? []).map(option => [option.id, 'currentValue' in option ? option.currentValue : undefined]))
  134. .toEqual([['model', modelValue], ['permission', 'danger-full-access']])
  135. // An out-of-vocabulary value is a protocol error, never a silent default.
  136. await expect(client.setSessionConfigOption({
  137. sessionId: created.sessionId, configId: 'permission', value: 'plan',
  138. })).rejects.toThrow(/unknown permission value/)
  139. }, 30_000)
  140. })
  141. describe.skipIf(!process.env.DEEPSEEK_API_KEY || !hasRunner)('default sandbox composition e2e: the live approval loop', () => {
  142. it('denial → model escalation → editor prompt → allow-once → the retried write lands on disk', async () => {
  143. workdir = await mkdtemp(join(tmpdir(), 'sandbox-acp-e2e-'))
  144. spawned = launchExampleAcpAgent(workdir, 'allow-once', 'read-only')
  145. const { client, permissionRequests, updates } = spawned
  146. await client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} })
  147. const { sessionId } = await client.newSession({ cwd: workdir, mcpServers: [] })
  148. const res = await client.prompt({
  149. sessionId,
  150. prompt: [{
  151. type: 'text',
  152. text: `${escalationPrompt(join(workdir, 'escalated.txt'), 'ACP_ESCALATION_OK')} Then stop.`,
  153. }],
  154. })
  155. expect(['end_turn', 'max_tokens']).toContain(res.stopReason)
  156. expect(includesReadOnlyDenial(updates)).toBe(true)
  157. // The WORLD: the approved escalated retry landed the write.
  158. const proof = await readFile(join(workdir, 'escalated.txt'), 'utf8')
  159. expect(proof).toContain('ACP_ESCALATION_OK')
  160. // The CHANNEL: the grant came through a real session/request_permission
  161. // prompt attached to the escalating tool call, offering exactly the
  162. // one-shot options.
  163. expect(permissionRequests.length).toBeGreaterThan(0)
  164. const prompt = permissionRequests[0]
  165. if (prompt === undefined) throw new Error('expected a permission request')
  166. expect(prompt.sessionId).toBe(sessionId)
  167. expect(typeof prompt.toolCall.toolCallId).toBe('string')
  168. expect(prompt.options.map(o => o.optionId).sort()).toEqual(['allow-once', 'reject-once'])
  169. }, 240_000)
  170. it('a rejected escalation stays denied: no write lands, the turn still ends', async () => {
  171. workdir = await mkdtemp(join(tmpdir(), 'sandbox-acp-e2e-'))
  172. spawned = launchExampleAcpAgent(workdir, 'reject-once', 'read-only')
  173. const { client, permissionRequests, updates } = spawned
  174. await client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} })
  175. const { sessionId } = await client.newSession({ cwd: workdir, mcpServers: [] })
  176. const res = await client.prompt({
  177. sessionId,
  178. prompt: [{
  179. type: 'text',
  180. text: `${escalationPrompt(join(workdir, 'refused.txt'), 'NO')} If approval is rejected, stop and say so.`,
  181. }],
  182. })
  183. expect(['end_turn', 'max_tokens']).toContain(res.stopReason)
  184. expect(includesReadOnlyDenial(updates)).toBe(true)
  185. // The WORLD: rejected means the file never appeared.
  186. await expect(readFile(join(workdir, 'refused.txt'), 'utf8')).rejects.toThrow()
  187. // And the rejection really flowed through a prompt (not a missing channel).
  188. expect(permissionRequests.length).toBeGreaterThan(0)
  189. }, 240_000)
  190. })