built-bin.e2e.ts 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166
  1. import { spawn } from 'node:child_process'
  2. import { cp, mkdtemp, mkdir, rm, symlink, writeFile, readFile } from 'node:fs/promises'
  3. import { existsSync } from 'node:fs'
  4. import { tmpdir } from 'node:os'
  5. import { dirname, join } from 'node:path'
  6. import { fileURLToPath } from 'node:url'
  7. import { afterEach, describe, expect, it } from 'vitest'
  8. /**
  9. * Published-entry smoke: run `lib/bin.js` under plain Node in a symlinked external consumer and
  10. * require the banner plus echo round-trip. This catches built-only early-exit and config-resolution
  11. * failures masked by tsx source smokes. It skips before build; `--expose-internals` enables Cordis
  12. * bare-plugin loading, matching the demo command.
  13. */
  14. const repoRoot = fileURLToPath(new URL('../../../../', import.meta.url))
  15. const stdioBin = join(repoRoot, 'packages/examples/stdio-demo/lib/bin.js')
  16. // Symlink each required workspace package by package name so plain Node resolves its built `main`,
  17. // matching an installed dependency rather than tsconfig paths.
  18. const dshPackages = [
  19. 'examples/agent-spine-demo', 'core/agent', 'core/session', 'core/system-prompt',
  20. 'core/tools', 'core/agent-loop', 'llm/llm', 'bash/bash', 'bash/bash-local',
  21. 'bash/tool-bash', 'support/invariants', 'ui/app-boot',
  22. 'session-persistence/session-persistence',
  23. 'session-persistence/session-persistence-jsonl', 'examples/stdio-demo',
  24. 'ui/stdio', 'ui/tool-ask-user', 'ui/user-interaction',
  25. ]
  26. const vendorPackages = [
  27. 'cordis', 'loader', 'include', 'timer', 'hmr', 'logger-console',
  28. 'schemastery', 'cosmokit',
  29. ]
  30. async function pkgName(absDir: string): Promise<string> {
  31. const json = JSON.parse(await readFile(join(absDir, 'package.json'), 'utf8')) as { name: string }
  32. return json.name
  33. }
  34. /**
  35. * Build a temporary external consumer with built workspace/vendor links and a mock-backed config.
  36. * The optional missing-but-disabled plugin verifies load guards accept intentionally fiber-less
  37. * entries rather than treating them as import failures.
  38. */
  39. async function makeConsumer(welcome: string, disabledBrokenEntry = false): Promise<string> {
  40. const dir = await mkdtemp(join(tmpdir(), 'stdio-built-bin-'))
  41. const nm = join(dir, 'node_modules')
  42. for (const rel of dshPackages) {
  43. const abs = join(repoRoot, 'packages', rel)
  44. const name = await pkgName(abs)
  45. const target = join(nm, name)
  46. await mkdir(dirname(target), { recursive: true })
  47. await symlink(abs, target)
  48. }
  49. for (const v of vendorPackages) {
  50. const abs = join(repoRoot, 'vendor', v)
  51. const name = await pkgName(abs)
  52. const target = join(nm, name)
  53. await mkdir(dirname(target), { recursive: true })
  54. await symlink(abs, target)
  55. }
  56. // The example's mock model + echo tool are example-local TS plugins (Node
  57. // 22.19+ — the engines floor — strips types natively, so plain `node` loads
  58. // them); they import the workspace packages the symlinked node_modules now
  59. // provides.
  60. await cp(join(repoRoot, 'examples/echo-agent/src'), join(dir, 'src'), { recursive: true })
  61. await writeFile(join(dir, 'cordis.yml'), [
  62. '- id: mock-llm',
  63. ' name: \'./src/mock-llm.ts\'',
  64. '- id: echo-tool',
  65. ' name: \'./src/echo-tool.ts\'',
  66. '- id: bash',
  67. ' name: \'@deepseek-ai/dsh-bash-local\'',
  68. '- id: stdio-agent',
  69. ' name: \'@deepseek-ai/dsh-stdio-demo\'',
  70. ' config:',
  71. ' model: mock-echo',
  72. ' persona: \'demo\'',
  73. ` welcome: '${welcome}'`,
  74. ...disabledBrokenEntry
  75. ? ['- id: off', ' name: \'./src/does-not-exist.ts\'', ' disabled: true']
  76. : [],
  77. '',
  78. ].join('\n'))
  79. return dir
  80. }
  81. /** Run the built bin in `cwd` against `configArg` with one stdin line; resolve with stdout/stderr + exit code. */
  82. function runBuiltBin(cwd: string, configArg: string, line: string): Promise<{ stdout: string; code: number; stderr: string }> {
  83. return new Promise((resolve, reject) => {
  84. // --expose-internals: the cordis Loader resolves bare plugin specifiers via
  85. // its internal module loader (active only under this flag); demo:echo passes
  86. // it too. NO tsx — this is the published `node lib/bin.js` path.
  87. const child = spawn(process.execPath, ['--expose-internals', stdioBin, configArg], {
  88. cwd,
  89. // Mock model: never calls the network, so no key needed.
  90. env: { ...process.env, DSH_HOME: join(cwd, '.dsh'), DSH_AGENTS_HOME: join(cwd, '.agents') },
  91. stdio: ['pipe', 'pipe', 'pipe'],
  92. })
  93. let stdout = ''
  94. let stderr = ''
  95. child.stdout.setEncoding('utf8')
  96. child.stdout.on('data', (c: string) => { stdout += c })
  97. child.stderr.setEncoding('utf8')
  98. child.stderr.on('data', (c: string) => { stderr += c })
  99. const timer = setTimeout(() => {
  100. child.kill('SIGKILL')
  101. reject(new Error(`built bin did not exit within 25s. stdout:\n${stdout}\nstderr:\n${stderr}`))
  102. }, 25_000)
  103. child.on('exit', (code) => { clearTimeout(timer); resolve({ stdout, code: code ?? -1, stderr }) })
  104. child.on('error', (err) => { clearTimeout(timer); reject(err) })
  105. child.stdin.write(`${line}\n`)
  106. child.stdin.end()
  107. })
  108. }
  109. let consumer: string | undefined
  110. afterEach(async () => {
  111. // Windows can briefly retain released handles after exit; retry removal.
  112. if (consumer !== undefined) await rm(consumer, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 })
  113. consumer = undefined
  114. })
  115. describe.skipIf(!existsSync(stdioBin))('dsh-stdio-demo BUILT bin (node lib/bin.js, no tsx)', () => {
  116. it('boots the published bin, prints its banner, and runs the echo tool round-trip', async () => {
  117. consumer = await makeConsumer('BUILT-BIN-OK ready.')
  118. const { stdout, code, stderr } = await runBuiltBin(consumer, './cordis.yml', 'echo hi')
  119. expect(stderr).not.toContain('UNHANDLED')
  120. expect(stderr).not.toContain('without inject')
  121. // The banner proves boot() awaited the tree (the settle-race regression would
  122. // exit 0 with empty stdout); the round-trip proves the whole app mounted.
  123. expect(stdout).toContain('BUILT-BIN-OK ready.')
  124. expect(stdout).toContain('[tool call] echo')
  125. expect(stdout).toContain('[tool result] ECHO: HI')
  126. expect(code).toBe(0)
  127. }, 30_000)
  128. it('boots cleanly when the config disables an (otherwise unresolvable) entry', async () => {
  129. // A `disabled: true` entry settles without a fiber by design; the fail-loud entry-load
  130. // guard must not mistake it for a failed import. The nonexistent path makes that distinction
  131. // observable while the successful round-trip proves boot continued.
  132. consumer = await makeConsumer('DISABLED-OK ready.', true)
  133. const { stdout, code, stderr } = await runBuiltBin(consumer, './cordis.yml', 'echo hi')
  134. expect(stderr).not.toContain('failed to load')
  135. expect(stdout).toContain('DISABLED-OK ready.')
  136. expect(stdout).toContain('[tool result] ECHO: HI')
  137. expect(code).toBe(0)
  138. }, 30_000)
  139. it('fails LOUD (non-zero exit + stderr) on a config whose directory does not exist', async () => {
  140. // boot() pre-resolves the bootstrap include to an absolute URL, so a nonexistent config
  141. // directory cannot break its import; the include plugin's own read must fail loud instead.
  142. consumer = await makeConsumer('unused')
  143. const { code, stderr } = await runBuiltBin(consumer, '/nonexistent/dir/cordis.yml', '')
  144. expect(code).not.toBe(0)
  145. expect(stderr).toContain('config file not found')
  146. }, 30_000)
  147. it('fails LOUD (non-zero exit + stderr) on a missing config file in a real directory', async () => {
  148. // Existing directory plus missing config exercises the include plugin's fail-loud path.
  149. consumer = await makeConsumer('unused')
  150. const { code, stderr } = await runBuiltBin(consumer, './does-not-exist.yml', '')
  151. expect(code).not.toBe(0)
  152. expect(stderr).toContain('config file not found')
  153. }, 30_000)
  154. })