inheritance.spec.ts 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183
  1. /** Policy inheritance through child session events appended before publication. */
  2. import { afterEach, beforeEach, describe, expect, it } from 'vitest'
  3. import { mkdtemp, readFile, realpath, rm } from 'node:fs/promises'
  4. import { tmpdir } from 'node:os'
  5. import { join } from 'node:path'
  6. import { Context } from 'cordis'
  7. import type { Agent } from '@deepseek-ai/dsh-agent'
  8. import AgentLoop from '@deepseek-ai/dsh-agent-loop'
  9. import { mountAgentLoopTestDependencies } from '@deepseek-ai/dsh-agent-loop-testkit'
  10. import SandboxedFileSystem from '@deepseek-ai/dsh-fs-sandbox'
  11. import type { ContentBlock } from '@deepseek-ai/dsh-llm'
  12. import SandboxPolicyService, { setSandboxMode } from '@deepseek-ai/dsh-sandbox-policy'
  13. import { SessionId, type SessionEvent } from '@deepseek-ai/dsh-session'
  14. import * as ToolFs from '@deepseek-ai/dsh-tool-fs'
  15. import ApprovalService, { setApprovalPolicy } from '@deepseek-ai/dsh-user-approval'
  16. import { MockAdapter, textResponse, toolCallResponse } from '../../../core/agent-loop/tests/mock-adapter.ts'
  17. import { startInProcessRun } from '../src/index.ts'
  18. type Script = ConstructorParameters<typeof MockAdapter>[0]
  19. const READ_ONLY_DENIAL = '[sandbox: file access denied under read-only mode]'
  20. const contexts: Context[] = []
  21. let workspace: string
  22. beforeEach(async () => {
  23. workspace = await realpath(await mkdtemp(join(tmpdir(), 'dsh-inherit-')))
  24. })
  25. afterEach(async () => {
  26. for (const ctx of contexts.splice(0).reverse()) await ctx.fiber.dispose()
  27. await rm(workspace, { recursive: true, force: true })
  28. })
  29. async function setupWalled(script: Script): Promise<{ ctx: Context; parent: Agent }> {
  30. const ctx = new Context()
  31. contexts.push(ctx)
  32. await mountAgentLoopTestDependencies(ctx)
  33. await ctx.plugin(SandboxPolicyService, { mode: 'workspace-write', workspaceRoot: workspace })
  34. await ctx.plugin(SandboxedFileSystem, { cwd: workspace })
  35. await ctx.plugin(ToolFs)
  36. await ctx.plugin(ApprovalService)
  37. await ctx.plugin(AgentLoop, { agents: [] })
  38. ctx.llm.registerAdapter(['mock'], new MockAdapter(script))
  39. const parent = ctx.agentLoop.create(
  40. SessionId('parent'),
  41. { provider: 'mock', model: 'mock' },
  42. { cwd: workspace },
  43. )
  44. return { ctx, parent }
  45. }
  46. function spawnRequest(parent: Agent) {
  47. return {
  48. prompt: [{ type: 'text' as const, text: 'child task' }],
  49. parent,
  50. signal: new AbortController().signal,
  51. }
  52. }
  53. function toolResultTexts(agent: Agent): string[] {
  54. return agent.session.events
  55. .filter((event): event is SessionEvent<'tool/result'> => event.type === 'tool/result')
  56. .map(event => event.data.message.content
  57. .flatMap(block => block.content)
  58. .filter((block): block is Extract<ContentBlock, { type: 'text' }> => block.type === 'text')
  59. .map(block => block.text)
  60. .join(''))
  61. }
  62. describe('in-process policy inheritance', () => {
  63. it('records parent overrides before publishing a spawn child', async () => {
  64. const script: Script = []
  65. const { ctx, parent } = await setupWalled(script)
  66. const blocked = join(workspace, 'spawn-blocked.txt')
  67. setSandboxMode(parent.session, 'read-only')
  68. setApprovalPolicy(parent.session, 'never')
  69. const parentLogLength = parent.session.events.length
  70. script.push(
  71. toolCallResponse('write', 'write', { file_path: blocked, content: 'escaped' }),
  72. textResponse('child done'),
  73. )
  74. const run = await startInProcessRun(spawnRequest(parent), {})
  75. try {
  76. const result = await run.result
  77. const child = run.localAgent as Agent
  78. await expect(readFile(blocked, 'utf8')).rejects.toMatchObject({ code: 'ENOENT' })
  79. expect(toolResultTexts(child).join('\n')).toContain(READ_ONLY_DENIAL)
  80. expect(result.stopReason).toBe('completed')
  81. expect(child.session.events.slice(0, 2)).toMatchObject([
  82. { type: 'sandbox/mode', seq: 0, data: { mode: 'read-only', source: 'delegation' } },
  83. { type: 'approval/policy', seq: 1, data: { policy: 'never', source: 'delegation' } },
  84. ])
  85. expect(child.session.firstLiveSeq).toBe(0)
  86. expect(child.session.header.seedLength).toBeUndefined()
  87. expect(ctx.sandboxPolicy.overrideOf(child.session)).toBe('read-only')
  88. expect(ctx.approval.overrideOf(child.session)).toBe('never')
  89. const request = child.session.events.find(
  90. (event): event is SessionEvent<'request/header'> => event.type === 'request/header',
  91. )
  92. expect(request?.data.header.system).toContain('Approval prompts are disabled')
  93. expect(parent.session.events).toHaveLength(parentLogLength)
  94. } finally {
  95. await run.dispose()
  96. }
  97. })
  98. it('places inherited events after a fork prefix so fresh policy wins stale seed state', async () => {
  99. const script: Script = []
  100. const { ctx, parent } = await setupWalled(script)
  101. const blocked = join(workspace, 'fork-blocked.txt')
  102. setSandboxMode(parent.session, 'workspace-write')
  103. const seed = [...parent.session.events]
  104. setSandboxMode(parent.session, 'read-only')
  105. script.push(
  106. toolCallResponse('write', 'write', { file_path: blocked, content: 'escaped' }),
  107. textResponse('child done'),
  108. )
  109. const run = await startInProcessRun(spawnRequest(parent), { seed })
  110. try {
  111. await run.result
  112. const child = run.localAgent as Agent
  113. expect(child.session.header.seedLength).toBe(1)
  114. expect(child.session.firstLiveSeq).toBe(seed.length)
  115. expect(child.session.events.filter(event => event.type === 'sandbox/mode')).toMatchObject([
  116. { seq: 0, data: { mode: 'workspace-write' } },
  117. { seq: 1, data: { mode: 'read-only', source: 'delegation' } },
  118. ])
  119. await expect(readFile(blocked, 'utf8')).rejects.toMatchObject({ code: 'ENOENT' })
  120. expect(ctx.sandboxPolicy.overrideOf(child.session)).toBe('read-only')
  121. setSandboxMode(child.session, 'danger-full-access')
  122. expect(ctx.sandboxPolicy.overrideOf(child.session)).toBe('danger-full-access')
  123. } finally {
  124. await run.dispose()
  125. }
  126. })
  127. it('captures policy at delegation before asynchronous child creation', async () => {
  128. const script: Script = [textResponse('child done')]
  129. const { ctx, parent } = await setupWalled(script)
  130. setSandboxMode(parent.session, 'read-only')
  131. const starting = startInProcessRun(spawnRequest(parent), {})
  132. setSandboxMode(parent.session, 'danger-full-access')
  133. const run = await starting
  134. try {
  135. await run.result
  136. const child = run.localAgent as Agent
  137. expect(ctx.sandboxPolicy.overrideOf(parent.session)).toBe('danger-full-access')
  138. expect(ctx.sandboxPolicy.overrideOf(child.session)).toBe('read-only')
  139. } finally {
  140. await run.dispose()
  141. }
  142. })
  143. it('does not freeze deployment defaults into an unswitched child', async () => {
  144. const script: Script = []
  145. const { parent } = await setupWalled(script)
  146. const allowed = join(workspace, 'default-allowed.txt')
  147. script.push(
  148. toolCallResponse('write', 'write', { file_path: allowed, content: 'fine' }),
  149. textResponse('child done'),
  150. )
  151. const run = await startInProcessRun(spawnRequest(parent), {})
  152. try {
  153. await run.result
  154. const child = run.localAgent as Agent
  155. expect(await readFile(allowed, 'utf8')).toBe('fine')
  156. expect(child.session.events.some(
  157. event => event.type === 'sandbox/mode' || event.type === 'approval/policy',
  158. )).toBe(false)
  159. expect(child.session.firstLiveSeq).toBe(0)
  160. } finally {
  161. await run.dispose()
  162. }
  163. })
  164. })