loader-composition.spec.ts 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158
  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. updateInbox: () => 'not-found',
  49. reserveTurnAdmission: () => undefined,
  50. cancel() {},
  51. whenIdle: () => Promise.resolve(),
  52. }
  53. ctx.agents.register(value)
  54. return value
  55. }
  56. function text(result: { content: { type: string; text?: string }[] }): string {
  57. return result.content.filter(block => block.type === 'text').map(block => block.text).join('')
  58. }
  59. const suite = process.platform === 'linux' || process.platform === 'darwin' ? describe : describe.skip
  60. suite('persistent Bash through a real cordis.yml Loader composition', () => {
  61. it('preserves cwd and environment across calls', async () => {
  62. root = await mkdtemp(join(tmpdir(), 'dsh-persistent-bash-loader-'))
  63. const configPath = join(root, 'cordis.yml')
  64. await writeFile(configPath, [
  65. "- name: '@deepseek-ai/dsh-agent'",
  66. "- name: '@deepseek-ai/dsh-system-prompt'",
  67. "- name: '@deepseek-ai/dsh-tools'",
  68. "- name: '@deepseek-ai/dsh-pty'",
  69. "- name: '@deepseek-ai/dsh-test-sandbox'",
  70. "- name: '@deepseek-ai/dsh-sandbox-policy'",
  71. ' config:',
  72. ' mode: danger-full-access',
  73. ` workspaceRoot: ${JSON.stringify(root)}`,
  74. "- name: '@deepseek-ai/dsh-pty-local'",
  75. ' config:',
  76. ' pollIntervalMs: 10',
  77. ' exactProbeAfterMs: 20',
  78. ' idleSilenceMs: 100',
  79. ' handoffGraceMs: 100',
  80. ' scrollbackLines: 20000',
  81. ' timeoutMs: 2000',
  82. ' disposeGraceMs: 500',
  83. "- name: '@deepseek-ai/dsh-tool-bash-persistent'",
  84. ' config:',
  85. ' timeoutMs: 5000',
  86. '',
  87. ].join('\n'))
  88. context = new Context()
  89. context.baseUrl = pathToFileURL(root).href + '/'
  90. await context.plugin(Loader)
  91. context.loader.builtins.include = Include
  92. const modules = new Map<string, unknown>([
  93. ['@deepseek-ai/dsh-agent', AgentRegistry],
  94. ['@deepseek-ai/dsh-system-prompt', SystemPrompt],
  95. ['@deepseek-ai/dsh-tools', ToolRegistry],
  96. ['@deepseek-ai/dsh-pty', PtyService],
  97. ['@deepseek-ai/dsh-test-sandbox', PassthroughSandbox],
  98. ['@deepseek-ai/dsh-sandbox-policy', SandboxPolicyService],
  99. ['@deepseek-ai/dsh-pty-local', PtyLocal],
  100. ['@deepseek-ai/dsh-tool-bash-persistent', ToolBashPersistent],
  101. ])
  102. context.loader.internal = {
  103. version: 'v2',
  104. async import(specifier: string) {
  105. if (!modules.has(specifier)) throw new Error(`unexpected Loader import: ${specifier}`)
  106. return modules.get(specifier)
  107. },
  108. } as unknown as NonNullable<typeof context.loader.internal>
  109. await context.loader.create({ name: 'cordis:include', config: { path: pathToFileURL(configPath).href } })
  110. await context.loader.await()
  111. const owner = agent(context, root)
  112. const signal = new AbortController().signal
  113. const execute = (id: string, command: string) => context!.tools.execute({
  114. signal,
  115. callId: CallId(id),
  116. name: 'bash',
  117. arguments: { command },
  118. agent: owner,
  119. })
  120. expect(context.tools.schemas().map(schema => schema.name)).toEqual(['bash'])
  121. await execute('state', 'export KEEP=loader; mkdir -p nested; cd nested')
  122. const observed = text(await execute('observe', 'printf "cwd=%s keep=%s\\n" "$PWD" "$KEEP"'))
  123. expect(observed).toContain(`cwd=${join(root, 'nested')} keep=loader`)
  124. expect(observed).not.toContain('DSH_PERSISTENT_BASH')
  125. const multiline = text(await execute(
  126. 'multiline',
  127. 'value="line one"\nprintf "%s:%s\\n" "$value" "it\'s fine"',
  128. ))
  129. expect(multiline).toBe("line one:it's fine")
  130. expect(multiline).not.toContain('DSH_PERSISTENT_BASH')
  131. const heredoc = text(await execute(
  132. 'heredoc',
  133. "cat <<'EOF'\nalpha\nbeta\nEOF",
  134. ))
  135. expect(heredoc).toBe('alpha\nbeta')
  136. const large = text(await execute('large-output', 'seq 1 12050'))
  137. expect(large.startsWith('1\n2\n3\n')).toBe(true)
  138. expect(large).toContain('<response clipped>')
  139. expect(large).not.toContain('beginning of this command output was dropped')
  140. const exited = text(await execute('exit', 'exit'))
  141. expect(exited).toContain('next bash call starts from the workspace')
  142. expect(text(await execute('after-exit', 'printf "%s\\n" "$PWD"'))).toBe(root)
  143. }, 20_000)
  144. })