loader-composition.spec.ts 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180
  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 '@deepseek-ai/cordis'
  7. import Loader from '@deepseek-ai/cordis-plugin-loader'
  8. import Include from '@deepseek-ai/cordis-plugin-include'
  9. import { ToolCallId } 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 TerminalSessionService from '@deepseek-ai/dsh-terminal'
  14. import * as TerminalLocal from '@deepseek-ai/dsh-terminal-bash'
  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 SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection'
  19. import LocalSubprocessRuntime from '@deepseek-ai/dsh-subprocess-local'
  20. import SystemPrompt from '@deepseek-ai/dsh-system-prompt'
  21. import ToolRuntime from '@deepseek-ai/dsh-tools'
  22. import * as ToolBashPersistent from '@deepseek-ai/dsh-tool-bash-persistent'
  23. import { unsupportedInbox } from '@deepseek-ai/dsh-agent-loop-testkit'
  24. let root: string | undefined
  25. let context: Context | undefined
  26. afterEach(async () => {
  27. await context?.fiber.dispose()
  28. context = undefined
  29. if (root !== undefined) await rm(root, { recursive: true, force: true })
  30. root = undefined
  31. })
  32. class PassthroughSandbox extends SandboxProvider {
  33. confine(argv: readonly string[], _policy: SandboxPolicy): ConfinedArgv {
  34. return { argv: [...argv], enforcement: 'full', denialSignatures: [], runnerFailureRules: [] }
  35. }
  36. }
  37. function agent(ctx: Context, cwd: string): Agent {
  38. const id = SessionId('persistent-bash-loader-agent')
  39. const scope = ctx.plugin(() => {})
  40. const session = Session.create(id, [], { version: 0, id, createdAt: 0, cwd })
  41. const value: Agent = {
  42. id,
  43. options: {},
  44. session,
  45. inbox: unsupportedInbox(),
  46. status: 'idle',
  47. ctx: scope.ctx,
  48. send: () => {},
  49. followup: () => {},
  50. steer: () => ({ outcome: Promise.resolve({ status: 'rejected' as const }) }),
  51. inject: () => {},
  52. cancel() {},
  53. runMaintenance: task => task(new AbortController().signal),
  54. whenIdle: () => Promise.resolve(),
  55. }
  56. ctx.agents.register(value)
  57. return value
  58. }
  59. function text(result: { content: { type: string; text?: string }[] }): string {
  60. return result.content.filter(block => block.type === 'text').map(block => block.text).join('')
  61. }
  62. const suite = process.platform === 'linux' || process.platform === 'darwin' ? describe : describe.skip
  63. suite('persistent Bash through a real cordis.yml Loader composition', () => {
  64. it('preserves cwd and environment across calls', async () => {
  65. root = await mkdtemp(join(tmpdir(), 'dsh-persistent-bash-loader-'))
  66. const configPath = join(root, 'cordis.yml')
  67. await writeFile(configPath, [
  68. "- name: '@deepseek-ai/dsh-agent'",
  69. "- name: '@deepseek-ai/dsh-system-prompt'",
  70. "- name: '@deepseek-ai/dsh-tools'",
  71. "- name: '@deepseek-ai/dsh-terminal'",
  72. "- name: '@deepseek-ai/dsh-test-sandbox'",
  73. "- name: '@deepseek-ai/dsh-session-projection'",
  74. "- name: '@deepseek-ai/dsh-sandbox-policy'",
  75. ' config:',
  76. ' mode: danger-full-access',
  77. ` workspaceRoot: ${JSON.stringify(root)}`,
  78. "- name: '@deepseek-ai/dsh-subprocess-local'",
  79. "- name: '@deepseek-ai/dsh-terminal-bash'",
  80. ' config:',
  81. ' pollIntervalMs: 10',
  82. ' exactProbeAfterMs: 20',
  83. // The silence tier is pushed beyond the send bound, so no send below can
  84. // settle as inferred_idle: every case proves the controlled-prompt fast
  85. // path that the production defaults (3.5s silence) would otherwise mask.
  86. ' idleSilenceMs: 30000',
  87. ' handoffGraceMs: 100',
  88. ' scrollbackLines: 20000',
  89. ' timeoutMs: 2000',
  90. ' disposeGraceMs: 500',
  91. "- name: '@deepseek-ai/dsh-tool-bash-persistent'",
  92. ' config:',
  93. ' timeoutMs: 5000',
  94. '',
  95. ].join('\n'))
  96. context = new Context()
  97. context.baseUrl = pathToFileURL(root).href + '/'
  98. await context.plugin(Loader)
  99. context.loader.builtins.include = Include
  100. const modules = new Map<string, unknown>([
  101. ['@deepseek-ai/dsh-agent', AgentRegistry],
  102. ['@deepseek-ai/dsh-system-prompt', SystemPrompt],
  103. ['@deepseek-ai/dsh-tools', ToolRuntime],
  104. ['@deepseek-ai/dsh-terminal', TerminalSessionService],
  105. ['@deepseek-ai/dsh-test-sandbox', PassthroughSandbox],
  106. ['@deepseek-ai/dsh-session-projection', SessionProjectionRegistry],
  107. ['@deepseek-ai/dsh-sandbox-policy', SandboxPolicyService],
  108. ['@deepseek-ai/dsh-subprocess-local', LocalSubprocessRuntime],
  109. ['@deepseek-ai/dsh-terminal-bash', TerminalLocal],
  110. ['@deepseek-ai/dsh-tool-bash-persistent', ToolBashPersistent],
  111. ])
  112. context.loader.internal = {
  113. version: 'v2',
  114. async import(specifier: string) {
  115. if (!modules.has(specifier)) throw new Error(`unexpected Loader import: ${specifier}`)
  116. return modules.get(specifier)
  117. },
  118. } as unknown as NonNullable<typeof context.loader.internal>
  119. await context.loader.create({ name: 'cordis:include', config: { path: pathToFileURL(configPath).href } })
  120. await context.loader.await()
  121. const owner = agent(context, root)
  122. const signal = new AbortController().signal
  123. const execute = (id: string, command: string) => context!.tools.execute({
  124. signal,
  125. callId: ToolCallId(id),
  126. name: 'bash',
  127. arguments: { command },
  128. agent: owner,
  129. })
  130. expect(context.tools.schemas().map(schema => schema.name)).toEqual(['bash'])
  131. await execute('state', 'export KEEP=loader; mkdir -p nested; cd nested')
  132. const observed = text(await execute('observe', 'printf "cwd=%s keep=%s\\n" "$PWD" "$KEEP"'))
  133. expect(observed).toContain(`cwd=${join(root, 'nested')} keep=loader`)
  134. expect(observed).not.toContain('DSH_PERSISTENT_BASH')
  135. const multiline = text(await execute(
  136. 'multiline',
  137. 'value="line one"\nprintf "%s:%s\\n" "$value" "it\'s fine"',
  138. ))
  139. expect(multiline).toBe("line one:it's fine")
  140. expect(multiline).not.toContain('DSH_PERSISTENT_BASH')
  141. const heredoc = text(await execute(
  142. 'heredoc',
  143. "cat <<'EOF'\nalpha\nbeta\nEOF",
  144. ))
  145. expect(heredoc).toBe('alpha\nbeta')
  146. const pipeline = text(await execute(
  147. 'pipeline',
  148. '{ sleep 0.1; printf "delayed\\n"; } | cat',
  149. ))
  150. expect(pipeline).toBe('delayed')
  151. const large = text(await execute('large-output', 'seq 1 12050'))
  152. expect(large.startsWith('1\n2\n3\n')).toBe(true)
  153. expect(large).toContain('<response clipped>')
  154. expect(large).not.toContain('beginning of this command output was dropped')
  155. // `exec` replaces the wrapper before its end marker prints; the seam's
  156. // stdin_read readiness is what returns the replacement shell's prompt
  157. // instead of spinning until the tool deadline.
  158. const execed = text(await execute('exec-replacement', 'exec bash --noprofile --norc -i'))
  159. expect(execed).toBe('dsh> ')
  160. const exited = text(await execute('exit', 'exit'))
  161. expect(exited).toContain('next bash call starts from the workspace')
  162. expect(text(await execute('after-exit', 'printf "%s\\n" "$PWD"'))).toBe(root)
  163. }, 20_000)
  164. })