args.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  1. /**
  2. * Commander adapter for the `dsh` command-line entry: the one place argv is
  3. * parsed and routed to a mode. `bin.ts` switches on the returned discriminant
  4. * and dynamic-imports that mode's module. One program: the default (no
  5. * subcommand) is the TUI/headless surface with option-only flags; `meta` and
  6. * `web` are real subcommands. Commander owns `--help`/`--version` and parse
  7. * errors — it prints and exits at the point of failure (a domain failure routes through
  8. * `command.error`), so this returns only a resolved mode.
  9. * @module @deepseek-ai/dsh/args
  10. */
  11. import { Command, CommanderError } from 'commander'
  12. /**
  13. * Interactive TUI: the default mode. `--config` applies an overlay over the
  14. * shipped composition in place of the personal one, `--config-replace` boots a
  15. * file as the whole tree instead, and `--resume <id>` rehydrates a session.
  16. */
  17. interface TuiInvocation {
  18. mode: 'tui'
  19. config?: string
  20. configReplace?: string
  21. resume?: string
  22. }
  23. /**
  24. * Print the composed config tree and exit, without booting: `--dump-config`
  25. * composes the shipped base, the surface overlay, and the `--config` or
  26. * personal overlay — exactly the layers that surface would boot;
  27. * `--dump-default-config` stops at the surface overlay (the shipped tree, no
  28. * user layer).
  29. */
  30. interface DumpConfigInvocation {
  31. mode: 'dump-config'
  32. surface: 'tui' | 'web'
  33. /** Omit the `--config`/personal layer and print only the shipped composition. */
  34. defaultOnly: boolean
  35. /** The `--config` overlay to compose instead of the personal one. */
  36. config?: string
  37. }
  38. /** Headless one-shot: `dsh -p "task"`. */
  39. interface HeadlessInvocation {
  40. mode: 'headless'
  41. prompt: string
  42. }
  43. /** Interactive fresh TUI over this harness checkout; accepts no default-surface options. */
  44. interface MetaInvocation {
  45. mode: 'meta'
  46. }
  47. /**
  48. * Guided fresh-session entry: `dsh upgrade` seeds the first turn with the
  49. * `dsh-upgrade` skill. It always mints a
  50. * fresh session in the invoking directory and takes no options — `--resume`,
  51. * `--config`, and `-p` are rejected as mistyped, so there is nothing to carry.
  52. */
  53. interface SkillSessionInvocation {
  54. mode: 'upgrade'
  55. }
  56. /**
  57. * Browser UI: `dsh web`. `host`/`port` are present only when the flag was
  58. * passed — pass-through overrides with no CLI default and no CLI validation:
  59. * the `dsh-host-webserver` schema (`host` a loopback/all-interfaces literal,
  60. * `port` a natural ≤ 65535) is the single source of both the default (the
  61. * shipped Web overlay value stands when a flag is absent) and validity (a bad
  62. * value fails loud at boot). `port` is `Number`-coerced only because the schema
  63. * wants a number, not a string. `dev` mounts the client HMR driver;
  64. * `workspaceRoot` is the parent directory for name-created workspaces.
  65. */
  66. interface WebInvocation {
  67. mode: 'web'
  68. /** Overlay of loader patches applied over the shipped web composition. */
  69. config?: string
  70. host?: string
  71. port?: number
  72. dev: boolean
  73. workspaceRoot?: string
  74. /** Extra authorities for the /api browser-trust fence (`host` or `host:port`); LAN IP literals are derived, not listed here. */
  75. trustedHosts?: string[]
  76. }
  77. /** The resolved `dsh` invocation: exactly one mode. `--help`/`--version`/errors exit inside {@link parseDshArgs}. */
  78. export type DshInvocation =
  79. | TuiInvocation
  80. | DumpConfigInvocation
  81. | HeadlessInvocation
  82. | MetaInvocation
  83. | SkillSessionInvocation
  84. | WebInvocation
  85. /** Raw web-subcommand options straight from Commander. */
  86. interface WebOptions {
  87. config?: string
  88. host?: string
  89. port?: string
  90. dev?: boolean
  91. workspaceRoot?: string
  92. trustedHost?: string[]
  93. dumpConfig?: boolean
  94. dumpDefaultConfig?: boolean
  95. }
  96. /**
  97. * Resolve the two dump flags for one surface, or return `undefined` when
  98. * neither was passed. Both flags together are contradictory (one includes the
  99. * user layer, the other excludes it) and fail loud through `error`.
  100. */
  101. function resolveDump(
  102. surface: 'tui' | 'web',
  103. options: { config?: string; dumpConfig?: boolean; dumpDefaultConfig?: boolean },
  104. error: (message: string) => never,
  105. ): DumpConfigInvocation | undefined {
  106. if (options.dumpConfig !== true && options.dumpDefaultConfig !== true) return undefined
  107. if (options.dumpConfig === true && options.dumpDefaultConfig === true) {
  108. error('error: --dump-config and --dump-default-config are mutually exclusive')
  109. }
  110. const defaultOnly = options.dumpDefaultConfig === true
  111. if (defaultOnly && options.config !== undefined) {
  112. error('error: --dump-default-config prints the shipped tree and takes no --config')
  113. }
  114. return {
  115. mode: 'dump-config',
  116. surface,
  117. defaultOnly,
  118. ...options.config !== undefined && { config: options.config },
  119. }
  120. }
  121. /**
  122. * Narrow the raw `web` options into a {@link WebInvocation}. No host/port
  123. * validation: both flow to the webserver schema, which is the sole gate. `port`
  124. * is coerced to a number (the schema rejects a string) but not range-checked
  125. * here — `NaN`/out-of-range fail loud at the schema on boot.
  126. */
  127. function resolveWeb(options: WebOptions): WebInvocation {
  128. return {
  129. mode: 'web',
  130. ...options.config !== undefined && { config: options.config },
  131. ...options.host !== undefined && { host: options.host },
  132. ...options.port !== undefined && { port: Number(options.port) },
  133. dev: options.dev === true,
  134. ...options.workspaceRoot !== undefined && { workspaceRoot: options.workspaceRoot },
  135. ...options.trustedHost !== undefined && { trustedHosts: options.trustedHost },
  136. }
  137. }
  138. /**
  139. * Resolve the raw argv into a {@link DshInvocation}, or print and exit for
  140. * `--help`/`--version`/a parse error. The default (no subcommand) is the
  141. * TUI/headless surface; `web` is a subcommand.
  142. * @param argv - the arguments after the node binary and script (`process.argv.slice(2)`).
  143. * @param version - the version string `--version` prints; read from this app's package.json.
  144. * @returns the resolved invocation (only reached on a valid, non-help invocation).
  145. */
  146. export function parseDshArgs(argv: readonly string[], version: string): DshInvocation {
  147. let resolved: DshInvocation | undefined
  148. const program = new Command()
  149. .name('dsh')
  150. .version(version, '-V, --version', 'output the version number')
  151. .description('dsh: DeepSeek Harness — an interactive coding agent for your terminal.\nRun `dsh` with no arguments to start a session in the current directory.')
  152. // The default surface takes no positional task, so `dsh "task"` fails
  153. // commander's arity check with no hint; these examples are where a first
  154. // reader learns the entry points and that a one-shot task rides `-p`.
  155. .addHelpText('after', `
  156. Examples:
  157. dsh start an interactive session in this directory
  158. dsh -p "run the tests" answer one task, print the result, and exit
  159. dsh --resume <id> continue a past session
  160. `)
  161. .exitOverride()
  162. // Stop parent options at a subcommand boundary so `web --config` belongs to
  163. // Web while `--config ... web` remains a leaked default-surface option.
  164. .enablePositionalOptions()
  165. // Default surface: option-only (no positional), so `web` can be a real
  166. // subcommand without a positional collision.
  167. .option('-p, --prompt <task>', 'answer this task without the interactive UI, then exit')
  168. .option('--resume <id>', 'continue a past session by id')
  169. .option('--config <path>', 'apply this overlay of loader patches instead of the personal one')
  170. .option('--config-replace <path>', 'boot this file as the entire tree, ignoring the shipped and personal configuration')
  171. .option('--dump-config', 'print the composed config tree (base + surface + --config/personal overlay) and exit')
  172. .option('--dump-default-config', 'print the shipped config tree (base + surface overlay, no user layer) and exit')
  173. .action((options: {
  174. config?: string
  175. configReplace?: string
  176. prompt?: string
  177. resume?: string
  178. dumpConfig?: boolean
  179. dumpDefaultConfig?: boolean
  180. }) => {
  181. const dump = resolveDump('tui', options, message => program.error(message))
  182. if (dump !== undefined) {
  183. // The dump prints composition; a boot-only flag alongside it would be
  184. // silently ignored, so reject the mix loud.
  185. if (options.prompt !== undefined || options.resume !== undefined || options.configReplace !== undefined) {
  186. program.error('error: --dump-config/--dump-default-config take none of -p/--prompt, --resume, or --config-replace')
  187. }
  188. resolved = dump
  189. return
  190. }
  191. if (options.prompt !== undefined) {
  192. // A headless prompt owns the invocation; an empty task has nothing to
  193. // run, and --config/--resume are TUI inputs that must not silently
  194. // vanish from a headless run.
  195. if (options.prompt === '') program.error('error: --prompt needs a task')
  196. if (options.config !== undefined || options.configReplace !== undefined || options.resume !== undefined) {
  197. program.error('error: --prompt takes no --config, --config-replace, or --resume')
  198. }
  199. resolved = { mode: 'headless', prompt: options.prompt }
  200. return
  201. }
  202. // An empty --resume= id would silently start a fresh session downstream
  203. // (agent-loop treats '' as no-resume), so a mistyped resume must fail loud.
  204. if (options.resume === '') program.error('error: --resume needs a session id')
  205. // The two config flags are mutually exclusive: one layers over the shipped
  206. // tree, the other discards it, so accepting both would silently drop one.
  207. if (options.config !== undefined && options.configReplace !== undefined) {
  208. program.error('error: --config and --config-replace are mutually exclusive')
  209. }
  210. resolved = {
  211. mode: 'tui',
  212. ...options.config !== undefined && { config: options.config },
  213. ...options.configReplace !== undefined && { configReplace: options.configReplace },
  214. ...options.resume !== undefined && { resume: options.resume },
  215. }
  216. })
  217. // Commander parses the parent (default-surface) options on either side of a
  218. // subcommand into `program.opts()`. For a subcommand that shares none of them,
  219. // a leaked config/prompt/resume option is a mistyped invocation that must fail
  220. // loud rather than silently run and drop the input.
  221. const rejectParentOptions = (command: string): void => {
  222. const parent = program.opts<{
  223. config?: string
  224. configReplace?: string
  225. prompt?: string
  226. resume?: string
  227. dumpConfig?: boolean
  228. dumpDefaultConfig?: boolean
  229. }>()
  230. if (parent.config !== undefined || parent.configReplace !== undefined
  231. || parent.prompt !== undefined || parent.resume !== undefined
  232. || parent.dumpConfig !== undefined || parent.dumpDefaultConfig !== undefined) {
  233. program.error(`error: ${command} takes none of --config, --config-replace, -p/--prompt, --resume, --dump-config, or --dump-default-config`)
  234. }
  235. }
  236. // Registration order is the rendered help order, so daily use comes first
  237. // and the harness-development surfaces (`web --dev`, `meta`) come last.
  238. // `upgrade` is a guided fresh-session entry: it takes no options and always
  239. // mints a fresh session, so nothing is left to carry.
  240. program
  241. .command('upgrade')
  242. .description('update this dsh installation to the latest version')
  243. .action(() => {
  244. rejectParentOptions('upgrade')
  245. resolved = { mode: 'upgrade' }
  246. })
  247. // Host and port name no default: the CLI passes neither through when the flag
  248. // is absent, so the shipped Web overlay value stands and restating it here
  249. // would duplicate a fact this file does not own.
  250. const web = program.command('web').description('serve the browser UI on the configured host and port')
  251. web
  252. .option('--config <path>', 'apply this overlay of loader patches over the shipped configuration')
  253. .option('--host <host>', 'bind host; pass 0.0.0.0 to reach it from another machine')
  254. .option('--port <port>', 'listen port; pass 0 to let the OS pick a free one')
  255. .option('--dev', 'developer mode: hot-reload the browser client')
  256. .option('--workspace-root <path>', 'parent directory for workspaces created from the browser UI')
  257. .option('--trusted-host <authority...>', 'extra authority the /api browser-trust fence accepts (host or host:port; repeatable)')
  258. .option('--dump-config', 'print the composed config tree (base + web + --config/personal overlay) and exit')
  259. .option('--dump-default-config', 'print the shipped config tree (base + web overlay, no user layer) and exit')
  260. .action((options: WebOptions) => {
  261. rejectParentOptions('web')
  262. const dump = resolveDump('web', options, message => program.error(message))
  263. if (dump !== undefined) {
  264. resolved = dump
  265. return
  266. }
  267. resolved = resolveWeb(options)
  268. })
  269. program
  270. .command('meta')
  271. .description('work on the dsh source that runs this command, from any directory')
  272. .action(() => {
  273. rejectParentOptions('meta')
  274. resolved = { mode: 'meta' }
  275. })
  276. try {
  277. program.parse(argv, { from: 'user' })
  278. } catch (error) {
  279. // Commander printed help/version/the error under `exitOverride`; exit with
  280. // the code it chose (0 for help/version, 1 for a parse or domain error).
  281. /* v8 ignore next -- Commander only throws CommanderError from parse/error under exitOverride */
  282. return process.exit(error instanceof CommanderError ? error.exitCode : 1)
  283. }
  284. /* v8 ignore next -- the default action or a subcommand action always resolves, or parse throws above */
  285. if (resolved === undefined) throw new Error('dsh: no invocation resolved')
  286. return resolved
  287. }