built-bin.e2e.ts 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  1. import { spawn } from 'node:child_process'
  2. import { existsSync } from 'node:fs'
  3. import { mkdtemp, mkdir, readFile, readdir, rm, symlink, writeFile } from 'node:fs/promises'
  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. const repoRoot = fileURLToPath(new URL('../../../../', import.meta.url))
  9. const cliBin = join(repoRoot, 'packages/examples/cli-demo/lib/bin.js')
  10. const dshPackages = [
  11. 'examples/agent-spine-demo', 'examples/cli-demo', 'core/agent', 'core/session',
  12. 'core/system-prompt', 'core/tools', 'core/agent-loop', 'llm/llm', 'bash/bash',
  13. 'bash/bash-local', 'bash/tool-bash', 'support/invariants', 'ui/app-boot',
  14. 'session-persistence/session-persistence', 'session-persistence/session-persistence-jsonl',
  15. 'context/workspace-context',
  16. ]
  17. const vendorPackages = ['cordis', 'loader', 'include', 'timer', 'schemastery', 'cosmokit']
  18. async function packageName(dir: string): Promise<string> {
  19. return (JSON.parse(await readFile(join(dir, 'package.json'), 'utf8')) as { name: string }).name
  20. }
  21. async function linkPackage(dir: string, nodeModules: string): Promise<void> {
  22. const target = join(nodeModules, await packageName(dir))
  23. await mkdir(dirname(target), { recursive: true })
  24. await symlink(dir, target)
  25. }
  26. async function makeConsumer(): Promise<string> {
  27. const dir = await mkdtemp(join(tmpdir(), 'cli-built-bin-'))
  28. const nodeModules = join(dir, 'node_modules')
  29. for (const rel of dshPackages) await linkPackage(join(repoRoot, 'packages', rel), nodeModules)
  30. for (const rel of vendorPackages) await linkPackage(join(repoRoot, 'vendor', rel), nodeModules)
  31. await writeFile(join(dir, 'mock-llm.mjs'), [
  32. "import { LlmAdapter } from '@deepseek-ai/dsh-llm'",
  33. 'class Mock extends LlmAdapter {',
  34. ' async * stream(options) {',
  35. " const text = options.messages.flatMap(message => message.content).filter(block => block.type === 'text').at(-1)?.text ?? ''",
  36. " yield { type: 'block-start', index: 0, blockType: 'text' }",
  37. " if (text === 'hang') {",
  38. " yield { type: 'text-delta', index: 0, text: 'partial' }",
  39. ' await new Promise((resolve, reject) => {',
  40. " const timer = setTimeout(() => reject(new Error('hang timeout')), 30000)",
  41. " const onAbort = () => { clearTimeout(timer); reject(new Error('aborted')) }",
  42. ' if (options.signal.aborted) onAbort()',
  43. " else options.signal.addEventListener('abort', onAbort, { once: true })",
  44. ' })',
  45. ' return',
  46. ' }',
  47. ' const reply = `BUILT: ${text}`',
  48. " yield { type: 'text-delta', index: 0, text: reply }",
  49. " yield { type: 'block-end', index: 0, block: { type: 'text', text: reply } }",
  50. " yield { type: 'usage', usage: { inputTokens: 4, outputTokens: 2 } }",
  51. " yield { type: 'finish', reason: { kind: 'stop' } }",
  52. ' }',
  53. '}',
  54. "export const name = 'built-cli-mock'",
  55. "export const inject = ['llm']",
  56. "export function apply(ctx) { ctx.llm.registerAdapter(['built-cli-mock'], new Mock()) }",
  57. '',
  58. ].join('\n'))
  59. await writeFile(join(dir, 'cordis.yml'), [
  60. '- id: mock-llm',
  61. " name: './mock-llm.mjs'",
  62. '- id: bash',
  63. " name: '@deepseek-ai/dsh-bash-local'",
  64. '- id: cli-agent',
  65. " name: '@deepseek-ai/dsh-cli-demo'",
  66. ' config:',
  67. ' provider: built-cli-mock',
  68. ' model: built-cli-mock',
  69. " persona: 'built CLI test'",
  70. " persistenceRoot: './.sessions'",
  71. ' workspaceContext: false',
  72. '',
  73. ].join('\n'))
  74. return dir
  75. }
  76. interface BinResult {
  77. readonly code: number
  78. readonly signal: NodeJS.Signals | null
  79. readonly stdout: string
  80. readonly stderr: string
  81. }
  82. function runBuiltBin(cwd: string, args: readonly string[], interrupt?: NodeJS.Signals): Promise<BinResult> {
  83. return new Promise((resolveResult, reject) => {
  84. const child = spawn(process.execPath, ['--expose-internals', cliBin, ...args], {
  85. cwd,
  86. env: { ...process.env, DSH_HOME: join(cwd, '.dsh'), DSH_AGENTS_HOME: join(cwd, '.agents') },
  87. stdio: ['ignore', 'pipe', 'pipe'],
  88. })
  89. let stdout = ''
  90. let stderr = ''
  91. let interrupted = false
  92. child.stdout.setEncoding('utf8')
  93. child.stdout.on('data', (chunk: string) => {
  94. stdout += chunk
  95. if (interrupt !== undefined && !interrupted && stdout.includes('assistant/chunk')) {
  96. interrupted = true
  97. child.kill(interrupt)
  98. }
  99. })
  100. child.stderr.setEncoding('utf8')
  101. child.stderr.on('data', (chunk: string) => { stderr += chunk })
  102. const timer = setTimeout(() => {
  103. child.kill('SIGKILL')
  104. reject(new Error(`built CLI did not exit. stdout:\n${stdout}\nstderr:\n${stderr}`))
  105. }, 25_000)
  106. child.once('error', (error) => { clearTimeout(timer); reject(error) })
  107. child.once('exit', (code, signal) => {
  108. clearTimeout(timer)
  109. resolveResult({ code: code ?? -1, signal, stdout, stderr })
  110. })
  111. })
  112. }
  113. let consumer: string | undefined
  114. afterEach(async () => {
  115. if (consumer !== undefined) await rm(consumer, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 })
  116. consumer = undefined
  117. })
  118. describe.skipIf(!existsSync(cliBin))('dsh-cli-demo BUILT bin', () => {
  119. it('runs text, json, and stream-json under plain Node and persists fresh sessions', async () => {
  120. consumer = await makeConsumer()
  121. const text = await runBuiltBin(consumer, ['--config', './cordis.yml', 'hello'])
  122. expect(text).toMatchObject({ code: 0, signal: null, stdout: 'BUILT: hello\n', stderr: '' })
  123. const json = await runBuiltBin(consumer, ['--config', './cordis.yml', '--output-format', 'json', 'json task'])
  124. expect(JSON.parse(json.stdout)).toMatchObject({
  125. type: 'result', success: true, result: 'BUILT: json task', reason: { kind: 'completed' },
  126. usage: { inputTokens: 4, outputTokens: 2 },
  127. })
  128. const stream = await runBuiltBin(consumer, ['--config', './cordis.yml', '--output-format', 'stream-json', 'stream task'])
  129. const lines = stream.stdout.trimEnd().split('\n').map(line => JSON.parse(line) as Record<string, unknown>)
  130. expect(lines[0]).toMatchObject({ type: 'session_event', event: { type: 'turn/start' } })
  131. expect(lines.at(-1)).toMatchObject({ type: 'result', success: true, result: 'BUILT: stream task' })
  132. const files = await readdir(join(consumer, '.sessions'), { recursive: true })
  133. expect(files.filter(file => file.endsWith('.jsonl'))).toHaveLength(3)
  134. }, 30_000)
  135. it('keeps stdout empty for invalid argv and missing config', async () => {
  136. consumer = await makeConsumer()
  137. for (const args of [
  138. ['--config', './cordis.yml'],
  139. ['--config', './cordis.yml', 'one', 'two'],
  140. ['--config', './missing.yml', 'task'],
  141. ]) {
  142. const result = await runBuiltBin(consumer, args)
  143. expect(result.code).not.toBe(0)
  144. expect(result.stdout).toBe('')
  145. expect(result.stderr.length).toBeGreaterThan(0)
  146. }
  147. }, 30_000)
  148. describe.skipIf(process.platform === 'win32')('POSIX signal delivery', () => {
  149. it.each([
  150. ['SIGINT', 130],
  151. ['SIGTERM', 143],
  152. ] as const)('cancels and disposes on %s with exit %i', async (signal, code) => {
  153. consumer = await makeConsumer()
  154. const result = await runBuiltBin(
  155. consumer,
  156. ['--config', './cordis.yml', '--output-format', 'stream-json', 'hang'],
  157. signal,
  158. )
  159. expect(result, JSON.stringify(result)).toMatchObject({ code, signal: null })
  160. expect(result.stdout).toContain('"kind":"aborted"')
  161. expect(result.stderr).toContain(`received ${signal}`)
  162. }, 30_000)
  163. })
  164. })