loader-composition.spec.ts 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156
  1. import { mkdtemp, rm, writeFile } from 'node:fs/promises'
  2. import { tmpdir } from 'node:os'
  3. import { join } from 'node:path'
  4. import { pathToFileURL } from 'node:url'
  5. import { afterEach, describe, expect, it } from 'vitest'
  6. import { Context } from 'cordis'
  7. import Loader from '@cordisjs/plugin-loader'
  8. import Include from '@cordisjs/plugin-include'
  9. import { CallId } from '@deepseek-ai/dsh-llm'
  10. import { Session, SessionId } from '@deepseek-ai/dsh-session'
  11. import AgentRegistry from '@deepseek-ai/dsh-agent'
  12. import type { Agent } from '@deepseek-ai/dsh-agent'
  13. import PtyService from '@deepseek-ai/dsh-pty'
  14. import * as PtyLocal from '@deepseek-ai/dsh-pty-local'
  15. import SandboxProvider from '@deepseek-ai/dsh-sandbox'
  16. import type { ConfinedArgv, SandboxPolicy } from '@deepseek-ai/dsh-sandbox'
  17. import SandboxPolicyService from '@deepseek-ai/dsh-sandbox-policy'
  18. import SystemPrompt from '@deepseek-ai/dsh-system-prompt'
  19. import ToolRegistry from '@deepseek-ai/dsh-tools'
  20. import * as ToolBashPersistent from '@deepseek-ai/dsh-tool-bash-persistent'
  21. let root: string | undefined
  22. let context: Context | undefined
  23. afterEach(async () => {
  24. await context?.fiber.dispose()
  25. context = undefined
  26. if (root !== undefined) await rm(root, { recursive: true, force: true })
  27. root = undefined
  28. })
  29. class PassthroughSandbox extends SandboxProvider {
  30. confine(argv: readonly string[], _policy: SandboxPolicy): ConfinedArgv {
  31. return { argv: [...argv], enforcement: 'full', denialSignatures: [], runnerFailureSignatures: [] }
  32. }
  33. }
  34. function agent(ctx: Context, cwd: string): Agent {
  35. const id = SessionId('persistent-bash-loader-agent')
  36. const scope = ctx.plugin(() => {})
  37. const value: Agent = {
  38. id,
  39. options: {},
  40. session: new Session(id, [], { version: 0, id, createdAt: 0, cwd }),
  41. status: 'idle',
  42. acceptsNextStep: false,
  43. ctx: scope.ctx,
  44. followup: () => {},
  45. steer: () => {},
  46. inject: () => {},
  47. send: () => {},
  48. cancel() {},
  49. whenIdle: () => Promise.resolve(),
  50. }
  51. ctx.agents.register(value)
  52. return value
  53. }
  54. function text(result: { content: { type: string; text?: string }[] }): string {
  55. return result.content.filter(block => block.type === 'text').map(block => block.text).join('')
  56. }
  57. const suite = process.platform === 'linux' || process.platform === 'darwin' ? describe : describe.skip
  58. suite('persistent Bash through a real cordis.yml Loader composition', () => {
  59. it('preserves cwd and environment across calls', async () => {
  60. root = await mkdtemp(join(tmpdir(), 'dsh-persistent-bash-loader-'))
  61. const configPath = join(root, 'cordis.yml')
  62. await writeFile(configPath, [
  63. "- name: '@deepseek-ai/dsh-agent'",
  64. "- name: '@deepseek-ai/dsh-system-prompt'",
  65. "- name: '@deepseek-ai/dsh-tools'",
  66. "- name: '@deepseek-ai/dsh-pty'",
  67. "- name: '@deepseek-ai/dsh-test-sandbox'",
  68. "- name: '@deepseek-ai/dsh-sandbox-policy'",
  69. ' config:',
  70. ' mode: danger-full-access',
  71. ` workspaceRoot: ${JSON.stringify(root)}`,
  72. "- name: '@deepseek-ai/dsh-pty-local'",
  73. ' config:',
  74. ' pollIntervalMs: 10',
  75. ' exactProbeAfterMs: 20',
  76. ' idleSilenceMs: 100',
  77. ' handoffGraceMs: 100',
  78. ' scrollbackLines: 20000',
  79. ' timeoutMs: 2000',
  80. ' disposeGraceMs: 500',
  81. "- name: '@deepseek-ai/dsh-tool-bash-persistent'",
  82. ' config:',
  83. ' timeoutMs: 5000',
  84. '',
  85. ].join('\n'))
  86. context = new Context()
  87. context.baseUrl = pathToFileURL(root).href + '/'
  88. await context.plugin(Loader)
  89. context.loader.builtins.include = Include
  90. const modules = new Map<string, unknown>([
  91. ['@deepseek-ai/dsh-agent', AgentRegistry],
  92. ['@deepseek-ai/dsh-system-prompt', SystemPrompt],
  93. ['@deepseek-ai/dsh-tools', ToolRegistry],
  94. ['@deepseek-ai/dsh-pty', PtyService],
  95. ['@deepseek-ai/dsh-test-sandbox', PassthroughSandbox],
  96. ['@deepseek-ai/dsh-sandbox-policy', SandboxPolicyService],
  97. ['@deepseek-ai/dsh-pty-local', PtyLocal],
  98. ['@deepseek-ai/dsh-tool-bash-persistent', ToolBashPersistent],
  99. ])
  100. context.loader.internal = {
  101. version: 'v2',
  102. async import(specifier: string) {
  103. if (!modules.has(specifier)) throw new Error(`unexpected Loader import: ${specifier}`)
  104. return modules.get(specifier)
  105. },
  106. } as unknown as NonNullable<typeof context.loader.internal>
  107. await context.loader.create({ name: 'cordis:include', config: { path: pathToFileURL(configPath).href } })
  108. await context.loader.await()
  109. const owner = agent(context, root)
  110. const signal = new AbortController().signal
  111. const execute = (id: string, command: string) => context!.tools.execute({
  112. signal,
  113. callId: CallId(id),
  114. name: 'bash',
  115. arguments: { command },
  116. agent: owner,
  117. })
  118. expect(context.tools.schemas().map(schema => schema.name)).toEqual(['bash'])
  119. await execute('state', 'export KEEP=loader; mkdir -p nested; cd nested')
  120. const observed = text(await execute('observe', 'printf "cwd=%s keep=%s\\n" "$PWD" "$KEEP"'))
  121. expect(observed).toContain(`cwd=${join(root, 'nested')} keep=loader`)
  122. expect(observed).not.toContain('DSH_PERSISTENT_BASH')
  123. const multiline = text(await execute(
  124. 'multiline',
  125. 'value="line one"\nprintf "%s:%s\\n" "$value" "it\'s fine"',
  126. ))
  127. expect(multiline).toBe("line one:it's fine")
  128. expect(multiline).not.toContain('DSH_PERSISTENT_BASH')
  129. const heredoc = text(await execute(
  130. 'heredoc',
  131. "cat <<'EOF'\nalpha\nbeta\nEOF",
  132. ))
  133. expect(heredoc).toBe('alpha\nbeta')
  134. const large = text(await execute('large-output', 'seq 1 12050'))
  135. expect(large.startsWith('1\n2\n3\n')).toBe(true)
  136. expect(large).toContain('<response clipped>')
  137. expect(large).not.toContain('beginning of this command output was dropped')
  138. const exited = text(await execute('exit', 'exit'))
  139. expect(exited).toContain('next bash call starts from the workspace')
  140. expect(text(await execute('after-exit', 'printf "%s\\n" "$PWD"'))).toBe(root)
  141. }, 20_000)
  142. })