built-bin.e2e.ts 58 KB

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