scripts.spec.ts 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669
  1. import { mkdtemp, mkdir, readFile, rm, symlink, writeFile } from 'node:fs/promises'
  2. import { tmpdir } from 'node:os'
  3. import { dirname, join } from 'node:path'
  4. import { PassThrough, Writable } from 'node:stream'
  5. import { fileURLToPath, pathToFileURL } from 'node:url'
  6. import { afterEach, describe, expect, expectTypeOf, it, vi } from 'vitest'
  7. import {
  8. HeadlessPromptPort,
  9. LocalPluginBlueprint,
  10. NpmPackageManager,
  11. SdkProject,
  12. featureId,
  13. createBuiltinRegistry,
  14. type CommandRunner,
  15. type NestedMultiSelectValue,
  16. type ProjectCreationRequest,
  17. type PromptPort,
  18. } from '@deepseek-ai/dsh-helper'
  19. import type {
  20. ConfirmPromptRequest,
  21. MultiSelectPromptRequest,
  22. NestedMultiSelectRequest,
  23. PromptOutcome,
  24. SecretPromptRequest,
  25. SelectPromptRequest,
  26. TextPromptRequest,
  27. } from '../../helper/src/questions/prompt-port.ts'
  28. import { runSDK, startSDK } from '@deepseek-ai/dsh-scripts'
  29. import { parseDshSdkArgs, parseSdkBootArgs } from '../src/args.ts'
  30. import { PluginBuild, ProjectBuild, runProjectBuild } from '../src/build.ts'
  31. import { runDshSdkCommand, type DshSdkCommandContext } from '../src/command.ts'
  32. import { runConfigCommand } from '../src/config.ts'
  33. import { ConfigWorkflow, type ConfigPlan } from '../src/config/config-workflow.ts'
  34. import { runCreatePluginCommand } from '../src/create-plugin.ts'
  35. import { reportCommandTelemetry, type CommandTelemetryEvent } from '../src/telemetry.ts'
  36. import { initialize, resolve as resolveLocalPlugin } from '../src/local-plugin-loader-hooks.ts'
  37. const temporary: string[] = []
  38. afterEach(async () => {
  39. await Promise.all(temporary.splice(0).map(path => rm(path, { recursive: true, force: true })))
  40. })
  41. class QueuePort implements PromptPort {
  42. readonly #answers: unknown[]
  43. constructor(answers: unknown[]) { this.#answers = [...answers] }
  44. next<T>(): Promise<PromptOutcome<T>> {
  45. return Promise.resolve({ status: 'answered', value: this.#answers.shift() as T })
  46. }
  47. text(_request: TextPromptRequest): Promise<PromptOutcome<string>> { return this.next() }
  48. secret(_request: SecretPromptRequest): Promise<PromptOutcome<string>> { return this.next() }
  49. select<T>(_request: SelectPromptRequest<T>): Promise<PromptOutcome<T>> { return this.next() }
  50. multiselect<T>(_request: MultiSelectPromptRequest<T>): Promise<PromptOutcome<readonly T[]>> { return this.next() }
  51. confirm(_request: ConfirmPromptRequest): Promise<PromptOutcome<boolean>> { return this.next() }
  52. nestedMultiselect<TValue, TChoice>(
  53. _request: NestedMultiSelectRequest<TValue, TChoice>,
  54. ): Promise<PromptOutcome<readonly NestedMultiSelectValue<TValue, TChoice>[]>> { return this.next() }
  55. }
  56. function outputBuffer(): { stream: Writable; read: () => string } {
  57. let text = ''
  58. return {
  59. stream: new Writable({ write(chunk, _encoding, callback) { text += String(chunk); callback() } }),
  60. read: () => text,
  61. }
  62. }
  63. function commandContext(cwd: string): DshSdkCommandContext & { readStdout: () => string; readStderr: () => string } {
  64. let stdout = ''
  65. let stderr = ''
  66. const stdin = Object.assign(new PassThrough(), { isTTY: true }) as unknown as NodeJS.ReadStream
  67. const output = Object.assign(new Writable({
  68. write(chunk, _encoding, callback) { stdout += String(chunk); callback() },
  69. }), { isTTY: true }) as unknown as NodeJS.WriteStream
  70. const error = new Writable({
  71. write(chunk, _encoding, callback) { stderr += String(chunk); callback() },
  72. }) as unknown as NodeJS.WriteStream
  73. return {
  74. cwd, stdin, stdout: output, stderr: error,
  75. readStdout: () => stdout,
  76. readStderr: () => stderr,
  77. }
  78. }
  79. function creation(
  80. extra: ProjectCreationRequest['features'] = [],
  81. localPlugins: readonly LocalPluginBlueprint[] = [],
  82. app: 'acp' | 'tui' | 'embed' = 'embed',
  83. ): ProjectCreationRequest {
  84. return {
  85. name: 'config-agent',
  86. description: 'config test',
  87. runtime: { model: 'deepseek-v4-flash' },
  88. packageManager: new NpmPackageManager('10.0.0'),
  89. releaseVersion: '0.0.1',
  90. features: [
  91. { id: featureId('provider'), options: ['deepseek'], secrets: { apiKey: 'key' } },
  92. { id: featureId('bash'), options: ['local'] },
  93. { id: featureId('app'), options: [app] },
  94. { id: featureId('persistence'), options: ['jsonl'] },
  95. ...extra,
  96. ],
  97. localPlugins,
  98. }
  99. }
  100. async function committedProject(
  101. extra: ProjectCreationRequest['features'] = [],
  102. localPlugins: readonly LocalPluginBlueprint[] = [],
  103. app: 'acp' | 'tui' | 'embed' = 'embed',
  104. ): Promise<SdkProject> {
  105. const root = await mkdtemp(join(tmpdir(), 'dsh-config-workflow-'))
  106. temporary.push(root)
  107. const request = creation(extra, localPlugins, app)
  108. const project = SdkProject.create(root, request)
  109. const registry = createBuiltinRegistry(project.profile)
  110. const edit = project.edit(registry)
  111. for (const item of request.features) edit.installFeature(registry.get(item.id), item)
  112. for (const plugin of localPlugins) edit.addPlugin(plugin)
  113. return (await edit.commit()).project
  114. }
  115. describe('Commander launcher arguments', () => {
  116. it('parses real subcommands and forwards arbitrary build options', () => {
  117. expect(parseDshSdkArgs([])).toMatchObject({ help: true })
  118. expect(parseDshSdkArgs(['start', 'index.js'])).toMatchObject({ command: 'start', target: 'index.js' })
  119. expect(parseDshSdkArgs(['dev'])).toEqual({ command: 'dev', forwarded: [], help: false })
  120. expect(parseDshSdkArgs(['build', '--watch', '--minify'])).toMatchObject({
  121. command: 'build', forwarded: ['--watch', '--minify'],
  122. })
  123. expect(parseDshSdkArgs(['start', 'index.js', '--', '--resume', 'session-1'])).toMatchObject({
  124. command: 'start', target: 'index.js', forwarded: ['--resume', 'session-1'],
  125. })
  126. expect(parseDshSdkArgs(['config'])).toMatchObject({ command: 'config' })
  127. expect(parseDshSdkArgs(['start'])).toEqual({ command: 'start', forwarded: [], help: false })
  128. expect(parseDshSdkArgs(['dev', 'index.ts'])).toMatchObject({ command: 'dev', target: 'index.ts' })
  129. expect(parseDshSdkArgs(['-h'])).toMatchObject({ help: true })
  130. expect(() => parseDshSdkArgs(['unknown'])).toThrow()
  131. expect(() => parseDshSdkArgs(['config', 'extra'])).toThrow()
  132. expect(() => parseDshSdkArgs(['config', '--', 'extra'])).toThrow('does not accept forwarded')
  133. expect(parseSdkBootArgs([
  134. '--model=mock', '--resume=session-1', '--custom=value', '--verbose', '--no-cache', '--max-depth=-1',
  135. ])).toEqual({
  136. model: 'mock', resume: 'session-1', custom: 'value', verbose: true, cache: false, 'max-depth': '-1',
  137. })
  138. })
  139. it('dispatches every command and maps failures to exit codes', async () => {
  140. const root = await mkdtemp(join(tmpdir(), 'dsh-command-'))
  141. temporary.push(root)
  142. const context = commandContext(root)
  143. const calls: unknown[] = []
  144. context.run = async (target, options) => { calls.push(['run', target, options]); return undefined }
  145. context.build = async (args, cwd) => { calls.push(['build', args, cwd]) }
  146. context.config = async () => { calls.push(['config']); return {} }
  147. await expect(runDshSdkCommand(['start', 'index.js', '--', '--resume', 'session-1'], context)).resolves.toBe(0)
  148. await expect(runDshSdkCommand(['dev', 'index.ts'], context)).resolves.toBe(0)
  149. await expect(runDshSdkCommand(['build', '--watch'], context)).resolves.toBe(0)
  150. await expect(runDshSdkCommand(['config'], context)).resolves.toBe(0)
  151. expect(calls).toHaveLength(4)
  152. expect(calls[0]).toEqual(['run', 'index.js', { cwd: root, argv: ['--resume', 'session-1'] }])
  153. expect(calls[1]).toEqual(['run', 'index.ts', { cwd: root, dev: true, argv: [] }])
  154. context.config = async () => ({ installError: new Error('offline') })
  155. await expect(runDshSdkCommand(['config'], context)).resolves.toBe(1)
  156. context.config = async () => { throw 'broken' }
  157. await expect(runDshSdkCommand(['config'], context)).resolves.toBe(1)
  158. expect(context.readStderr()).toContain('broken')
  159. await expect(runDshSdkCommand(['unknown'], context)).resolves.toBe(1)
  160. await expect(runDshSdkCommand([], context)).resolves.toBe(0)
  161. expect(context.readStdout()).toContain('Usage: dsh-sdk')
  162. expect(context.readStdout()).toContain('create <source>')
  163. const defaults = commandContext(root)
  164. await writeFile(join(root, 'main.mjs'), 'export function main() { return "ok" }\n')
  165. await expect(runDshSdkCommand(['start', 'main.mjs'], defaults)).resolves.toBe(0)
  166. await expect(runDshSdkCommand(['build'], defaults)).resolves.toBe(0)
  167. defaults.port = new QueuePort([[]])
  168. await expect(runDshSdkCommand(['config'], defaults)).resolves.toBe(1)
  169. })
  170. })
  171. describe('build profiles and invocation', () => {
  172. it('discovers root and plugin targets and creates independent profiles', async () => {
  173. const root = await mkdtemp(join(tmpdir(), 'dsh-build-profile-'))
  174. temporary.push(root)
  175. await mkdir(join(root, 'plugins', 'one', 'src'), { recursive: true })
  176. await writeFile(join(root, 'index.ts'), 'export {}\n')
  177. await writeFile(join(root, 'plugins', 'one', 'package.json'), '{"name":"one"}\n')
  178. await writeFile(join(root, 'plugins', 'one', 'src', 'index.ts'), 'export {}\n')
  179. expect(ProjectBuild({ cwd: root, entry: ['index.ts'] })).toEqual([
  180. { cwd: root, entry: ['index.ts'] },
  181. { workspace: { include: ['plugins/*'] } },
  182. ])
  183. expect(PluginBuild({ entry: ['src/index.ts'], dts: true })).toEqual({ entry: ['src/index.ts'], dts: true })
  184. expect(() => ProjectBuild({ workspace: true })).toThrow('owns workspace discovery')
  185. expect(() => PluginBuild({ workspace: true })).toThrow('does not accept nested workspace')
  186. expect(ProjectBuild({ cwd: join(root, 'empty'), entry: ['index.ts'] })).toEqual([
  187. { cwd: join(root, 'empty'), entry: ['index.ts'] },
  188. ])
  189. expect(ProjectBuild({ entry: ['index.ts'] })[0]).toMatchObject({ entry: ['index.ts'] })
  190. })
  191. it('runs the project-installed tsdown and reports child failure', async () => {
  192. const root = await mkdtemp(join(tmpdir(), 'dsh-build-run-'))
  193. temporary.push(root)
  194. await writeFile(join(root, 'package.json'), '{"type":"module"}\n')
  195. await writeFile(join(root, 'index.ts'), 'export {}\n')
  196. await writeFile(join(root, 'tsdown.config.ts'), 'export default {}\n')
  197. await mkdir(join(root, 'node_modules'), { recursive: true })
  198. const manifest = fileURLToPath(import.meta.resolve('tsdown/package.json'))
  199. await symlink(dirname(manifest), join(root, 'node_modules', 'tsdown'))
  200. const calls: string[][] = []
  201. const runner: CommandRunner = {
  202. run: async (command, args) => {
  203. calls.push([command, ...args])
  204. return { exitCode: 0, signal: null }
  205. },
  206. }
  207. await runProjectBuild(['--watch'], root, runner)
  208. expect(calls[0]?.[0]).toBe(process.execPath)
  209. expect(calls[0]?.at(-1)).toBe('--watch')
  210. const failed: CommandRunner = { run: async () => ({ exitCode: 2, signal: null }) }
  211. await expect(runProjectBuild([], root, failed)).rejects.toThrow('exited with code 2')
  212. const killed: CommandRunner = { run: async () => ({ exitCode: null, signal: 'SIGTERM' }) }
  213. await expect(runProjectBuild([], root, killed)).rejects.toThrow('killed by SIGTERM')
  214. })
  215. it('recognizes every tsdown config source', async () => {
  216. const manifest = fileURLToPath(import.meta.resolve('tsdown/package.json'))
  217. for (const extension of ['cts', 'cjs', 'json']) {
  218. const root = await mkdtemp(join(tmpdir(), `dsh-build-${extension}-`))
  219. temporary.push(root)
  220. await writeFile(join(root, 'package.json'), '{"type":"module"}\n')
  221. await writeFile(join(root, `tsdown.config.${extension}`), '{}\n')
  222. await mkdir(join(root, 'node_modules'), { recursive: true })
  223. await symlink(dirname(manifest), join(root, 'node_modules', 'tsdown'))
  224. let called = false
  225. await runProjectBuild([], root, {
  226. run: async () => { called = true; return { exitCode: 0, signal: null } },
  227. })
  228. expect(called).toBe(true)
  229. }
  230. const root = await mkdtemp(join(tmpdir(), 'dsh-build-package-json-'))
  231. temporary.push(root)
  232. await writeFile(join(root, 'package.json'), '{"type":"module","tsdown":{}}\n')
  233. await mkdir(join(root, 'node_modules'), { recursive: true })
  234. await symlink(dirname(manifest), join(root, 'node_modules', 'tsdown'))
  235. let called = false
  236. await runProjectBuild([], root, {
  237. run: async () => { called = true; return { exitCode: 0, signal: null } },
  238. })
  239. expect(called).toBe(true)
  240. })
  241. it('reports missing and malformed project tsdown executables', async () => {
  242. const missing = await mkdtemp(join(tmpdir(), 'dsh-build-missing-'))
  243. temporary.push(missing)
  244. await writeFile(join(missing, 'package.json'), '{"type":"module"}')
  245. await writeFile(join(missing, 'tsdown.config.ts'), 'export default {}\n')
  246. await expect(runProjectBuild([], missing)).rejects.toThrow('requires tsdown')
  247. const malformed = await mkdtemp(join(tmpdir(), 'dsh-build-malformed-'))
  248. temporary.push(malformed)
  249. await writeFile(join(malformed, 'package.json'), '{"type":"module"}')
  250. await writeFile(join(malformed, 'tsdown.config.ts'), 'export default {}\n')
  251. await mkdir(join(malformed, 'node_modules', 'tsdown'), { recursive: true })
  252. await writeFile(join(malformed, 'node_modules', 'tsdown', 'package.json'), JSON.stringify({
  253. name: 'tsdown', version: '0.0.0', exports: { './package.json': './package.json' }, bin: {},
  254. }))
  255. await expect(runProjectBuild([], malformed)).rejects.toThrow('has no executable')
  256. await writeFile(join(malformed, 'node_modules', 'tsdown', 'package.json'), JSON.stringify({
  257. name: 'tsdown', version: '0.0.0', exports: { './package.json': './package.json' },
  258. }))
  259. await expect(runProjectBuild([], malformed)).rejects.toThrow('has no executable')
  260. const stringBin = await mkdtemp(join(tmpdir(), 'dsh-build-string-bin-'))
  261. temporary.push(stringBin)
  262. await writeFile(join(stringBin, 'package.json'), '{"type":"module"}')
  263. await writeFile(join(stringBin, 'tsdown.config.js'), 'export default {}\n')
  264. await mkdir(join(stringBin, 'node_modules', 'tsdown'), { recursive: true })
  265. await writeFile(join(stringBin, 'node_modules', 'tsdown', 'package.json'), JSON.stringify({
  266. name: 'tsdown', version: '0.0.0', exports: { './package.json': './package.json' }, bin: 'cli.js',
  267. }))
  268. await writeFile(join(stringBin, 'node_modules', 'tsdown', 'cli.js'), '')
  269. let command = ''
  270. await runProjectBuild([], stringBin, {
  271. run: async (_node, args) => { command = args[0] ?? ''; return { exitCode: 0, signal: null } },
  272. })
  273. expect(command).toContain('cli.js')
  274. })
  275. it('returns a no-op for a project with no build targets and hints on a missing start target', async () => {
  276. const root = await mkdtemp(join(tmpdir(), 'dsh-no-build-'))
  277. temporary.push(root)
  278. let called = false
  279. await runProjectBuild([], root, { run: async () => { called = true; return { exitCode: 0, signal: null } } })
  280. expect(called).toBe(false)
  281. const unreadableManifest = await mkdtemp(join(tmpdir(), 'dsh-build-unreadable-manifest-'))
  282. temporary.push(unreadableManifest)
  283. await mkdir(join(unreadableManifest, 'package.json'))
  284. await expect(runProjectBuild([], unreadableManifest)).rejects.toThrow()
  285. await expect(runSDK('index.js', { cwd: root })).rejects.toThrow('Run dsh-sdk build first')
  286. })
  287. it('invokes the target module main export and rejects passive modules', async () => {
  288. const root = await mkdtemp(join(tmpdir(), 'dsh-module-main-'))
  289. temporary.push(root)
  290. await writeFile(join(root, 'main.mjs'), 'export function main(context) { return context }\n')
  291. await writeFile(join(root, 'passive.mjs'), 'export const value = 1\n')
  292. await expect(runSDK('main.mjs', {
  293. cwd: root,
  294. argv: ['--model=mock', '--resume=session-1', 'custom'],
  295. })).resolves.toEqual({
  296. argv: ['--model=mock', '--resume=session-1', 'custom'],
  297. args: { model: 'mock', resume: 'session-1' }, cwd: root, mode: 'start',
  298. })
  299. await expect(runSDK('passive.mjs', { cwd: root })).rejects.toThrow('must export function main()')
  300. })
  301. it('boots empty Cordis configs and delegates targetless runs', async () => {
  302. expectTypeOf(runSDK).toBeCallableWith()
  303. const root = await mkdtemp(join(tmpdir(), 'dsh-start-sdk-'))
  304. temporary.push(root)
  305. await writeFile(join(root, 'cordis.yml'), '[]\n')
  306. const byUrl = await startSDK(pathToFileURL(join(root, 'cordis.yml')))
  307. await byUrl.fiber.dispose()
  308. const byRun = await runSDK(undefined, { cwd: root }) as import('cordis').Context
  309. await byRun.fiber.dispose()
  310. const dev = await startSDK('./cordis.yml', { cwd: root, dev: true })
  311. await dev.fiber.dispose()
  312. await expect(startSDK(new URL('https://example.invalid/cordis.yml'), { cwd: root })).rejects.toThrow()
  313. })
  314. it('validates local plugin metadata in dev mode', async () => {
  315. const malformed = await mkdtemp(join(tmpdir(), 'dsh-dev-malformed-'))
  316. temporary.push(malformed)
  317. await mkdir(join(malformed, 'plugins', 'bad'), { recursive: true })
  318. await expect(runSDK('missing.ts', { cwd: malformed, dev: true })).rejects.toThrow('cannot load local plugin metadata')
  319. const absent = await mkdtemp(join(tmpdir(), 'dsh-dev-absent-'))
  320. temporary.push(absent)
  321. await expect(runSDK('missing.ts', { cwd: absent, dev: true })).rejects.toThrow('cannot start missing target')
  322. const unnamed = await mkdtemp(join(tmpdir(), 'dsh-dev-unnamed-'))
  323. temporary.push(unnamed)
  324. await mkdir(join(unnamed, 'plugins', 'bad', 'src'), { recursive: true })
  325. await writeFile(join(unnamed, 'plugins', 'bad', 'package.json'), '{}')
  326. await writeFile(join(unnamed, 'plugins', 'bad', 'src/index.ts'), 'export {}\n')
  327. await expect(runSDK('missing.ts', { cwd: unnamed, dev: true })).rejects.toThrow('has no name')
  328. const duplicate = await mkdtemp(join(tmpdir(), 'dsh-dev-duplicate-'))
  329. temporary.push(duplicate)
  330. for (const name of ['one', 'two']) {
  331. await mkdir(join(duplicate, 'plugins', name, 'src'), { recursive: true })
  332. await writeFile(join(duplicate, 'plugins', name, 'package.json'), '{"name":"same"}')
  333. await writeFile(join(duplicate, 'plugins', name, 'src/index.ts'), 'export {}\n')
  334. }
  335. await expect(runSDK('missing.ts', { cwd: duplicate, dev: true })).rejects.toThrow('duplicate local plugin')
  336. const valid = await mkdtemp(join(tmpdir(), 'dsh-dev-valid-'))
  337. temporary.push(valid)
  338. await mkdir(join(valid, 'plugins', 'one', 'src'), { recursive: true })
  339. await writeFile(join(valid, 'plugins', 'README.md'), 'skip\n')
  340. await writeFile(join(valid, 'plugins', 'one', 'package.json'), '{"name":"local"}')
  341. await writeFile(join(valid, 'plugins', 'one', 'src/index.ts'), 'export {}\n')
  342. await writeFile(join(valid, 'main.ts'), 'export function main() { return "dev" }\n')
  343. await expect(runSDK('main.ts', { cwd: valid, dev: true })).resolves.toBe('dev')
  344. await expect(runSDK('missing.ts', { cwd: valid, dev: true })).rejects.toThrow('cannot start missing target')
  345. })
  346. it('maps only exact local package names through the loader hook', async () => {
  347. initialize({ mappings: { local: 'file:///tmp/local.ts' } })
  348. const next = async (specifier: string) => ({ url: specifier, format: 'module' as const })
  349. const context: import('node:module').ResolveHookContext = {
  350. conditions: [], importAttributes: {}, parentURL: undefined,
  351. }
  352. await expect(resolveLocalPlugin('local', context, next)).resolves.toMatchObject({ url: 'file:///tmp/local.ts' })
  353. await expect(resolveLocalPlugin('other', context, next)).resolves.toMatchObject({ url: 'other' })
  354. })
  355. })
  356. describe('ConfigWorkflow', () => {
  357. it('opens a project through the config command prompt seam', async () => {
  358. const project = await committedProject()
  359. const context = commandContext(project.root)
  360. context.port = new QueuePort([[]])
  361. context.install = async () => { throw new Error('install should not run') }
  362. await expect(runConfigCommand(context)).resolves.toEqual({})
  363. delete context.port
  364. delete context.install
  365. context.stdin.isTTY = false
  366. await expect(runConfigCommand(context)).rejects.toThrow('interactive TTY')
  367. context.stdin.isTTY = true
  368. context.stdout.isTTY = false
  369. await expect(runConfigCommand(context)).rejects.toThrow('interactive TTY')
  370. })
  371. it('accumulates a disable and commits only after Review & Apply', async () => {
  372. const project = await committedProject([{ id: featureId('todo'), options: ['default'] }])
  373. const registry = createBuiltinRegistry(project.profile)
  374. const output = outputBuffer()
  375. const workflow = new ConfigWorkflow(new QueuePort([
  376. [], true,
  377. ]), output.stream, async () => { throw new Error('install should not run') })
  378. const result = await workflow.run(project, registry)
  379. expect(result.commit?.project.cordis.entry('tool-todo')?.disabled).toBe(true)
  380. expect(output.read()).toContain('Disable feature: todo')
  381. })
  382. it('reconciles a headless plan without prompting and preserves custom plugins', async () => {
  383. const project = await committedProject([], [new LocalPluginBlueprint('plugin', 'plugin')])
  384. const registry = createBuiltinRegistry(project.profile)
  385. const output = outputBuffer()
  386. let installs = 0
  387. const plan: ConfigPlan = {
  388. features: [
  389. { id: featureId('bash'), options: ['local'] },
  390. { id: featureId('persistence'), options: ['jsonl'] },
  391. { id: featureId('todo'), options: ['default'] },
  392. { id: featureId('web'), options: ['exa'], secrets: { apiKey: 'exa-key' } },
  393. ],
  394. }
  395. const result = await new ConfigWorkflow(
  396. new HeadlessPromptPort(), output.stream, async () => { installs += 1 },
  397. ).run(project, registry, plan)
  398. expect(result.commit?.project.cordis.entry('tool-todo')).toBeDefined()
  399. // the unlisted custom local plugin keeps its enabled state (not nuked by the plan)
  400. expect(result.commit?.project.cordis.entry('plugin')?.disabled).toBeFalsy()
  401. expect(installs).toBe(1)
  402. })
  403. it('installs once after NPM dependency changes and keeps committed files on install failure', async () => {
  404. const project = await committedProject()
  405. const registry = createBuiltinRegistry(project.profile)
  406. const output = outputBuffer()
  407. let installs = 0
  408. const workflow = new ConfigWorkflow(new QueuePort([
  409. [{ value: 'feature:todo', choices: [] }], true,
  410. ]), output.stream, async () => {
  411. installs += 1
  412. throw new Error('offline')
  413. })
  414. const result = await workflow.run(project, registry)
  415. expect(installs).toBe(1)
  416. expect(result.installError?.message).toBe('offline')
  417. expect(result.commit?.project.cordis.entry('tool-todo')).toBeDefined()
  418. expect(output.read()).toContain('Changes were committed, but install failed')
  419. })
  420. it('cancels apply and enables a disabled feature without reinstalling', async () => {
  421. const project = await committedProject([{ id: featureId('todo'), options: ['default'] }])
  422. const registry = createBuiltinRegistry(project.profile)
  423. const cancelled = await new ConfigWorkflow(new QueuePort([[], false]), outputBuffer().stream).run(project, registry)
  424. expect(cancelled).toEqual({})
  425. const disable = project.edit(registry)
  426. disable.disableFeature(registry.get(featureId('todo')))
  427. const disabled = (await disable.commit()).project
  428. let installs = 0
  429. const enabled = await new ConfigWorkflow(new QueuePort([
  430. [{ value: 'feature:todo', choices: [] }], true,
  431. ]), outputBuffer().stream, async () => { installs += 1 }).run(disabled, createBuiltinRegistry(disabled.profile))
  432. expect(enabled.commit?.project.cordis.entry('tool-todo')?.disabled).toBeUndefined()
  433. expect(installs).toBe(0)
  434. })
  435. it('toggles custom Cordis config entries without changing NPM dependencies', async () => {
  436. const project = await committedProject([], [new LocalPluginBlueprint('sample', 'plugin')])
  437. await expect(new ConfigWorkflow(new QueuePort([
  438. [{ value: 'plugin:sample', choices: [] }],
  439. ]), outputBuffer().stream).run(project, createBuiltinRegistry(project.profile))).resolves.toEqual({})
  440. const output = outputBuffer()
  441. const disabled = await new ConfigWorkflow(new QueuePort([[], true]), output.stream).run(
  442. project, createBuiltinRegistry(project.profile),
  443. )
  444. expect(disabled.commit?.project.cordis.entry('sample')?.disabled).toBe(true)
  445. expect(output.read()).toContain('Disable custom plugin: sample')
  446. const next = disabled.commit?.project
  447. if (!next) throw new Error('custom toggle did not commit')
  448. const enabled = await new ConfigWorkflow(new QueuePort([
  449. [{ value: 'plugin:sample', choices: [] }], true,
  450. ]), outputBuffer().stream).run(next, createBuiltinRegistry(next.profile))
  451. expect(enabled.commit?.project.cordis.entry('sample')?.disabled).toBeUndefined()
  452. })
  453. it('shows inconsistent features as diagnostic-only rows', async () => {
  454. const complete = await committedProject()
  455. await writeFile(join(complete.root, 'cordis.yml'), `${await readFile(join(complete.root, 'cordis.yml'), 'utf8')}- id: web-search-exa
  456. name: '@deepseek-ai/dsh-web-search-exa'
  457. `)
  458. const project = await SdkProject.open(complete.root)
  459. const port = new QueuePort([[]])
  460. await expect(new ConfigWorkflow(port, outputBuffer().stream).run(project, createBuiltinRegistry(project.profile)))
  461. .resolves.toEqual({})
  462. })
  463. it('uses the default installer and normalizes non-Error install failures', async () => {
  464. const project = await committedProject()
  465. const install = vi.spyOn(NpmPackageManager.prototype, 'install').mockResolvedValue()
  466. await new ConfigWorkflow(new QueuePort([
  467. [{ value: 'feature:todo', choices: [] }], true,
  468. ])).run(project, createBuiltinRegistry(project.profile))
  469. expect(install).toHaveBeenCalledOnce()
  470. install.mockRestore()
  471. const next = await committedProject()
  472. const failed = await new ConfigWorkflow(new QueuePort([
  473. [{ value: 'feature:todo', choices: [] }], true,
  474. ]), outputBuffer().stream, async () => { throw 'offline-string' }).run(next, createBuiltinRegistry(next.profile))
  475. expect(failed.installError?.message).toBe('offline-string')
  476. })
  477. it('reconciles a child option selected in the feature tree', async () => {
  478. const project = await committedProject()
  479. const registry = createBuiltinRegistry(project.profile)
  480. let installs = 0
  481. const workflow = new ConfigWorkflow(new QueuePort([
  482. [{ value: 'feature:persistence', choices: ['sqlite'] }], true,
  483. ]), outputBuffer().stream, async () => { installs += 1 })
  484. const result = await workflow.run(project, registry)
  485. expect(result.commit?.project.cordis.entry('session-persistence')).toMatchObject({
  486. name: '@deepseek-ai/dsh-session-persistence-sqlite',
  487. config: { path: './.sessions/sessions.sqlite' },
  488. })
  489. expect(installs).toBe(1)
  490. })
  491. it('switches required provider and interface options', async () => {
  492. const project = await committedProject()
  493. const registry = createBuiltinRegistry(project.profile)
  494. const workflow = new ConfigWorkflow(new QueuePort([
  495. [
  496. { value: 'feature:provider', choices: ['custom'] },
  497. { value: 'feature:app', choices: ['tui'] },
  498. { value: 'feature:persistence', choices: ['jsonl'] },
  499. ],
  500. 'https://provider.example/v1',
  501. 'custom-key',
  502. true,
  503. ]), outputBuffer().stream, async () => {})
  504. const result = await workflow.run(project, registry)
  505. const provider = result.commit?.project.cordis.entry('llm-pi-ai')
  506. expect(provider?.config?.apiKey).toBeDefined()
  507. expect(provider?.config?.baseURL).toBe('https://provider.example/v1')
  508. expect(result.commit?.project.cordis.entry('tui')).toBeDefined()
  509. expect(result.commit?.project.cordis.entry('agent-loop')).toBeDefined()
  510. expect(result.commit?.project.cordis.entry('agent-core')).toBeUndefined()
  511. })
  512. it('disables ask-user when switching its app interface to embed', async () => {
  513. const project = await committedProject([
  514. { id: featureId('ask-user'), options: ['default'] },
  515. ], [], 'acp')
  516. const registry = createBuiltinRegistry(project.profile)
  517. const output = outputBuffer()
  518. const workflow = new ConfigWorkflow(new QueuePort([
  519. [
  520. { value: 'feature:provider', choices: ['deepseek'] },
  521. { value: 'feature:app', choices: ['embed'] },
  522. { value: 'feature:persistence', choices: ['jsonl'] },
  523. { value: 'feature:ask-user', choices: ['default'] },
  524. ],
  525. true,
  526. ]), output.stream, async () => {})
  527. const result = await workflow.run(project, registry)
  528. expect(result.commit?.project.profile.runInterface).toBe('embed')
  529. expect(result.commit?.project.cordis.entry('tool-ask-user')?.disabled).toBe(true)
  530. expect(output.read()).toContain('Disable feature: ask-user')
  531. })
  532. })
  533. describe('dsh-sdk create', () => {
  534. const writeDependency = (name: string) => async (_m: unknown, spec: string, cwd: string): Promise<void> => {
  535. const path = join(cwd, 'package.json')
  536. const manifest = JSON.parse(await readFile(path, 'utf8')) as { dependencies?: Record<string, string> }
  537. manifest.dependencies = { ...manifest.dependencies, [name]: spec }
  538. await writeFile(path, JSON.stringify(manifest, null, 2))
  539. }
  540. it('adds a dependency and mounts it after confirmation', async () => {
  541. const project = await committedProject()
  542. const context = { ...commandContext(project.root), port: new QueuePort([true]), add: writeDependency('my-ext-plugin') }
  543. const result = await runCreatePluginCommand('github:o/r#sha', context)
  544. expect(result?.project.cordis.entry('my-ext-plugin')?.name).toBe('my-ext-plugin')
  545. expect(context.readStdout()).toContain('Mounted my-ext-plugin')
  546. })
  547. it('derives the cordis id from a scoped package name', async () => {
  548. const project = await committedProject()
  549. const context = { ...commandContext(project.root), port: new QueuePort([true]), add: writeDependency('@acme/cool-plugin') }
  550. const result = await runCreatePluginCommand('@acme/cool-plugin@1.0.0', context)
  551. expect(result?.project.cordis.entry('cool-plugin')?.name).toBe('@acme/cool-plugin')
  552. })
  553. it('returns undefined and adds nothing when declined', async () => {
  554. const project = await committedProject()
  555. let added = false
  556. const context = {
  557. ...commandContext(project.root),
  558. port: new QueuePort([false]),
  559. add: async () => { added = true },
  560. }
  561. await expect(runCreatePluginCommand('pkg@1.0.0', context)).resolves.toBeUndefined()
  562. expect(added).toBe(false)
  563. })
  564. it('rejects an empty source, a non-TTY session, and a no-op add', async () => {
  565. const project = await committedProject()
  566. await expect(runCreatePluginCommand(' ', { ...commandContext(project.root), port: new QueuePort([]) }))
  567. .rejects.toThrow('requires a plugin source')
  568. const noTty = commandContext(project.root)
  569. noTty.stdin.isTTY = false
  570. noTty.stdout.isTTY = false
  571. await expect(runCreatePluginCommand('pkg@1.0.0', noTty)).rejects.toThrow('interactive TTY')
  572. const noOutTty = commandContext(project.root)
  573. noOutTty.stdout.isTTY = false
  574. await expect(runCreatePluginCommand('pkg@1.0.0', noOutTty)).rejects.toThrow('interactive TTY')
  575. await expect(runCreatePluginCommand('pkg@1.0.0', {
  576. ...commandContext(project.root), port: new QueuePort([true]), add: async () => {},
  577. })).rejects.toThrow('added no new dependency')
  578. })
  579. it('dispatches create through the launcher', async () => {
  580. const project = await committedProject()
  581. const context = commandContext(project.root)
  582. context.createPlugin = async () => undefined
  583. await expect(runDshSdkCommand(['create', 'pkg@1.0.0'], context)).resolves.toBe(0)
  584. })
  585. })
  586. describe('command telemetry', () => {
  587. it('reports when consent allows and skips when denied or faulting', async () => {
  588. const dir = await mkdtemp(join(tmpdir(), 'dsh-telemetry-'))
  589. temporary.push(dir)
  590. const sent: unknown[] = []
  591. const reporter = { report: () => { sent.push(1) }, flush: async () => {} }
  592. await reportCommandTelemetry(
  593. { command: 'build', cwd: dir, durationMs: 5, success: true },
  594. { resolve: async () => ({ allowed: true, reason: 'absent' }), reporter },
  595. )
  596. expect(sent).toHaveLength(1)
  597. await reportCommandTelemetry(
  598. { command: 'build', cwd: dir, durationMs: 5, success: true },
  599. { resolve: async () => ({ allowed: false, reason: 'disabled' }), reporter },
  600. )
  601. expect(sent).toHaveLength(1)
  602. await expect(reportCommandTelemetry(
  603. { command: 'build', cwd: dir, durationMs: 5, success: true },
  604. { resolve: async () => { throw new Error('boom') }, reporter },
  605. )).resolves.toBeUndefined()
  606. expect(sent).toHaveLength(1)
  607. })
  608. it('emits a telemetry event carrying each command outcome', async () => {
  609. const project = await committedProject()
  610. const events: CommandTelemetryEvent[] = []
  611. const context = commandContext(project.root)
  612. context.telemetry = async (event) => { events.push(event) }
  613. context.build = async () => {}
  614. await expect(runDshSdkCommand(['build'], context)).resolves.toBe(0)
  615. expect(events).toHaveLength(1)
  616. expect(events[0]).toMatchObject({ command: 'build', cwd: project.root, success: true })
  617. await runDshSdkCommand([], context)
  618. expect(events).toHaveLength(1)
  619. context.build = async () => { throw new Error('boom') }
  620. await expect(runDshSdkCommand(['build'], context)).resolves.toBe(1)
  621. expect(events[1]).toMatchObject({ command: 'build', success: false })
  622. context.config = async () => ({ installError: new Error('offline') })
  623. await expect(runDshSdkCommand(['config'], context)).resolves.toBe(1)
  624. expect(events.at(-1)).toMatchObject({ command: 'config', success: false })
  625. })
  626. })