built-bin.e2e.ts 42 KB

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