@kjanat/dreamcli 2.4.1 → 3.0.0-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (94) hide show
  1. package/CHANGELOG.md +169 -1
  2. package/README.md +14 -7
  3. package/dist/core/cli/index.d.mts +283 -81
  4. package/dist/core/cli/index.mjs +1 -1
  5. package/dist/core/cli/planner.d.mts +27 -5
  6. package/dist/core/cli/planner.mjs +1 -1
  7. package/dist/core/cli/root-help.d.mts +16 -2
  8. package/dist/core/cli/root-help.mjs +3 -5
  9. package/dist/core/cli/root-surface.d.mts +18 -3
  10. package/dist/core/cli/root-surface.mjs +1 -1
  11. package/dist/core/cli/runtime-preflight.d.mts +31 -5
  12. package/dist/core/cli/runtime-preflight.mjs +1 -1
  13. package/dist/core/completion/index.d.mts +32 -1
  14. package/dist/core/completion/index.mjs +1 -1
  15. package/dist/core/completion/shells/shared.d.mts +10 -0
  16. package/dist/core/completion/shells/shared.mjs +1 -1
  17. package/dist/core/config/index.d.mts +2 -2
  18. package/dist/core/config/package-json.d.mts +93 -20
  19. package/dist/core/config/package-json.mjs +3 -1
  20. package/dist/core/help/index.d.mts +45 -1
  21. package/dist/core/help/index.mjs +6 -6
  22. package/dist/core/json-schema/index.mjs +1 -1
  23. package/dist/core/json-schema/meta-descriptions.generated.d.mts +38 -38
  24. package/dist/core/parse/index.d.mts +15 -1
  25. package/dist/core/parse/index.mjs +1 -1
  26. package/dist/core/prompt/index.d.mts +11 -3
  27. package/dist/core/prompt/index.mjs +3 -3
  28. package/dist/core/resolve/coerce.mjs +1 -1
  29. package/dist/core/resolve/flags.mjs +1 -1
  30. package/dist/core/resolve/property.d.mts +2 -0
  31. package/dist/core/resolve/property.mjs +1 -1
  32. package/dist/core/schema/arg.d.mts +90 -10
  33. package/dist/core/schema/arg.mjs +1 -1
  34. package/dist/core/schema/command.d.mts +3 -1
  35. package/dist/core/schema/flag.d.mts +92 -2
  36. package/dist/core/schema/flag.mjs +1 -1
  37. package/dist/core/schema/index.d.mts +2 -1
  38. package/dist/core/schema/number-constraints.d.mts +96 -0
  39. package/dist/core/schema/number-constraints.mjs +1 -0
  40. package/dist/core/schema/prompt.d.mts +15 -0
  41. package/dist/core/schema/run.d.mts +4 -4
  42. package/dist/core/testkit/index.d.mts +9 -5
  43. package/dist/core/testkit/index.mjs +1 -1
  44. package/dist/index.d.mts +4 -3
  45. package/dist/index.mjs +1 -1
  46. package/dist/runtime/auto.mjs +1 -1
  47. package/dist/runtime/bun.mjs +1 -1
  48. package/dist/runtime/deno.mjs +2 -2
  49. package/dist/runtime/node.mjs +2 -2
  50. package/dist/version.mjs +1 -1
  51. package/examples/basic.ts +5 -1
  52. package/examples/gh/package.json +2 -7
  53. package/examples/pwsh-demo/package.json +1 -7
  54. package/examples/pwsh-demo/src/main.test.ts +1 -4
  55. package/examples/pwsh-demo/src/main.ts +14 -4
  56. package/examples/transport-launcher.ts +85 -0
  57. package/package.json +15 -24
  58. package/src/core/cli/dispatch.ts +7 -1
  59. package/src/core/cli/index.ts +521 -122
  60. package/src/core/cli/planner.ts +192 -23
  61. package/src/core/cli/root-help.ts +195 -105
  62. package/src/core/cli/root-surface.ts +25 -12
  63. package/src/core/cli/runtime-preflight.ts +43 -8
  64. package/src/core/completion/index.ts +50 -0
  65. package/src/core/completion/shells/powershell.ts +2 -2
  66. package/src/core/completion/shells/shared.ts +30 -3
  67. package/src/core/config/index.ts +12 -2
  68. package/src/core/config/package-json.ts +250 -41
  69. package/src/core/execution/index.ts +1 -4
  70. package/src/core/help/index.ts +57 -10
  71. package/src/core/json-schema/index.ts +23 -4
  72. package/src/core/json-schema/meta-descriptions.generated.ts +115 -98
  73. package/src/core/parse/index.ts +62 -1
  74. package/src/core/prompt/index.ts +54 -14
  75. package/src/core/resolve/coerce.ts +73 -5
  76. package/src/core/resolve/flags.ts +14 -0
  77. package/src/core/resolve/property.ts +4 -4
  78. package/src/core/schema/arg.ts +125 -3
  79. package/src/core/schema/command.ts +3 -1
  80. package/src/core/schema/flag.ts +120 -4
  81. package/src/core/schema/index.ts +5 -0
  82. package/src/core/schema/number-constraints.ts +153 -0
  83. package/src/core/schema/prompt.ts +15 -0
  84. package/src/core/schema/run.ts +4 -4
  85. package/src/core/testkit/index.ts +32 -8
  86. package/src/index.ts +8 -0
  87. package/src/runtime/auto.ts +0 -24
  88. package/src/runtime/bun.ts +0 -7
  89. package/src/runtime/deno.ts +0 -2
  90. package/src/runtime/node.ts +0 -11
  91. package/src/runtime/support.ts +1 -59
  92. package/src/schema.ts +16 -0
  93. package/dist/runtime/support.d.mts +0 -42
  94. package/dist/runtime/support.mjs +0 -1
