primary-runtime.spec.ts 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130
  1. import { mkdir, mkdtemp, readFile, rename, rm, symlink, writeFile } from 'node:fs/promises'
  2. import { tmpdir } from 'node:os'
  3. import { dirname, join } from 'node:path'
  4. import { pathToFileURL } from 'node:url'
  5. import { afterEach, expect, it } from 'vitest'
  6. import { Context } from '@deepseek-ai/cordis'
  7. import Loader from '@deepseek-ai/cordis-plugin-loader'
  8. import Include from '@deepseek-ai/cordis-plugin-include'
  9. import AgentRegistry from '@deepseek-ai/dsh-agent'
  10. import SystemPrompt from '@deepseek-ai/dsh-system-prompt'
  11. import ToolRuntime from '@deepseek-ai/dsh-tools'
  12. import { ToolCallId } from '@deepseek-ai/dsh-llm'
  13. import { installPrimaryRuntime, readPrimaryRuntime, workspaceDependencyPaths, type PrimaryRuntimeManifest } from '../src/primary-runtime.ts'
  14. import * as workspaceDependencies from '../src/workspace-dependencies.ts'
  15. const roots: string[] = []
  16. afterEach(async () => { await Promise.all(roots.splice(0).map(root => rm(root, { recursive: true, force: true }))) })
  17. async function fixture() {
  18. const directory = await mkdtemp(join(tmpdir(), 'dsh-primary-runtime-'))
  19. roots.push(directory)
  20. const source = join(directory, 'resources')
  21. const root = join(directory, 'home', 'dsh-runtimes', 'dsh-primary-runtime')
  22. const manifest: PrimaryRuntimeManifest = {
  23. desktopVersion: '1.0.0', platform: process.platform === 'win32' ? 'win32' : 'darwin', arch: process.arch,
  24. components: { python: '3.12.14', node: '24.21.0', pnpm: '11.7.0', numpy: '2.3.5', pandas: '3.0.1' },
  25. }
  26. const paths = workspaceDependencyPaths(source, manifest)
  27. for (const path of [paths.python, paths.node, paths.pnpm]) {
  28. await mkdir(dirname(path), { recursive: true })
  29. await writeFile(path, 'interpreter')
  30. }
  31. await mkdir(paths.pythonPackages, { recursive: true })
  32. await mkdir(paths.nodePackages, { recursive: true })
  33. await writeFile(join(source, 'runtime.json'), JSON.stringify(manifest))
  34. return { source, root, manifest, directory }
  35. }
  36. it.each(['win32', 'darwin'])('returns %s interpreter and package paths', (platform) => {
  37. const manifest: PrimaryRuntimeManifest = { desktopVersion: '1', platform, arch: 'x64', components: { python: '3.12.14', node: '24.21.0', pnpm: '11.7.0', numpy: '2.3.5', pandas: '3.0.1' } }
  38. const paths = workspaceDependencyPaths('/runtime', manifest)
  39. expect(paths.python).toBe(join('/runtime', 'dependencies', 'python', ...(platform === 'win32' ? ['python.exe'] : ['bin', 'python3'])))
  40. expect(paths.pythonPackages).toBe(join('/runtime', 'dependencies', 'python', ...(platform === 'win32' ? ['Lib'] : ['lib', 'python3.12']), 'site-packages'))
  41. })
  42. it.skipIf(process.platform === 'linux')('installs offline, reuses the same release, and leaves environment and user packages unchanged', async () => {
  43. const { source, root } = await fixture()
  44. const environment = { ...process.env }
  45. const installed = await installPrimaryRuntime(source, root)
  46. await writeFile(join(installed.pythonPackages, 'user-package.py'), 'user content')
  47. expect(await installPrimaryRuntime(source, root)).toEqual(installed)
  48. expect(await readFile(join(installed.pythonPackages, 'user-package.py'), 'utf8')).toBe('user content')
  49. expect(process.env).toEqual(environment)
  50. })
  51. it.skipIf(process.platform === 'linux')('replaces release components and recovers an interrupted directory swap', async () => {
  52. const { source, root, manifest } = await fixture()
  53. await installPrimaryRuntime(source, root)
  54. await rename(root, `${root}.previous`)
  55. await writeFile(join(source, 'runtime.json'), JSON.stringify({ ...manifest, desktopVersion: '2.0.0' }))
  56. await installPrimaryRuntime(source, root)
  57. expect((await readPrimaryRuntime(root)).desktopVersion).toBe('2.0.0')
  58. })
  59. it.skipIf(process.platform === 'linux')('keeps the installed release when the replacement payload is incomplete', async () => {
  60. const { source, root, manifest } = await fixture()
  61. await installPrimaryRuntime(source, root)
  62. await writeFile(join(source, 'runtime.json'), JSON.stringify({ ...manifest, desktopVersion: '2.0.0' }))
  63. await rm(workspaceDependencyPaths(source, manifest).python)
  64. await expect(installPrimaryRuntime(source, root)).rejects.toThrow()
  65. expect((await readPrimaryRuntime(root)).desktopVersion).toBe('1.0.0')
  66. })
  67. it.skipIf(process.platform === 'linux')('refuses linked installation directories without modifying their targets', async () => {
  68. const { source, root, directory } = await fixture()
  69. const outside = join(directory, 'outside')
  70. await mkdir(outside)
  71. await writeFile(join(outside, 'keep'), 'untouched')
  72. await mkdir(dirname(root), { recursive: true })
  73. await symlink(outside, root, process.platform === 'win32' ? 'junction' : 'dir')
  74. await expect(installPrimaryRuntime(source, root)).rejects.toThrow('filesystem link')
  75. expect(await readFile(join(outside, 'keep'), 'utf8')).toBe('untouched')
  76. })
  77. it('rejects malformed metadata and incompatible targets', async () => {
  78. const { source, root, manifest } = await fixture()
  79. await writeFile(join(source, 'runtime.json'), JSON.stringify({ ...manifest, arch: process.arch === 'x64' ? 'arm64' : 'x64' }))
  80. await expect(installPrimaryRuntime(source, root)).rejects.toThrow('incompatible')
  81. await writeFile(join(source, 'runtime.json'), JSON.stringify({ ...manifest, components: { ...manifest.components, python: '../escape' } }))
  82. await expect(readPrimaryRuntime(source)).rejects.toThrow('invalid metadata')
  83. })
  84. it.skipIf(process.platform === 'linux')('loads the real tool through Cordis, exposes installed paths, and unregisters on disposal', async () => {
  85. const { source, root, manifest, directory } = await fixture()
  86. const ctx = new Context()
  87. try {
  88. ctx.baseUrl = pathToFileURL(directory).href + '/'
  89. await ctx.plugin(Loader)
  90. ctx.loader.builtins.include = Include
  91. const modules = new Map<string, unknown>([
  92. ['agents', AgentRegistry], ['systemPrompt', SystemPrompt], ['tools', ToolRuntime], ['dependencies', workspaceDependencies],
  93. ])
  94. ctx.loader.internal = {
  95. version: 'v2',
  96. async import(specifier: string) {
  97. if (!modules.has(specifier)) throw new Error(`unexpected plugin ${specifier}`)
  98. return modules.get(specifier)
  99. },
  100. } as unknown as NonNullable<typeof ctx.loader.internal>
  101. const config = join(directory, 'cordis.yml')
  102. await writeFile(config, `- name: agents\n- name: systemPrompt\n- name: tools\n- name: dependencies\n config:\n source: ${JSON.stringify(source)}\n root: ${JSON.stringify(root)}\n`)
  103. await ctx.loader.create({ name: 'cordis:include', config: { path: pathToFileURL(config).href } })
  104. await ctx.loader.await()
  105. for (const entry of ctx.loader.entries()) await entry.fiber?.await()
  106. const environment = { ...process.env }
  107. const request = { signal: new AbortController().signal, name: 'load_workspace_dependencies', arguments: {} }
  108. const results = await Promise.all(['first', 'second'].map(id => ctx.tools.execute({ ...request, callId: ToolCallId(id) })))
  109. for (const result of results) {
  110. expect(result.isError).toBe(false)
  111. expect(result.content).toEqual([{ type: 'text', text: JSON.stringify(workspaceDependencyPaths(root, manifest), undefined, 2) }])
  112. }
  113. expect(process.env).toEqual(environment)
  114. const entry = [...ctx.loader.entries()].find(entry => entry.options.name === 'dependencies')
  115. expect(entry).toBeDefined()
  116. await entry?.fiber?.dispose()
  117. expect(ctx.tools.schemas().some(tool => tool.name === 'load_workspace_dependencies')).toBe(false)
  118. } finally {
  119. await ctx.fiber.dispose()
  120. }
  121. })