loader-composition.spec.ts 6.8 KB

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