loader-composition.spec.ts 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168
  1. import { spawnSync } from 'node:child_process'
  2. import { mkdtemp, 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, { agentEvents, 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: undefined as never,
  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. Object.assign(value, { inbox: new Inbox(value.ctx, value.session, agentEvents(value.ctx, value)) })
  61. ctx.agents.register(value)
  62. return value
  63. }
  64. function text(result: { content: { type: string; text?: string }[] }): string {
  65. return result.content.filter(block => block.type === 'text').map(block => block.text).join('')
  66. }
  67. describe.skipIf(!hasPwsh)('persistent pwsh through a real cordis.yml Loader composition', () => {
  68. it('preserves cwd and environment across calls', async () => {
  69. root = await mkdtemp(join(tmpdir(), 'dsh-persistent-pwsh-loader-'))
  70. const configPath = join(root, 'cordis.yml')
  71. await writeFile(configPath, [
  72. "- name: '@deepseek-ai/dsh-agent'",
  73. "- name: '@deepseek-ai/dsh-system-prompt'",
  74. "- name: '@deepseek-ai/dsh-tools'",
  75. "- name: '@deepseek-ai/dsh-terminal'",
  76. "- name: '@deepseek-ai/dsh-test-sandbox'",
  77. "- name: '@deepseek-ai/dsh-sandbox-policy'",
  78. ' config:',
  79. ' mode: danger-full-access',
  80. ` workspaceRoot: ${JSON.stringify(root)}`,
  81. "- name: '@deepseek-ai/dsh-subprocess-local'",
  82. "- name: '@deepseek-ai/dsh-terminal-bash'",
  83. ' config:',
  84. ' shellDialect: pwsh',
  85. ' pollIntervalMs: 10',
  86. ' exactProbeAfterMs: 20',
  87. ' idleSilenceMs: 300',
  88. ' handoffGraceMs: 300',
  89. ' scrollbackLines: 20000',
  90. ' timeoutMs: 8000',
  91. ' disposeGraceMs: 500',
  92. "- name: '@deepseek-ai/dsh-tool-pwsh-persistent'",
  93. ' config:',
  94. ' timeoutMs: 20000',
  95. '',
  96. ].join('\n'))
  97. context = new Context()
  98. context.baseUrl = pathToFileURL(root).href + '/'
  99. await context.plugin(Loader)
  100. context.loader.builtins.include = Include
  101. const modules = new Map<string, unknown>([
  102. ['@deepseek-ai/dsh-agent', AgentRegistry],
  103. ['@deepseek-ai/dsh-system-prompt', SystemPrompt],
  104. ['@deepseek-ai/dsh-tools', ToolRegistry],
  105. ['@deepseek-ai/dsh-terminal', TerminalSessionService],
  106. ['@deepseek-ai/dsh-test-sandbox', PassthroughSandbox],
  107. ['@deepseek-ai/dsh-sandbox-policy', SandboxPolicyService],
  108. ['@deepseek-ai/dsh-subprocess-local', LocalSubprocessService],
  109. ['@deepseek-ai/dsh-terminal-bash', TerminalBash],
  110. ['@deepseek-ai/dsh-tool-pwsh-persistent', ToolPwshPersistent],
  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: CallId(id),
  126. name: 'pwsh',
  127. arguments: { command },
  128. agent: owner,
  129. })
  130. expect(context.tools.schemas().map(schema => schema.name)).toEqual(['pwsh'])
  131. await execute('state', '$env:KEEP = "loader"; New-Item -ItemType Directory -Force -Path nested | Out-Null; Set-Location nested')
  132. const observed = text(await execute('observe', 'Write-Output "cwd=$PWD keep=$env:KEEP"'))
  133. expect(observed).toContain(`cwd=${join(root, 'nested')} keep=loader`)
  134. expect(observed).not.toContain('DSH_PERSISTENT_PWSH')
  135. const multiline = text(await execute(
  136. 'multiline',
  137. '$value = "line one"\nWrite-Output "${value}:it\'s fine"',
  138. ))
  139. expect(multiline).toBe("line one:it's fine")
  140. expect(multiline).not.toContain('DSH_PERSISTENT_PWSH')
  141. const hereString = text(await execute(
  142. 'here-string',
  143. "$h = @'\nalpha\nbeta\n'@\nWrite-Output $h",
  144. ))
  145. expect(hereString).toBe('alpha\nbeta')
  146. const large = text(await execute('large-output', '1..12050 | ForEach-Object { $_ }'))
  147. expect(large.startsWith('1\n2\n3\n')).toBe(true)
  148. expect(large).toContain('<response clipped>')
  149. expect(large).not.toContain('beginning of this command output was dropped')
  150. const exited = text(await execute('exit', 'exit'))
  151. expect(exited).toContain('next pwsh call starts from the workspace')
  152. expect(text(await execute('after-exit', 'Write-Output "$PWD"'))).toBe(root)
  153. }, 60_000)
  154. })