loader-composition.spec.ts 7.3 KB

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