built-bin.e2e.ts 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058
  1. import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'
  2. import { tmpdir } from 'node:os'
  3. import { join } from 'node:path'
  4. import { createInterface } from 'node:readline'
  5. import { Readable, Writable } from 'node:stream'
  6. import { fileURLToPath, pathToFileURL } from 'node:url'
  7. import {
  8. client as createAcpClientApp,
  9. methods,
  10. ndJsonStream,
  11. PROTOCOL_VERSION,
  12. type SessionNotification,
  13. } from '@agentclientprotocol/sdk'
  14. import { startMockLlmServer } from '@deepseek-ai/dsh-llm-mock-server'
  15. import { entryListSchema } from '@deepseek-ai/cordis-plugin-include'
  16. import { execa } from 'execa'
  17. import * as yaml from 'js-yaml'
  18. import { afterEach, beforeEach, describe, expect, it } from 'vitest'
  19. /** Published-entry acceptance for argument errors, profile lifecycle, and boot-free config dumps. */
  20. const repoRoot = fileURLToPath(new URL('../../../', import.meta.url))
  21. // The dsh built bin cold-starts slowly on the contended self-hosted Windows pool; the
  22. // execa deadline, its error text, the outer vitest case budget, and waitForFile all
  23. // share this value so a widening cannot leave a stale 25s diagnostic behind.
  24. const SPAWN_TIMEOUT_MS = 60_000
  25. // The release version, including a prerelease such as 0.0.1-rc.1: `--version`
  26. // prints what this manifest carries, so no test may pin it to a literal.
  27. const cliVersion = (JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')) as { version: string }).version
  28. const dshBin = join(repoRoot, 'apps/cli/lib/bin.js')
  29. const invalidProvider = fileURLToPath(new URL('./fixtures/invalid-provider.cordis.yml', import.meta.url))
  30. async function runBuiltBin(
  31. args: readonly string[] = [],
  32. env: Readonly<Record<string, string | undefined>> = {},
  33. cwd?: string,
  34. ): Promise<{ stdout: string; code: number; stderr: string }> {
  35. const childEnv = Object.fromEntries(
  36. Object.entries({ ...process.env, ...env })
  37. .filter((entry): entry is [string, string] => entry[1] !== undefined),
  38. )
  39. const result = await execa(process.execPath, [dshBin, ...args], {
  40. input: '',
  41. timeout: SPAWN_TIMEOUT_MS,
  42. killSignal: 'SIGKILL',
  43. reject: false,
  44. env: childEnv,
  45. extendEnv: false,
  46. ...cwd === undefined ? {} : { cwd },
  47. })
  48. if (result.timedOut) {
  49. throw new Error(`dsh built bin did not exit within ${SPAWN_TIMEOUT_MS / 1_000}s. stdout:\n${result.stdout}\nstderr:\n${result.stderr}`)
  50. }
  51. return { stdout: result.stdout, code: result.exitCode ?? -1, stderr: result.stderr }
  52. }
  53. async function waitForFile(file: string): Promise<void> {
  54. const deadline = Date.now() + SPAWN_TIMEOUT_MS
  55. while (!existsSync(file)) {
  56. if (Date.now() >= deadline) throw new Error(`dsh profile lifecycle marker did not appear: ${file}`)
  57. await new Promise(resolve => setTimeout(resolve, 20))
  58. }
  59. }
  60. interface ProfileLifecycleFixture {
  61. home: string
  62. ready: string
  63. settled: string
  64. disposed: string
  65. interrupt: string
  66. }
  67. /**
  68. * A minimal custom profile: one lifecycle-marker plugin bundle listed in
  69. * dsh.profile.bundles, no dsh-base — proving out-of-box composition machinery without
  70. * booting the entire product tree.
  71. */
  72. function createProfileLifecycleFixture(): ProfileLifecycleFixture {
  73. const home = mkdtempSync(join(tmpdir(), 'dsh-profile-lifecycle-'))
  74. const ready = join(home, 'ready')
  75. const settled = join(home, 'settled')
  76. const disposed = join(home, 'disposed')
  77. const interrupt = join(home, 'interrupt')
  78. const bundleDir = join(home, 'lifecycle-bundle')
  79. mkdirSync(bundleDir, { recursive: true })
  80. writeFileSync(join(bundleDir, 'plugin.mjs'), [
  81. "import { existsSync, writeFileSync } from 'node:fs'",
  82. "import { join } from 'node:path'",
  83. "export const name = 'profile-lifecycle-fixture'",
  84. 'export function apply(ctx, config = {}) {',
  85. ' let active = true',
  86. ' // Keep the event loop alive so process lifetime is signal-owned, like a real surface.',
  87. ' // Windows has no deliverable SIGTERM; the marker emits the same process event there.',
  88. ' let interrupted = false',
  89. ' const heartbeat = setInterval(() => {',
  90. ' if (interrupted || !existsSync(process.env.RAW_INTERRUPT_FILE)) return',
  91. ' interrupted = true',
  92. " process.emit('SIGTERM')",
  93. ' }, 20)',
  94. ' // Echo the mounted generation so the hot-reload e2e can assert both an',
  95. ' // applied override and its removal reverting to this bundle default.',
  96. " writeFileSync(join(process.env.DSH_HOME, 'config-echo'), String(config.generation ?? 'bundle-default'))",
  97. " writeFileSync(process.env.RAW_READY_FILE, 'ready')",
  98. ' void ctx.loader.await().then(() => {',
  99. " if (active) writeFileSync(process.env.RAW_SETTLED_FILE, 'settled')",
  100. ' })',
  101. ' ctx.effect(() => () => {',
  102. ' active = false',
  103. ' clearInterval(heartbeat)',
  104. " writeFileSync(process.env.RAW_DISPOSED_FILE, 'disposed')",
  105. ' })',
  106. '}',
  107. '',
  108. ].join('\n'))
  109. writeFileSync(join(bundleDir, 'cordis.patch.yml'), [
  110. '- insert:',
  111. ' - id: profile-lifecycle-fixture',
  112. ` name: ${pathToFileURL(join(bundleDir, 'plugin.mjs')).href}`,
  113. '',
  114. ].join('\n'))
  115. writeFileSync(join(bundleDir, 'package.json'), JSON.stringify({
  116. name: 'dsh-lifecycle-bundle',
  117. version: '0.0.0',
  118. type: 'module',
  119. dsh: { bundle: { patch: './cordis.patch.yml' } },
  120. }, undefined, 2))
  121. const profileDir = join(home, 'profiles', 'lifecycle')
  122. mkdirSync(join(profileDir, 'node_modules'), { recursive: true })
  123. writeFileSync(join(profileDir, 'package.json'), JSON.stringify({
  124. name: 'dsh-profile-lifecycle',
  125. private: true,
  126. dependencies: {},
  127. dsh: { profile: { bundles: ['dsh-lifecycle-bundle'] } },
  128. }, undefined, 2))
  129. // Hand-place the "installed" bundle where profile resolution finds it.
  130. writeFileSync(join(profileDir, 'cordis.patch.yml'), '[]\n')
  131. const linkTarget = join(profileDir, 'node_modules', 'dsh-lifecycle-bundle')
  132. mkdirSync(join(profileDir, 'node_modules'), { recursive: true })
  133. try {
  134. rmSync(linkTarget, { recursive: true, force: true })
  135. } catch { /* fresh dir */ }
  136. // Copy-free: a package.json redirecting via a relative main is enough for require.resolve.
  137. mkdirSync(linkTarget, { recursive: true })
  138. for (const file of ['package.json', 'cordis.patch.yml', 'plugin.mjs']) {
  139. writeFileSync(join(linkTarget, file), readFileSync(join(bundleDir, file)))
  140. }
  141. return { home, ready, settled, disposed, interrupt }
  142. }
  143. function startProfileLifecycle(fixture: ProfileLifecycleFixture, args: readonly string[] = []) {
  144. return execa(process.execPath, [dshBin, '--profile', 'lifecycle', ...args], {
  145. cwd: fixture.home,
  146. input: '',
  147. timeout: SPAWN_TIMEOUT_MS,
  148. killSignal: 'SIGKILL',
  149. reject: false,
  150. env: {
  151. DSH_HOME: fixture.home,
  152. RAW_READY_FILE: fixture.ready,
  153. RAW_SETTLED_FILE: fixture.settled,
  154. RAW_DISPOSED_FILE: fixture.disposed,
  155. RAW_INTERRUPT_FILE: fixture.interrupt,
  156. },
  157. })
  158. }
  159. function requestProfileShutdown(
  160. child: Pick<ReturnType<typeof startProfileLifecycle>, 'kill'>,
  161. fixture: Pick<ProfileLifecycleFixture, 'interrupt'>,
  162. ): void {
  163. if (process.platform === 'win32') {
  164. writeFileSync(fixture.interrupt, 'interrupt')
  165. return
  166. }
  167. child.kill('SIGTERM')
  168. }
  169. function createEnvironmentProbeProfile(home: string, project: string): void {
  170. const pluginFile = join(project, 'environment-probe.mjs')
  171. writeFileSync(pluginFile, [
  172. "export const name = 'environment-probe'",
  173. "export const inject = ['llm']",
  174. 'export function apply(ctx) {',
  175. ' void ctx.loader.await().then(async () => {',
  176. " let text = ''",
  177. ' for await (const chunk of ctx.llm.stream({',
  178. " provider: 'deepseek-official',",
  179. " model: 'deepseek-v4-flash',",
  180. ' messages: [],',
  181. ' maxTokens: 32,',
  182. ' })) {',
  183. " if (chunk.type === 'text-delta') text += chunk.text",
  184. ' }',
  185. ' process.stdout.write(`${text}\\n`)',
  186. " if (process.platform === 'win32') process.emit('SIGTERM')",
  187. " else process.kill(process.pid, 'SIGTERM')",
  188. ' })',
  189. '}',
  190. '',
  191. ].join('\n'))
  192. const profileDir = join(home, 'profiles', 'environment-probe')
  193. mkdirSync(profileDir, { recursive: true })
  194. writeFileSync(join(profileDir, 'package.json'), JSON.stringify({
  195. name: 'dsh-profile-environment-probe',
  196. private: true,
  197. dependencies: {},
  198. dsh: { profile: { bundles: ['@deepseek-ai/dsh-base'] } },
  199. }, undefined, 2))
  200. writeFileSync(join(profileDir, 'cordis.patch.yml'), [
  201. '- insert:',
  202. ' - id: environment-probe',
  203. ` name: ${pathToFileURL(pluginFile).href}`,
  204. '',
  205. ].join('\n'))
  206. }
  207. interface StartupFixture {
  208. home: string
  209. ready: string
  210. echo: string
  211. interrupt: string
  212. /** An always-running row's echo, used to observe that a user patch reload landed. */
  213. witness: string
  214. }
  215. /**
  216. * A custom profile whose ordinary provider plugin injects `cmdlineArgs`, plus
  217. * a row that reads its app-owned service through a `!!js` config expression.
  218. * Both plugin modules resolve
  219. * `@deepseek-ai/dsh-cmdline` and `commander` through the profile module
  220. * fallback, exactly as an installed out-of-tree bundle does.
  221. */
  222. function createStartupFixture(): StartupFixture {
  223. const home = mkdtempSync(join(tmpdir(), 'dsh-profile-startup-'))
  224. const profileDir = join(home, 'profiles', 'startup')
  225. // Written straight into the installed location: a row module resolves its
  226. // own imports from where it is installed, and only inside the profile does
  227. // Node's parent walk reach the installation fallback these plugins need.
  228. const bundleDir = join(profileDir, 'node_modules', 'dsh-startup-bundle')
  229. mkdirSync(bundleDir, { recursive: true })
  230. writeFileSync(join(bundleDir, 'startup.mjs'), [
  231. "import { Command } from 'commander'",
  232. "import { parseCmdline } from '@deepseek-ai/dsh-cmdline'",
  233. "export const name = 'fixture-startup'",
  234. "export const inject = ['cmdlineArgs']",
  235. 'export function apply(ctx) {',
  236. " const program = new Command().name('fixture').option('--generation <value>', 'echoed generation')",
  237. " program.action(() => ctx.provide('fixtureStartup', { generation: program.opts().generation }))",
  238. ' parseCmdline(ctx, program)',
  239. '}',
  240. '',
  241. ].join('\n'))
  242. writeFileSync(join(bundleDir, 'waiting.mjs'), [
  243. "import { existsSync, writeFileSync } from 'node:fs'",
  244. "import { join } from 'node:path'",
  245. "export const name = 'startup-fixture'",
  246. 'export function apply(ctx, config = {}) {',
  247. ' let interrupted = false',
  248. ' const heartbeat = setInterval(() => {',
  249. ' if (interrupted || !existsSync(process.env.RAW_INTERRUPT_FILE)) return',
  250. ' interrupted = true',
  251. " process.emit('SIGTERM')",
  252. ' }, 20)',
  253. " writeFileSync(join(process.env.DSH_HOME, 'config-echo'), String(config.generation ?? 'bundle-default'))",
  254. " writeFileSync(process.env.RAW_READY_FILE, 'ready')",
  255. ' ctx.effect(() => () => { clearInterval(heartbeat) })',
  256. '}',
  257. '',
  258. ].join('\n'))
  259. writeFileSync(join(bundleDir, 'witness.mjs'), [
  260. "import { writeFileSync } from 'node:fs'",
  261. "import { join } from 'node:path'",
  262. "export const name = 'reload-witness'",
  263. 'export function apply(ctx, config = {}) {',
  264. " writeFileSync(join(process.env.DSH_HOME, 'witness'), String(config.generation ?? 'bundle-default'))",
  265. '}',
  266. '',
  267. ].join('\n'))
  268. writeFileSync(join(bundleDir, 'cordis.patch.yml'), [
  269. '- insert:',
  270. ' - id: startup-fixture',
  271. ` name: ${pathToFileURL(join(bundleDir, 'waiting.mjs')).href}`,
  272. ' inject: [fixtureStartup]',
  273. ' config:',
  274. // Lazy interpolation runs only after the provider's service is injected.
  275. " generation: !!js ctx.fixtureStartup.generation ?? 'bundle-default'",
  276. ' - id: fixture-startup',
  277. ` name: ${pathToFileURL(join(bundleDir, 'startup.mjs')).href}`,
  278. ' - id: reload-witness',
  279. ` name: ${pathToFileURL(join(bundleDir, 'witness.mjs')).href}`,
  280. '',
  281. ].join('\n'))
  282. writeFileSync(join(bundleDir, 'package.json'), JSON.stringify({
  283. name: 'dsh-startup-bundle',
  284. version: '0.0.0',
  285. type: 'module',
  286. dsh: { bundle: { patch: './cordis.patch.yml' } },
  287. }, undefined, 2))
  288. writeFileSync(join(profileDir, 'package.json'), JSON.stringify({
  289. name: 'dsh-profile-startup',
  290. private: true,
  291. dependencies: {},
  292. dsh: { profile: { bundles: ['dsh-startup-bundle'] } },
  293. }, undefined, 2))
  294. writeFileSync(join(profileDir, 'cordis.patch.yml'), '[]\n')
  295. return {
  296. home,
  297. ready: join(home, 'ready'),
  298. echo: join(home, 'config-echo'),
  299. interrupt: join(home, 'interrupt'),
  300. witness: join(home, 'witness'),
  301. }
  302. }
  303. function startStartupProfile(fixture: StartupFixture, args: readonly string[]) {
  304. return execa(process.execPath, [dshBin, '--profile', 'startup', ...args], {
  305. cwd: fixture.home,
  306. input: '',
  307. reject: false,
  308. timeout: SPAWN_TIMEOUT_MS,
  309. killSignal: 'SIGKILL',
  310. env: {
  311. DSH_HOME: fixture.home,
  312. RAW_READY_FILE: fixture.ready,
  313. RAW_INTERRUPT_FILE: fixture.interrupt,
  314. },
  315. })
  316. }
  317. describe.skipIf(!existsSync(dshBin))('dsh BUILT bin (node lib/bin.js, no tsx)', () => {
  318. it('requires --profile and rejects removed commands', async () => {
  319. const bare = await runBuiltBin()
  320. expect(bare.code).toBe(1)
  321. expect(bare.stdout).toBe('')
  322. expect(bare.stderr).toContain('--profile <name> is required')
  323. const help = await runBuiltBin(['--help'])
  324. expect(help.code).toBe(0)
  325. expect(help.stdout).toContain('dsh --profile web')
  326. expect(help.stdout).toContain('dsh plugin --profile')
  327. expect(help.stdout).not.toMatch(/^\s+(?:tui|meta|upgrade)\b/mu)
  328. for (const removed of [['tui'], ['--config', 'x.yml'], ['-p', 'task'], ['run', 'task']]) {
  329. const result = await runBuiltBin(removed)
  330. expect(result.code).toBe(1)
  331. }
  332. }, SPAWN_TIMEOUT_MS * 3 + 30_000)
  333. it('routes help and usage errors without activating startup-dependent rows', async () => {
  334. const home = mkdtempSync(join(tmpdir(), 'dsh-app-help-'))
  335. try {
  336. const web = await runBuiltBin(['--profile', 'web', '--help'], {
  337. DSH_HOME: home,
  338. DSH_TELEMETRY_DISABLED: '1',
  339. })
  340. expect(web.code).toBe(0)
  341. expect(web.stderr).toBe('')
  342. expect(web.stdout).toContain('Usage: dsh --profile web')
  343. expect(web.stdout).toContain('--port <port>')
  344. expect(web.stdout).not.toContain('dsh web: http://')
  345. const wildcardHost = await runBuiltBin(['web', '--host', '0.0.0.0'], {
  346. DSH_HOME: home,
  347. DSH_TELEMETRY_DISABLED: '1',
  348. })
  349. expect(wildcardHost.code).toBe(1)
  350. expect(wildcardHost.stdout).toBe('')
  351. expect(wildcardHost.stderr).toContain('--host 0.0.0.0 is intentionally not supported yet for safety: it would expose remote code execution to the network; use 127.0.0.1 instead')
  352. expect(wildcardHost.stderr).not.toContain('dsh web: http://')
  353. const headlessHelp = await runBuiltBin(['--profile', 'headless', '--help'], {
  354. DSH_HOME: home,
  355. DSH_TELEMETRY_DISABLED: '1',
  356. })
  357. expect(headlessHelp.code).toBe(0)
  358. expect(headlessHelp.stderr).toBe('')
  359. expect(headlessHelp.stdout).toContain('Usage: dsh --profile headless')
  360. const sdkHelp = await runBuiltBin(['--profile', 'sdk', '--help'], {
  361. DSH_HOME: home,
  362. DSH_TELEMETRY_DISABLED: '1',
  363. })
  364. expect(sdkHelp.code).toBe(0)
  365. expect(sdkHelp.stderr).toBe('')
  366. expect(sdkHelp.stdout).toContain('Usage: dsh --profile sdk')
  367. const acpHelp = await runBuiltBin(['--profile', 'acp', '--help'], {
  368. DSH_HOME: home,
  369. DSH_TELEMETRY_DISABLED: '1',
  370. })
  371. expect(acpHelp.code).toBe(0)
  372. expect(acpHelp.stderr).toBe('')
  373. expect(acpHelp.stdout).toContain('Usage: dsh --profile acp')
  374. const missingTask = await runBuiltBin(['--profile', 'headless'], {
  375. DSH_HOME: home,
  376. DSH_TELEMETRY_DISABLED: '1',
  377. })
  378. expect(missingTask.code).toBe(1)
  379. expect(missingTask.stderr).toContain('a task is required')
  380. } finally {
  381. rmSync(home, { recursive: true, force: true })
  382. }
  383. }, SPAWN_TIMEOUT_MS * 3 + 30_000)
  384. it('reports SDK startup failure when stdin reaches EOF first', async () => {
  385. const home = mkdtempSync(join(tmpdir(), 'dsh-built-sdk-startup-failure-'))
  386. const patch = join(home, 'broken-sdk.cordis.yml')
  387. writeFileSync(patch, [
  388. '- insert:',
  389. ' - id: missing-sdk-startup-plugin',
  390. ' name: "@deepseek-ai/dsh-missing-sdk-startup-plugin"',
  391. '',
  392. ].join('\n'))
  393. try {
  394. const result = await runBuiltBin(['--profile', 'sdk', '--patch', patch], {
  395. DSH_HOME: home,
  396. DSH_TELEMETRY_DISABLED: '1',
  397. DEEPSEEK_API_KEY: 'built-sdk-startup-failure-no-call',
  398. }, home)
  399. expect(result.code).toBe(1)
  400. expect(result.stdout).toBe('')
  401. expect(result.stderr).toContain('plugin tree failed to load')
  402. expect(result.stderr).toContain('@deepseek-ai/dsh-missing-sdk-startup-plugin')
  403. } finally {
  404. rmSync(home, { recursive: true, force: true })
  405. }
  406. }, SPAWN_TIMEOUT_MS + 30_000)
  407. it('serves the SDK protocol with an absolute-path overlay plugin and exits after shutdown', async () => {
  408. const home = mkdtempSync(join(tmpdir(), 'dsh-built-sdk-'))
  409. const pluginPath = join(home, 'plugin #100%.mjs')
  410. const marker = join(home, 'plugin-loaded')
  411. writeFileSync(pluginPath, [
  412. "import { writeFileSync } from 'node:fs'",
  413. 'export function apply(ctx, config) { writeFileSync(config.marker, "loaded") }',
  414. '',
  415. ].join('\n'))
  416. const patch = join(home, 'absolute.patch.yml')
  417. writeFileSync(patch, JSON.stringify([{ insert: [
  418. { id: 'absolute-plugin', name: pluginPath, config: { marker } },
  419. ] }]))
  420. const child = execa(process.execPath, [dshBin, '--profile', 'sdk', '--patch', patch], {
  421. cwd: home,
  422. reject: false,
  423. timeout: SPAWN_TIMEOUT_MS,
  424. killSignal: 'SIGKILL',
  425. env: {
  426. ...process.env,
  427. DSH_HOME: home,
  428. DSH_TELEMETRY_DISABLED: '1',
  429. DEEPSEEK_API_KEY: 'built-sdk-profile-no-call',
  430. },
  431. extendEnv: false,
  432. })
  433. const stdoutLines = createInterface({ input: child.stdout, crlfDelay: Infinity })[Symbol.asyncIterator]()
  434. let stderr = ''
  435. child.stderr.on('data', (chunk: Buffer) => { stderr += chunk.toString('utf8') })
  436. const response = async (id: number): Promise<Record<string, unknown>> => {
  437. for (;;) {
  438. const line = await stdoutLines.next()
  439. if (line.done) throw new Error(`SDK profile stdout closed before response ${String(id)}; stderr=${stderr}`)
  440. let value: Record<string, unknown>
  441. try {
  442. value = JSON.parse(line.value) as Record<string, unknown>
  443. } catch {
  444. throw new Error(`SDK profile wrote non-JSON stdout: ${line.value}`)
  445. }
  446. if (value.id === id) return value
  447. }
  448. }
  449. try {
  450. child.stdin.write(`${JSON.stringify({
  451. jsonrpc: '2.0',
  452. id: 1,
  453. method: 'initialize',
  454. params: { cwd: home, provider: 'deepseek-official', model: 'deepseek-v4-flash' },
  455. })}\n`)
  456. const initialized = await response(1)
  457. expect(initialized, `${JSON.stringify(initialized)}\n${stderr}`).toMatchObject({
  458. jsonrpc: '2.0',
  459. id: 1,
  460. result: { serverInfo: { name: 'deepseek-harness-sdk-runtime' } },
  461. })
  462. child.stdin.write(`${JSON.stringify({ jsonrpc: '2.0', id: 2, method: 'shutdown' })}\n`)
  463. expect(await response(2)).toEqual({ jsonrpc: '2.0', id: 2, result: {} })
  464. const result = await child
  465. expect(result.timedOut, stderr).toBe(false)
  466. expect(result.signal, stderr).toBeUndefined()
  467. expect(result.exitCode, stderr).toBe(0)
  468. expect(stderr).toBe('')
  469. expect(readFileSync(marker, 'utf8')).toBe('loaded')
  470. } finally {
  471. child.kill('SIGKILL')
  472. await child
  473. rmSync(home, { recursive: true, force: true })
  474. }
  475. }, SPAWN_TIMEOUT_MS + 30_000)
  476. it('runs a mock-backed ACP turn through the acp profile and exits on disconnect', async () => {
  477. const apiKey = 'built-acp-profile-key'
  478. const server = await startMockLlmServer({
  479. sequence: ['success'],
  480. apiKey,
  481. successText: 'ACP BUILT PROFILE OK',
  482. })
  483. const home = mkdtempSync(join(tmpdir(), 'dsh-built-acp-'))
  484. const child = execa(process.execPath, [dshBin, '--profile', 'acp'], {
  485. cwd: home,
  486. reject: false,
  487. timeout: SPAWN_TIMEOUT_MS,
  488. killSignal: 'SIGKILL',
  489. env: {
  490. ...process.env,
  491. DSH_HOME: home,
  492. DSH_TELEMETRY_DISABLED: '1',
  493. DEEPSEEK_API_KEY: apiKey,
  494. DEEPSEEK_BASE_URL: server.baseURL,
  495. DSH_PERMISSION_MODE: 'danger-full-access',
  496. },
  497. extendEnv: false,
  498. })
  499. const rawOut: string[] = []
  500. const passthrough = new Readable({ read() {} })
  501. child.stdout.on('data', (chunk: Buffer) => {
  502. rawOut.push(chunk.toString('utf8'))
  503. passthrough.push(chunk)
  504. })
  505. child.stdout.on('end', () => { passthrough.push(null) })
  506. const stream = ndJsonStream(
  507. Writable.toWeb(child.stdin) as WritableStream<Uint8Array>,
  508. Readable.toWeb(passthrough) as ReadableStream<Uint8Array>,
  509. )
  510. const updates: SessionNotification['update'][] = []
  511. const clientApp = createAcpClientApp({ name: 'dsh-built-acp-profile' })
  512. .onNotification(methods.client.session.update, ({ params }) => {
  513. updates.push(params.update)
  514. return Promise.resolve()
  515. })
  516. .onRequest(methods.client.session.requestPermission, () => {
  517. return Promise.resolve({ outcome: { outcome: 'cancelled' } })
  518. })
  519. const client = clientApp.connect(stream).agent
  520. try {
  521. const initialized = await client.request(methods.agent.initialize, {
  522. protocolVersion: PROTOCOL_VERSION,
  523. clientCapabilities: {},
  524. })
  525. expect(initialized.agentInfo).toMatchObject({ name: 'deepseek-harness-acp' })
  526. expect(initialized.agentCapabilities).toEqual({
  527. mcpCapabilities: { http: true },
  528. promptCapabilities: { image: false, audio: false, embeddedContext: false },
  529. sessionCapabilities: { close: {}, list: {}, resume: {} },
  530. })
  531. expect('_meta' in initialized).toBe(false)
  532. const session = await client.request(methods.agent.session.new, { cwd: home, mcpServers: [] })
  533. expect(session.sessionId).toBeTruthy()
  534. expect(await client.request(methods.agent.session.prompt, {
  535. sessionId: session.sessionId,
  536. prompt: [{ type: 'text', text: 'reply from the built ACP profile' }],
  537. })).toEqual({ stopReason: 'end_turn' })
  538. expect(updates).toContainEqual(expect.objectContaining({
  539. sessionUpdate: 'agent_message_chunk',
  540. content: { type: 'text', text: 'ACP BUILT PROFILE OK' },
  541. }))
  542. const message = updates.find(update => update.sessionUpdate === 'agent_message_chunk')
  543. expect(message !== undefined && 'messageId' in message && typeof message.messageId === 'string').toBe(true)
  544. expect(server.requests).toHaveLength(1)
  545. child.stdin.end()
  546. const result = await child
  547. expect(result.exitCode, `signal=${String(result.signal)}; stderr=${result.stderr}`).toBe(0)
  548. expect(result.stderr).toBe('')
  549. for (const line of rawOut.join('').split('\n').filter(value => value.trim() !== '')) {
  550. expect(() => JSON.parse(line) as unknown).not.toThrow()
  551. }
  552. } finally {
  553. child.kill('SIGKILL')
  554. await child
  555. await server.close()
  556. rmSync(home, { recursive: true, force: true })
  557. }
  558. }, SPAWN_TIMEOUT_MS + 30_000)
  559. it('runs the headless profile through its app-owned task positional', async () => {
  560. const apiKey = 'built-dsh-headless-key'
  561. const server = await startMockLlmServer({
  562. sequence: ['reasoning_success'],
  563. apiKey,
  564. reasoningText: 'Inspecting the published entry.',
  565. successText: 'published headless profile reached the mock',
  566. })
  567. const home = mkdtempSync(join(tmpdir(), 'dsh-built-headless-'))
  568. try {
  569. const result = await runBuiltBin(['--profile', 'headless', 'answer', 'from', 'the', 'published', 'entry'], {
  570. DSH_HOME: home,
  571. DSH_TELEMETRY_DISABLED: '1',
  572. DEEPSEEK_API_KEY: apiKey,
  573. DEEPSEEK_BASE_URL: server.baseURL,
  574. })
  575. expect(result.code, result.stderr).toBe(0)
  576. expect(result.stdout).toBe('published headless profile reached the mock')
  577. expect(result.stderr).toBe('dsh: reasoning:\nInspecting the published entry.')
  578. expect(server.requests.length).toBeGreaterThan(0)
  579. expect(server.requests.every(request => request.path === '/chat/completions')).toBe(true)
  580. expect(JSON.stringify(server.requests.map(request => request.body))).toContain('answer from the published entry')
  581. } finally {
  582. await server.close()
  583. rmSync(home, { recursive: true, force: true })
  584. }
  585. }, SPAWN_TIMEOUT_MS + 30_000)
  586. it('does not load a project environment for --version', async () => {
  587. const project = mkdtempSync(join(tmpdir(), 'dsh-version-project-'))
  588. writeFileSync(join(project, '.env'), 'PATH=/project-only-path\n')
  589. try {
  590. const result = await runBuiltBin(['--version'], {}, project)
  591. expect(result).toEqual({ code: 0, stdout: cliVersion, stderr: '' })
  592. } finally {
  593. rmSync(project, { recursive: true, force: true })
  594. }
  595. })
  596. it.skipIf(process.platform === 'win32')('runs through an installed-style symlink', async () => {
  597. const installation = mkdtempSync(join(tmpdir(), 'dsh-bin-link-'))
  598. const installedBin = join(installation, 'dsh')
  599. symlinkSync(dshBin, installedBin)
  600. try {
  601. const result = await execa(process.execPath, [installedBin, '--version'], {
  602. input: '',
  603. timeout: SPAWN_TIMEOUT_MS,
  604. killSignal: 'SIGKILL',
  605. reject: false,
  606. })
  607. expect(result.exitCode).toBe(0)
  608. expect(result.stdout).toBe(cliVersion)
  609. expect(result.stderr).toBe('')
  610. } finally {
  611. rmSync(installation, { recursive: true, force: true })
  612. }
  613. })
  614. it('fails loud on a nonexistent profile with the plugin-command hint', async () => {
  615. const home = mkdtempSync(join(tmpdir(), 'dsh-missing-profile-'))
  616. try {
  617. const result = await runBuiltBin(['--profile', 'nope'], { DSH_HOME: home })
  618. expect(result.code).toBe(1)
  619. expect(result.stderr).toContain('profile "nope" does not exist')
  620. expect(result.stderr).toContain('dsh plugin --profile nope add')
  621. } finally {
  622. rmSync(home, { recursive: true, force: true })
  623. }
  624. }, SPAWN_TIMEOUT_MS + 30_000)
  625. it('uses the launching endpoint and managed credential through the published entry', async () => {
  626. const apiKey = 'built-home-layer-key'
  627. const server = await startMockLlmServer({
  628. sequence: ['success'],
  629. apiKey,
  630. successText: 'launching endpoint reached the mock',
  631. })
  632. const home = mkdtempSync(join(tmpdir(), 'dsh-home-environment-'))
  633. const project = mkdtempSync(join(tmpdir(), 'dsh-home-project-'))
  634. writeFileSync(join(home, '.credentials.yaml'), `version: 1\nrefs:\n DEEPSEEK_API_KEY: ${apiKey}\n`, { mode: 0o600 })
  635. createEnvironmentProbeProfile(home, project)
  636. try {
  637. const result = await runBuiltBin(
  638. ['--profile', 'environment-probe'],
  639. {
  640. DSH_HOME: home,
  641. DSH_TELEMETRY_DISABLED: '1',
  642. DEEPSEEK_API_KEY: undefined,
  643. DEEPSEEK_BASE_URL: server.baseURL,
  644. },
  645. project,
  646. )
  647. expect(
  648. result.code,
  649. `${result.stderr}\nstdout:\n${result.stdout}\nmock requests: ${String(server.requests.length)}`,
  650. ).toBe(0)
  651. expect(result.stdout).toBe('launching endpoint reached the mock')
  652. expect(result.stdout).not.toContain(apiKey)
  653. expect(result.stderr).not.toContain(apiKey)
  654. expect(server.requests).toHaveLength(1)
  655. expect(server.requests[0]?.path).toBe('/chat/completions')
  656. expect(server.requests[0]?.headers.authorization).toBe(`Bearer ${apiKey}`)
  657. expect(JSON.stringify(server.requests[0]?.body)).not.toContain(apiKey)
  658. } finally {
  659. await server.close()
  660. rmSync(home, { recursive: true, force: true })
  661. rmSync(project, { recursive: true, force: true })
  662. }
  663. }, SPAWN_TIMEOUT_MS + 30_000)
  664. it('reports a patch-overlay boot failure without hanging', async () => {
  665. // The HMR main watcher's initial scan once refreshed the include
  666. // mid-initial-apply, deadlocking the failing apply's rollback against the
  667. // refresh drain: dsh exited 13 with no diagnostic instead of settling
  668. // ([vendor/README.md](../../../vendor/README.md)).
  669. const home = mkdtempSync(join(tmpdir(), 'dsh-invalid-patch-'))
  670. try {
  671. const result = await runBuiltBin(['--profile', 'web', '--patch', invalidProvider], {
  672. DSH_HOME: home,
  673. DEEPSEEK_API_KEY: 'keyless-invalid-config',
  674. DSH_TELEMETRY_DISABLED: '1',
  675. })
  676. expect(result.code).toBe(1)
  677. expect(result.stdout).toBe('')
  678. expect(result.stderr).toContain('llm-pi-ai')
  679. } finally {
  680. rmSync(home, { recursive: true, force: true })
  681. }
  682. }, SPAWN_TIMEOUT_MS + 30_000)
  683. it('lets a profile without a parser ignore app arguments and dispose on a startup-time signal', async () => {
  684. const fixture = createProfileLifecycleFixture()
  685. const child = startProfileLifecycle(fixture, ['--unclaimed'])
  686. try {
  687. await waitForFile(fixture.ready)
  688. requestProfileShutdown(child, fixture)
  689. const result = await child
  690. expect(result.exitCode, `${result.stderr}\nstdout:\n${result.stdout}\nsignal: ${String(result.signal)}`).toBe(0)
  691. expect(result.signal).toBeUndefined()
  692. expect(existsSync(fixture.disposed)).toBe(true)
  693. } finally {
  694. child.kill('SIGKILL')
  695. rmSync(fixture.home, { recursive: true, force: true })
  696. }
  697. }, SPAWN_TIMEOUT_MS + 30_000)
  698. it('fully settles a custom profile, hot-reloads its patch layer with removal reverting, and disposes on a signal', async () => {
  699. const fixture = createProfileLifecycleFixture()
  700. const child = startProfileLifecycle(fixture)
  701. const profilePatch = join(fixture.home, 'profiles', 'lifecycle', 'cordis.patch.yml')
  702. const configFile = join(fixture.home, 'config-echo')
  703. try {
  704. await waitForFile(fixture.settled)
  705. // The live profile layer: even without an hmr row in the composition,
  706. // the launcher mounts a config-only watcher, so an edited
  707. // cordis.patch.yml lands in the running tree (the reload disposes the
  708. // patched row's old fiber — observable as the disposed marker — and
  709. // mounts the new config, which echoes its generation and re-writes the
  710. // ready marker).
  711. rmSync(fixture.ready)
  712. writeFileSync(profilePatch, [
  713. '- id: profile-lifecycle-fixture',
  714. ' config:',
  715. ' generation: 2',
  716. '',
  717. ].join('\n'))
  718. await waitForFile(fixture.ready)
  719. expect(readFileSync(configFile, 'utf8')).toBe('2')
  720. // Unlink exercises layer removal without racing Chokidar's change-event
  721. // suppression window after the preceding edit. The bundle default must return.
  722. rmSync(fixture.ready)
  723. rmSync(profilePatch)
  724. await waitForFile(fixture.ready)
  725. expect(existsSync(profilePatch)).toBe(false)
  726. expect(readFileSync(configFile, 'utf8')).toBe('bundle-default')
  727. // The home-level user layer ($DSH_HOME/cordis.patch.yml) is live too
  728. // and outranks the per-profile layer.
  729. rmSync(fixture.ready)
  730. writeFileSync(join(fixture.home, 'cordis.patch.yml'), [
  731. '- id: profile-lifecycle-fixture',
  732. ' config:',
  733. ' generation: home',
  734. '',
  735. ].join('\n'))
  736. await waitForFile(fixture.ready)
  737. expect(readFileSync(configFile, 'utf8')).toBe('home')
  738. requestProfileShutdown(child, fixture)
  739. const result = await child
  740. expect(result.exitCode, `${result.stderr}\nstdout:\n${result.stdout}\nsignal: ${String(result.signal)}`).toBe(0)
  741. expect(result.signal).toBeUndefined()
  742. expect(existsSync(fixture.disposed)).toBe(true)
  743. } finally {
  744. child.kill('SIGKILL')
  745. await child
  746. rmSync(fixture.home, { recursive: true, force: true })
  747. }
  748. }, SPAWN_TIMEOUT_MS + 30_000)
  749. it('hands the app arguments to the profile, which applies them before its rows start', async () => {
  750. const fixture = createStartupFixture()
  751. const child = startStartupProfile(fixture, ['--generation', 'flagged'])
  752. try {
  753. await waitForFile(fixture.ready)
  754. // The consumer started once, already carrying the flag value: the
  755. // launcher never saw --generation, and the app provider resolved it first.
  756. expect(readFileSync(fixture.echo, 'utf8')).toBe('flagged')
  757. requestProfileShutdown(child, fixture)
  758. expect((await child).exitCode).toBe(0)
  759. } finally {
  760. child.kill('SIGKILL')
  761. rmSync(fixture.home, { recursive: true, force: true })
  762. }
  763. }, SPAWN_TIMEOUT_MS + 30_000)
  764. it('starts a consumer on its composed value when the invocation carries no app arguments', async () => {
  765. const fixture = createStartupFixture()
  766. const child = startStartupProfile(fixture, [])
  767. try {
  768. await waitForFile(fixture.ready)
  769. expect(readFileSync(fixture.echo, 'utf8')).toBe('bundle-default')
  770. requestProfileShutdown(child, fixture)
  771. expect((await child).exitCode).toBe(0)
  772. } finally {
  773. child.kill('SIGKILL')
  774. rmSync(fixture.home, { recursive: true, force: true })
  775. }
  776. }, SPAWN_TIMEOUT_MS + 30_000)
  777. it('keeps the app arguments across a user patch reload', async () => {
  778. // A live edit recomposes every row while the provider service remains
  779. // active, so each config expression reads the same invocation value (a
  780. // served port does not move back to its composed fallback).
  781. const fixture = createStartupFixture()
  782. const profilePatch = join(fixture.home, 'profiles', 'startup', 'cordis.patch.yml')
  783. const child = startStartupProfile(fixture, ['--generation', 'flagged'])
  784. try {
  785. // Both rows: the waiting one carries the flag value, and the witness is
  786. // what a reload will re-mount. They start independently, so neither
  787. // marker implies the other.
  788. await waitForFile(fixture.ready)
  789. await waitForFile(fixture.witness)
  790. expect(readFileSync(fixture.echo, 'utf8')).toBe('flagged')
  791. // An edit to an unrelated row: the witness re-mounts, which is how this
  792. // test knows the whole tree was recomposed.
  793. rmSync(fixture.witness)
  794. writeFileSync(profilePatch, [
  795. '- id: reload-witness',
  796. ' config:',
  797. ' generation: reloaded',
  798. '',
  799. ].join('\n'))
  800. await waitForFile(fixture.witness)
  801. expect(readFileSync(fixture.witness, 'utf8')).toBe('reloaded')
  802. expect(readFileSync(fixture.echo, 'utf8')).toBe('flagged')
  803. requestProfileShutdown(child, fixture)
  804. expect((await child).exitCode).toBe(0)
  805. } finally {
  806. child.kill('SIGKILL')
  807. rmSync(fixture.home, { recursive: true, force: true })
  808. }
  809. }, SPAWN_TIMEOUT_MS + 30_000)
  810. it("prints the app's own help, starts none of its rows, and exits", async () => {
  811. const fixture = createStartupFixture()
  812. try {
  813. const result = await startStartupProfile(fixture, ['--help'])
  814. expect(result.exitCode).toBe(0)
  815. expect(result.stdout).toContain('Usage: fixture')
  816. expect(result.stdout).toContain('--generation')
  817. expect(existsSync(fixture.ready)).toBe(false)
  818. } finally {
  819. rmSync(fixture.home, { recursive: true, force: true })
  820. }
  821. }, SPAWN_TIMEOUT_MS + 30_000)
  822. it('anchors a relative add spec to the invoking directory, not the profile', async () => {
  823. // `dsh plugin --profile x add .` from a plugin checkout must install THAT
  824. // checkout — pnpm's cwd is the profile directory, so an un-anchored `.`
  825. // would self-link the profile.
  826. const home = mkdtempSync(join(tmpdir(), 'dsh-plugin-anchor-'))
  827. const checkout = mkdtempSync(join(tmpdir(), 'dsh-plugin-checkout-'))
  828. try {
  829. writeFileSync(join(checkout, 'package.json'), JSON.stringify({
  830. name: 'anchored-bundle',
  831. version: '1.0.0',
  832. dsh: { bundle: { patch: './cordis.patch.yml' } },
  833. }))
  834. writeFileSync(join(checkout, 'cordis.patch.yml'), '[]\n')
  835. const result = await execa(process.execPath, [dshBin, 'plugin', '--profile', 'anchor', 'add', '.'], {
  836. cwd: checkout,
  837. input: '',
  838. timeout: SPAWN_TIMEOUT_MS,
  839. killSignal: 'SIGKILL',
  840. reject: false,
  841. env: { DSH_HOME: home },
  842. })
  843. expect(result.exitCode).toBe(0)
  844. const manifest = JSON.parse(readFileSync(join(home, 'profiles', 'anchor', 'package.json'), 'utf8')) as {
  845. dependencies: Record<string, string>
  846. dsh: { profile: { bundles: string[] } }
  847. }
  848. expect(Object.keys(manifest.dependencies)).toEqual(['anchored-bundle'])
  849. expect(manifest.dsh.profile.bundles).toContain('anchored-bundle')
  850. const removed = await runBuiltBin(
  851. ['plugin', '--profile', 'anchor', 'remove', 'anchored-bundle'],
  852. { DSH_HOME: home },
  853. checkout,
  854. )
  855. expect(removed.code).toBe(0)
  856. const afterRemove = JSON.parse(
  857. readFileSync(join(home, 'profiles', 'anchor', 'package.json'), 'utf8'),
  858. ) as {
  859. dependencies?: Record<string, string>
  860. dsh: { profile: { bundles: string[] } }
  861. }
  862. expect(Object.keys(afterRemove.dependencies ?? {})).toEqual([])
  863. expect(afterRemove.dsh.profile.bundles).not.toContain('anchored-bundle')
  864. } finally {
  865. rmSync(home, { recursive: true, force: true })
  866. rmSync(checkout, { recursive: true, force: true })
  867. }
  868. }, SPAWN_TIMEOUT_MS * 2 + 30_000)
  869. it('activates a dependency that gained dsh.bundle in a later update', async () => {
  870. // Reconcile runs against the INSTALLED state on every successful pnpm
  871. // run, so `update` (not only `add`) activates a package whose newer
  872. // version declares dsh.bundle. Simulated without a registry: hand-place
  873. // the installed package, flip its manifest, and run a benign pnpm verb.
  874. const home = mkdtempSync(join(tmpdir(), 'dsh-plugin-update-'))
  875. try {
  876. const profileDir = join(home, 'profiles', 'up')
  877. const installed = join(profileDir, 'node_modules', 'late-bundle')
  878. mkdirSync(installed, { recursive: true })
  879. writeFileSync(join(profileDir, 'package.json'), JSON.stringify({
  880. name: 'dsh-profile-up',
  881. private: true,
  882. dependencies: { 'late-bundle': 'file:./late-bundle' },
  883. dsh: { profile: { bundles: ['@deepseek-ai/dsh-base'] } },
  884. }))
  885. writeFileSync(join(profileDir, 'cordis.patch.yml'), '[]\n')
  886. // v1: no dsh manifest — a plain dependency.
  887. writeFileSync(join(installed, 'package.json'), JSON.stringify({ name: 'late-bundle', version: '1.0.0' }))
  888. const first = await runBuiltBin(['plugin', '--profile', 'up', 'root'], { DSH_HOME: home })
  889. expect(first.code).toBe(0)
  890. let manifest = JSON.parse(readFileSync(join(profileDir, 'package.json'), 'utf8')) as { dsh: { profile: { bundles: string[] } } }
  891. expect(manifest.dsh.profile.bundles).toEqual(['@deepseek-ai/dsh-base'])
  892. // v2: the installed package now declares dsh.bundle (an update landed).
  893. writeFileSync(join(installed, 'package.json'), JSON.stringify({
  894. name: 'late-bundle', version: '2.0.0', dsh: { bundle: { patch: './cordis.patch.yml' } },
  895. }))
  896. writeFileSync(join(installed, 'cordis.patch.yml'), '[]\n')
  897. const second = await runBuiltBin(['plugin', '--profile', 'up', 'root'], { DSH_HOME: home })
  898. expect(second.code).toBe(0)
  899. manifest = JSON.parse(readFileSync(join(profileDir, 'package.json'), 'utf8')) as { dsh: { profile: { bundles: string[] } } }
  900. expect(manifest.dsh.profile.bundles).toEqual(['@deepseek-ai/dsh-base', 'late-bundle'])
  901. } finally {
  902. rmSync(home, { recursive: true, force: true })
  903. }
  904. }, SPAWN_TIMEOUT_MS * 2 + 30_000)
  905. describe('config dump', () => {
  906. let home: string
  907. beforeEach(() => { home = mkdtempSync(join(tmpdir(), 'dsh-dump-bin-')) })
  908. afterEach(() => { rmSync(home, { recursive: true, force: true }) })
  909. it('prints the web profile bundle layers without a user layer', async () => {
  910. const { stdout, code, stderr } = await runBuiltBin(['--profile', 'web', '--dump-default-config'], { DSH_HOME: home })
  911. expect(code).toBe(0)
  912. expect(stderr).toBe('')
  913. expect(stdout).toContain("name: '@deepseek-ai/dsh-agent-loop'")
  914. expect(stdout).toContain('agents: []')
  915. expect(stdout).toContain('# == @deepseek-ai/dsh-base')
  916. expect(stdout).toContain("name: '@deepseek-ai/dsh-host-webserver'")
  917. expect(existsSync(join(home, 'profiles', 'node_modules'))).toBe(false)
  918. }, SPAWN_TIMEOUT_MS + 30_000)
  919. it('prints the headless profile without Host or browser layers', async () => {
  920. const { stdout, code, stderr } = await runBuiltBin(
  921. ['--profile', 'headless', '--dump-default-config'],
  922. { DSH_HOME: home },
  923. )
  924. expect(code).toBe(0)
  925. expect(stderr).toBe('')
  926. expect(stdout).toContain("name: '@deepseek-ai/dsh-headless'")
  927. expect(stdout).not.toMatch(/name: '@deepseek-ai\/dsh-host-/)
  928. expect(stdout).not.toContain("name: '@deepseek-ai/dsh-web-app'")
  929. expect(stdout).not.toMatch(/name: '@deepseek-ai\/dsh-client-/)
  930. }, SPAWN_TIMEOUT_MS + 30_000)
  931. it('prints the exact standalone sdk-minimal tree without dsh-base', async () => {
  932. const { stdout, code, stderr } = await runBuiltBin(
  933. ['--profile', 'sdk-minimal', '--dump-default-config'],
  934. { DSH_HOME: home },
  935. )
  936. expect(code).toBe(0)
  937. expect(stderr).toBe('')
  938. const rows = yaml.load(stdout, { schema: entryListSchema }) as Array<{ id?: string; name?: string }>
  939. expect(rows.map(row => [row.id, row.name])).toEqual([
  940. ['sdk-app-startup', '@deepseek-ai/dsh-sdk-app'],
  941. ['sdk-jsonrpc-server', '@deepseek-ai/dsh-sdk-jsonrpc-server'],
  942. ['deepseek-llm-api-extensions', '@deepseek-ai/dsh-deepseek-llm-api-extensions'],
  943. ['session-log-deepseek', '@deepseek-ai/dsh-session-log-deepseek'],
  944. ['plugin-package-inventory-deepseek', '@deepseek-ai/dsh-plugin-package-inventory-deepseek'],
  945. ['llm-deepseek', '@deepseek-ai/dsh-llm-deepseek'],
  946. ['sandbox', '@deepseek-ai/dsh-sandbox-local'],
  947. ['session-projection', '@deepseek-ai/dsh-session-projection'],
  948. ['sandbox-policy', '@deepseek-ai/dsh-sandbox-policy'],
  949. ['subprocess', '@deepseek-ai/dsh-subprocess-local'],
  950. ['pty', '@deepseek-ai/dsh-terminal'],
  951. ['terminal-bash', '@deepseek-ai/dsh-terminal-bash'],
  952. ['terminal-pwsh', '@deepseek-ai/dsh-terminal-bash'],
  953. ['fs-local', '@deepseek-ai/dsh-fs-local'],
  954. ['timer', '@deepseek-ai/cordis-plugin-timer'],
  955. ['llm', '@deepseek-ai/dsh-llm'],
  956. ['session', '@deepseek-ai/dsh-session'],
  957. ['session-title', '@deepseek-ai/dsh-session-title'],
  958. ['system-prompt', '@deepseek-ai/dsh-system-prompt'],
  959. ['tools', '@deepseek-ai/dsh-tools'],
  960. ['agent', '@deepseek-ai/dsh-agent'],
  961. ['llm-retry', '@deepseek-ai/dsh-llm-retry'],
  962. ['jobs', '@deepseek-ai/dsh-jobs-local'],
  963. ['invariants', '@deepseek-ai/dsh-invariants'],
  964. ['session-invariant', '@deepseek-ai/dsh-session/invariant'],
  965. ['agent-invariant', '@deepseek-ai/dsh-agent/invariant'],
  966. ['scope-invariant', '@deepseek-ai/dsh-scope/invariant'],
  967. ['agent-loop-invariant', '@deepseek-ai/dsh-agent-loop/invariant'],
  968. ['agent-loop', '@deepseek-ai/dsh-agent-loop'],
  969. ['persistent-bash', '@deepseek-ai/dsh-tool-bash-persistent'],
  970. ['persistent-pwsh', '@deepseek-ai/dsh-tool-pwsh-persistent'],
  971. ['str-replace-editor', '@deepseek-ai/dsh-tool-str-replace-editor'],
  972. ['sessions', '@deepseek-ai/dsh-session-persistence-jsonl'],
  973. ])
  974. expect(stdout).toContain('# == @deepseek-ai/dsh-sdk-minimal')
  975. expect(stdout).not.toContain('@deepseek-ai/dsh-base')
  976. expect(stdout).not.toContain('@deepseek-ai/dsh-web-app')
  977. }, SPAWN_TIMEOUT_MS * 2 + 30_000)
  978. it('composes the profile user layer and a --patch overlay in order', async () => {
  979. // Auto-init the web profile first, then write its user layer.
  980. const init = await runBuiltBin(['--profile', 'web', '--dump-default-config'], { DSH_HOME: home })
  981. expect(init.code).toBe(0)
  982. const profilePatch = join(home, 'profiles', 'web', 'cordis.patch.yml')
  983. writeFileSync(profilePatch, [
  984. '- id: agent-loop',
  985. ' config:',
  986. ' agents:',
  987. ' - id: personal',
  988. ' provider: personal-provider',
  989. ' model: personal-model',
  990. '- id: absent-row',
  991. ' config:',
  992. ' x: 1',
  993. '',
  994. ].join('\n'))
  995. const overlay = join(home, 'overlay.cordis.yml')
  996. writeFileSync(overlay, [
  997. '- id: agent-loop',
  998. ' config:',
  999. ' agents:',
  1000. ' - id: configured',
  1001. ' provider: configured-provider',
  1002. ' model: configured-model',
  1003. '',
  1004. ].join('\n'))
  1005. const { stdout, code, stderr } = await runBuiltBin(
  1006. ['--profile', 'web', '--patch', overlay, '--dump-config'],
  1007. { DSH_HOME: home },
  1008. )
  1009. expect(code).toBe(0)
  1010. expect(stdout).toContain('provider: configured-provider')
  1011. expect(stdout).not.toContain('personal-provider')
  1012. // Both layers patched the row; the comment lists them in application order.
  1013. expect(stdout).toContain(`patched by ${profilePatch}, ${overlay}`)
  1014. expect(stderr).toContain('patch: entry "absent-row" not found')
  1015. }, SPAWN_TIMEOUT_MS * 2 + 30_000)
  1016. })
  1017. })