escalation.e2e.ts 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186
  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 model and Permissions selects and honors a permission switch without a model call', 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. const modelValue = JSON.stringify(['deepseek', 'deepseek-v4-flash'])
  107. expect(advertised.map(option => [option.id, 'currentValue' in option ? option.currentValue : undefined]))
  108. .toEqual([['model', modelValue], ['permission', 'workspace-write']])
  109. // A switch responds with the COMPLETE refreshed state (the spec contract),
  110. // and the new current survives in the response of a second switch.
  111. const afterFullAccess = await client.setSessionConfigOption({
  112. sessionId: created.sessionId, configId: 'permission', value: 'danger-full-access',
  113. })
  114. expect(afterFullAccess.configOptions?.find(option => option.id === 'permission'))
  115. .toMatchObject({ currentValue: 'danger-full-access' })
  116. const again = await client.setSessionConfigOption({
  117. sessionId: created.sessionId, configId: 'permission', value: 'danger-full-access',
  118. })
  119. expect((again.configOptions ?? []).map(option => [option.id, 'currentValue' in option ? option.currentValue : undefined]))
  120. .toEqual([['model', modelValue], ['permission', 'danger-full-access']])
  121. // An out-of-vocabulary value is a protocol error, never a silent default.
  122. await expect(client.setSessionConfigOption({
  123. sessionId: created.sessionId, configId: 'permission', value: 'plan',
  124. })).rejects.toThrow(/unknown permission value/)
  125. }, 30_000)
  126. })
  127. describe.skipIf(!process.env.DEEPSEEK_API_KEY || !hasRunner)('default sandbox composition e2e: the live approval loop', () => {
  128. it('denial → model escalation → editor prompt → allow-once → the retried write lands on disk', async () => {
  129. workdir = await mkdtemp(join(tmpdir(), 'sandbox-acp-e2e-'))
  130. spawned = launchExampleAcpAgent(workdir, 'allow-once')
  131. const { client, permissionRequests } = spawned
  132. await client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} })
  133. const { sessionId } = await client.newSession({ cwd: workdir, mcpServers: [] })
  134. const res = await client.prompt({
  135. sessionId,
  136. prompt: [{ type: 'text', text: `The sandbox already denied writing ${workdir}/escalated.txt. Create it now containing exactly "ACP_ESCALATION_OK": `
  137. + 'one single bash call with sandbox_permissions set to danger-full-access and a one-sentence justification, then stop.' }],
  138. })
  139. expect(['end_turn', 'max_tokens']).toContain(res.stopReason)
  140. // The WORLD: the approved escalated retry landed the write.
  141. const proof = await readFile(join(workdir, 'escalated.txt'), 'utf8')
  142. expect(proof).toContain('ACP_ESCALATION_OK')
  143. // The CHANNEL: the grant came through a real session/request_permission
  144. // prompt attached to the escalating tool call, offering exactly the
  145. // one-shot options.
  146. expect(permissionRequests.length).toBeGreaterThan(0)
  147. const prompt = permissionRequests[0]
  148. if (prompt === undefined) throw new Error('expected a permission request')
  149. expect(prompt.sessionId).toBe(sessionId)
  150. expect(typeof prompt.toolCall.toolCallId).toBe('string')
  151. expect(prompt.options.map(o => o.optionId).sort()).toEqual(['allow-once', 'reject-once'])
  152. }, 240_000)
  153. it('a rejected escalation stays denied: no write lands, the turn still ends', async () => {
  154. workdir = await mkdtemp(join(tmpdir(), 'sandbox-acp-e2e-'))
  155. spawned = launchExampleAcpAgent(workdir, 'reject-once')
  156. const { client, permissionRequests } = spawned
  157. await client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} })
  158. const { sessionId } = await client.newSession({ cwd: workdir, mcpServers: [] })
  159. const res = await client.prompt({
  160. sessionId,
  161. prompt: [{ type: 'text', text: `The sandbox already denied writing ${workdir}/refused.txt. Create it now containing "NO": `
  162. + '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.' }],
  163. })
  164. expect(['end_turn', 'max_tokens']).toContain(res.stopReason)
  165. // The WORLD: rejected means the file never appeared.
  166. await expect(readFile(join(workdir, 'refused.txt'), 'utf8')).rejects.toThrow()
  167. // And the rejection really flowed through a prompt (not a missing channel).
  168. expect(permissionRequests.length).toBeGreaterThan(0)
  169. }, 240_000)
  170. })