args.ts 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196
  1. /**
  2. * Commander adapter for the `dsh` command line.
  3. *
  4. * The launcher parses only what it owns — which profile to boot, which extra
  5. * patch overlays to apply, and the config dumps — and hands **everything after
  6. * its own flags** to the booted tree verbatim, where injected app plugins parse
  7. * their own flag families and print their own `--help` (see
  8. * `@deepseek-ai/dsh-cmdline`). Launcher flags therefore come first: the first
  9. * token this parser does not recognize starts the inner arguments, so
  10. * `dsh --profile tui --resume abc` boots the tui profile with `--resume abc`,
  11. * and `dsh --profile web -h` prints the web app's help, not this one's.
  12. *
  13. * `dsh <name>` abbreviates `dsh --profile <name>`; `plugin` manages a profile's
  14. * plugin dependencies by forwarding to pnpm.
  15. * @module @deepseek-ai/dsh/args
  16. */
  17. import { Command, CommanderError, InvalidArgumentError } from 'commander'
  18. /** Boot a named profile and hand it the invocation's inner arguments. */
  19. interface ProfileInvocation {
  20. mode: 'profile'
  21. profile: string
  22. /** Shipped template used once to initialize a missing profile. */
  23. fromDefaultProfile?: string | undefined
  24. /** Extra patch-list overlays applied after the profile's own layer, in argv order. */
  25. patches: string[]
  26. /** Everything after the launcher's own flags, verbatim, for injected app plugins. */
  27. args: string[]
  28. }
  29. /** Print a composed profile tree and exit without booting. */
  30. interface DumpConfigInvocation {
  31. mode: 'dump-config'
  32. profile: string
  33. /** Shipped template used once to initialize a missing profile. */
  34. fromDefaultProfile?: string | undefined
  35. /** Omit the profile's user layer and --patch overlays; print bundle layers only. */
  36. defaultOnly: boolean
  37. patches: string[]
  38. }
  39. /** Manage a profile's plugins: forward `args` to pnpm inside the profile directory. */
  40. interface PluginInvocation {
  41. mode: 'plugin'
  42. profile: string
  43. /** Raw pnpm arguments, verbatim. */
  44. args: string[]
  45. }
  46. /** The resolved `dsh` invocation. Help, version, and errors exit inside {@link parseDshArgs}. */
  47. export type DshInvocation = ProfileInvocation | DumpConfigInvocation | PluginInvocation
  48. /** Launcher flags for profile boot and configuration dumps. */
  49. interface BootOptions {
  50. patch?: string[]
  51. dumpConfig?: boolean
  52. dumpDefaultConfig?: boolean
  53. fromDefaultProfile?: string
  54. }
  55. /**
  56. * Repeatable single-value collector: `--patch a.yml --patch b.yml`. Never
  57. * variadic — a variadic `--patch` would swallow the inner arguments.
  58. */
  59. const collect = (value: string, previous: string[] = []): string[] => [...previous, value]
  60. function selectProfile(value: string, previous?: string): string {
  61. if (previous !== undefined) throw new InvalidArgumentError('select a profile only once')
  62. return value
  63. }
  64. function rejectElectronProfile(program: Command, profile: string): void {
  65. if (profile.toLowerCase() === 'desktop') {
  66. program.error('error: profile "desktop" is managed exclusively by the Electron application')
  67. }
  68. }
  69. /** The launcher's own help text; each app prints its own. */
  70. const HELP_EXAMPLES = `
  71. Examples:
  72. dsh web boot the web profile (same as: dsh --profile web)
  73. dsh rescue --from-default-profile web
  74. create rescue from the shipped web template, then boot it
  75. dsh headless "run the tests" answer one task, print the result, and exit
  76. dsh tui --patch ./extra.yml boot a custom profile with one extra overlay
  77. dsh tui --resume <session> arguments after the launcher flags reach the app
  78. dsh web --help the web app's own flags and help
  79. dsh plugin --profile tui add <package> install a plugin into the tui profile
  80. `
  81. /**
  82. * Resolve a boot or dump invocation from the launcher flags and the leftover
  83. * inner arguments.
  84. * @param program - the command whose options were parsed.
  85. * @param profile - the profile these flags boot.
  86. * @param options - the launcher flags commander collected.
  87. * @param args - the leftover arguments, in argv order.
  88. * @returns the resolved invocation.
  89. */
  90. function resolveBoot(program: Command, profile: string, options: BootOptions, args: string[]): DshInvocation {
  91. const patches = options.patch ?? []
  92. if (patches.includes('')) program.error('error: --patch needs a path')
  93. if (options.fromDefaultProfile === '') program.error('error: --from-default-profile needs a name')
  94. if (options.dumpConfig !== true && options.dumpDefaultConfig !== true) {
  95. return { mode: 'profile', profile, fromDefaultProfile: options.fromDefaultProfile, patches, args }
  96. }
  97. if (options.dumpConfig === true && options.dumpDefaultConfig === true) {
  98. program.error('error: --dump-config and --dump-default-config are mutually exclusive')
  99. }
  100. // The dump is boot-free: it never runs app command-line providers, so it
  101. // cannot show what those flags would decide, and printing a tree that differs
  102. // from the same invocation's boot would mislead.
  103. if (args.length > 0) {
  104. program.error(`error: config dumps take no app arguments, got ${args.map(argument => JSON.stringify(argument)).join(' ')}`)
  105. }
  106. const defaultOnly = options.dumpDefaultConfig === true
  107. if (defaultOnly && patches.length > 0) {
  108. program.error('error: --dump-default-config prints the bundle layers and takes no --patch')
  109. }
  110. return { mode: 'dump-config', profile, fromDefaultProfile: options.fromDefaultProfile, defaultOnly, patches }
  111. }
  112. /**
  113. * Resolve argv into one invocation, or print and exit for help, version, or an
  114. * error.
  115. * @param argv - arguments after the Node binary and script.
  116. * @param version - version string printed by `--version`.
  117. * @returns the resolved invocation.
  118. */
  119. export function parseDshArgs(argv: readonly string[], version: string): DshInvocation {
  120. const first = argv[0]
  121. let resolved: DshInvocation | undefined
  122. // Annotated, not inferred: the actions below call back into `program`, and an
  123. // inferred type would be circular through its own chain.
  124. const program: Command = new Command()
  125. program
  126. .name('dsh')
  127. .version(version, '-V, --version', 'output the version number')
  128. .usage('[--profile] <name> [options] [app-args...]\n dsh plugin --profile <name> <pnpm-args...>')
  129. .description('dsh: boot a DeepSeek Harness profile — an ordered stack of plugin-bundle patch layers under your own overrides.')
  130. .addHelpText('after', HELP_EXAMPLES)
  131. .exitOverride()
  132. // The launcher's flags come first and end at the first token it does not
  133. // know; everything from there on belongs to the booted app, including
  134. // its -h. `dsh -h` with no profile still prints this help, below.
  135. .helpOption(false)
  136. .helpCommand(false)
  137. .allowUnknownOption()
  138. .passThroughOptions()
  139. .enablePositionalOptions()
  140. .argument('[args...]', 'arguments for the booted profile\'s app (see: dsh --profile <name> --help)')
  141. .option('--profile <name>', 'the profile under $DSH_HOME/profiles to boot', selectProfile)
  142. .option('--from-default-profile <name>', 'initialize a new custom profile from a shipped profile template')
  143. .option('--patch <path>', 'extra patch-list overlay applied after the profile layer (repeatable)', collect)
  144. .option('--dump-config', 'print the composed profile tree and exit')
  145. .option('--dump-default-config', 'print the profile tree without its user layer or --patch overlays and exit')
  146. .action((args: string[], options: BootOptions & { profile?: string }) => {
  147. // With the app owning -h, the launcher's own help is what a bare
  148. // `dsh -h` (no profile to hand it to) must print.
  149. if (options.profile === undefined) {
  150. if (args.some(argument => argument === '-h' || argument === '--help')) program.help()
  151. program.error('error: --profile <name> is required')
  152. }
  153. const profile = options.profile
  154. if (profile === '') program.error('error: --profile needs a name')
  155. rejectElectronProfile(program, profile)
  156. resolved = resolveBoot(program, profile, options, args)
  157. })
  158. if (first === 'plugin') {
  159. const plugin = program.command('plugin').description('manage a profile\'s plugins by forwarding the remaining arguments to pnpm in the profile directory')
  160. plugin
  161. .requiredOption('--profile <name>', 'the profile whose plugins to manage (initialized on first use)', selectProfile)
  162. .allowUnknownOption()
  163. .argument('[args...]', 'pnpm arguments, forwarded verbatim (add <pkg>, remove <pkg>, why <pkg>, ...)')
  164. .action((args: string[], options: { profile: string }) => {
  165. if (options.profile === '') program.error('error: --profile needs a name')
  166. rejectElectronProfile(plugin, options.profile)
  167. if (args.length === 0) program.error('error: plugin needs pnpm arguments to forward (e.g. add <package>)')
  168. resolved = { mode: 'plugin', profile: options.profile, args }
  169. })
  170. }
  171. try {
  172. const expanded = first !== undefined && !first.startsWith('-') && first !== 'plugin'
  173. ? ['--profile', ...argv]
  174. : argv
  175. program.parse(expanded, { from: 'user' })
  176. } catch (error) {
  177. return process.exit(error instanceof CommanderError ? error.exitCode : 1)
  178. }
  179. /* v8 ignore next -- an action resolves or Commander throws */
  180. if (resolved === undefined) throw new Error('dsh: no invocation resolved')
  181. return resolved
  182. }