loader-composition.spec.ts 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180
  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_FORMAT_VERSION, 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, [], {
  46. version: SESSION_FORMAT_VERSION, id, createdAt: 0, cwd, isSeeded: false,
  47. })
  48. const value: Agent = {
  49. id,
  50. options: {},
  51. session,
  52. inbox: new Inbox(session, { inserted: () => {}, discarded: () => {}, claimed: () => {} }),
  53. status: 'idle',
  54. ctx: scope.ctx,
  55. send: () => {},
  56. followup: () => {},
  57. steer: () => ({ outcome: Promise.resolve({ status: 'rejected' as const }) }),
  58. inject: () => {},
  59. cancel() {},
  60. runMaintenance: task => task(new AbortController().signal),
  61. whenIdle: () => Promise.resolve(),
  62. }
  63. ctx.agents.register(value)
  64. return value
  65. }
  66. function text(result: { content: { type: string; text?: string }[] }): string {
  67. return result.content.filter(block => block.type === 'text').map(block => block.text).join('')
  68. }
  69. describe.skipIf(!hasPwsh)('persistent pwsh through a real cordis.yml Loader composition', () => {
  70. it('preserves cwd and environment across calls', async () => {
  71. root = await realpath(await mkdtemp(join(tmpdir(), 'dsh-persistent-pwsh-loader-')))
  72. const configPath = join(root, 'cordis.yml')
  73. await writeFile(configPath, [
  74. "- name: '@deepseek-ai/dsh-agent'",
  75. "- name: '@deepseek-ai/dsh-system-prompt'",
  76. "- name: '@deepseek-ai/dsh-tools'",
  77. "- name: '@deepseek-ai/dsh-terminal'",
  78. "- name: '@deepseek-ai/dsh-test-sandbox'",
  79. "- name: '@deepseek-ai/dsh-session-projection'",
  80. "- name: '@deepseek-ai/dsh-sandbox-policy'",
  81. ' config:',
  82. ' mode: danger-full-access',
  83. ` workspaceRoot: ${JSON.stringify(root)}`,
  84. "- name: '@deepseek-ai/dsh-subprocess-local'",
  85. "- name: '@deepseek-ai/dsh-terminal-bash'",
  86. ' config:',
  87. ' shellDialect: pwsh',
  88. ' pollIntervalMs: 10',
  89. ' exactProbeAfterMs: 20',
  90. ' idleSilenceMs: 300',
  91. ' handoffGraceMs: 300',
  92. ' scrollbackLines: 20000',
  93. // The first call pays the full pwsh cold-start latency (spawn + .NET +
  94. // PSReadLine + Defender) inside the tool deadline; a 60s bound on the
  95. // fully loaded self-hosted Windows pool is exceeded often enough to
  96. // reset the session mid-test (2026-09-01, two runs ~62s each). 300s
  97. // matches the dsh-tool-pwsh-persistent product default; the
  98. // dsh-terminal-bash value bounds one send plus the complete startup
  99. // sequence, so it covers the same cold start (its 30s product default
  100. // would not).
  101. ' timeoutMs: 300000',
  102. ' disposeGraceMs: 500',
  103. "- name: '@deepseek-ai/dsh-tool-pwsh-persistent'",
  104. ' config:',
  105. ' timeoutMs: 300000',
  106. '',
  107. ].join('\n'))
  108. context = new Context()
  109. context.baseUrl = pathToFileURL(root).href + '/'
  110. await context.plugin(Loader)
  111. context.loader.builtins.include = Include
  112. const modules = new Map<string, unknown>([
  113. ['@deepseek-ai/dsh-agent', AgentRegistry],
  114. ['@deepseek-ai/dsh-system-prompt', SystemPrompt],
  115. ['@deepseek-ai/dsh-tools', ToolRegistry],
  116. ['@deepseek-ai/dsh-terminal', TerminalSessionService],
  117. ['@deepseek-ai/dsh-test-sandbox', PassthroughSandbox],
  118. ['@deepseek-ai/dsh-session-projection', SessionProjectionRegistry],
  119. ['@deepseek-ai/dsh-sandbox-policy', SandboxPolicyService],
  120. ['@deepseek-ai/dsh-subprocess-local', LocalSubprocessService],
  121. ['@deepseek-ai/dsh-terminal-bash', TerminalBash],
  122. ['@deepseek-ai/dsh-tool-pwsh-persistent', ToolPwshPersistent],
  123. ])
  124. context.loader.internal = {
  125. version: 'v2',
  126. async import(specifier: string) {
  127. if (!modules.has(specifier)) throw new Error(`unexpected Loader import: ${specifier}`)
  128. return modules.get(specifier)
  129. },
  130. } as unknown as NonNullable<typeof context.loader.internal>
  131. await context.loader.create({ name: 'cordis:include', config: { path: pathToFileURL(configPath).href } })
  132. await context.loader.await()
  133. const owner = agent(context, root)
  134. const signal = new AbortController().signal
  135. const execute = (id: string, command: string) => context!.tools.execute({
  136. signal,
  137. callId: ToolCallId(id),
  138. name: 'pwsh',
  139. arguments: { command },
  140. agent: owner,
  141. })
  142. expect(context.tools.schemas().map(schema => schema.name)).toEqual(['pwsh'])
  143. await execute('state', '$env:KEEP = "loader"; New-Item -ItemType Directory -Force -Path nested | Out-Null; Set-Location nested')
  144. const observed = text(await execute('observe', 'Write-Output "cwd=$PWD keep=$env:KEEP"'))
  145. expect(observed).toContain(`cwd=${join(root, 'nested')} keep=loader`)
  146. expect(observed).not.toContain('DSH_PERSISTENT_PWSH')
  147. const multiline = text(await execute(
  148. 'multiline',
  149. '$value = "line one"\nWrite-Output "${value}:it\'s fine"',
  150. ))
  151. expect(multiline).toBe("line one:it's fine")
  152. expect(multiline).not.toContain('DSH_PERSISTENT_PWSH')
  153. const hereString = text(await execute(
  154. 'here-string',
  155. "$h = @'\nalpha\nbeta\n'@\nWrite-Output $h",
  156. ))
  157. expect(hereString).toBe('alpha\nbeta')
  158. const large = text(await execute('large-output', '1..12050 | ForEach-Object { $_ }'))
  159. expect(large.startsWith('1\n2\n3\n')).toBe(true)
  160. expect(large).toContain('<response clipped>')
  161. expect(large).not.toContain('beginning of this command output was dropped')
  162. const exited = text(await execute('exit', 'exit'))
  163. expect(exited).toContain('next pwsh call starts from the workspace')
  164. expect(text(await execute('after-exit', 'Write-Output "$PWD"'))).toBe(root)
  165. }, 120_000)
  166. })