@@ -10,6 +10,8 @@
10
10
  * @internal
11
11
  */
12
12
 
13
+ import type { CompletionOptions, Shell } from '#internals/core/completion/index.ts';
14
+ import { normalizeShell } from '#internals/core/completion/index.ts';
13
15
  import { CLIError, ParseError } from '#internals/core/errors/index.ts';
14
16
  import type { HelpOptions } from '#internals/core/help/index.ts';
15
17
  import type { OutputPolicy } from '#internals/core/output/contracts.ts';
@@ -39,6 +41,13 @@ interface PlannerSchemaLike {
39
41
  readonly commands: readonly ErasedCommand[];
40
42
  /** Fallback command when no subcommand token matches. */
41
43
  readonly defaultCommand: ErasedCommand | undefined;
44
+ /**
45
+ * Eager `--completions <shell>` flag configuration, when `.completions()`
46
+ * was registered with `{ as: 'flag' }`. `undefined` disables interception.
47
+ */
48
+ readonly completionsFlag:
49
+ | { readonly shells: readonly Shell[]; readonly options: CompletionOptions | undefined }
50
+ | undefined;
42
51
  /** Plugins forwarded into every matched execution plan. */
43
52
  readonly plugins: readonly CLIPlugin[];
44
53
  }
@@ -59,6 +68,19 @@ interface RootVersionOutcome {
59
68
  readonly version: string;
60
69
  }
61
70
 
71
+ /** Root-level `--completions [shell]` interception outcome. */
72
+ interface RootCompletionsOutcome {
73
+ /** Discriminant — argv matched the eager `--completions [shell]` flag. */
74
+ readonly kind: 'root-completions';
75
+ /**
76
+ * Resolved, validated target shell, or `undefined` when the flag was given
77
+ * without a value and the shell should be auto-detected from the environment.
78
+ */
79
+ readonly shell: Shell | undefined;
80
+ /** Generator options captured at build time. */
81
+ readonly options: CompletionOptions | undefined;
82
+ }
83
+
62
84
  /** CLI-level dispatch failure before command execution starts. */
