args.ts 8.9 KB

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