loader-composition.spec.ts 7.0 KB

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