built-bin.e2e.ts 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  1. import { spawn } from 'node:child_process'
  2. import { mkdtemp, mkdir, readdir, 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, pathToFileURL } from 'node:url'
  7. import {
  8. ClientSideConnection,
  9. ndJsonStream,
  10. PROTOCOL_VERSION,
  11. type Agent as AcpAgent,
  12. type Client,
  13. type RequestPermissionRequest,
  14. type RequestPermissionResponse,
  15. type SessionNotification,
  16. } from '@agentclientprotocol/sdk'
  17. import { Readable, Writable } from 'node:stream'
  18. import { promisify } from 'node:util'
  19. import { zstdDecompress } from 'node:zlib'
  20. import { afterEach, describe, expect, it } from 'vitest'
  21. /**
  22. * Published-entry smoke: run `lib/bin.js` under plain Node in a symlinked external consumer and
  23. * complete a mock-backed turn. This catches built-only settle races, stdout protocol leaks, and
  24. * published persistence behavior that the tsx source-path smoke cannot. It skips before build;
  25. * `--expose-internals` enables Cordis bare-plugin loading.
  26. */
  27. const repoRoot = fileURLToPath(new URL('../../../../', import.meta.url))
  28. const acpBin = join(repoRoot, 'packages/examples/acp-demo/lib/bin.js')
  29. const decompress = promisify(zstdDecompress)
  30. const dshPackages = [
  31. 'examples/agent-spine-demo', 'core/agent', 'core/session', 'core/system-prompt',
  32. 'core/tools', 'core/agent-loop', 'llm/llm', 'bash/bash',
  33. 'bash/bash-local', 'bash/tool-bash', 'context/workspace-context', 'support/invariants', 'ui/app-boot',
  34. 'session-persistence/session-persistence',
  35. 'session-persistence/session-persistence-jsonl', 'ui/acp', 'examples/acp-demo', 'util/paths',
  36. ]
  37. const vendorPackages = [
  38. 'cordis', 'loader', 'include', 'timer', 'hmr', 'logger-console',
  39. 'schemastery', 'cosmokit',
  40. ]
  41. // Resolve ACP's declared third-party dependencies from that package, not this test: pnpm's strict
  42. // layout need not hoist them. Symlink those exact paths into the plain-Node consumer.
  43. const npmDeps = ['@agentclientprotocol/sdk', 'zod']
  44. const acpPkgDir = join(repoRoot, 'packages/ui/acp')
  45. async function pkgName(absDir: string): Promise<string> {
  46. const json = JSON.parse(await readFile(join(absDir, 'package.json'), 'utf8')) as { name: string }
  47. return json.name
  48. }
  49. async function link(target: string, name: string, nm: string): Promise<void> {
  50. const dest = join(nm, name)
  51. await mkdir(dirname(dest), { recursive: true })
  52. await symlink(target, dest)
  53. }
  54. /** Build a temp consumer dir + a minimal acp `cordis.yml`. Returns the dir. */
  55. async function makeConsumer(): Promise<string> {
  56. const dir = await mkdtemp(join(tmpdir(), 'acp-built-bin-'))
  57. const nm = join(dir, 'node_modules')
  58. for (const rel of dshPackages) {
  59. const abs = join(repoRoot, 'packages', rel)
  60. await link(abs, await pkgName(abs), nm)
  61. }
  62. for (const v of vendorPackages) {
  63. const abs = join(repoRoot, 'vendor', v)
  64. await link(abs, await pkgName(abs), nm)
  65. }
  66. for (const dep of npmDeps) {
  67. // Resolve from `ui/acp`'s package.json URL (the package that declares the
  68. // dep), not this test file's location — `acp-agent` does not depend on these.
  69. const fromAcp = pathToFileURL(join(acpPkgDir, 'package.json')).href
  70. const resolved = fileURLToPath(import.meta.resolve(`${dep}/package.json`, fromAcp))
  71. await link(dirname(resolved), dep, nm)
  72. }
  73. await writeFile(join(dir, 'mock-llm.mjs'), [
  74. "import { LlmAdapter } from '@deepseek-ai/dsh-llm'",
  75. 'class Mock extends LlmAdapter {',
  76. ' async * stream() {',
  77. " yield { type: 'block-start', index: 0, blockType: 'text' }",
  78. " yield { type: 'text-delta', index: 0, text: 'ACP BUILT OK' }",
  79. " yield { type: 'block-end', index: 0, block: { type: 'text', text: 'ACP BUILT OK' } }",
  80. " yield { type: 'finish', reason: { kind: 'stop' } }",
  81. ' }',
  82. '}',
  83. "export const name = 'built-acp-mock'",
  84. "export const inject = ['llm']",
  85. "export function apply(ctx) { ctx.llm.registerAdapter(['built-acp-mock'], new Mock()) }",
  86. '',
  87. ].join('\n'))
  88. await writeFile(join(dir, 'cordis.yml'), [
  89. '- id: mock-llm',
  90. ' name: \'./mock-llm.mjs\'',
  91. '- id: bash',
  92. ' name: \'@deepseek-ai/dsh-bash-local\'',
  93. '- id: acp-agent',
  94. ' name: \'@deepseek-ai/dsh-acp-demo\'',
  95. ' config:',
  96. ' provider: built-acp-mock',
  97. ' model: built-acp-mock',
  98. ' persona: \'test agent\'',
  99. ' workspaceContext: false',
  100. '',
  101. ].join('\n'))
  102. return dir
  103. }
  104. let consumer: string | undefined
  105. let child: ReturnType<typeof spawn> | undefined
  106. afterEach(async () => {
  107. if (child !== undefined) {
  108. const proc = child
  109. child = undefined
  110. // Windows retains the child's cwd and session-log handles until process
  111. // teardown completes, so await exit before removing the temp directory.
  112. if (proc.exitCode === null && proc.signalCode === null) {
  113. const exited = new Promise<void>((resolve) => { proc.once('exit', () => { resolve() }) })
  114. proc.kill('SIGKILL')
  115. await exited
  116. }
  117. }
  118. // Windows can briefly retain released handles after exit; retry removal.
  119. if (consumer !== undefined) await rm(consumer, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 })
  120. consumer = undefined
  121. })
  122. describe.skipIf(!existsSync(acpBin))('dsh-acp-demo BUILT bin (node lib/bin.js, no tsx)', () => {
  123. it('boots the published bin, completes a turn, and writes default Zstandard persistence', async () => {
  124. consumer = await makeConsumer()
  125. child = spawn(process.execPath, ['--expose-internals', acpBin, '--config', './cordis.yml'], {
  126. cwd: consumer,
  127. env: {
  128. ...process.env,
  129. DSH_HOME: join(consumer, '.dsh'),
  130. DSH_AGENTS_HOME: join(consumer, '.agents'),
  131. },
  132. stdio: ['pipe', 'pipe', 'pipe'],
  133. })
  134. const stderr: string[] = []
  135. child.stderr!.setEncoding('utf8')
  136. child.stderr!.on('data', (c: string) => stderr.push(c))
  137. // Tee raw stdout for a protocol-purity check, and feed it to the SDK client.
  138. const rawOut: string[] = []
  139. const passthrough = new Readable({ read() {} })
  140. child.stdout!.on('data', (buf: Buffer) => { rawOut.push(buf.toString('utf8')); passthrough.push(buf) })
  141. child.stdout!.on('end', () => passthrough.push(null))
  142. const stream = ndJsonStream(
  143. Writable.toWeb(child.stdin!) as WritableStream<Uint8Array>,
  144. Readable.toWeb(passthrough) as ReadableStream<Uint8Array>,
  145. )
  146. const makeClient = (_a: AcpAgent): Client => ({
  147. sessionUpdate(_p: SessionNotification): Promise<void> { return Promise.resolve() },
  148. requestPermission(_p: RequestPermissionRequest): Promise<RequestPermissionResponse> {
  149. return Promise.resolve({ outcome: { outcome: 'cancelled' } })
  150. },
  151. })
  152. const client = new ClientSideConnection(makeClient, stream)
  153. const init = await client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} })
  154. // A response at all proves the built bin booted the bridge (the settle-race
  155. // regression would exit before answering); loadSession proves the real app
  156. // mounted, not a collapsed export shape.
  157. expect(init.agentCapabilities?.loadSession).toBe(true)
  158. const { sessionId } = await client.newSession({ cwd: consumer, mcpServers: [] })
  159. const result = await client.prompt({ sessionId, prompt: [{ type: 'text', text: 'reply' }] })
  160. expect(result.stopReason).toBe('end_turn')
  161. const sessionsRoot = join(consumer, '.sessions')
  162. let log: string | undefined
  163. await expect.poll(async () => {
  164. log = (await readdir(sessionsRoot, { recursive: true })).find(file => file.endsWith('.jsonl.zstd'))
  165. return log
  166. }).toBeTypeOf('string')
  167. const compressed = await readFile(join(sessionsRoot, log!))
  168. expect(compressed.subarray(0, 4).toString('hex')).toBe('28b52ffd')
  169. expect(JSON.parse((await decompress(compressed)).toString())).toMatchObject({ type: 'session', id: sessionId })
  170. expect(stderr.join('')).not.toContain('without inject')
  171. // stdout purity: every emitted line is a JSON-RPC frame, no logger leak.
  172. for (const line of rawOut.join('').split('\n').filter(l => l.trim().length > 0)) {
  173. expect(() => JSON.parse(line) as unknown).not.toThrow()
  174. }
  175. }, 30_000)
  176. it('fails LOUD (non-zero exit + stderr) on a config whose directory does not exist', async () => {
  177. // boot() pre-resolves the bootstrap include to an absolute URL, so a nonexistent config
  178. // directory cannot break its import; the include plugin's own read must fail loud instead.
  179. const { code, stderr } = await runBinExpectingExit('/nonexistent/dir/cordis.yml')
  180. expect(code).not.toBe(0)
  181. expect(stderr).toContain('config file not found')
  182. }, 30_000)
  183. it('fails LOUD (non-zero exit + stderr) on a missing config file in a real directory', async () => {
  184. // Existing directory plus missing config exercises the include plugin's fail-loud path.
  185. consumer = await makeConsumer()
  186. const { code, stderr } = await runBinExpectingExit('./does-not-exist.yml', consumer)
  187. expect(code).not.toBe(0)
  188. expect(stderr).toContain('config file not found')
  189. }, 30_000)
  190. })
  191. /** Spawn the built acp bin against `configArg` and resolve with its exit code + stderr. */
  192. function runBinExpectingExit(configArg: string, cwd: string = tmpdir()): Promise<{ code: number; stderr: string }> {
  193. return new Promise((resolve, reject) => {
  194. const proc = spawn(process.execPath, ['--expose-internals', acpBin, '--config', configArg], {
  195. cwd,
  196. env: {
  197. ...process.env,
  198. DSH_HOME: join(cwd, '.dsh'),
  199. DSH_AGENTS_HOME: join(cwd, '.agents'),
  200. },
  201. stdio: ['pipe', 'pipe', 'pipe'],
  202. })
  203. child = proc
  204. let stderr = ''
  205. proc.stderr.setEncoding('utf8')
  206. proc.stderr.on('data', (c: string) => { stderr += c })
  207. const timer = setTimeout(() => { proc.kill('SIGKILL'); reject(new Error(`bin did not exit within 25s. stderr:\n${stderr}`)) }, 25_000)
  208. proc.on('exit', (code) => { clearTimeout(timer); resolve({ code: code ?? -1, stderr }) })
  209. proc.on('error', (err) => { clearTimeout(timer); reject(err) })
  210. proc.stdin.end()
  211. })
  212. }