built-bin.e2e.ts 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024
  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 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 through the sdk profile and exits after shutdown', async () => {
  408. const home = mkdtempSync(join(tmpdir(), 'dsh-built-sdk-'))
  409. const child = execa(process.execPath, [dshBin, '--profile', 'sdk'], {
  410. cwd: home,
  411. reject: false,
  412. timeout: SPAWN_TIMEOUT_MS,
  413. killSignal: 'SIGKILL',
  414. env: {
  415. ...process.env,
  416. DSH_HOME: home,
  417. DSH_TELEMETRY_DISABLED: '1',
  418. DEEPSEEK_API_KEY: 'built-sdk-profile-no-call',
  419. },
  420. extendEnv: false,
  421. })
  422. const stdoutLines = createInterface({ input: child.stdout, crlfDelay: Infinity })[Symbol.asyncIterator]()
  423. let stderr = ''
  424. child.stderr.on('data', (chunk: Buffer) => { stderr += chunk.toString('utf8') })
  425. const response = async (id: number): Promise<Record<string, unknown>> => {
  426. for (;;) {
  427. const line = await stdoutLines.next()
  428. if (line.done) throw new Error(`SDK profile stdout closed before response ${String(id)}; stderr=${stderr}`)
  429. let value: Record<string, unknown>
  430. try {
  431. value = JSON.parse(line.value) as Record<string, unknown>
  432. } catch {
  433. throw new Error(`SDK profile wrote non-JSON stdout: ${line.value}`)
  434. }
  435. if (value.id === id) return value
  436. }
  437. }
  438. try {
  439. child.stdin.write(`${JSON.stringify({
  440. jsonrpc: '2.0',
  441. id: 1,
  442. method: 'initialize',
  443. params: { cwd: home, provider: 'deepseek-official', model: 'deepseek-v4-flash' },
  444. })}\n`)
  445. expect(await response(1)).toMatchObject({
  446. jsonrpc: '2.0',
  447. id: 1,
  448. result: { serverInfo: { name: 'deepseek-harness-sdk-runtime' } },
  449. })
  450. child.stdin.write(`${JSON.stringify({ jsonrpc: '2.0', id: 2, method: 'shutdown' })}\n`)
  451. expect(await response(2)).toEqual({ jsonrpc: '2.0', id: 2, result: {} })
  452. const result = await child
  453. expect(result.exitCode, `signal=${String(result.signal)}; stderr=${stderr}`).toBe(0)
  454. expect(stderr).toBe('')
  455. } finally {
  456. child.kill('SIGKILL')
  457. await child
  458. rmSync(home, { recursive: true, force: true })
  459. }
  460. }, SPAWN_TIMEOUT_MS + 30_000)
  461. it('runs a mock-backed ACP turn through the acp profile and exits on disconnect', async () => {
  462. const apiKey = 'built-acp-profile-key'
  463. const server = await startMockLlmServer({
  464. sequence: ['success'],
  465. apiKey,
  466. successText: 'ACP BUILT PROFILE OK',
  467. })
  468. const home = mkdtempSync(join(tmpdir(), 'dsh-built-acp-'))
  469. const child = execa(process.execPath, [dshBin, '--profile', 'acp'], {
  470. cwd: home,
  471. reject: false,
  472. timeout: SPAWN_TIMEOUT_MS,
  473. killSignal: 'SIGKILL',
  474. env: {
  475. ...process.env,
  476. DSH_HOME: home,
  477. DSH_TELEMETRY_DISABLED: '1',
  478. DEEPSEEK_API_KEY: apiKey,
  479. DEEPSEEK_BASE_URL: server.baseURL,
  480. DSH_PERMISSION_MODE: 'danger-full-access',
  481. },
  482. extendEnv: false,
  483. })
  484. const rawOut: string[] = []
  485. const passthrough = new Readable({ read() {} })
  486. child.stdout.on('data', (chunk: Buffer) => {
  487. rawOut.push(chunk.toString('utf8'))
  488. passthrough.push(chunk)
  489. })
  490. child.stdout.on('end', () => { passthrough.push(null) })
  491. const stream = ndJsonStream(
  492. Writable.toWeb(child.stdin) as WritableStream<Uint8Array>,
  493. Readable.toWeb(passthrough) as ReadableStream<Uint8Array>,
  494. )
  495. const updates: SessionNotification['update'][] = []
  496. const clientApp = createAcpClientApp({ name: 'dsh-built-acp-profile' })
  497. .onNotification(methods.client.session.update, ({ params }) => {
  498. updates.push(params.update)
  499. return Promise.resolve()
  500. })
  501. .onRequest(methods.client.session.requestPermission, () => {
  502. return Promise.resolve({ outcome: { outcome: 'cancelled' } })
  503. })
  504. const client = clientApp.connect(stream).agent
  505. try {
  506. const initialized = await client.request(methods.agent.initialize, {
  507. protocolVersion: PROTOCOL_VERSION,
  508. clientCapabilities: {},
  509. })
  510. expect(initialized.agentInfo).toMatchObject({ name: 'deepseek-harness-acp' })
  511. expect(initialized.agentCapabilities).toEqual({
  512. mcpCapabilities: { http: true },
  513. promptCapabilities: { image: false, audio: false, embeddedContext: false },
  514. sessionCapabilities: { close: {}, list: {}, resume: {} },
  515. })
  516. expect('_meta' in initialized).toBe(false)
  517. const session = await client.request(methods.agent.session.new, { cwd: home, mcpServers: [] })
  518. expect(session.sessionId).toBeTruthy()
  519. expect(await client.request(methods.agent.session.prompt, {
  520. sessionId: session.sessionId,
  521. prompt: [{ type: 'text', text: 'reply from the built ACP profile' }],
  522. })).toEqual({ stopReason: 'end_turn' })
  523. expect(updates).toContainEqual(expect.objectContaining({
  524. sessionUpdate: 'agent_message_chunk',
  525. content: { type: 'text', text: 'ACP BUILT PROFILE OK' },
  526. }))
  527. const message = updates.find(update => update.sessionUpdate === 'agent_message_chunk')
  528. expect(message !== undefined && 'messageId' in message && typeof message.messageId === 'string').toBe(true)
  529. expect(server.requests).toHaveLength(1)
  530. child.stdin.end()
  531. const result = await child
  532. expect(result.exitCode, `signal=${String(result.signal)}; stderr=${result.stderr}`).toBe(0)
  533. expect(result.stderr).toBe('')
  534. for (const line of rawOut.join('').split('\n').filter(value => value.trim() !== '')) {
  535. expect(() => JSON.parse(line) as unknown).not.toThrow()
  536. }
  537. } finally {
  538. child.kill('SIGKILL')
  539. await child
  540. await server.close()
  541. rmSync(home, { recursive: true, force: true })
  542. }
  543. }, SPAWN_TIMEOUT_MS + 30_000)
  544. it('runs the headless profile through its app-owned task positional', async () => {
  545. const apiKey = 'built-dsh-headless-key'
  546. const server = await startMockLlmServer({
  547. sequence: ['reasoning_success'],
  548. apiKey,
  549. reasoningText: 'Inspecting the published entry.',
  550. successText: 'published headless profile reached the mock',
  551. })
  552. const home = mkdtempSync(join(tmpdir(), 'dsh-built-headless-'))
  553. try {
  554. const result = await runBuiltBin(['--profile', 'headless', 'answer', 'from', 'the', 'published', 'entry'], {
  555. DSH_HOME: home,
  556. DSH_TELEMETRY_DISABLED: '1',
  557. DEEPSEEK_API_KEY: apiKey,
  558. DEEPSEEK_BASE_URL: server.baseURL,
  559. })
  560. expect(result.code, result.stderr).toBe(0)
  561. expect(result.stdout).toBe('published headless profile reached the mock')
  562. expect(result.stderr).toBe('dsh: reasoning:\nInspecting the published entry.')
  563. expect(server.requests.length).toBeGreaterThan(0)
  564. expect(server.requests.every(request => request.path === '/chat/completions')).toBe(true)
  565. expect(JSON.stringify(server.requests.map(request => request.body))).toContain('answer from the published entry')
  566. } finally {
  567. await server.close()
  568. rmSync(home, { recursive: true, force: true })
  569. }
  570. }, SPAWN_TIMEOUT_MS + 30_000)
  571. it('does not load a project environment for --version', async () => {
  572. const project = mkdtempSync(join(tmpdir(), 'dsh-version-project-'))
  573. writeFileSync(join(project, '.env'), 'PATH=/project-only-path\n')
  574. try {
  575. const result = await runBuiltBin(['--version'], {}, project)
  576. expect(result).toEqual({ code: 0, stdout: cliVersion, stderr: '' })
  577. } finally {
  578. rmSync(project, { recursive: true, force: true })
  579. }
  580. })
  581. it('fails loud on a nonexistent profile with the plugin-command hint', async () => {
  582. const home = mkdtempSync(join(tmpdir(), 'dsh-missing-profile-'))
  583. try {
  584. const result = await runBuiltBin(['--profile', 'nope'], { DSH_HOME: home })
  585. expect(result.code).toBe(1)
  586. expect(result.stderr).toContain('profile "nope" does not exist')
  587. expect(result.stderr).toContain('dsh plugin --profile nope add')
  588. } finally {
  589. rmSync(home, { recursive: true, force: true })
  590. }
  591. }, SPAWN_TIMEOUT_MS + 30_000)
  592. it('uses the launching endpoint and managed credential through the published entry', async () => {
  593. const apiKey = 'built-home-layer-key'
  594. const server = await startMockLlmServer({
  595. sequence: ['success'],
  596. apiKey,
  597. successText: 'launching endpoint reached the mock',
  598. })
  599. const home = mkdtempSync(join(tmpdir(), 'dsh-home-environment-'))
  600. const project = mkdtempSync(join(tmpdir(), 'dsh-home-project-'))
  601. writeFileSync(join(home, '.credentials.yaml'), `version: 1\nrefs:\n DEEPSEEK_API_KEY: ${apiKey}\n`, { mode: 0o600 })
  602. createEnvironmentProbeProfile(home, project)
  603. try {
  604. const result = await runBuiltBin(
  605. ['--profile', 'environment-probe'],
  606. {
  607. DSH_HOME: home,
  608. DSH_TELEMETRY_DISABLED: '1',
  609. DEEPSEEK_API_KEY: undefined,
  610. DEEPSEEK_BASE_URL: server.baseURL,
  611. },
  612. project,
  613. )
  614. expect(
  615. result.code,
  616. `${result.stderr}\nstdout:\n${result.stdout}\nmock requests: ${String(server.requests.length)}`,
  617. ).toBe(0)
  618. expect(result.stdout).toBe('launching endpoint reached the mock')
  619. expect(result.stdout).not.toContain(apiKey)
  620. expect(result.stderr).not.toContain(apiKey)
  621. expect(server.requests).toHaveLength(1)
  622. expect(server.requests[0]?.path).toBe('/chat/completions')
  623. expect(server.requests[0]?.headers.authorization).toBe(`Bearer ${apiKey}`)
  624. expect(JSON.stringify(server.requests[0]?.body)).not.toContain(apiKey)
  625. } finally {
  626. await server.close()
  627. rmSync(home, { recursive: true, force: true })
  628. rmSync(project, { recursive: true, force: true })
  629. }
  630. }, SPAWN_TIMEOUT_MS + 30_000)
  631. it('reports a patch-overlay boot failure without hanging', async () => {
  632. // The HMR main watcher's initial scan once refreshed the include
  633. // mid-initial-apply, deadlocking the failing apply's rollback against the
  634. // refresh drain: dsh exited 13 with no diagnostic instead of settling
  635. // ([Agent Note](../../../.agents/notes/implemented/bug-fix/2026-08-03-hmr-initial-scan-boot-deadlock.md)).
  636. const home = mkdtempSync(join(tmpdir(), 'dsh-invalid-patch-'))
  637. try {
  638. const result = await runBuiltBin(['--profile', 'web', '--patch', invalidProvider], {
  639. DSH_HOME: home,
  640. DEEPSEEK_API_KEY: 'keyless-invalid-config',
  641. DSH_TELEMETRY_DISABLED: '1',
  642. })
  643. expect(result.code).toBe(1)
  644. expect(result.stdout).toBe('')
  645. expect(result.stderr).toContain('llm-pi-ai')
  646. } finally {
  647. rmSync(home, { recursive: true, force: true })
  648. }
  649. }, SPAWN_TIMEOUT_MS + 30_000)
  650. it('lets a profile without a parser ignore app arguments and dispose on a startup-time signal', async () => {
  651. const fixture = createProfileLifecycleFixture()
  652. const child = startProfileLifecycle(fixture, ['--unclaimed'])
  653. try {
  654. await waitForFile(fixture.ready)
  655. requestProfileShutdown(child, fixture)
  656. const result = await child
  657. expect(result.exitCode, `${result.stderr}\nstdout:\n${result.stdout}\nsignal: ${String(result.signal)}`).toBe(0)
  658. expect(result.signal).toBeUndefined()
  659. expect(existsSync(fixture.disposed)).toBe(true)
  660. } finally {
  661. child.kill('SIGKILL')
  662. rmSync(fixture.home, { recursive: true, force: true })
  663. }
  664. }, SPAWN_TIMEOUT_MS + 30_000)
  665. it('fully settles a custom profile, hot-reloads its patch layer with removal reverting, and disposes on a signal', async () => {
  666. const fixture = createProfileLifecycleFixture()
  667. const child = startProfileLifecycle(fixture)
  668. const profilePatch = join(fixture.home, 'profiles', 'lifecycle', 'cordis.patch.yml')
  669. const configFile = join(fixture.home, 'config-echo')
  670. try {
  671. await waitForFile(fixture.settled)
  672. // The live profile layer: even without an hmr row in the composition,
  673. // the launcher mounts a config-only watcher, so an edited
  674. // cordis.patch.yml lands in the running tree (the reload disposes the
  675. // patched row's old fiber — observable as the disposed marker — and
  676. // mounts the new config, which echoes its generation and re-writes the
  677. // ready marker).
  678. rmSync(fixture.ready)
  679. writeFileSync(profilePatch, [
  680. '- id: profile-lifecycle-fixture',
  681. ' config:',
  682. ' generation: 2',
  683. '',
  684. ].join('\n'))
  685. await waitForFile(fixture.ready)
  686. expect(readFileSync(configFile, 'utf8')).toBe('2')
  687. // Removal reverts: the bundle's inserted row must return to its own
  688. // default config, not keep the removed override — the insert-aliasing
  689. // regression (a shared patch object mutated in place by a former
  690. // generation would make this impossible).
  691. rmSync(fixture.ready)
  692. writeFileSync(profilePatch, '[]\n')
  693. await waitForFile(fixture.ready)
  694. expect(readFileSync(configFile, 'utf8')).toBe('bundle-default')
  695. // The home-level user layer ($DSH_HOME/cordis.patch.yml) is live too
  696. // and outranks the per-profile layer.
  697. rmSync(fixture.ready)
  698. writeFileSync(join(fixture.home, 'cordis.patch.yml'), [
  699. '- id: profile-lifecycle-fixture',
  700. ' config:',
  701. ' generation: home',
  702. '',
  703. ].join('\n'))
  704. await waitForFile(fixture.ready)
  705. expect(readFileSync(configFile, 'utf8')).toBe('home')
  706. requestProfileShutdown(child, fixture)
  707. const result = await child
  708. expect(result.exitCode, `${result.stderr}\nstdout:\n${result.stdout}\nsignal: ${String(result.signal)}`).toBe(0)
  709. expect(result.signal).toBeUndefined()
  710. expect(existsSync(fixture.disposed)).toBe(true)
  711. } finally {
  712. child.kill('SIGKILL')
  713. rmSync(fixture.home, { recursive: true, force: true })
  714. }
  715. }, SPAWN_TIMEOUT_MS + 30_000)
  716. it('hands the app arguments to the profile, which applies them before its rows start', async () => {
  717. const fixture = createStartupFixture()
  718. const child = startStartupProfile(fixture, ['--generation', 'flagged'])
  719. try {
  720. await waitForFile(fixture.ready)
  721. // The consumer started once, already carrying the flag value: the
  722. // launcher never saw --generation, and the app provider resolved it first.
  723. expect(readFileSync(fixture.echo, 'utf8')).toBe('flagged')
  724. requestProfileShutdown(child, fixture)
  725. expect((await child).exitCode).toBe(0)
  726. } finally {
  727. child.kill('SIGKILL')
  728. rmSync(fixture.home, { recursive: true, force: true })
  729. }
  730. }, SPAWN_TIMEOUT_MS + 30_000)
  731. it('starts a consumer on its composed value when the invocation carries no app arguments', async () => {
  732. const fixture = createStartupFixture()
  733. const child = startStartupProfile(fixture, [])
  734. try {
  735. await waitForFile(fixture.ready)
  736. expect(readFileSync(fixture.echo, 'utf8')).toBe('bundle-default')
  737. requestProfileShutdown(child, fixture)
  738. expect((await child).exitCode).toBe(0)
  739. } finally {
  740. child.kill('SIGKILL')
  741. rmSync(fixture.home, { recursive: true, force: true })
  742. }
  743. }, SPAWN_TIMEOUT_MS + 30_000)
  744. it('keeps the app arguments across a user patch reload', async () => {
  745. // A live edit recomposes every row while the provider service remains
  746. // active, so each config expression reads the same invocation value (a
  747. // served port does not move back to its composed fallback).
  748. const fixture = createStartupFixture()
  749. const profilePatch = join(fixture.home, 'profiles', 'startup', 'cordis.patch.yml')
  750. const child = startStartupProfile(fixture, ['--generation', 'flagged'])
  751. try {
  752. // Both rows: the waiting one carries the flag value, and the witness is
  753. // what a reload will re-mount. They start independently, so neither
  754. // marker implies the other.
  755. await waitForFile(fixture.ready)
  756. await waitForFile(fixture.witness)
  757. expect(readFileSync(fixture.echo, 'utf8')).toBe('flagged')
  758. // An edit to an unrelated row: the witness re-mounts, which is how this
  759. // test knows the whole tree was recomposed.
  760. rmSync(fixture.witness)
  761. writeFileSync(profilePatch, [
  762. '- id: reload-witness',
  763. ' config:',
  764. ' generation: reloaded',
  765. '',
  766. ].join('\n'))
  767. await waitForFile(fixture.witness)
  768. expect(readFileSync(fixture.witness, 'utf8')).toBe('reloaded')
  769. expect(readFileSync(fixture.echo, 'utf8')).toBe('flagged')
  770. requestProfileShutdown(child, fixture)
  771. expect((await child).exitCode).toBe(0)
  772. } finally {
  773. child.kill('SIGKILL')
  774. rmSync(fixture.home, { recursive: true, force: true })
  775. }
  776. }, SPAWN_TIMEOUT_MS + 30_000)
  777. it("prints the app's own help, starts none of its rows, and exits", async () => {
  778. const fixture = createStartupFixture()
  779. try {
  780. const result = await startStartupProfile(fixture, ['--help'])
  781. expect(result.exitCode).toBe(0)
  782. expect(result.stdout).toContain('Usage: fixture')
  783. expect(result.stdout).toContain('--generation')
  784. expect(existsSync(fixture.ready)).toBe(false)
  785. } finally {
  786. rmSync(fixture.home, { recursive: true, force: true })
  787. }
  788. }, SPAWN_TIMEOUT_MS + 30_000)
  789. it('anchors a relative add spec to the invoking directory, not the profile', async () => {
  790. // `dsh plugin --profile x add .` from a plugin checkout must install THAT
  791. // checkout — pnpm's cwd is the profile directory, so an un-anchored `.`
  792. // would self-link the profile.
  793. const home = mkdtempSync(join(tmpdir(), 'dsh-plugin-anchor-'))
  794. const checkout = mkdtempSync(join(tmpdir(), 'dsh-plugin-checkout-'))
  795. try {
  796. writeFileSync(join(checkout, 'package.json'), JSON.stringify({
  797. name: 'anchored-bundle',
  798. version: '1.0.0',
  799. dsh: { bundle: { patch: './cordis.patch.yml' } },
  800. }))
  801. writeFileSync(join(checkout, 'cordis.patch.yml'), '[]\n')
  802. const result = await execa(process.execPath, [dshBin, 'plugin', '--profile', 'anchor', 'add', '.'], {
  803. cwd: checkout,
  804. input: '',
  805. timeout: SPAWN_TIMEOUT_MS,
  806. killSignal: 'SIGKILL',
  807. reject: false,
  808. env: { DSH_HOME: home },
  809. })
  810. expect(result.exitCode).toBe(0)
  811. const manifest = JSON.parse(readFileSync(join(home, 'profiles', 'anchor', 'package.json'), 'utf8')) as {
  812. dependencies: Record<string, string>
  813. dsh: { profile: { bundles: string[] } }
  814. }
  815. expect(Object.keys(manifest.dependencies)).toEqual(['anchored-bundle'])
  816. expect(manifest.dsh.profile.bundles).toContain('anchored-bundle')
  817. const removed = await runBuiltBin(
  818. ['plugin', '--profile', 'anchor', 'remove', 'anchored-bundle'],
  819. { DSH_HOME: home },
  820. checkout,
  821. )
  822. expect(removed.code).toBe(0)
  823. const afterRemove = JSON.parse(
  824. readFileSync(join(home, 'profiles', 'anchor', 'package.json'), 'utf8'),
  825. ) as {
  826. dependencies?: Record<string, string>
  827. dsh: { profile: { bundles: string[] } }
  828. }
  829. expect(Object.keys(afterRemove.dependencies ?? {})).toEqual([])
  830. expect(afterRemove.dsh.profile.bundles).not.toContain('anchored-bundle')
  831. } finally {
  832. rmSync(home, { recursive: true, force: true })
  833. rmSync(checkout, { recursive: true, force: true })
  834. }
  835. }, SPAWN_TIMEOUT_MS * 2 + 30_000)
  836. it('activates a dependency that gained dsh.bundle in a later update', async () => {
  837. // Reconcile runs against the INSTALLED state on every successful pnpm
  838. // run, so `update` (not only `add`) activates a package whose newer
  839. // version declares dsh.bundle. Simulated without a registry: hand-place
  840. // the installed package, flip its manifest, and run a benign pnpm verb.
  841. const home = mkdtempSync(join(tmpdir(), 'dsh-plugin-update-'))
  842. try {
  843. const profileDir = join(home, 'profiles', 'up')
  844. const installed = join(profileDir, 'node_modules', 'late-bundle')
  845. mkdirSync(installed, { recursive: true })
  846. writeFileSync(join(profileDir, 'package.json'), JSON.stringify({
  847. name: 'dsh-profile-up',
  848. private: true,
  849. dependencies: { 'late-bundle': 'file:./late-bundle' },
  850. dsh: { profile: { bundles: ['@deepseek-ai/dsh-base'] } },
  851. }))
  852. writeFileSync(join(profileDir, 'cordis.patch.yml'), '[]\n')
  853. // v1: no dsh manifest — a plain dependency.
  854. writeFileSync(join(installed, 'package.json'), JSON.stringify({ name: 'late-bundle', version: '1.0.0' }))
  855. const first = await runBuiltBin(['plugin', '--profile', 'up', 'root'], { DSH_HOME: home })
  856. expect(first.code).toBe(0)
  857. let manifest = JSON.parse(readFileSync(join(profileDir, 'package.json'), 'utf8')) as { dsh: { profile: { bundles: string[] } } }
  858. expect(manifest.dsh.profile.bundles).toEqual(['@deepseek-ai/dsh-base'])
  859. // v2: the installed package now declares dsh.bundle (an update landed).
  860. writeFileSync(join(installed, 'package.json'), JSON.stringify({
  861. name: 'late-bundle', version: '2.0.0', dsh: { bundle: { patch: './cordis.patch.yml' } },
  862. }))
  863. writeFileSync(join(installed, 'cordis.patch.yml'), '[]\n')
  864. const second = await runBuiltBin(['plugin', '--profile', 'up', 'root'], { DSH_HOME: home })
  865. expect(second.code).toBe(0)
  866. manifest = JSON.parse(readFileSync(join(profileDir, 'package.json'), 'utf8')) as { dsh: { profile: { bundles: string[] } } }
  867. expect(manifest.dsh.profile.bundles).toEqual(['@deepseek-ai/dsh-base', 'late-bundle'])
  868. } finally {
  869. rmSync(home, { recursive: true, force: true })
  870. }
  871. }, SPAWN_TIMEOUT_MS * 2 + 30_000)
  872. describe('config dump', () => {
  873. let home: string
  874. beforeEach(() => { home = mkdtempSync(join(tmpdir(), 'dsh-dump-bin-')) })
  875. afterEach(() => { rmSync(home, { recursive: true, force: true }) })
  876. it('prints the web profile bundle layers without a user layer', async () => {
  877. const { stdout, code, stderr } = await runBuiltBin(['--profile', 'web', '--dump-default-config'], { DSH_HOME: home })
  878. expect(code).toBe(0)
  879. expect(stderr).toBe('')
  880. expect(stdout).toContain("name: '@deepseek-ai/dsh-agent-loop'")
  881. expect(stdout).toContain('agents: []')
  882. expect(stdout).toContain('# == @deepseek-ai/dsh-base')
  883. expect(stdout).toContain("name: '@deepseek-ai/dsh-host-webserver'")
  884. expect(existsSync(join(home, 'profiles', 'node_modules'))).toBe(false)
  885. }, SPAWN_TIMEOUT_MS + 30_000)
  886. it('prints the headless profile without Host or browser layers', async () => {
  887. const { stdout, code, stderr } = await runBuiltBin(
  888. ['--profile', 'headless', '--dump-default-config'],
  889. { DSH_HOME: home },
  890. )
  891. expect(code).toBe(0)
  892. expect(stderr).toBe('')
  893. expect(stdout).toContain("name: '@deepseek-ai/dsh-headless'")
  894. expect(stdout).not.toMatch(/name: '@deepseek-ai\/dsh-host-/)
  895. expect(stdout).not.toContain("name: '@deepseek-ai/dsh-web-app'")
  896. expect(stdout).not.toMatch(/name: '@deepseek-ai\/dsh-client-/)
  897. }, SPAWN_TIMEOUT_MS + 30_000)
  898. it('prints the exact standalone sdk-minimal tree without dsh-base', async () => {
  899. const { stdout, code, stderr } = await runBuiltBin(
  900. ['--profile', 'sdk-minimal', '--dump-default-config'],
  901. { DSH_HOME: home },
  902. )
  903. expect(code).toBe(0)
  904. expect(stderr).toBe('')
  905. const rows = yaml.load(stdout, { schema: entryListSchema }) as Array<{ id?: string; name?: string }>
  906. expect(rows.map(row => [row.id, row.name])).toEqual([
  907. ['sdk-app-startup', '@deepseek-ai/dsh-sdk-app'],
  908. ['sdk-jsonrpc-server', '@deepseek-ai/dsh-sdk-jsonrpc-server'],
  909. ['deepseek-llm-api-extensions', '@deepseek-ai/dsh-deepseek-llm-api-extensions'],
  910. ['session-log-deepseek', '@deepseek-ai/dsh-session-log-deepseek'],
  911. ['plugin-package-inventory-deepseek', '@deepseek-ai/dsh-plugin-package-inventory-deepseek'],
  912. ['llm-deepseek', '@deepseek-ai/dsh-llm-deepseek'],
  913. ['sandbox', '@deepseek-ai/dsh-sandbox-local'],
  914. ['session-projection', '@deepseek-ai/dsh-session-projection'],
  915. ['sandbox-policy', '@deepseek-ai/dsh-sandbox-policy'],
  916. ['subprocess', '@deepseek-ai/dsh-subprocess-local'],
  917. ['pty', '@deepseek-ai/dsh-terminal'],
  918. ['terminal-bash', '@deepseek-ai/dsh-terminal-bash'],
  919. ['terminal-pwsh', '@deepseek-ai/dsh-terminal-bash'],
  920. ['fs-local', '@deepseek-ai/dsh-fs-local'],
  921. ['timer', '@deepseek-ai/cordis-plugin-timer'],
  922. ['llm', '@deepseek-ai/dsh-llm'],
  923. ['session', '@deepseek-ai/dsh-session'],
  924. ['session-title', '@deepseek-ai/dsh-session-title'],
  925. ['system-prompt', '@deepseek-ai/dsh-system-prompt'],
  926. ['tools', '@deepseek-ai/dsh-tools'],
  927. ['agent', '@deepseek-ai/dsh-agent'],
  928. ['llm-retry', '@deepseek-ai/dsh-llm-retry'],
  929. ['jobs', '@deepseek-ai/dsh-jobs-local'],
  930. ['invariants', '@deepseek-ai/dsh-invariants'],
  931. ['session-invariant', '@deepseek-ai/dsh-session/invariant'],
  932. ['agent-invariant', '@deepseek-ai/dsh-agent/invariant'],
  933. ['scope-invariant', '@deepseek-ai/dsh-scope/invariant'],
  934. ['agent-loop-invariant', '@deepseek-ai/dsh-agent-loop/invariant'],
  935. ['agent-loop', '@deepseek-ai/dsh-agent-loop'],
  936. ['persistent-bash', '@deepseek-ai/dsh-tool-bash-persistent'],
  937. ['persistent-pwsh', '@deepseek-ai/dsh-tool-pwsh-persistent'],
  938. ['str-replace-editor', '@deepseek-ai/dsh-tool-str-replace-editor'],
  939. ['sessions', '@deepseek-ai/dsh-session-persistence-jsonl'],
  940. ])
  941. expect(stdout).toContain('# == @deepseek-ai/dsh-sdk-minimal')
  942. expect(stdout).not.toContain('@deepseek-ai/dsh-base')
  943. expect(stdout).not.toContain('@deepseek-ai/dsh-web-app')
  944. }, SPAWN_TIMEOUT_MS * 2 + 30_000)
  945. it('composes the profile user layer and a --patch overlay in order', async () => {
  946. // Auto-init the web profile first, then write its user layer.
  947. const init = await runBuiltBin(['--profile', 'web', '--dump-default-config'], { DSH_HOME: home })
  948. expect(init.code).toBe(0)
  949. const profilePatch = join(home, 'profiles', 'web', 'cordis.patch.yml')
  950. writeFileSync(profilePatch, [
  951. '- id: agent-loop',
  952. ' config:',
  953. ' agents:',
  954. ' - id: personal',
  955. ' provider: personal-provider',
  956. ' model: personal-model',
  957. '- id: absent-row',
  958. ' config:',
  959. ' x: 1',
  960. '',
  961. ].join('\n'))
  962. const overlay = join(home, 'overlay.cordis.yml')
  963. writeFileSync(overlay, [
  964. '- id: agent-loop',
  965. ' config:',
  966. ' agents:',
  967. ' - id: configured',
  968. ' provider: configured-provider',
  969. ' model: configured-model',
  970. '',
  971. ].join('\n'))
  972. const { stdout, code, stderr } = await runBuiltBin(
  973. ['--profile', 'web', '--patch', overlay, '--dump-config'],
  974. { DSH_HOME: home },
  975. )
  976. expect(code).toBe(0)
  977. expect(stdout).toContain('provider: configured-provider')
  978. expect(stdout).not.toContain('personal-provider')
  979. // Both layers patched the row; the comment lists them in application order.
  980. expect(stdout).toContain(`patched by ${profilePatch}, ${overlay}`)
  981. expect(stderr).toContain('patch: entry "absent-row" not found')
  982. }, SPAWN_TIMEOUT_MS * 2 + 30_000)
  983. })
  984. })