63
85
  interface DispatchErrorOutcome {
64
86
  /** Discriminant — dispatch could not resolve a command from argv. */
@@ -84,6 +106,7 @@ interface PlannerMatchOutcome {
84
106
  type DispatchOutcome =
85
107
  | RootHelpOutcome
86
108
  | RootVersionOutcome
109
+ | RootCompletionsOutcome
87
110
  | DispatchErrorOutcome
88
111
  | PlannerMatchOutcome;
89
112
 
@@ -291,12 +314,136 @@ function findUnknownFlagBeforePositional(
291
314
  return undefined;
292
315
  }
293
316
 
317
+ /**
318
+ * Result of scanning the pre-`--`, `--json`-stripped head for root interception.
319
+ * @internal
320
+ */
321
+ interface RootHeadScan {
322
+ /**
323
+ * `--help` / `-h` appeared in the head before any command-dispatch token.
324
+ *
325
+ * Mirrors the global reach of `--version` (#29): a help flag preceded only by
326
+ * flags (no subcommand token) is a *root* help request. A help flag that
327
+ * follows a subcommand token is left to that command's executor, so
328
+ * `app sub --help` still renders the subcommand's help.
329
+ */
330
+ readonly helpBeforeCommand: boolean;
331
+ /** First command-dispatch (positional) token, or `undefined` when the head is all flags. */
332
+ readonly firstCommandToken: string | undefined;
333
+ /** Index of {@linkcode firstCommandToken} in the head, or `-1` when absent. */
334
+ readonly commandTokenIndex: number;
335
+ }
336
+
337
+ /**
338
+ * Scan the pre-`--`, `--json`-stripped head to locate the first command-dispatch
339
+ * token and detect a root-level `--help` / `-h` ahead of it.
340
+ *
341
+ * Value-flag arity is honoured (via `valueFlags`) so a flag value that happens
342
+ * to look like a command name is not mistaken for one — matching how
343
+ * {@linkcode dispatch} reads the same argv.
344
+ *
345
+ * @internal
346
+ */
347
+ function scanRootHead(
348
+ head: readonly string[],
349
+ valueFlags: ReturnType<typeof buildFlagLookup> | undefined,
350
+ ): RootHeadScan {
351
+ for (let index = 0; index < head.length; index++) {
352
+ const token = head[index];
353
+ if (token === undefined) continue;
354
+
355
+ if (token === '--help' || token === '-h') {
356
+ return { helpBeforeCommand: true, firstCommandToken: undefined, commandTokenIndex: -1 };
357
+ }
358
+
359
+ // Positional (command-dispatch) token: `-` alone or anything not flag-shaped.
360
+ if (token === '-' || !token.startsWith('-')) {
361
+ return { helpBeforeCommand: false, firstCommandToken: token, commandTokenIndex: index };
362
+ }
363
+
364
+ if (token.startsWith('--')) {
365
+ const equalsIndex = token.indexOf('=');
366
+ const name = token.slice(2, equalsIndex === -1 ? undefined : equalsIndex);
367
+ const entry = valueFlags?.get(name);
368
+ if (entry !== undefined && equalsIndex === -1 && flagExpectsValue(entry[1])) index++;
369
+ continue;
370
+ }
371
+
372
+ // Short-flag cluster: consume a trailing value-expecting flag's argument.
373
+ const chars = token.slice(1);
374
+ for (let charIndex = 0; charIndex < chars.length; charIndex++) {
375
+ const entry = valueFlags?.get(chars.charAt(charIndex));
376
+ if (entry === undefined || !flagExpectsValue(entry[1])) continue;
377
+ if (charIndex === chars.length - 1) index++;
378
+ break;
379
+ }
380
+ }
381
+
382
+ return { helpBeforeCommand: false, firstCommandToken: undefined, commandTokenIndex: -1 };
383
+ }
384
+
385
+ /**
386
+ * Detect and resolve the eager `--completions [shell]` flag before dispatch.
387
+ *
388
+ * Accepts `--completions <shell>` and `--completions=<shell>`. When no value is
389
+ * given (`--completions` alone, or followed by another flag), the shell is left
390
+ * `undefined` so the caller can auto-detect it from the environment. Scans only
391
+ * before a `--` separator so a literal positional survives.
392
+ *
393
+ * Returns `undefined` when the flag is absent, a `root-completions` outcome
394
+ * otherwise, or a `dispatch-error` when an explicit value names an unknown shell.
395
+ *
396
+ * @internal
397
+ */
398
+ function planCompletionsFlag(
399
+ argv: readonly string[],
400
+ config: { readonly shells: readonly Shell[]; readonly options: CompletionOptions | undefined },
401
+ ): RootCompletionsOutcome | DispatchErrorOutcome | undefined {
402
+ const separatorIndex = argv.indexOf('--');
403
+ const scanEnd = separatorIndex === -1 ? argv.length : separatorIndex;
404
+
405
+ for (let index = 0; index < scanEnd; index++) {
406
+ const token = argv[index];
407
+ if (token === undefined) continue;
408
+
409
+ let rawShell: string | undefined;
410
+ if (token === '--completions') {
411
+ const next = index + 1 < scanEnd ? argv[index + 1] : undefined;
412
+ rawShell = next !== undefined && !next.startsWith('-') ? next : undefined;
413
+ } else if (token.startsWith('--completions=')) {
414
+ rawShell = token.slice('--completions='.length);
415
+ } else {
416
+ continue;
417
+ }
418
+
419
+ // No explicit value → defer to environment auto-detection.
420
+ if (rawShell === undefined || rawShell === '') {
421
+ return { kind: 'root-completions', shell: undefined, options: config.options };
422
+ }
423
+
424
+ const shell = normalizeShell(rawShell);
425
+ if (shell === undefined || !config.shells.includes(shell)) {
426
+ return {
427
+ kind: 'dispatch-error',
428
+ error: new ParseError(`Unknown shell '${rawShell}'`, {
429
+ code: 'INVALID_VALUE',
430
+ suggest: `Valid shells: ${config.shells.join(', ')}`,
431
+ }),
432
+ };
433
+ }
434
+
435
+ return { kind: 'root-completions', shell, options: config.options };
436
+ }
437
+
438
+ return undefined;
439
+ }
440
+
294
441
  /**
295
442
  * Decide what to do with an argv invocation before any command executes.
296
443
  *
297
- * Handles root interception (`--help`, `--version`, bare `help` token),
298
- * dispatches into the command tree, falls back to the default command, and
299
- * produces structured errors for unknown commands/flags.
444
+ * Handles root interception (`--help`, `--version`, `--completions <shell>`,
445
+ * bare `help` token), dispatches into the command tree, falls back to the
446
+ * default command, and produces structured errors for unknown commands/flags.
300
447
  * @internal
301
448
  */
302
449
  function planInvocation(options: PlanInvocationOptions): InvocationPlan {
@@ -310,6 +457,13 @@ function planInvocation(options: PlanInvocationOptions): InvocationPlan {
310
457
  const filteredHead = head.includes('--json') ? head.filter((arg) => arg !== '--json') : head;
311
458
  const filteredArgv = separatorIndex === -1 ? filteredHead : [...filteredHead, ...tail];
312
459
 
460
+ const defaultCommand = options.schema.defaultCommand;
461
+ // At the root, a default command's flags govern value-flag arity so a
462
+ // space-separated value (`mycli --region eu`) is not misread as a command
463
+ // name — both for root interception below and dispatch (see #25).
464
+ const rootValueFlags =
465
+ defaultCommand !== undefined ? buildFlagLookup(defaultCommand.schema.flags) : undefined;
466
+
313
467
  if (
314
468
  options.schema.version !== undefined &&
315
469
  (includesBeforeSeparator(options.argv, '--version') ||
@@ -321,20 +475,35 @@ function planInvocation(options: PlanInvocationOptions): InvocationPlan {
321
475
  };
322
476
  }
323
477
 
324
- const firstArg = filteredArgv[0];
325
- if (firstArg === '--help' || firstArg === '-h') {
478
+ if (options.schema.completionsFlag !== undefined) {
479
+ const completionsOutcome = planCompletionsFlag(options.argv, options.schema.completionsFlag);
480
+ if (completionsOutcome !== undefined) {
481
+ return completionsOutcome;
482
+ }
483
+ }
484
+
485
+ // `--help` / `-h` is intercepted at the root with the same positional reach as
486
+ // `--version` (#29): a help flag preceded only by flags (no subcommand token)
487
+ // is a root request, so `app --verbose --help` mirrors `app --verbose --version`.
488
+ // A help flag *after* a subcommand token is left to that command's executor,
489
+ // keeping `app sub --help` scoped to the subcommand (version stays global by
490
+ // design — there is no per-command version).
491
+ const headScan = scanRootHead(filteredHead, rootValueFlags);
492
+ if (headScan.helpBeforeCommand) {
326
493
  return {
327
494
  kind: 'root-help',
328
495
  help: options.help,
329
496
  };
330
497
  }
331
498
 
332
- if (firstArg === 'help') {
499
+ // Bare `help` token: a root help request (or `<command> --help` forwarding)
500
+ // when it is the first command token and no real `help` command is registered.
501
+ if (headScan.firstCommandToken === 'help') {
333
502
  const hasRealHelpCommand = options.schema.commands.some(
334
503
  (command) => command.schema.name === 'help' || command.schema.aliases.includes('help'),
335
504
  );
336
505
  if (!hasRealHelpCommand) {
337
- const rest = filteredArgv.slice(1);
506
+ const rest = filteredArgv.slice(headScan.commandTokenIndex + 1);
338
507
  if (rest.length === 0) {
339
508
  return {
340
509
  kind: 'root-help',
@@ -349,29 +518,25 @@ function planInvocation(options: PlanInvocationOptions): InvocationPlan {
349
518
  }
350
519
  }
351
520
 
352
- if (firstArg === undefined && options.schema.defaultCommand === undefined) {
353
- return {
354
- kind: 'root-help',
355
- help: options.help,
356
- };
357
- }
358
-
359
- if (options.schema.commands.length === 0) {
521
+ // A CLI with no commands and no default is misconfigured: report NO_ACTION
522
+ // even for a bare invocation, rather than masking it with empty root help.
523
+ if (options.schema.commands.length === 0 && defaultCommand === undefined) {
360
524
  return {
361
525
  kind: 'dispatch-error',
362
526
  error: new CLIError('No commands registered', {
363
527
  code: 'NO_ACTION',
364
- suggest: 'Add commands via .command() before calling .run()',
528
+ suggest: 'Add commands via .command() or .default() before calling .run()',
365
529
  }),
366
530
  };
367
531
  }
368
532
 
369
- const defaultCommand = options.schema.defaultCommand;
370
- // At the root, a default command's flags govern value-flag arity so a
371
- // space-separated value (`mycli --region eu`) is not misread as a command
372
- // name and stolen from the default-command fallback (see #25).
373
- const rootValueFlags =
374
- defaultCommand !== undefined ? buildFlagLookup(defaultCommand.schema.flags) : undefined;
533
+ if (filteredArgv.length === 0 && defaultCommand === undefined) {
534
+ return {
535
+ kind: 'root-help',
536
+ help: options.help,
537
+ };
538
+ }
539
+
375
540
  const result = dispatch(
376
541
  filteredArgv,
377
542
  buildRootCommandMap(options.schema.commands),
@@ -384,7 +549,10 @@ function planInvocation(options: PlanInvocationOptions): InvocationPlan {
384
549
  if (defaultCommand !== undefined && result.parentPath.length === 0) {
385
550
  const suggestion =
386
551
  result.input !== '' ? findClosestCommand(result.input, result.candidates) : undefined;
387
- if (suggestion === undefined && canDelegateUnknownRootToDefault(defaultCommand, result.input)) {
552
+ if (
553
+ suggestion === undefined &&
554
+ canDelegateUnknownRootToDefault(defaultCommand, result.input)
555
+ ) {
388
556
  return buildPlannerMatchOutcome(
389
557
  options.schema,
390
558
  defaultCommand,
@@ -481,6 +649,7 @@ export type {
481
649
  PlanInvocationOptions,
482
650
  PlannerMatchOutcome,
483
651
  PlannerSchemaLike,
652
+ RootCompletionsOutcome,
484
653
  RootHelpOutcome,
485
654
  RootVersionOutcome,
486
655
  };
@@ -9,9 +9,11 @@
9
9
  */
10
10
 
11
11
  import { osc8, padEnd, wrapText } from '#internals/core/help/ansi.ts';
12
- import type { HelpOptions } from '#internals/core/help/index.ts';
13
- import { formatHelpSections } from '#internals/core/help/index.ts';
12
+ import type { FlagEntry, HelpOptions } from '#internals/core/help/index.ts';
13
+ import { formatFlagEntriesBlock, formatHelpSections } from '#internals/core/help/index.ts';
14
14
  import type { CommandSchema } from '#internals/core/schema/command.ts';
15
+ import { command } from '#internals/core/schema/command.ts';
16
+ import type { FlagSchema } from '#internals/core/schema/flag.ts';
15
17
  import { resolveRootSurface } from './root-surface.ts';
16
18
 
17
19
  // Re-use CLISchema inline to avoid circular import through the barrel.
@@ -32,6 +34,13 @@ interface CLISchemaLike {
32
34
  readonly version: string | undefined;
33
35
  }
34
36
  | undefined;
37
+ readonly completionsFlag?: { readonly shells: readonly string[] } | undefined;
38
+ /**
39
+ * Config discovery settings. Only its presence is read — defined means
40
+ * `.config()` enabled the built-in `--config <path>` flag, so root help
41
+ * advertises it in `Global options:`.
42
+ */
43
+ readonly configSettings?: { readonly appName: string } | undefined;
35
44
  }
36
45
 
37
46
  // --- Root help formatter
@@ -40,110 +49,180 @@ interface CLISchemaLike {
40
49
  * Generate root-level help text for the CLI program.
41
50
  *
42
51
  * Shows program name, version, description, usage line, and available
43
- * commands. When the default command is the only visible top-level
44
- * command, merges the root summary with that command's detailed help.
52
+ * subcommands. The default command is the CLI's root *surface*: its arguments
53
+ * and flags are rendered inline (unless `inlineDefault` is `false`) and it is
54
+ * omitted from the `Commands:` list unless `showDefaultInCommands` is set. When
55
+ * `.completions({ as: 'flag' })` is active, the eager `--completions <shell>`
56
+ * flag is advertised in the `Flags:` section.
45
57
  *
46
58
  * @internal
47
59
  */
48
60
  function formatRootHelp(schema: CLISchemaLike, options?: HelpOptions): string {
49
61
  const width = options?.width ?? 80;
62
+ const binName = options?.binName ?? schema.name;
50
63
  const hyperlinks = options?.hyperlinks === true;
51
- const rootSurface = resolveRootSurface(schema);
52
- if (rootSurface.hasSingleVisibleDefault) {
53
- const defaultCommand = rootSurface.visibleDefaultCommand;
54
- if (defaultCommand !== undefined) {
55
- const sections = buildRootSections(
56
- schema,
57
- rootSurface.visibleCommands,
58
- rootSurface.visibleDefaultCommand,
64
+ const inlineDefault = options?.inlineDefault ?? true;
65
+ const showDefaultInCommands = options?.showDefaultInCommands ?? false;
66
+
67
+ const surface = resolveRootSurface(schema);
68
+ const defaultCommand = surface.visibleDefaultCommand;
69
+ // `inlineDefault: false` hides the default command's args/flags, but the eager
70
+ // `--completions` flag is a root-level option that must still be advertised, so
71
+ // a synthetic completions-only surface is rendered even then.
72
+ //
73
+ // Exception: when the default command is the *only* surface — no visible
74
+ // subcommands AND no eager `--completions` flag to advertise — suppressing it
75
+ // would collapse root help to a bare `Usage: <bin> [options]` with no
76
+ // discoverable interface at all. In that case the default is always rendered
77
+ // inline regardless of `inlineDefault`. (With a completions flag the synthetic
78
+ // surface still gives a discoverable path, so `inlineDefault: false` is honored.)
79
+ const defaultIsSoleSurface =
80
+ !surface.hasVisibleSubcommands && schema.completionsFlag === undefined;
81
+ const renderDefaultInline = inlineDefault || defaultIsSoleSurface;
82
+ const inlineDefaultCommand = renderDefaultInline ? defaultCommand : undefined;
83
+ const surfaceCommand = resolveSurfaceCommand(schema, inlineDefaultCommand);
84
+ const inline = surfaceCommand !== undefined;
85
+
86
+ const sections: string[] = [formatHeader(schema, hyperlinks)];
87
+ if (schema.description !== undefined) {
88
+ sections.push(schema.description);
89
+ }
90
+
91
+ // ---- Usage --------------------------------------------------------------
92
+ // A real default makes the command optional (`[command]`); without one a
93
+ // command must be chosen (`<command>`). With no subcommands at all, the
94
+ // default command's own usage stands alone.
95
+ const placeholder = surface.hasVisibleSubcommands
96
+ ? defaultCommand !== undefined
97
+ ? '[command]'
98
+ : '<command>'
99
+ : '';
100
+ const rootUsage =
101
+ placeholder.length > 0
102
+ ? `Usage: ${binName} ${placeholder} [options]`
103
+ : `Usage: ${binName} [options]`;
104
+
105
+ let surfaceSections: string[] = [];
106
+ if (inline && surfaceCommand !== undefined) {
107
+ surfaceSections = [
108
+ ...formatHelpSections(surfaceCommand, {
109
+ ...options,
110
+ binName,
111
+ isDefaultHelp: true,
112
+ }),
113
+ ];
114
+ }
115
+ const surfaceUsage = surfaceSections.shift();
116
+ // Merge the surface usage into the root usage only when the default command is
117
+ // actually inlined; a completions-only synthetic surface keeps the root usage.
118
+ if (inline && surfaceUsage !== undefined && inlineDefaultCommand !== undefined) {
119
+ sections.push(
120
+ surface.hasVisibleSubcommands ? mergeUsageSections(rootUsage, surfaceUsage) : surfaceUsage,
121
+ );
122
+ } else {
123
+ sections.push(rootUsage);
124
+ }
125
+
126
+ // ---- Commands -----------------------------------------------------------
127
+ const listedCommands =
128
+ showDefaultInCommands && defaultCommand !== undefined
129
+ ? [...surface.visibleSubcommands, defaultCommand]
130
+ : surface.visibleSubcommands;
131
+ if (listedCommands.length > 0) {
132
+ sections.push(
133
+ formatRootCommandsSection(
134
+ listedCommands,
135
+ showDefaultInCommands ? defaultCommand?.name : undefined,
59
136
  width,
60
- hyperlinks,
61
- );
62
- const usageIndex = sections.findIndex((section) => section.startsWith('Usage: '));
63
- const commandSections = [
64
- ...formatHelpSections(defaultCommand, {
65
- ...options,
66
- binName: schema.name,
67
- isDefaultHelp: true,
68
- }),
69
- ];
70
- const commandUsage = commandSections.shift();
71
- if (usageIndex !== -1 && commandUsage !== undefined) {
72
- sections[usageIndex] = mergeUsageSections(sections[usageIndex] ?? '', commandUsage);
73
- }
74
- if (
75
- defaultCommand.description !== undefined &&
76
- schema.description !== undefined &&
77
- defaultCommand.description === schema.description
78
- ) {
79
- commandSections.shift();
80
- }
81
- sections.push(...commandSections);
82
- return `${sections.join('\n\n')}\n`;
137
+ ),
138
+ );
139
+ }
140
+
141
+ // ---- Inline default surface (args/flags) --------------------------------
142
+ if (inline && surfaceCommand !== undefined) {
143
+ // Drop the surface command's description when it duplicates the program
144
+ // description already printed at the top.
145
+ if (
146
+ surfaceCommand.description !== undefined &&
147
+ surfaceCommand.description === schema.description &&
148
+ surfaceSections[0] === surfaceCommand.description
149
+ ) {
150
+ surfaceSections.shift();
83
151
  }
152
+ sections.push(...surfaceSections);
84
153
  }
85
154
 
86
- const sections = buildRootSections(
87
- schema,
88
- rootSurface.visibleCommands,
89
- rootSurface.visibleDefaultCommand,
90
- width,
91
- hyperlinks,
92
- );
93
- const placeholder = commandPlaceholder(
94
- rootSurface.visibleCommands,
95
- rootSurface.visibleDefaultCommand,
96
- );
97
- sections.push(
98
- placeholder.length > 0
99
- ? `Run '${schema.name} ${placeholder} --help' for more information.`
100
- : `Run '${schema.name} --help' for more information.`,
101
- );
155
+ // ---- Global options (active built-in flags) -----------------------------
156
+ // Built-ins are framework-provided and never appear in any command schema, so
157
+ // they are advertised here for discoverability (#32). `--completions` is not
158
+ // listed: when active it is already injected into the inline surface's flags.
159
+ const globalOptions = formatGlobalOptionsSection(schema, width);
160
+ if (globalOptions.length > 0) {
161
+ sections.push(globalOptions);
162
+ }
163
+
164
+ // ---- Footer -------------------------------------------------------------
165
+ const footerVisible = options?.footer ?? surface.hasVisibleSubcommands;
166
+ if (footerVisible) {
167
+ const footerPlaceholder = surface.hasVisibleSubcommands
168
+ ? defaultCommand !== undefined
169
+ ? ' [command]'
170
+ : ' <command>'
171
+ : '';
172
+ sections.push(`Run '${binName}${footerPlaceholder} --help' for more information.`);
173
+ }
102
174
 
103
175
  return `${sections.join('\n\n')}\n`;
104
176
  }
105
177
 
106
178
  /**
107
- * Assemble the header, description, usage, and commands sections for root help.
179
+ * Resolve the command rendered inline as the CLI's root surface.
180
+ *
181
+ * Returns the default command, augmented with the eager `--completions <shell>`
182
+ * flag when `.completions({ as: 'flag' })` is active. When there is no default
183
+ * command but the completions flag is configured, a synthetic surface carrying
184
+ * just that flag is returned so the flag is still advertised. Returns
185
+ * `undefined` when there is nothing to render inline.
108
186
  *
109
- * @param schema - The CLI schema.
110
- * @param visibleCommands - Non-hidden top-level commands.
111
- * @param width - Terminal width for text wrapping.
112
- * @param hyperlinks - Whether to emit OSC 8 hyperlinks in the header.
113
- * @returns Ordered help sections (joined later with blank lines).
114
187
  * @internal
115
188
  */
116
- function buildRootSections(
189
+ function resolveSurfaceCommand(
117
190
  schema: CLISchemaLike,
118
- visibleCommands: readonly CommandSchema[],
119
- visibleDefaultCommand: CommandSchema | undefined,
120
- width: number,
121
- hyperlinks: boolean,
122
- ): string[] {
123
- const sections: string[] = [];
124
-
125
- // ---- Header: name + version ---------------------------------------------
126
- sections.push(formatHeader(schema, hyperlinks));
127
-
128
- // ---- Description --------------------------------------------------------
129
- if (schema.description !== undefined) {
130
- sections.push(schema.description);
131
- }
132
-
133
- // ---- Usage line ---------------------------------------------------------
134
- const placeholder = commandPlaceholder(visibleCommands, visibleDefaultCommand);
135
- sections.push(
136
- placeholder.length > 0
137
- ? `Usage: ${schema.name} ${placeholder} [options]`
138
- : `Usage: ${schema.name} [options]`,
139
- );
140
-
141
- // ---- Commands list (skip hidden) ----------------------------------------
142
- if (visibleCommands.length > 0) {
143
- sections.push(formatRootCommandsSection(visibleCommands, visibleDefaultCommand?.name, width));
144
- }
191
+ defaultCommand: CommandSchema | undefined,
192
+ ): CommandSchema | undefined {
193
+ if (schema.completionsFlag === undefined) return defaultCommand;
194
+ const base = defaultCommand ?? command(schema.name).schema;
195
+ return {
196
+ ...base,
197
+ flags: { completions: completionsFlagSchema(schema.completionsFlag.shells), ...base.flags },
198
+ };
199
+ }
145
200
 
146
- return sections;
201
+ /**
202
+ * Build the synthetic, render-only flag schema for the eager `--completions`
203
+ * flag. It never participates in parsing (the planner intercepts the flag
204
+ * directly); it exists purely so root help can list
205
+ * `--completions <bash|zsh|…>` in its `Flags:` section.
206
+ *
207
+ * @internal
208
+ */
209
+ function completionsFlagSchema(shells: readonly string[]): FlagSchema {
210
+ return {
211
+ kind: 'enum',
212
+ presence: 'optional',
213
+ defaultValue: undefined,
214
+ aliases: [],
215
+ envVar: undefined,
216
+ configPath: undefined,
217
+ description: 'Print a shell completion script and exit',
218
+ enumValues: shells,
219
+ elementSchema: undefined,
220
+ numberConstraints: undefined,
221
+ prompt: undefined,
222
+ parseFn: undefined,
223
+ deprecated: undefined,
224
+ propagate: false,
225
+ };
147
226
  }
148
227
 
149
228
  /**
@@ -168,25 +247,6 @@ function formatHeader(schema: CLISchemaLike, hyperlinks: boolean): string {
168
247
  return `${name} ${links?.version !== undefined ? osc8(links.version, version) : version}`;
169
248
  }
170
249
 
171
- /**
172
- * Return the usage-line placeholder for commands (`<command>`, `[command]`, or empty).
173
- *
174
- * @param visibleCommands - Non-hidden top-level commands.
175
- * @param defaultCommand - The default command, if any.
176
- * @returns Placeholder string for the usage line.
177
- * @internal
178
- */
179
- function commandPlaceholder(
180
- visibleCommands: readonly CommandSchema[],
181
- defaultCommand: CommandSchema | undefined,
182
- ): string {
183
- if (visibleCommands.length === 0 && defaultCommand === undefined) {
184
- return '';
185
- }
186
-
187
- return defaultCommand !== undefined ? '[command]' : '<command>';
188
- }
189
-
190
250
  /**
191
251
  * Format the "Commands:" section with aligned names and descriptions.
192
252
  *
@@ -231,6 +291,36 @@ function formatRootCommandsSection(
231
291
  return lines.join('\n');
232
292
  }
233
293
 
294
+ /**
295
+ * Build the `Global options:` section advertising the active built-in flags.
296
+ *
297
+ * `--help, -h` and `--json` are always available; `--version, -V` is shown only
298
+ * when the program declares a version; `--config <path>` only when `.config()`
299
+ * enabled config discovery. The eager `--completions` flag is intentionally
300
+ * omitted — it is advertised via the inline surface when active.
301
+ *
302
+ * @param schema - The CLI schema (read for `version` and `configSettings`).
303
+ * @param width - Terminal width for description wrapping.
304
+ * @returns Formatted `Global options:` block (always non-empty).
305
+ * @internal
306
+ */
307
+ function formatGlobalOptionsSection(schema: CLISchemaLike, width: number): string {
308
+ const entries: FlagEntry[] = [
309
+ { left: '-h, --help', description: 'Show this help message and exit' },
310
+ ];
311
+ if (schema.version !== undefined) {
312
+ entries.push({ left: '-V, --version', description: 'Print the version number and exit' });
313
+ }
314
+ entries.push({ left: '--json', description: 'Emit machine-readable JSON output' });
315
+ if (schema.configSettings !== undefined) {
316
+ entries.push({
317
+ left: '--config <path>',
318
+ description: 'Load configuration from the given file',
319
+ });
320
+ }
321
+ return formatFlagEntriesBlock('Global options:', entries, width);
322
+ }
323
+
234
324
  /**
235
325
  * Merge root and default-command usage lines into a single block.
236
326
  *