built-bin.e2e.ts 11 KB

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