built-bin.e2e.ts 49 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147
  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('creates a custom profile from the shipped web template before booting it', async () => {
  626. const home = mkdtempSync(join(tmpdir(), 'dsh-from-default-profile-'))
  627. try {
  628. const created = await runBuiltBin(
  629. ['--profile', 'rescue', '--from-default-profile', 'web', '--help'],
  630. { DSH_HOME: home, DSH_TELEMETRY_DISABLED: '1' },
  631. )
  632. expect(created.code).toBe(0)
  633. expect(created.stderr).toBe('')
  634. expect(created.stdout).toContain('Usage: dsh --profile web')
  635. const dir = join(home, 'profiles', 'rescue')
  636. const manifest = JSON.parse(readFileSync(join(dir, 'package.json'), 'utf8')) as {
  637. dependencies: Record<string, string>
  638. dsh: { profile: { bundles: string[]; patchReload: string } }
  639. }
  640. expect(manifest.dependencies).toEqual({})
  641. expect(manifest.dsh.profile).toEqual({
  642. bundles: ['@deepseek-ai/dsh-base', '@deepseek-ai/dsh-web-app'],
  643. patchReload: 'live',
  644. })
  645. expect(readFileSync(join(dir, 'cordis.patch.yml'), 'utf8')).toContain('[]')
  646. expect(readFileSync(join(dir, 'pnpm-workspace.yaml'), 'utf8')).toContain('nodeLinker: hoisted')
  647. const repeated = await runBuiltBin(
  648. ['--profile', 'rescue', '--from-default-profile', 'web', '--help'],
  649. { DSH_HOME: home, DSH_TELEMETRY_DISABLED: '1' },
  650. )
  651. expect(repeated.code).toBe(1)
  652. expect(repeated.stdout).toBe('')
  653. expect(repeated.stderr).toContain('profile "rescue" already exists')
  654. expect(repeated.stderr).toContain('omit --from-default-profile to use it')
  655. const reopened = await runBuiltBin(
  656. ['--profile', 'rescue', '--help'],
  657. { DSH_HOME: home, DSH_TELEMETRY_DISABLED: '1' },
  658. )
  659. expect(reopened.code).toBe(0)
  660. expect(reopened.stderr).toBe('')
  661. expect(reopened.stdout).toContain('Usage: dsh --profile web')
  662. } finally {
  663. rmSync(home, { recursive: true, force: true })
  664. }
  665. }, SPAWN_TIMEOUT_MS * 3 + 30_000)
  666. it('keeps a newly created profile when application boot rejects its arguments', async () => {
  667. const home = mkdtempSync(join(tmpdir(), 'dsh-from-default-profile-failed-boot-'))
  668. try {
  669. const failed = await runBuiltBin(
  670. ['--profile', 'rescue', '--from-default-profile', 'web', '--port', 'not-a-number'],
  671. { DSH_HOME: home, DSH_TELEMETRY_DISABLED: '1' },
  672. )
  673. expect(failed.code).toBe(1)
  674. expect(failed.stderr).toContain('--port must be a number')
  675. expect(existsSync(join(home, 'profiles', 'rescue', 'package.json'))).toBe(true)
  676. const retried = await runBuiltBin(
  677. ['--profile', 'rescue', '--help'],
  678. { DSH_HOME: home, DSH_TELEMETRY_DISABLED: '1' },
  679. )
  680. expect(retried.code).toBe(0)
  681. expect(retried.stderr).toBe('')
  682. expect(retried.stdout).toContain('Usage: dsh --profile web')
  683. } finally {
  684. rmSync(home, { recursive: true, force: true })
  685. }
  686. }, SPAWN_TIMEOUT_MS * 2 + 30_000)
  687. it('uses the launching endpoint and managed credential through the published entry', async () => {
  688. const apiKey = 'built-home-layer-key'
  689. const server = await startMockLlmServer({
  690. sequence: ['success'],
  691. apiKey,
  692. successText: 'launching endpoint reached the mock',
  693. })
  694. const home = mkdtempSync(join(tmpdir(), 'dsh-home-environment-'))
  695. const project = mkdtempSync(join(tmpdir(), 'dsh-home-project-'))
  696. writeFileSync(join(home, '.credentials.yaml'), `version: 1\nrefs:\n DEEPSEEK_API_KEY: ${apiKey}\n`, { mode: 0o600 })
  697. createEnvironmentProbeProfile(home, project)
  698. try {
  699. const result = await runBuiltBin(
  700. ['--profile', 'environment-probe'],
  701. {
  702. DSH_HOME: home,
  703. DSH_TELEMETRY_DISABLED: '1',
  704. DEEPSEEK_API_KEY: undefined,
  705. DEEPSEEK_BASE_URL: server.baseURL,
  706. },
  707. project,
  708. )
  709. expect(
  710. result.code,
  711. `${result.stderr}\nstdout:\n${result.stdout}\nmock requests: ${String(server.requests.length)}`,
  712. ).toBe(0)
  713. expect(result.stdout).toBe('launching endpoint reached the mock')
  714. expect(result.stdout).not.toContain(apiKey)
  715. expect(result.stderr).not.toContain(apiKey)
  716. expect(server.requests).toHaveLength(1)
  717. expect(server.requests[0]?.path).toBe('/chat/completions')
  718. expect(server.requests[0]?.headers.authorization).toBe(`Bearer ${apiKey}`)
  719. expect(JSON.stringify(server.requests[0]?.body)).not.toContain(apiKey)
  720. } finally {
  721. await server.close()
  722. rmSync(home, { recursive: true, force: true })
  723. rmSync(project, { recursive: true, force: true })
  724. }
  725. }, SPAWN_TIMEOUT_MS + 30_000)
  726. it('reports a patch-overlay boot failure without hanging', async () => {
  727. // The HMR main watcher's initial scan once refreshed the include
  728. // mid-initial-apply, deadlocking the failing apply's rollback against the
  729. // refresh drain: dsh exited 13 with no diagnostic instead of settling
  730. // ([vendor/README.md](../../../vendor/README.md)).
  731. const home = mkdtempSync(join(tmpdir(), 'dsh-invalid-patch-'))
  732. try {
  733. const result = await runBuiltBin(['--profile', 'web', '--patch', invalidProvider], {
  734. DSH_HOME: home,
  735. DEEPSEEK_API_KEY: 'keyless-invalid-config',
  736. DSH_TELEMETRY_DISABLED: '1',
  737. })
  738. expect(result.code).toBe(1)
  739. expect(result.stdout).toBe('')
  740. expect(result.stderr).toContain('llm-pi-ai')
  741. } finally {
  742. rmSync(home, { recursive: true, force: true })
  743. }
  744. }, SPAWN_TIMEOUT_MS + 30_000)
  745. it('lets a profile without a parser ignore app arguments and dispose on a startup-time signal', async () => {
  746. const fixture = createProfileLifecycleFixture()
  747. const child = startProfileLifecycle(fixture, ['--unclaimed'])
  748. try {
  749. await waitForFile(fixture.ready)
  750. requestProfileShutdown(child, fixture)
  751. const result = await child
  752. expect(result.exitCode, `${result.stderr}\nstdout:\n${result.stdout}\nsignal: ${String(result.signal)}`).toBe(0)
  753. expect(result.signal).toBeUndefined()
  754. expect(existsSync(fixture.disposed)).toBe(true)
  755. } finally {
  756. child.kill('SIGKILL')
  757. rmSync(fixture.home, { recursive: true, force: true })
  758. }
  759. }, SPAWN_TIMEOUT_MS + 30_000)
  760. it('fully settles a custom profile, hot-reloads its patch layer with removal reverting, and disposes on a signal', async () => {
  761. const fixture = createProfileLifecycleFixture()
  762. const child = startProfileLifecycle(fixture)
  763. const profilePatch = join(fixture.home, 'profiles', 'lifecycle', 'cordis.patch.yml')
  764. const configFile = join(fixture.home, 'config-echo')
  765. try {
  766. await waitForFile(fixture.settled)
  767. // The live profile layer: even without an hmr row in the composition,
  768. // the launcher mounts a config-only watcher, so an edited
  769. // cordis.patch.yml lands in the running tree (the reload disposes the
  770. // patched row's old fiber — observable as the disposed marker — and
  771. // mounts the new config, which echoes its generation and re-writes the
  772. // ready marker).
  773. rmSync(fixture.ready)
  774. writeFileSync(profilePatch, [
  775. '- id: profile-lifecycle-fixture',
  776. ' config:',
  777. ' generation: 2',
  778. '',
  779. ].join('\n'))
  780. await waitForFile(fixture.ready)
  781. expect(readFileSync(configFile, 'utf8')).toBe('2')
  782. // Unlink exercises layer removal without racing Chokidar's change-event
  783. // suppression window after the preceding edit. The bundle default must return.
  784. rmSync(fixture.ready)
  785. rmSync(profilePatch)
  786. await waitForFile(fixture.ready)
  787. expect(existsSync(profilePatch)).toBe(false)
  788. expect(readFileSync(configFile, 'utf8')).toBe('bundle-default')
  789. // The home-level user layer ($DSH_HOME/cordis.patch.yml) is live too
  790. // and outranks the per-profile layer.
  791. rmSync(fixture.ready)
  792. writeFileSync(join(fixture.home, 'cordis.patch.yml'), [
  793. '- id: profile-lifecycle-fixture',
  794. ' config:',
  795. ' generation: home',
  796. '',
  797. ].join('\n'))
  798. await waitForFile(fixture.ready)
  799. expect(readFileSync(configFile, 'utf8')).toBe('home')
  800. requestProfileShutdown(child, fixture)
  801. const result = await child
  802. expect(result.exitCode, `${result.stderr}\nstdout:\n${result.stdout}\nsignal: ${String(result.signal)}`).toBe(0)
  803. expect(result.signal).toBeUndefined()
  804. expect(existsSync(fixture.disposed)).toBe(true)
  805. } finally {
  806. child.kill('SIGKILL')
  807. await child
  808. rmSync(fixture.home, { recursive: true, force: true })
  809. }
  810. }, SPAWN_TIMEOUT_MS + 30_000)
  811. it('hands the app arguments to the profile, which applies them before its rows start', async () => {
  812. const fixture = createStartupFixture()
  813. const child = startStartupProfile(fixture, ['--generation', 'flagged'])
  814. try {
  815. await waitForFile(fixture.ready)
  816. // The consumer started once, already carrying the flag value: the
  817. // launcher never saw --generation, and the app provider resolved it first.
  818. expect(readFileSync(fixture.echo, 'utf8')).toBe('flagged')
  819. requestProfileShutdown(child, fixture)
  820. expect((await child).exitCode).toBe(0)
  821. } finally {
  822. child.kill('SIGKILL')
  823. rmSync(fixture.home, { recursive: true, force: true })
  824. }
  825. }, SPAWN_TIMEOUT_MS + 30_000)
  826. it('starts a consumer on its composed value when the invocation carries no app arguments', async () => {
  827. const fixture = createStartupFixture()
  828. const child = startStartupProfile(fixture, [])
  829. try {
  830. await waitForFile(fixture.ready)
  831. expect(readFileSync(fixture.echo, 'utf8')).toBe('bundle-default')
  832. requestProfileShutdown(child, fixture)
  833. expect((await child).exitCode).toBe(0)
  834. } finally {
  835. child.kill('SIGKILL')
  836. rmSync(fixture.home, { recursive: true, force: true })
  837. }
  838. }, SPAWN_TIMEOUT_MS + 30_000)
  839. it('keeps the app arguments across a user patch reload', async () => {
  840. // A live edit recomposes every row while the provider service remains
  841. // active, so each config expression reads the same invocation value (a
  842. // served port does not move back to its composed fallback).
  843. const fixture = createStartupFixture()
  844. const profilePatch = join(fixture.home, 'profiles', 'startup', 'cordis.patch.yml')
  845. const child = startStartupProfile(fixture, ['--generation', 'flagged'])
  846. try {
  847. // Both rows: the waiting one carries the flag value, and the witness is
  848. // what a reload will re-mount. They start independently, so neither
  849. // marker implies the other.
  850. await waitForFile(fixture.ready)
  851. await waitForFile(fixture.witness)
  852. expect(readFileSync(fixture.echo, 'utf8')).toBe('flagged')
  853. // An edit to an unrelated row: the witness re-mounts, which is how this
  854. // test knows the whole tree was recomposed.
  855. rmSync(fixture.witness)
  856. writeFileSync(profilePatch, [
  857. '- id: reload-witness',
  858. ' config:',
  859. ' generation: reloaded',
  860. '',
  861. ].join('\n'))
  862. await waitForFile(fixture.witness)
  863. expect(readFileSync(fixture.witness, 'utf8')).toBe('reloaded')
  864. expect(readFileSync(fixture.echo, 'utf8')).toBe('flagged')
  865. requestProfileShutdown(child, fixture)
  866. expect((await child).exitCode).toBe(0)
  867. } finally {
  868. child.kill('SIGKILL')
  869. rmSync(fixture.home, { recursive: true, force: true })
  870. }
  871. }, SPAWN_TIMEOUT_MS + 30_000)
  872. it("prints the app's own help, starts none of its rows, and exits", async () => {
  873. const fixture = createStartupFixture()
  874. try {
  875. const result = await startStartupProfile(fixture, ['--help'])
  876. expect(result.exitCode).toBe(0)
  877. expect(result.stdout).toContain('Usage: fixture')
  878. expect(result.stdout).toContain('--generation')
  879. expect(existsSync(fixture.ready)).toBe(false)
  880. } finally {
  881. rmSync(fixture.home, { recursive: true, force: true })
  882. }
  883. }, SPAWN_TIMEOUT_MS + 30_000)
  884. it('anchors a relative add spec to the invoking directory, not the profile', async () => {
  885. // `dsh plugin --profile x add .` from a plugin checkout must install THAT
  886. // checkout — pnpm's cwd is the profile directory, so an un-anchored `.`
  887. // would self-link the profile.
  888. const home = mkdtempSync(join(tmpdir(), 'dsh-plugin-anchor-'))
  889. const checkout = mkdtempSync(join(tmpdir(), 'dsh-plugin-checkout-'))
  890. try {
  891. writeFileSync(join(checkout, 'package.json'), JSON.stringify({
  892. name: 'anchored-bundle',
  893. version: '1.0.0',
  894. dsh: { bundle: { patch: './cordis.patch.yml' } },
  895. }))
  896. writeFileSync(join(checkout, 'cordis.patch.yml'), '[]\n')
  897. const result = await execa(process.execPath, [dshBin, 'plugin', '--profile', 'anchor', 'add', '.'], {
  898. cwd: checkout,
  899. input: '',
  900. timeout: SPAWN_TIMEOUT_MS,
  901. killSignal: 'SIGKILL',
  902. reject: false,
  903. env: { DSH_HOME: home },
  904. })
  905. expect(result.exitCode).toBe(0)
  906. const manifest = JSON.parse(readFileSync(join(home, 'profiles', 'anchor', 'package.json'), 'utf8')) as {
  907. dependencies: Record<string, string>
  908. dsh: { profile: { bundles: string[] } }
  909. }
  910. expect(Object.keys(manifest.dependencies)).toEqual(['anchored-bundle'])
  911. expect(manifest.dsh.profile.bundles).toContain('anchored-bundle')
  912. const removed = await runBuiltBin(
  913. ['plugin', '--profile', 'anchor', 'remove', 'anchored-bundle'],
  914. { DSH_HOME: home },
  915. checkout,
  916. )
  917. expect(removed.code).toBe(0)
  918. const afterRemove = JSON.parse(
  919. readFileSync(join(home, 'profiles', 'anchor', 'package.json'), 'utf8'),
  920. ) as {
  921. dependencies?: Record<string, string>
  922. dsh: { profile: { bundles: string[] } }
  923. }
  924. expect(Object.keys(afterRemove.dependencies ?? {})).toEqual([])
  925. expect(afterRemove.dsh.profile.bundles).not.toContain('anchored-bundle')
  926. } finally {
  927. rmSync(home, { recursive: true, force: true })
  928. rmSync(checkout, { recursive: true, force: true })
  929. }
  930. }, SPAWN_TIMEOUT_MS * 2 + 30_000)
  931. it('activates a dependency that gained dsh.bundle in a later update', async () => {
  932. // Reconcile runs against the INSTALLED state on every successful pnpm
  933. // run, so `update` (not only `add`) activates a package whose newer
  934. // version declares dsh.bundle. Simulated without a registry: hand-place
  935. // the installed package, flip its manifest, and run a benign pnpm verb.
  936. const home = mkdtempSync(join(tmpdir(), 'dsh-plugin-update-'))
  937. try {
  938. const profileDir = join(home, 'profiles', 'up')
  939. const installed = join(profileDir, 'node_modules', 'late-bundle')
  940. mkdirSync(installed, { recursive: true })
  941. writeFileSync(join(profileDir, 'package.json'), JSON.stringify({
  942. name: 'dsh-profile-up',
  943. private: true,
  944. dependencies: { 'late-bundle': 'file:./late-bundle' },
  945. dsh: { profile: { bundles: ['@deepseek-ai/dsh-base'] } },
  946. }))
  947. writeFileSync(join(profileDir, 'cordis.patch.yml'), '[]\n')
  948. // v1: no dsh manifest — a plain dependency.
  949. writeFileSync(join(installed, 'package.json'), JSON.stringify({ name: 'late-bundle', version: '1.0.0' }))
  950. const first = await runBuiltBin(['plugin', '--profile', 'up', 'root'], { DSH_HOME: home })
  951. expect(first.code).toBe(0)
  952. let manifest = JSON.parse(readFileSync(join(profileDir, 'package.json'), 'utf8')) as { dsh: { profile: { bundles: string[] } } }
  953. expect(manifest.dsh.profile.bundles).toEqual(['@deepseek-ai/dsh-base'])
  954. // v2: the installed package now declares dsh.bundle (an update landed).
  955. writeFileSync(join(installed, 'package.json'), JSON.stringify({
  956. name: 'late-bundle', version: '2.0.0', dsh: { bundle: { patch: './cordis.patch.yml' } },
  957. }))
  958. writeFileSync(join(installed, 'cordis.patch.yml'), '[]\n')
  959. const second = await runBuiltBin(['plugin', '--profile', 'up', 'root'], { DSH_HOME: home })
  960. expect(second.code).toBe(0)
  961. manifest = JSON.parse(readFileSync(join(profileDir, 'package.json'), 'utf8')) as { dsh: { profile: { bundles: string[] } } }
  962. expect(manifest.dsh.profile.bundles).toEqual(['@deepseek-ai/dsh-base', 'late-bundle'])
  963. } finally {
  964. rmSync(home, { recursive: true, force: true })
  965. }
  966. }, SPAWN_TIMEOUT_MS * 2 + 30_000)
  967. describe('config dump', () => {
  968. let home: string
  969. beforeEach(() => { home = mkdtempSync(join(tmpdir(), 'dsh-dump-bin-')) })
  970. afterEach(() => { rmSync(home, { recursive: true, force: true }) })
  971. it('prints the web profile bundle layers without a user layer', async () => {
  972. const { stdout, code, stderr } = await runBuiltBin(['--profile', 'web', '--dump-default-config'], { DSH_HOME: home })
  973. expect(code).toBe(0)
  974. expect(stderr).toBe('')
  975. expect(stdout).toContain("name: '@deepseek-ai/dsh-agent-loop'")
  976. expect(stdout).toContain('agents: []')
  977. expect(stdout).toContain('# == @deepseek-ai/dsh-base')
  978. expect(stdout).toContain("name: '@deepseek-ai/dsh-host-webserver'")
  979. expect(existsSync(join(home, 'profiles', 'node_modules'))).toBe(false)
  980. }, SPAWN_TIMEOUT_MS + 30_000)
  981. it('creates a custom profile from a shipped template before printing it', async () => {
  982. const { stdout, code, stderr } = await runBuiltBin(
  983. ['--profile', 'rescue', '--from-default-profile', 'web', '--dump-default-config'],
  984. { DSH_HOME: home },
  985. )
  986. expect(code).toBe(0)
  987. expect(stderr).toBe('')
  988. expect(stdout).toContain('# == @deepseek-ai/dsh-web-app')
  989. expect(existsSync(join(home, 'profiles', 'rescue', 'package.json'))).toBe(true)
  990. }, SPAWN_TIMEOUT_MS + 30_000)
  991. it('rejects an unknown source before creating the target profile', async () => {
  992. const { stdout, code, stderr } = await runBuiltBin(
  993. ['--profile', 'rescue', '--from-default-profile', 'unknown', '--dump-default-config'],
  994. { DSH_HOME: home },
  995. )
  996. expect(code).toBe(1)
  997. expect(stdout).toBe('')
  998. expect(stderr).toContain('unknown default profile "unknown"')
  999. expect(stderr).toContain('"web"')
  1000. expect(existsSync(join(home, 'profiles', 'rescue'))).toBe(false)
  1001. }, SPAWN_TIMEOUT_MS + 30_000)
  1002. it('prints the headless profile without Host or browser layers', async () => {
  1003. const { stdout, code, stderr } = await runBuiltBin(
  1004. ['--profile', 'headless', '--dump-default-config'],
  1005. { DSH_HOME: home },
  1006. )
  1007. expect(code).toBe(0)
  1008. expect(stderr).toBe('')
  1009. expect(stdout).toContain("name: '@deepseek-ai/dsh-headless'")
  1010. expect(stdout).not.toMatch(/name: '@deepseek-ai\/dsh-host-/)
  1011. expect(stdout).not.toContain("name: '@deepseek-ai/dsh-web-app'")
  1012. expect(stdout).not.toMatch(/name: '@deepseek-ai\/dsh-client-/)
  1013. }, SPAWN_TIMEOUT_MS + 30_000)
  1014. it('prints the exact standalone sdk-minimal tree without dsh-base', async () => {
  1015. const { stdout, code, stderr } = await runBuiltBin(
  1016. ['--profile', 'sdk-minimal', '--dump-default-config'],
  1017. { DSH_HOME: home },
  1018. )
  1019. expect(code).toBe(0)
  1020. expect(stderr).toBe('')
  1021. const rows = yaml.load(stdout, { schema: entryListSchema }) as Array<{ id?: string; name?: string }>
  1022. expect(rows.map(row => [row.id, row.name])).toEqual([
  1023. ['sdk-app-startup', '@deepseek-ai/dsh-sdk-app'],
  1024. ['sdk-jsonrpc-server', '@deepseek-ai/dsh-sdk-jsonrpc-server'],
  1025. ['deepseek-llm-api-extensions', '@deepseek-ai/dsh-deepseek-llm-api-extensions'],
  1026. ['session-log-deepseek', '@deepseek-ai/dsh-session-log-deepseek'],
  1027. ['plugin-package-inventory-deepseek', '@deepseek-ai/dsh-plugin-package-inventory-deepseek'],
  1028. ['llm-deepseek', '@deepseek-ai/dsh-llm-deepseek'],
  1029. ['sandbox', '@deepseek-ai/dsh-sandbox-local'],
  1030. ['session-projection', '@deepseek-ai/dsh-session-projection'],
  1031. ['sandbox-policy', '@deepseek-ai/dsh-sandbox-policy'],
  1032. ['subprocess', '@deepseek-ai/dsh-subprocess-local'],
  1033. ['pty', '@deepseek-ai/dsh-terminal'],
  1034. ['terminal-bash', '@deepseek-ai/dsh-terminal-bash'],
  1035. ['terminal-pwsh', '@deepseek-ai/dsh-terminal-bash'],
  1036. ['timer', '@deepseek-ai/cordis-plugin-timer'],
  1037. ['llm', '@deepseek-ai/dsh-llm'],
  1038. ['session', '@deepseek-ai/dsh-session'],
  1039. ['session-title', '@deepseek-ai/dsh-session-title'],
  1040. ['system-prompt', '@deepseek-ai/dsh-system-prompt'],
  1041. ['tools', '@deepseek-ai/dsh-tools'],
  1042. ['agent', '@deepseek-ai/dsh-agent'],
  1043. ['llm-retry', '@deepseek-ai/dsh-llm-retry'],
  1044. ['jobs', '@deepseek-ai/dsh-jobs-local'],
  1045. ['invariants', '@deepseek-ai/dsh-invariants'],
  1046. ['session-invariant', '@deepseek-ai/dsh-session/invariant'],
  1047. ['agent-invariant', '@deepseek-ai/dsh-agent/invariant'],
  1048. ['scope-invariant', '@deepseek-ai/dsh-scope/invariant'],
  1049. ['agent-loop-invariant', '@deepseek-ai/dsh-agent-loop/invariant'],
  1050. ['agent-loop', '@deepseek-ai/dsh-agent-loop'],
  1051. ['persistent-bash', '@deepseek-ai/dsh-tool-bash-persistent'],
  1052. ['persistent-pwsh', '@deepseek-ai/dsh-tool-pwsh-persistent'],
  1053. ['sessions', '@deepseek-ai/dsh-session-persistence-jsonl'],
  1054. ])
  1055. expect(stdout).toContain('# == @deepseek-ai/dsh-sdk-minimal')
  1056. expect(stdout).not.toContain('@deepseek-ai/dsh-base')
  1057. expect(stdout).not.toContain('@deepseek-ai/dsh-web-app')
  1058. }, SPAWN_TIMEOUT_MS * 2 + 30_000)
  1059. it('composes the profile user layer and a --patch overlay in order', async () => {
  1060. // Auto-init the web profile first, then write its user layer.
  1061. const init = await runBuiltBin(['--profile', 'web', '--dump-default-config'], { DSH_HOME: home })
  1062. expect(init.code).toBe(0)
  1063. const profilePatch = join(home, 'profiles', 'web', 'cordis.patch.yml')
  1064. writeFileSync(profilePatch, [
  1065. '- id: agent-loop',
  1066. ' config:',
  1067. ' agents:',
  1068. ' - id: personal',
  1069. ' provider: personal-provider',
  1070. ' model: personal-model',
  1071. '- id: absent-row',
  1072. ' config:',
  1073. ' x: 1',
  1074. '',
  1075. ].join('\n'))
  1076. const overlay = join(home, 'overlay.cordis.yml')
  1077. writeFileSync(overlay, [
  1078. '- id: agent-loop',
  1079. ' config:',
  1080. ' agents:',
  1081. ' - id: configured',
  1082. ' provider: configured-provider',
  1083. ' model: configured-model',
  1084. '',
  1085. ].join('\n'))
  1086. const { stdout, code, stderr } = await runBuiltBin(
  1087. ['--profile', 'web', '--patch', overlay, '--dump-config'],
  1088. { DSH_HOME: home },
  1089. )
  1090. expect(code).toBe(0)
  1091. expect(stdout).toContain('provider: configured-provider')
  1092. expect(stdout).not.toContain('personal-provider')
  1093. // Both layers patched the row; the comment lists them in application order.
  1094. expect(stdout).toContain(`patched by ${profilePatch}, ${overlay}`)
  1095. expect(stderr).toContain('patch: entry "absent-row" not found')
  1096. }, SPAWN_TIMEOUT_MS * 2 + 30_000)
  1097. })
  1098. })