loader-composition.spec.ts 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171
  1. import { spawnSync } from 'node:child_process'
  2. import { mkdtemp, realpath, rm, writeFile } from 'node:fs/promises'
  3. import { tmpdir } from 'node:os'
  4. import { join } from 'node:path'
  5. import { pathToFileURL } from 'node:url'
  6. import { afterEach, describe, expect, it } from 'vitest'
  7. import { Context } from '@deepseek-ai/cordis'
  8. import Loader from '@deepseek-ai/cordis-plugin-loader'
  9. import Include from '@deepseek-ai/cordis-plugin-include'
  10. import { ToolCallId } from '@deepseek-ai/dsh-llm'
  11. import { Session, SessionId } from '@deepseek-ai/dsh-session'
  12. import AgentRegistry from '@deepseek-ai/dsh-agent'
  13. import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection'
  14. import type { Agent } from '@deepseek-ai/dsh-agent'
  15. import TerminalSessionService from '@deepseek-ai/dsh-terminal'
  16. import * as TerminalBash from '@deepseek-ai/dsh-terminal-bash'
  17. import SandboxProvider from '@deepseek-ai/dsh-sandbox'
  18. import type { ConfinedArgv, SandboxPolicy } from '@deepseek-ai/dsh-sandbox'
  19. import SandboxPolicyService from '@deepseek-ai/dsh-sandbox-policy'
  20. import LocalSubprocessService from '@deepseek-ai/dsh-subprocess-local'
  21. import { resolvePwshPath } from '@deepseek-ai/dsh-pwsh-local/src/resolve.ts'
  22. import SystemPrompt from '@deepseek-ai/dsh-system-prompt'
  23. import ToolRegistry from '@deepseek-ai/dsh-tools'
  24. import * as ToolPwshPersistent from '@deepseek-ai/dsh-tool-pwsh-persistent'
  25. import { unsupportedInbox } from '@deepseek-ai/dsh-agent-loop-testkit'
  26. const hasPwsh = spawnSync(
  27. resolvePwshPath(), ['-NoLogo', '-NoProfile', '-NonInteractive', '-Command', '$true'],
  28. { encoding: 'utf8' },
  29. ).status === 0
  30. let root: string | undefined
  31. let context: Context | undefined
  32. afterEach(async () => {
  33. await context?.fiber.dispose()
  34. context = undefined
  35. if (root !== undefined) await rm(root, { recursive: true, force: true })
  36. root = undefined
  37. })
  38. class PassthroughSandbox extends SandboxProvider {
  39. confine(argv: readonly string[], _policy: SandboxPolicy): ConfinedArgv {
  40. return { argv: [...argv], enforcement: 'full', denialSignatures: [], runnerFailureRules: [] }
  41. }
  42. }
  43. function agent(ctx: Context, cwd: string): Agent {
  44. const id = SessionId('persistent-pwsh-loader-agent')
  45. const scope = ctx.plugin(() => {})
  46. const session = Session.create(id, [], { version: 0, id, createdAt: 0, cwd })
  47. const value: Agent = {
  48. id,
  49. options: {},
  50. session,
  51. inbox: unsupportedInbox(),
  52. status: 'idle',
  53. ctx: scope.ctx,
  54. send: () => {},
  55. followup: () => {},
  56. steer: () => ({ outcome: Promise.resolve({ status: 'rejected' as const }) }),
  57. inject: () => {},
  58. cancel() {},
  59. runMaintenance: task => task(new AbortController().signal),
  60. whenIdle: () => Promise.resolve(),
  61. }
  62. ctx.agents.register(value)
  63. return value
  64. }
  65. function text(result: { content: { type: string; text?: string }[] }): string {
  66. return result.content.filter(block => block.type === 'text').map(block => block.text).join('')
  67. }
  68. describe.skipIf(!hasPwsh)('persistent pwsh through a real cordis.yml Loader composition', () => {
  69. it('preserves cwd and environment across calls', async () => {
  70. root = await realpath(await mkdtemp(join(tmpdir(), 'dsh-persistent-pwsh-loader-')))
  71. const configPath = join(root, 'cordis.yml')
  72. await writeFile(configPath, [
  73. "- name: '@deepseek-ai/dsh-agent'",
  74. "- name: '@deepseek-ai/dsh-system-prompt'",
  75. "- name: '@deepseek-ai/dsh-tools'",
  76. "- name: '@deepseek-ai/dsh-terminal'",
  77. "- name: '@deepseek-ai/dsh-test-sandbox'",
  78. "- name: '@deepseek-ai/dsh-session-projection'",
  79. "- name: '@deepseek-ai/dsh-sandbox-policy'",
  80. ' config:',
  81. ' mode: danger-full-access',
  82. ` workspaceRoot: ${JSON.stringify(root)}`,
  83. "- name: '@deepseek-ai/dsh-subprocess-local'",
  84. "- name: '@deepseek-ai/dsh-terminal-bash'",
  85. ' config:',
  86. ' shellDialect: pwsh',
  87. ' pollIntervalMs: 10',
  88. ' exactProbeAfterMs: 20',
  89. ' idleSilenceMs: 300',
  90. ' handoffGraceMs: 300',
  91. ' scrollbackLines: 20000',
  92. ' timeoutMs: 60000',
  93. ' disposeGraceMs: 500',
  94. "- name: '@deepseek-ai/dsh-tool-pwsh-persistent'",
  95. ' config:',
  96. ' timeoutMs: 60000',
  97. '',
  98. ].join('\n'))
  99. context = new Context()
  100. context.baseUrl = pathToFileURL(root).href + '/'
  101. await context.plugin(Loader)
  102. context.loader.builtins.include = Include
  103. const modules = new Map<string, unknown>([
  104. ['@deepseek-ai/dsh-agent', AgentRegistry],
  105. ['@deepseek-ai/dsh-system-prompt', SystemPrompt],
  106. ['@deepseek-ai/dsh-tools', ToolRegistry],
  107. ['@deepseek-ai/dsh-terminal', TerminalSessionService],
  108. ['@deepseek-ai/dsh-test-sandbox', PassthroughSandbox],
  109. ['@deepseek-ai/dsh-session-projection', SessionProjectionRegistry],
  110. ['@deepseek-ai/dsh-sandbox-policy', SandboxPolicyService],
  111. ['@deepseek-ai/dsh-subprocess-local', LocalSubprocessService],
  112. ['@deepseek-ai/dsh-terminal-bash', TerminalBash],
  113. ['@deepseek-ai/dsh-tool-pwsh-persistent', ToolPwshPersistent],
  114. ])
  115. context.loader.internal = {
  116. version: 'v2',
  117. async import(specifier: string) {
  118. if (!modules.has(specifier)) throw new Error(`unexpected Loader import: ${specifier}`)
  119. return modules.get(specifier)
  120. },
  121. } as unknown as NonNullable<typeof context.loader.internal>
  122. await context.loader.create({ name: 'cordis:include', config: { path: pathToFileURL(configPath).href } })
  123. await context.loader.await()
  124. const owner = agent(context, root)
  125. const signal = new AbortController().signal
  126. const execute = (id: string, command: string) => context!.tools.execute({
  127. signal,
  128. callId: ToolCallId(id),
  129. name: 'pwsh',
  130. arguments: { command },
  131. agent: owner,
  132. })
  133. expect(context.tools.schemas().map(schema => schema.name)).toEqual(['pwsh'])
  134. await execute('state', '$env:KEEP = "loader"; New-Item -ItemType Directory -Force -Path nested | Out-Null; Set-Location nested')
  135. const observed = text(await execute('observe', 'Write-Output "cwd=$PWD keep=$env:KEEP"'))
  136. expect(observed).toContain(`cwd=${join(root, 'nested')} keep=loader`)
  137. expect(observed).not.toContain('DSH_PERSISTENT_PWSH')
  138. const multiline = text(await execute(
  139. 'multiline',
  140. '$value = "line one"\nWrite-Output "${value}:it\'s fine"',
  141. ))
  142. expect(multiline).toBe("line one:it's fine")
  143. expect(multiline).not.toContain('DSH_PERSISTENT_PWSH')
  144. const hereString = text(await execute(
  145. 'here-string',
  146. "$h = @'\nalpha\nbeta\n'@\nWrite-Output $h",
  147. ))
  148. expect(hereString).toBe('alpha\nbeta')
  149. const large = text(await execute('large-output', '1..12050 | ForEach-Object { $_ }'))
  150. expect(large.startsWith('1\n2\n3\n')).toBe(true)
  151. expect(large).toContain('<response clipped>')
  152. expect(large).not.toContain('beginning of this command output was dropped')
  153. const exited = text(await execute('exit', 'exit'))
  154. expect(exited).toContain('next pwsh call starts from the workspace')
  155. expect(text(await execute('after-exit', 'Write-Output "$PWD"'))).toBe(root)
  156. }, 120_000)
  157. })