args.ts 9.2 KB

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