built-bin.e2e.ts 54 KB

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